(self["webpackChunkgosling_widget"] = self["webpackChunkgosling_widget"] || []).push([[589],{

/***/ 8718:
/***/ ((module) => {

"use strict";


var has = Object.prototype.hasOwnProperty
  , prefix = '~';

/**
 * Constructor to create a storage for our `EE` objects.
 * An `Events` instance is a plain object whose properties are event names.
 *
 * @constructor
 * @private
 */
function Events() {}

//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
  Events.prototype = Object.create(null);

  //
  // This hack is needed because the `__proto__` property is still inherited in
  // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  //
  if (!new Events().__proto__) prefix = false;
}

/**
 * Representation of a single event listener.
 *
 * @param {Function} fn The listener function.
 * @param {*} context The context to invoke the listener with.
 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
 * @constructor
 * @private
 */
function EE(fn, context, once) {
  this.fn = fn;
  this.context = context;
  this.once = once || false;
}

/**
 * Add a listener for a given event.
 *
 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
 * @param {(String|Symbol)} event The event name.
 * @param {Function} fn The listener function.
 * @param {*} context The context to invoke the listener with.
 * @param {Boolean} once Specify if the listener is a one-time listener.
 * @returns {EventEmitter}
 * @private
 */
function addListener(emitter, event, fn, context, once) {
  if (typeof fn !== 'function') {
    throw new TypeError('The listener must be a function');
  }

  var listener = new EE(fn, context || emitter, once)
    , evt = prefix ? prefix + event : event;

  if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  else emitter._events[evt] = [emitter._events[evt], listener];

  return emitter;
}

/**
 * Clear event by name.
 *
 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
 * @param {(String|Symbol)} evt The Event name.
 * @private
 */
function clearEvent(emitter, evt) {
  if (--emitter._eventsCount === 0) emitter._events = new Events();
  else delete emitter._events[evt];
}

/**
 * Minimal `EventEmitter` interface that is molded against the Node.js
 * `EventEmitter` interface.
 *
 * @constructor
 * @public
 */
function EventEmitter() {
  this._events = new Events();
  this._eventsCount = 0;
}

/**
 * Return an array listing the events for which the emitter has registered
 * listeners.
 *
 * @returns {Array}
 * @public
 */
EventEmitter.prototype.eventNames = function eventNames() {
  var names = []
    , events
    , name;

  if (this._eventsCount === 0) return names;

  for (name in (events = this._events)) {
    if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  }

  if (Object.getOwnPropertySymbols) {
    return names.concat(Object.getOwnPropertySymbols(events));
  }

  return names;
};

/**
 * Return the listeners registered for a given event.
 *
 * @param {(String|Symbol)} event The event name.
 * @returns {Array} The registered listeners.
 * @public
 */
EventEmitter.prototype.listeners = function listeners(event) {
  var evt = prefix ? prefix + event : event
    , handlers = this._events[evt];

  if (!handlers) return [];
  if (handlers.fn) return [handlers.fn];

  for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
    ee[i] = handlers[i].fn;
  }

  return ee;
};

/**
 * Return the number of listeners listening to a given event.
 *
 * @param {(String|Symbol)} event The event name.
 * @returns {Number} The number of listeners.
 * @public
 */
EventEmitter.prototype.listenerCount = function listenerCount(event) {
  var evt = prefix ? prefix + event : event
    , listeners = this._events[evt];

  if (!listeners) return 0;
  if (listeners.fn) return 1;
  return listeners.length;
};

/**
 * Calls each of the listeners registered for a given event.
 *
 * @param {(String|Symbol)} event The event name.
 * @returns {Boolean} `true` if the event had listeners, else `false`.
 * @public
 */
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  var evt = prefix ? prefix + event : event;

  if (!this._events[evt]) return false;

  var listeners = this._events[evt]
    , len = arguments.length
    , args
    , i;

  if (listeners.fn) {
    if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);

    switch (len) {
      case 1: return listeners.fn.call(listeners.context), true;
      case 2: return listeners.fn.call(listeners.context, a1), true;
      case 3: return listeners.fn.call(listeners.context, a1, a2), true;
      case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
      case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
      case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
    }

    for (i = 1, args = new Array(len -1); i < len; i++) {
      args[i - 1] = arguments[i];
    }

    listeners.fn.apply(listeners.context, args);
  } else {
    var length = listeners.length
      , j;

    for (i = 0; i < length; i++) {
      if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);

      switch (len) {
        case 1: listeners[i].fn.call(listeners[i].context); break;
        case 2: listeners[i].fn.call(listeners[i].context, a1); break;
        case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
        case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
        default:
          if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
            args[j - 1] = arguments[j];
          }

          listeners[i].fn.apply(listeners[i].context, args);
      }
    }
  }

  return true;
};

/**
 * Add a listener for a given event.
 *
 * @param {(String|Symbol)} event The event name.
 * @param {Function} fn The listener function.
 * @param {*} [context=this] The context to invoke the listener with.
 * @returns {EventEmitter} `this`.
 * @public
 */
EventEmitter.prototype.on = function on(event, fn, context) {
  return addListener(this, event, fn, context, false);
};

/**
 * Add a one-time listener for a given event.
 *
 * @param {(String|Symbol)} event The event name.
 * @param {Function} fn The listener function.
 * @param {*} [context=this] The context to invoke the listener with.
 * @returns {EventEmitter} `this`.
 * @public
 */
EventEmitter.prototype.once = function once(event, fn, context) {
  return addListener(this, event, fn, context, true);
};

/**
 * Remove the listeners of a given event.
 *
 * @param {(String|Symbol)} event The event name.
 * @param {Function} fn Only remove the listeners that match this function.
 * @param {*} context Only remove the listeners that have this context.
 * @param {Boolean} once Only remove one-time listeners.
 * @returns {EventEmitter} `this`.
 * @public
 */
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  var evt = prefix ? prefix + event : event;

  if (!this._events[evt]) return this;
  if (!fn) {
    clearEvent(this, evt);
    return this;
  }

  var listeners = this._events[evt];

  if (listeners.fn) {
    if (
      listeners.fn === fn &&
      (!once || listeners.once) &&
      (!context || listeners.context === context)
    ) {
      clearEvent(this, evt);
    }
  } else {
    for (var i = 0, events = [], length = listeners.length; i < length; i++) {
      if (
        listeners[i].fn !== fn ||
        (once && !listeners[i].once) ||
        (context && listeners[i].context !== context)
      ) {
        events.push(listeners[i]);
      }
    }

    //
    // Reset the array, or remove it completely if we have no more listeners.
    //
    if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
    else clearEvent(this, evt);
  }

  return this;
};

/**
 * Remove all listeners, or those of the specified event.
 *
 * @param {(String|Symbol)} [event] The event name.
 * @returns {EventEmitter} `this`.
 * @public
 */
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  var evt;

  if (event) {
    evt = prefix ? prefix + event : event;
    if (this._events[evt]) clearEvent(this, evt);
  } else {
    this._events = new Events();
    this._eventsCount = 0;
  }

  return this;
};

//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;

//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;

//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;

//
// Expose the module.
//
if (true) {
  module.exports = EventEmitter;
}


/***/ }),

/***/ 9742:
/***/ ((__unused_webpack_module, exports) => {

"use strict";


exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}


/***/ }),

/***/ 8764:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



const base64 = __webpack_require__(9742)
const ieee754 = __webpack_require__(645)
const customInspectSymbol =
  (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
    ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
    : null

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

const K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 *               implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * We report that the browser does not support typed arrays if the are not subclassable
 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 * for __proto__ and has a buggy typed array implementation.
 */
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()

if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
    typeof console.error === 'function') {
  console.error(
    'This browser lacks typed array (Uint8Array) support which is required by ' +
    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  )
}

function typedArraySupport () {
  // Can typed array instances can be augmented?
  try {
    const arr = new Uint8Array(1)
    const proto = { foo: function () { return 42 } }
    Object.setPrototypeOf(proto, Uint8Array.prototype)
    Object.setPrototypeOf(arr, proto)
    return arr.foo() === 42
  } catch (e) {
    return false
  }
}

Object.defineProperty(Buffer.prototype, 'parent', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.buffer
  }
})

Object.defineProperty(Buffer.prototype, 'offset', {
  enumerable: true,
  get: function () {
    if (!Buffer.isBuffer(this)) return undefined
    return this.byteOffset
  }
})

function createBuffer (length) {
  if (length > K_MAX_LENGTH) {
    throw new RangeError('The value "' + length + '" is invalid for option "size"')
  }
  // Return an augmented `Uint8Array` instance
  const buf = new Uint8Array(length)
  Object.setPrototypeOf(buf, Buffer.prototype)
  return buf
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new TypeError(
        'The "string" argument must be of type string. Received type number'
      )
    }
    return allocUnsafe(arg)
  }
  return from(arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192 // not used by this implementation

function from (value, encodingOrOffset, length) {
  if (typeof value === 'string') {
    return fromString(value, encodingOrOffset)
  }

  if (ArrayBuffer.isView(value)) {
    return fromArrayView(value)
  }

  if (value == null) {
    throw new TypeError(
      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
      'or Array-like Object. Received type ' + (typeof value)
    )
  }

  if (isInstance(value, ArrayBuffer) ||
      (value && isInstance(value.buffer, ArrayBuffer))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof SharedArrayBuffer !== 'undefined' &&
      (isInstance(value, SharedArrayBuffer) ||
      (value && isInstance(value.buffer, SharedArrayBuffer)))) {
    return fromArrayBuffer(value, encodingOrOffset, length)
  }

  if (typeof value === 'number') {
    throw new TypeError(
      'The "value" argument must not be of type number. Received type number'
    )
  }

  const valueOf = value.valueOf && value.valueOf()
  if (valueOf != null && valueOf !== value) {
    return Buffer.from(valueOf, encodingOrOffset, length)
  }

  const b = fromObject(value)
  if (b) return b

  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
      typeof value[Symbol.toPrimitive] === 'function') {
    return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)
  }

  throw new TypeError(
    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
    'or Array-like Object. Received type ' + (typeof value)
  )
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(value, encodingOrOffset, length)
}

// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
Object.setPrototypeOf(Buffer, Uint8Array)

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be of type number')
  } else if (size < 0) {
    throw new RangeError('The value "' + size + '" is invalid for option "size"')
  }
}

function alloc (size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpreted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(size).fill(fill, encoding)
      : createBuffer(size).fill(fill)
  }
  return createBuffer(size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(size, fill, encoding)
}

function allocUnsafe (size) {
  assertSize(size)
  return createBuffer(size < 0 ? 0 : checked(size) | 0)
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(size)
}

function fromString (string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('Unknown encoding: ' + encoding)
  }

  const length = byteLength(string, encoding) | 0
  let buf = createBuffer(length)

  const actual = buf.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    buf = buf.slice(0, actual)
  }

  return buf
}

function fromArrayLike (array) {
  const length = array.length < 0 ? 0 : checked(array.length) | 0
  const buf = createBuffer(length)
  for (let i = 0; i < length; i += 1) {
    buf[i] = array[i] & 255
  }
  return buf
}

function fromArrayView (arrayView) {
  if (isInstance(arrayView, Uint8Array)) {
    const copy = new Uint8Array(arrayView)
    return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
  }
  return fromArrayLike(arrayView)
}

function fromArrayBuffer (array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('"offset" is outside of buffer bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('"length" is outside of buffer bounds')
  }

  let buf
  if (byteOffset === undefined && length === undefined) {
    buf = new Uint8Array(array)
  } else if (length === undefined) {
    buf = new Uint8Array(array, byteOffset)
  } else {
    buf = new Uint8Array(array, byteOffset, length)
  }

  // Return an augmented `Uint8Array` instance
  Object.setPrototypeOf(buf, Buffer.prototype)

  return buf
}

function fromObject (obj) {
  if (Buffer.isBuffer(obj)) {
    const len = checked(obj.length) | 0
    const buf = createBuffer(len)

    if (buf.length === 0) {
      return buf
    }

    obj.copy(buf, 0, 0, len)
    return buf
  }

  if (obj.length !== undefined) {
    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
      return createBuffer(0)
    }
    return fromArrayLike(obj)
  }

  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
    return fromArrayLike(obj.data)
  }
}

function checked (length) {
  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= K_MAX_LENGTH) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return b != null && b._isBuffer === true &&
    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}

Buffer.compare = function compare (a, b) {
  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError(
      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
    )
  }

  if (a === b) return 0

  let x = a.length
  let y = b.length

  for (let i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!Array.isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  let i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  const buffer = Buffer.allocUnsafe(length)
  let pos = 0
  for (i = 0; i < list.length; ++i) {
    let buf = list[i]
    if (isInstance(buf, Uint8Array)) {
      if (pos + buf.length > buffer.length) {
        if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
        buf.copy(buffer, pos)
      } else {
        Uint8Array.prototype.set.call(
          buffer,
          buf,
          pos
        )
      }
    } else if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    } else {
      buf.copy(buffer, pos)
    }
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    throw new TypeError(
      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
      'Received type ' + typeof string
    )
  }

  const len = string.length
  const mustMatch = (arguments.length > 2 && arguments[2] === true)
  if (!mustMatch && len === 0) return 0

  // Use a for loop to avoid recursion
  let loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) {
          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
        }
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  let loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  const i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  const len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (let i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  const len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (let i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  const len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (let i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  const length = this.length
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.toLocaleString = Buffer.prototype.toString

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  let str = ''
  const max = exports.INSPECT_MAX_BYTES
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  if (this.length > max) str += ' ... '
  return '<Buffer ' + str + '>'
}
if (customInspectSymbol) {
  Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (isInstance(target, Uint8Array)) {
    target = Buffer.from(target, target.offset, target.byteLength)
  }
  if (!Buffer.isBuffer(target)) {
    throw new TypeError(
      'The "target" argument must be one of type Buffer or Uint8Array. ' +
      'Received type ' + (typeof target)
    )
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  let x = thisEnd - thisStart
  let y = end - start
  const len = Math.min(x, y)

  const thisCopy = this.slice(thisStart, thisEnd)
  const targetCopy = target.slice(start, end)

  for (let i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset // Coerce to Number.
  if (numberIsNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  let indexSize = 1
  let arrLength = arr.length
  let valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  let i
  if (dir) {
    let foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      let found = true
      for (let j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  const remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  const strLen = string.length

  if (length > strLen / 2) {
    length = strLen / 2
  }
  let i
  for (i = 0; i < length; ++i) {
    const parsed = parseInt(string.substr(i * 2, 2), 16)
    if (numberIsNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset >>> 0
    if (isFinite(length)) {
      length = length >>> 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  const remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  let loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
      case 'latin1':
      case 'binary':
        return asciiWrite(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  const res = []

  let i = start
  while (i < end) {
    const firstByte = buf[i]
    let codePoint = null
    let bytesPerSequence = (firstByte > 0xEF)
      ? 4
      : (firstByte > 0xDF)
          ? 3
          : (firstByte > 0xBF)
              ? 2
              : 1

    if (i + bytesPerSequence <= end) {
      let secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  const len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  let res = ''
  let i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  let ret = ''
  end = Math.min(buf.length, end)

  for (let i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  let ret = ''
  end = Math.min(buf.length, end)

  for (let i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  const len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  let out = ''
  for (let i = start; i < end; ++i) {
    out += hexSliceLookupTable[buf[i]]
  }
  return out
}

function utf16leSlice (buf, start, end) {
  const bytes = buf.slice(start, end)
  let res = ''
  // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
  for (let i = 0; i < bytes.length - 1; i += 2) {
    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  const len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  const newBuf = this.subarray(start, end)
  // Return an augmented `Uint8Array` instance
  Object.setPrototypeOf(newBuf, Buffer.prototype)

  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUintLE =
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  let val = this[offset]
  let mul = 1
  let i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUintBE =
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  let val = this[offset + --byteLength]
  let mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUint8 =
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUint16LE =
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUint16BE =
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUint32LE =
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUint32BE =
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const lo = first +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 24

  const hi = this[++offset] +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    last * 2 ** 24

  return BigInt(lo) + (BigInt(hi) << BigInt(32))
})

Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const hi = first * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    this[++offset]

  const lo = this[++offset] * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    last

  return (BigInt(hi) << BigInt(32)) + BigInt(lo)
})

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  let val = this[offset]
  let mul = 1
  let i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  let i = byteLength
  let mul = 1
  let val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  const val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 2, this.length)
  const val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const val = this[offset + 4] +
    this[offset + 5] * 2 ** 8 +
    this[offset + 6] * 2 ** 16 +
    (last << 24) // Overflow

  return (BigInt(val) << BigInt(32)) +
    BigInt(first +
    this[++offset] * 2 ** 8 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 24)
})

Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {
  offset = offset >>> 0
  validateNumber(offset, 'offset')
  const first = this[offset]
  const last = this[offset + 7]
  if (first === undefined || last === undefined) {
    boundsError(offset, this.length - 8)
  }

  const val = (first << 24) + // Overflow
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    this[++offset]

  return (BigInt(val) << BigInt(32)) +
    BigInt(this[++offset] * 2 ** 24 +
    this[++offset] * 2 ** 16 +
    this[++offset] * 2 ** 8 +
    last)
})

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  offset = offset >>> 0
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUintLE =
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    const maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  let mul = 1
  let i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUintBE =
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  byteLength = byteLength >>> 0
  if (!noAssert) {
    const maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  let i = byteLength - 1
  let mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUint8 =
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeUint16LE =
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeUint16BE =
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeUint32LE =
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset + 3] = (value >>> 24)
  this[offset + 2] = (value >>> 16)
  this[offset + 1] = (value >>> 8)
  this[offset] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeUint32BE =
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

function wrtBigUInt64LE (buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7)

  let lo = Number(value & BigInt(0xffffffff))
  buf[offset++] = lo
  lo = lo >> 8
  buf[offset++] = lo
  lo = lo >> 8
  buf[offset++] = lo
  lo = lo >> 8
  buf[offset++] = lo
  let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))
  buf[offset++] = hi
  hi = hi >> 8
  buf[offset++] = hi
  hi = hi >> 8
  buf[offset++] = hi
  hi = hi >> 8
  buf[offset++] = hi
  return offset
}

function wrtBigUInt64BE (buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7)

  let lo = Number(value & BigInt(0xffffffff))
  buf[offset + 7] = lo
  lo = lo >> 8
  buf[offset + 6] = lo
  lo = lo >> 8
  buf[offset + 5] = lo
  lo = lo >> 8
  buf[offset + 4] = lo
  let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))
  buf[offset + 3] = hi
  hi = hi >> 8
  buf[offset + 2] = hi
  hi = hi >> 8
  buf[offset + 1] = hi
  hi = hi >> 8
  buf[offset] = hi
  return offset + 8
}

Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {
  return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
})

Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {
  return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
})

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    const limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  let i = 0
  let mul = 1
  let sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    const limit = Math.pow(2, (8 * byteLength) - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  let i = byteLength - 1
  let mul = 1
  let sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  this[offset] = (value >>> 8)
  this[offset + 1] = (value & 0xff)
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  this[offset] = (value & 0xff)
  this[offset + 1] = (value >>> 8)
  this[offset + 2] = (value >>> 16)
  this[offset + 3] = (value >>> 24)
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  this[offset] = (value >>> 24)
  this[offset + 1] = (value >>> 16)
  this[offset + 2] = (value >>> 8)
  this[offset + 3] = (value & 0xff)
  return offset + 4
}

Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {
  return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
})

Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {
  return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
})

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  value = +value
  offset = offset >>> 0
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  const len = end - start

  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
    // Use built-in when available, missing from IE11
    this.copyWithin(targetStart, start, end)
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, end),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
    if (val.length === 1) {
      const code = val.charCodeAt(0)
      if ((encoding === 'utf8' && code < 128) ||
          encoding === 'latin1') {
        // Fast path: If `val` fits into a single byte, use that numeric value.
        val = code
      }
    }
  } else if (typeof val === 'number') {
    val = val & 255
  } else if (typeof val === 'boolean') {
    val = Number(val)
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  let i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    const bytes = Buffer.isBuffer(val)
      ? val
      : Buffer.from(val, encoding)
    const len = bytes.length
    if (len === 0) {
      throw new TypeError('The value "' + val +
        '" is invalid for argument "value"')
    }
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// CUSTOM ERRORS
// =============

// Simplified versions from Node, changed for Buffer-only usage
const errors = {}
function E (sym, getMessage, Base) {
  errors[sym] = class NodeError extends Base {
    constructor () {
      super()

      Object.defineProperty(this, 'message', {
        value: getMessage.apply(this, arguments),
        writable: true,
        configurable: true
      })

      // Add the error code to the name to include it in the stack trace.
      this.name = `${this.name} [${sym}]`
      // Access the stack to generate the error message including the error code
      // from the name.
      this.stack // eslint-disable-line no-unused-expressions
      // Reset the name to the actual name.
      delete this.name
    }

    get code () {
      return sym
    }

    set code (value) {
      Object.defineProperty(this, 'code', {
        configurable: true,
        enumerable: true,
        value,
        writable: true
      })
    }

    toString () {
      return `${this.name} [${sym}]: ${this.message}`
    }
  }
}

E('ERR_BUFFER_OUT_OF_BOUNDS',
  function (name) {
    if (name) {
      return `${name} is outside of buffer bounds`
    }

    return 'Attempt to access memory outside buffer bounds'
  }, RangeError)
E('ERR_INVALID_ARG_TYPE',
  function (name, actual) {
    return `The "${name}" argument must be of type number. Received type ${typeof actual}`
  }, TypeError)
E('ERR_OUT_OF_RANGE',
  function (str, range, input) {
    let msg = `The value of "${str}" is out of range.`
    let received = input
    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
      received = addNumericalSeparator(String(input))
    } else if (typeof input === 'bigint') {
      received = String(input)
      if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
        received = addNumericalSeparator(received)
      }
      received += 'n'
    }
    msg += ` It must be ${range}. Received ${received}`
    return msg
  }, RangeError)

function addNumericalSeparator (val) {
  let res = ''
  let i = val.length
  const start = val[0] === '-' ? 1 : 0
  for (; i >= start + 4; i -= 3) {
    res = `_${val.slice(i - 3, i)}${res}`
  }
  return `${val.slice(0, i)}${res}`
}

// CHECK FUNCTIONS
// ===============

function checkBounds (buf, offset, byteLength) {
  validateNumber(offset, 'offset')
  if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
    boundsError(offset, buf.length - (byteLength + 1))
  }
}

function checkIntBI (value, min, max, buf, offset, byteLength) {
  if (value > max || value < min) {
    const n = typeof min === 'bigint' ? 'n' : ''
    let range
    if (byteLength > 3) {
      if (min === 0 || min === BigInt(0)) {
        range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`
      } else {
        range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
                `${(byteLength + 1) * 8 - 1}${n}`
      }
    } else {
      range = `>= ${min}${n} and <= ${max}${n}`
    }
    throw new errors.ERR_OUT_OF_RANGE('value', range, value)
  }
  checkBounds(buf, offset, byteLength)
}

function validateNumber (value, name) {
  if (typeof value !== 'number') {
    throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
  }
}

function boundsError (value, length, type) {
  if (Math.floor(value) !== value) {
    validateNumber(value, type)
    throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)
  }

  if (length < 0) {
    throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
  }

  throw new errors.ERR_OUT_OF_RANGE(type || 'offset',
                                    `>= ${type ? 1 : 0} and <= ${length}`,
                                    value)
}

// HELPER FUNCTIONS
// ================

const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node takes equal signs as end of the Base64 encoding
  str = str.split('=')[0]
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = str.trim().replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  let codePoint
  const length = string.length
  let leadSurrogate = null
  const bytes = []

  for (let i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  const byteArray = []
  for (let i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  let c, hi, lo
  const byteArray = []
  for (let i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  let i
  for (i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
  return obj instanceof type ||
    (obj != null && obj.constructor != null && obj.constructor.name != null &&
      obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
  // For IE11 support
  return obj !== obj // eslint-disable-line no-self-compare
}

// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
const hexSliceLookupTable = (function () {
  const alphabet = '0123456789abcdef'
  const table = new Array(256)
  for (let i = 0; i < 16; ++i) {
    const i16 = i * 16
    for (let j = 0; j < 16; ++j) {
      table[i16 + j] = alphabet[i] + alphabet[j]
    }
  }
  return table
})()

// Return not function with Error if BigInt not supported
function defineBigIntMethod (fn) {
  return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
}

function BufferBigIntNotDefined () {
  throw new Error('BigInt not supported')
}


/***/ }),

/***/ 1227:
/***/ ((module, exports, __webpack_require__) => {

/* provided dependency */ var process = __webpack_require__(4155);
/* eslint-env browser */

/**
 * This is the web browser implementation of `debug()`.
 */

exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
	let warned = false;

	return () => {
		if (!warned) {
			warned = true;
			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
		}
	};
})();

/**
 * Colors.
 */

exports.colors = [
	'#0000CC',
	'#0000FF',
	'#0033CC',
	'#0033FF',
	'#0066CC',
	'#0066FF',
	'#0099CC',
	'#0099FF',
	'#00CC00',
	'#00CC33',
	'#00CC66',
	'#00CC99',
	'#00CCCC',
	'#00CCFF',
	'#3300CC',
	'#3300FF',
	'#3333CC',
	'#3333FF',
	'#3366CC',
	'#3366FF',
	'#3399CC',
	'#3399FF',
	'#33CC00',
	'#33CC33',
	'#33CC66',
	'#33CC99',
	'#33CCCC',
	'#33CCFF',
	'#6600CC',
	'#6600FF',
	'#6633CC',
	'#6633FF',
	'#66CC00',
	'#66CC33',
	'#9900CC',
	'#9900FF',
	'#9933CC',
	'#9933FF',
	'#99CC00',
	'#99CC33',
	'#CC0000',
	'#CC0033',
	'#CC0066',
	'#CC0099',
	'#CC00CC',
	'#CC00FF',
	'#CC3300',
	'#CC3333',
	'#CC3366',
	'#CC3399',
	'#CC33CC',
	'#CC33FF',
	'#CC6600',
	'#CC6633',
	'#CC9900',
	'#CC9933',
	'#CCCC00',
	'#CCCC33',
	'#FF0000',
	'#FF0033',
	'#FF0066',
	'#FF0099',
	'#FF00CC',
	'#FF00FF',
	'#FF3300',
	'#FF3333',
	'#FF3366',
	'#FF3399',
	'#FF33CC',
	'#FF33FF',
	'#FF6600',
	'#FF6633',
	'#FF9900',
	'#FF9933',
	'#FFCC00',
	'#FFCC33'
];

/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */

// eslint-disable-next-line complexity
function useColors() {
	// NB: In an Electron preload script, document will be defined but not fully
	// initialized. Since we know we're in Chrome, we'll just detect this case
	// explicitly
	if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
		return true;
	}

	// Internet Explorer and Edge do not support colors.
	if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
		return false;
	}

	// Is webkit? http://stackoverflow.com/a/16459606/376773
	// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
	return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
		// Is firebug? http://stackoverflow.com/a/398120/376773
		(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
		// Is firefox >= v31?
		// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
		// Double check webkit in userAgent just in case we are in a worker
		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}

/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */

function formatArgs(args) {
	args[0] = (this.useColors ? '%c' : '') +
		this.namespace +
		(this.useColors ? ' %c' : ' ') +
		args[0] +
		(this.useColors ? '%c ' : ' ') +
		'+' + module.exports.humanize(this.diff);

	if (!this.useColors) {
		return;
	}

	const c = 'color: ' + this.color;
	args.splice(1, 0, c, 'color: inherit');

	// The final "%c" is somewhat tricky, because there could be other
	// arguments passed either before or after the %c, so we need to
	// figure out the correct index to insert the CSS into
	let index = 0;
	let lastC = 0;
	args[0].replace(/%[a-zA-Z%]/g, match => {
		if (match === '%%') {
			return;
		}
		index++;
		if (match === '%c') {
			// We only are interested in the *last* %c
			// (the user may have provided their own)
			lastC = index;
		}
	});

	args.splice(lastC, 0, c);
}

/**
 * Invokes `console.debug()` when available.
 * No-op when `console.debug` is not a "function".
 * If `console.debug` is not available, falls back
 * to `console.log`.
 *
 * @api public
 */
exports.log = console.debug || console.log || (() => {});

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */
function save(namespaces) {
	try {
		if (namespaces) {
			exports.storage.setItem('debug', namespaces);
		} else {
			exports.storage.removeItem('debug');
		}
	} catch (error) {
		// Swallow
		// XXX (@Qix-) should we be logging these?
	}
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */
function load() {
	let r;
	try {
		r = exports.storage.getItem('debug');
	} catch (error) {
		// Swallow
		// XXX (@Qix-) should we be logging these?
	}

	// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
	if (!r && typeof process !== 'undefined' && 'env' in process) {
		r = process.env.DEBUG;
	}

	return r;
}

/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */

function localstorage() {
	try {
		// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
		// The Browser also has localStorage in the global context.
		return localStorage;
	} catch (error) {
		// Swallow
		// XXX (@Qix-) should we be logging these?
	}
}

module.exports = __webpack_require__(2447)(exports);

const {formatters} = module.exports;

/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */

formatters.j = function (v) {
	try {
		return JSON.stringify(v);
	} catch (error) {
		return '[UnexpectedJSONParseError]: ' + error.message;
	}
};


/***/ }),

/***/ 2447:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {


/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 */

function setup(env) {
	createDebug.debug = createDebug;
	createDebug.default = createDebug;
	createDebug.coerce = coerce;
	createDebug.disable = disable;
	createDebug.enable = enable;
	createDebug.enabled = enabled;
	createDebug.humanize = __webpack_require__(7824);
	createDebug.destroy = destroy;

	Object.keys(env).forEach(key => {
		createDebug[key] = env[key];
	});

	/**
	* The currently active debug mode names, and names to skip.
	*/

	createDebug.names = [];
	createDebug.skips = [];

	/**
	* Map of special "%n" handling functions, for the debug "format" argument.
	*
	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
	*/
	createDebug.formatters = {};

	/**
	* Selects a color for a debug namespace
	* @param {String} namespace The namespace string for the debug instance to be colored
	* @return {Number|String} An ANSI color code for the given namespace
	* @api private
	*/
	function selectColor(namespace) {
		let hash = 0;

		for (let i = 0; i < namespace.length; i++) {
			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
			hash |= 0; // Convert to 32bit integer
		}

		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
	}
	createDebug.selectColor = selectColor;

	/**
	* Create a debugger with the given `namespace`.
	*
	* @param {String} namespace
	* @return {Function}
	* @api public
	*/
	function createDebug(namespace) {
		let prevTime;
		let enableOverride = null;
		let namespacesCache;
		let enabledCache;

		function debug(...args) {
			// Disabled?
			if (!debug.enabled) {
				return;
			}

			const self = debug;

			// Set `diff` timestamp
			const curr = Number(new Date());
			const ms = curr - (prevTime || curr);
			self.diff = ms;
			self.prev = prevTime;
			self.curr = curr;
			prevTime = curr;

			args[0] = createDebug.coerce(args[0]);

			if (typeof args[0] !== 'string') {
				// Anything else let's inspect with %O
				args.unshift('%O');
			}

			// Apply any `formatters` transformations
			let index = 0;
			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
				// If we encounter an escaped % then don't increase the array index
				if (match === '%%') {
					return '%';
				}
				index++;
				const formatter = createDebug.formatters[format];
				if (typeof formatter === 'function') {
					const val = args[index];
					match = formatter.call(self, val);

					// Now we need to remove `args[index]` since it's inlined in the `format`
					args.splice(index, 1);
					index--;
				}
				return match;
			});

			// Apply env-specific formatting (colors, etc.)
			createDebug.formatArgs.call(self, args);

			const logFn = self.log || createDebug.log;
			logFn.apply(self, args);
		}

		debug.namespace = namespace;
		debug.useColors = createDebug.useColors();
		debug.color = createDebug.selectColor(namespace);
		debug.extend = extend;
		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.

		Object.defineProperty(debug, 'enabled', {
			enumerable: true,
			configurable: false,
			get: () => {
				if (enableOverride !== null) {
					return enableOverride;
				}
				if (namespacesCache !== createDebug.namespaces) {
					namespacesCache = createDebug.namespaces;
					enabledCache = createDebug.enabled(namespace);
				}

				return enabledCache;
			},
			set: v => {
				enableOverride = v;
			}
		});

		// Env-specific initialization logic for debug instances
		if (typeof createDebug.init === 'function') {
			createDebug.init(debug);
		}

		return debug;
	}

	function extend(namespace, delimiter) {
		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
		newDebug.log = this.log;
		return newDebug;
	}

	/**
	* Enables a debug mode by namespaces. This can include modes
	* separated by a colon and wildcards.
	*
	* @param {String} namespaces
	* @api public
	*/
	function enable(namespaces) {
		createDebug.save(namespaces);
		createDebug.namespaces = namespaces;

		createDebug.names = [];
		createDebug.skips = [];

		let i;
		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
		const len = split.length;

		for (i = 0; i < len; i++) {
			if (!split[i]) {
				// ignore empty strings
				continue;
			}

			namespaces = split[i].replace(/\*/g, '.*?');

			if (namespaces[0] === '-') {
				createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
			} else {
				createDebug.names.push(new RegExp('^' + namespaces + '$'));
			}
		}
	}

	/**
	* Disable debug output.
	*
	* @return {String} namespaces
	* @api public
	*/
	function disable() {
		const namespaces = [
			...createDebug.names.map(toNamespace),
			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
		].join(',');
		createDebug.enable('');
		return namespaces;
	}

	/**
	* Returns true if the given mode name is enabled, false otherwise.
	*
	* @param {String} name
	* @return {Boolean}
	* @api public
	*/
	function enabled(name) {
		if (name[name.length - 1] === '*') {
			return true;
		}

		let i;
		let len;

		for (i = 0, len = createDebug.skips.length; i < len; i++) {
			if (createDebug.skips[i].test(name)) {
				return false;
			}
		}

		for (i = 0, len = createDebug.names.length; i < len; i++) {
			if (createDebug.names[i].test(name)) {
				return true;
			}
		}

		return false;
	}

	/**
	* Convert regexp to namespace
	*
	* @param {RegExp} regxep
	* @return {String} namespace
	* @api private
	*/
	function toNamespace(regexp) {
		return regexp.toString()
			.substring(2, regexp.toString().length - 2)
			.replace(/\.\*\?$/, '*');
	}

	/**
	* Coerce `val`.
	*
	* @param {Mixed} val
	* @return {Mixed}
	* @api private
	*/
	function coerce(val) {
		if (val instanceof Error) {
			return val.stack || val.message;
		}
		return val;
	}

	/**
	* XXX DO NOT USE. This is a temporary stub function.
	* XXX It WILL be removed in the next major release.
	*/
	function destroy() {
		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
	}

	createDebug.enable(createDebug.load());

	return createDebug;
}

module.exports = setup;


/***/ }),

/***/ 9187:
/***/ ((module) => {

"use strict";


module.exports = earcut;
module.exports["default"] = earcut;

function earcut(data, holeIndices, dim) {

    dim = dim || 2;

    var hasHoles = holeIndices && holeIndices.length,
        outerLen = hasHoles ? holeIndices[0] * dim : data.length,
        outerNode = linkedList(data, 0, outerLen, dim, true),
        triangles = [];

    if (!outerNode || outerNode.next === outerNode.prev) return triangles;

    var minX, minY, maxX, maxY, x, y, invSize;

    if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);

    // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
    if (data.length > 80 * dim) {
        minX = maxX = data[0];
        minY = maxY = data[1];

        for (var i = dim; i < outerLen; i += dim) {
            x = data[i];
            y = data[i + 1];
            if (x < minX) minX = x;
            if (y < minY) minY = y;
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
        }

        // minX, minY and invSize are later used to transform coords into integers for z-order calculation
        invSize = Math.max(maxX - minX, maxY - minY);
        invSize = invSize !== 0 ? 1 / invSize : 0;
    }

    earcutLinked(outerNode, triangles, dim, minX, minY, invSize);

    return triangles;
}

// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
    var i, last;

    if (clockwise === (signedArea(data, start, end, dim) > 0)) {
        for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
    } else {
        for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
    }

    if (last && equals(last, last.next)) {
        removeNode(last);
        last = last.next;
    }

    return last;
}

// eliminate colinear or duplicate points
function filterPoints(start, end) {
    if (!start) return start;
    if (!end) end = start;

    var p = start,
        again;
    do {
        again = false;

        if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
            removeNode(p);
            p = end = p.prev;
            if (p === p.next) break;
            again = true;

        } else {
            p = p.next;
        }
    } while (again || p !== end);

    return end;
}

// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
    if (!ear) return;

    // interlink polygon nodes in z-order
    if (!pass && invSize) indexCurve(ear, minX, minY, invSize);

    var stop = ear,
        prev, next;

    // iterate through ears, slicing them one by one
    while (ear.prev !== ear.next) {
        prev = ear.prev;
        next = ear.next;

        if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
            // cut off the triangle
            triangles.push(prev.i / dim);
            triangles.push(ear.i / dim);
            triangles.push(next.i / dim);

            removeNode(ear);

            // skipping the next vertex leads to less sliver triangles
            ear = next.next;
            stop = next.next;

            continue;
        }

        ear = next;

        // if we looped through the whole remaining polygon and can't find any more ears
        if (ear === stop) {
            // try filtering points and slicing again
            if (!pass) {
                earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);

            // if this didn't work, try curing all small self-intersections locally
            } else if (pass === 1) {
                ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
                earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);

            // as a last resort, try splitting the remaining polygon into two
            } else if (pass === 2) {
                splitEarcut(ear, triangles, dim, minX, minY, invSize);
            }

            break;
        }
    }
}

// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
    var a = ear.prev,
        b = ear,
        c = ear.next;

    if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

    // now make sure we don't have other points inside the potential ear
    var p = ear.next.next;

    while (p !== ear.prev) {
        if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.next;
    }

    return true;
}

function isEarHashed(ear, minX, minY, invSize) {
    var a = ear.prev,
        b = ear,
        c = ear.next;

    if (area(a, b, c) >= 0) return false; // reflex, can't be an ear

    // triangle bbox; min & max are calculated like this for speed
    var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
        minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
        maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
        maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);

    // z-order range for the current triangle bbox;
    var minZ = zOrder(minTX, minTY, minX, minY, invSize),
        maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);

    var p = ear.prevZ,
        n = ear.nextZ;

    // look for points inside the triangle in both directions
    while (p && p.z >= minZ && n && n.z <= maxZ) {
        if (p !== ear.prev && p !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.prevZ;

        if (n !== ear.prev && n !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
            area(n.prev, n, n.next) >= 0) return false;
        n = n.nextZ;
    }

    // look for remaining points in decreasing z-order
    while (p && p.z >= minZ) {
        if (p !== ear.prev && p !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
            area(p.prev, p, p.next) >= 0) return false;
        p = p.prevZ;
    }

    // look for remaining points in increasing z-order
    while (n && n.z <= maxZ) {
        if (n !== ear.prev && n !== ear.next &&
            pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
            area(n.prev, n, n.next) >= 0) return false;
        n = n.nextZ;
    }

    return true;
}

// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
    var p = start;
    do {
        var a = p.prev,
            b = p.next.next;

        if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {

            triangles.push(a.i / dim);
            triangles.push(p.i / dim);
            triangles.push(b.i / dim);

            // remove two nodes involved
            removeNode(p);
            removeNode(p.next);

            p = start = b;
        }
        p = p.next;
    } while (p !== start);

    return filterPoints(p);
}

// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
    // look for a valid diagonal that divides the polygon into two
    var a = start;
    do {
        var b = a.next.next;
        while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
                // split the polygon in two by the diagonal
                var c = splitPolygon(a, b);

                // filter colinear points around the cuts
                a = filterPoints(a, a.next);
                c = filterPoints(c, c.next);

                // run earcut on each half
                earcutLinked(a, triangles, dim, minX, minY, invSize);
                earcutLinked(c, triangles, dim, minX, minY, invSize);
                return;
            }
            b = b.next;
        }
        a = a.next;
    } while (a !== start);
}

// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
    var queue = [],
        i, len, start, end, list;

    for (i = 0, len = holeIndices.length; i < len; i++) {
        start = holeIndices[i] * dim;
        end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        list = linkedList(data, start, end, dim, false);
        if (list === list.next) list.steiner = true;
        queue.push(getLeftmost(list));
    }

    queue.sort(compareX);

    // process holes from left to right
    for (i = 0; i < queue.length; i++) {
        outerNode = eliminateHole(queue[i], outerNode);
        outerNode = filterPoints(outerNode, outerNode.next);
    }

    return outerNode;
}

function compareX(a, b) {
    return a.x - b.x;
}

// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole, outerNode) {
    var bridge = findHoleBridge(hole, outerNode);
    if (!bridge) {
        return outerNode;
    }

    var bridgeReverse = splitPolygon(bridge, hole);

    // filter collinear points around the cuts
    var filteredBridge = filterPoints(bridge, bridge.next);
    filterPoints(bridgeReverse, bridgeReverse.next);

    // Check if input node was removed by the filtering
    return outerNode === bridge ? filteredBridge : outerNode;
}

// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
    var p = outerNode,
        hx = hole.x,
        hy = hole.y,
        qx = -Infinity,
        m;

    // find a segment intersected by a ray from the hole's leftmost point to the left;
    // segment's endpoint with lesser x will be potential connection point
    do {
        if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
            var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
            if (x <= hx && x > qx) {
                qx = x;
                if (x === hx) {
                    if (hy === p.y) return p;
                    if (hy === p.next.y) return p.next;
                }
                m = p.x < p.next.x ? p : p.next;
            }
        }
        p = p.next;
    } while (p !== outerNode);

    if (!m) return null;

    if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint

    // look for points inside the triangle of hole point, segment intersection and endpoint;
    // if there are no points found, we have a valid connection;
    // otherwise choose the point of the minimum angle with the ray as connection point

    var stop = m,
        mx = m.x,
        my = m.y,
        tanMin = Infinity,
        tan;

    p = m;

    do {
        if (hx >= p.x && p.x >= mx && hx !== p.x &&
                pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {

            tan = Math.abs(hy - p.y) / (hx - p.x); // tangential

            if (locallyInside(p, hole) &&
                (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
                m = p;
                tanMin = tan;
            }
        }

        p = p.next;
    } while (p !== stop);

    return m;
}

// whether sector in vertex m contains sector in vertex p in the same coordinates
function sectorContainsSector(m, p) {
    return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
}

// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, invSize) {
    var p = start;
    do {
        if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
        p.prevZ = p.prev;
        p.nextZ = p.next;
        p = p.next;
    } while (p !== start);

    p.prevZ.nextZ = null;
    p.prevZ = null;

    sortLinked(p);
}

// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
    var i, p, q, e, tail, numMerges, pSize, qSize,
        inSize = 1;

    do {
        p = list;
        list = null;
        tail = null;
        numMerges = 0;

        while (p) {
            numMerges++;
            q = p;
            pSize = 0;
            for (i = 0; i < inSize; i++) {
                pSize++;
                q = q.nextZ;
                if (!q) break;
            }
            qSize = inSize;

            while (pSize > 0 || (qSize > 0 && q)) {

                if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
                    e = p;
                    p = p.nextZ;
                    pSize--;
                } else {
                    e = q;
                    q = q.nextZ;
                    qSize--;
                }

                if (tail) tail.nextZ = e;
                else list = e;

                e.prevZ = tail;
                tail = e;
            }

            p = q;
        }

        tail.nextZ = null;
        inSize *= 2;

    } while (numMerges > 1);

    return list;
}

// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder(x, y, minX, minY, invSize) {
    // coords are transformed into non-negative 15-bit integer range
    x = 32767 * (x - minX) * invSize;
    y = 32767 * (y - minY) * invSize;

    x = (x | (x << 8)) & 0x00FF00FF;
    x = (x | (x << 4)) & 0x0F0F0F0F;
    x = (x | (x << 2)) & 0x33333333;
    x = (x | (x << 1)) & 0x55555555;

    y = (y | (y << 8)) & 0x00FF00FF;
    y = (y | (y << 4)) & 0x0F0F0F0F;
    y = (y | (y << 2)) & 0x33333333;
    y = (y | (y << 1)) & 0x55555555;

    return x | (y << 1);
}

// find the leftmost node of a polygon ring
function getLeftmost(start) {
    var p = start,
        leftmost = start;
    do {
        if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
        p = p.next;
    } while (p !== start);

    return leftmost;
}

// check if a point lies within a convex triangle
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
    return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
           (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
           (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}

// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a, b) {
    return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
           (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
            (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
            equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
}

// signed area of a triangle
function area(p, q, r) {
    return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}

// check if two points are equal
function equals(p1, p2) {
    return p1.x === p2.x && p1.y === p2.y;
}

// check if two segments intersect
function intersects(p1, q1, p2, q2) {
    var o1 = sign(area(p1, q1, p2));
    var o2 = sign(area(p1, q1, q2));
    var o3 = sign(area(p2, q2, p1));
    var o4 = sign(area(p2, q2, q1));

    if (o1 !== o2 && o3 !== o4) return true; // general case

    if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
    if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
    if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
    if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2

    return false;
}

// for collinear points p, q, r, check if point q lies on segment pr
function onSegment(p, q, r) {
    return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
}

function sign(num) {
    return num > 0 ? 1 : num < 0 ? -1 : 0;
}

// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
    var p = a;
    do {
        if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
                intersects(p, p.next, a, b)) return true;
        p = p.next;
    } while (p !== a);

    return false;
}

// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
    return area(a.prev, a, a.next) < 0 ?
        area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
        area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}

// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
    var p = a,
        inside = false,
        px = (a.x + b.x) / 2,
        py = (a.y + b.y) / 2;
    do {
        if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
                (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
            inside = !inside;
        p = p.next;
    } while (p !== a);

    return inside;
}

// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
    var a2 = new Node(a.i, a.x, a.y),
        b2 = new Node(b.i, b.x, b.y),
        an = a.next,
        bp = b.prev;

    a.next = b;
    b.prev = a;

    a2.next = an;
    an.prev = a2;

    b2.next = a2;
    a2.prev = b2;

    bp.next = b2;
    b2.prev = bp;

    return b2;
}

// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
    var p = new Node(i, x, y);

    if (!last) {
        p.prev = p;
        p.next = p;

    } else {
        p.next = last.next;
        p.prev = last;
        last.next.prev = p;
        last.next = p;
    }
    return p;
}

function removeNode(p) {
    p.next.prev = p.prev;
    p.prev.next = p.next;

    if (p.prevZ) p.prevZ.nextZ = p.nextZ;
    if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}

function Node(i, x, y) {
    // vertex index in coordinates array
    this.i = i;

    // vertex coordinates
    this.x = x;
    this.y = y;

    // previous and next vertex nodes in a polygon ring
    this.prev = null;
    this.next = null;

    // z-order curve value
    this.z = null;

    // previous and next nodes in z-order
    this.prevZ = null;
    this.nextZ = null;

    // indicates whether this is a steiner point
    this.steiner = false;
}

// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
    var hasHoles = holeIndices && holeIndices.length;
    var outerLen = hasHoles ? holeIndices[0] * dim : data.length;

    var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
    if (hasHoles) {
        for (var i = 0, len = holeIndices.length; i < len; i++) {
            var start = holeIndices[i] * dim;
            var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
            polygonArea -= Math.abs(signedArea(data, start, end, dim));
        }
    }

    var trianglesArea = 0;
    for (i = 0; i < triangles.length; i += 3) {
        var a = triangles[i] * dim;
        var b = triangles[i + 1] * dim;
        var c = triangles[i + 2] * dim;
        trianglesArea += Math.abs(
            (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
            (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
    }

    return polygonArea === 0 && trianglesArea === 0 ? 0 :
        Math.abs((trianglesArea - polygonArea) / polygonArea);
};

function signedArea(data, start, end, dim) {
    var sum = 0;
    for (var i = start, j = end - dim; i < end; i += dim) {
        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
        j = i;
    }
    return sum;
}

// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
    var dim = data[0][0].length,
        result = {vertices: [], holes: [], dimensions: dim},
        holeIndex = 0;

    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].length; j++) {
            for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
        }
        if (i > 0) {
            holeIndex += data[i - 1].length;
            result.holes.push(holeIndex);
        }
    }
    return result;
};


/***/ }),

/***/ 1589:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "GoslingComponent": () => (/* binding */ GoslingComponent),
  "GoslingSchema": () => (/* binding */ GoslingSchema),
  "GoslingTemplates": () => (/* binding */ GoslingTemplates),
  "ThemeSchema": () => (/* binding */ theme_schema),
  "compile": () => (/* binding */ compile),
  "embed": () => (/* binding */ gosling_es_embed),
  "init": () => (/* binding */ init),
  "name": () => (/* binding */ gosling_es_name),
  "validateGoslingSpec": () => (/* binding */ validateGoslingSpec),
  "version": () => (/* binding */ version)
});

;// CONCATENATED MODULE: ./node_modules/lodash-es/isUndefined.js
/**
 * Checks if `value` is `undefined`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
 * @example
 *
 * _.isUndefined(void 0);
 * // => true
 *
 * _.isUndefined(null);
 * // => false
 */
function isUndefined(value) {
  return value === undefined;
}

/* harmony default export */ const lodash_es_isUndefined = (isUndefined);

// EXTERNAL MODULE: ./node_modules/lodash-es/_root.js
var _root = __webpack_require__(6169);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_Symbol.js


/** Built-in value references. */
var _Symbol_Symbol = _root/* default.Symbol */.Z.Symbol;

/* harmony default export */ const _Symbol = (_Symbol_Symbol);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getRawTag.js


/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _getRawTag_hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/** Built-in value references. */
var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag(value) {
  var isOwn = _getRawTag_hasOwnProperty.call(value, symToStringTag),
      tag = value[symToStringTag];

  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}

/* harmony default export */ const _getRawTag = (getRawTag);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_objectToString.js
/** Used for built-in method references. */
var _objectToString_objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var _objectToString_nativeObjectToString = _objectToString_objectProto.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString(value) {
  return _objectToString_nativeObjectToString.call(value);
}

/* harmony default export */ const _objectToString = (objectToString);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetTag.js




/** `Object#toString` result references. */
var nullTag = '[object Null]',
    undefinedTag = '[object Undefined]';

/** Built-in value references. */
var _baseGetTag_symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }
  return (_baseGetTag_symToStringTag && _baseGetTag_symToStringTag in Object(value))
    ? _getRawTag(value)
    : _objectToString(value);
}

/* harmony default export */ const _baseGetTag = (baseGetTag);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isObject.js
/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

/* harmony default export */ const lodash_es_isObject = (isObject);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isFunction.js



/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    proxyTag = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  if (!lodash_es_isObject(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = _baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}

/* harmony default export */ const lodash_es_isFunction = (isFunction);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_coreJsData.js


/** Used to detect overreaching core-js shims. */
var coreJsData = _root/* default.__core-js_shared__ */.Z["__core-js_shared__"];

/* harmony default export */ const _coreJsData = (coreJsData);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isMasked.js


/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}

/* harmony default export */ const _isMasked = (isMasked);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_toSource.js
/** Used for built-in method references. */
var funcProto = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}

/* harmony default export */ const _toSource = (toSource);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNative.js





/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var _baseIsNative_funcProto = Function.prototype,
    _baseIsNative_objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var _baseIsNative_funcToString = _baseIsNative_funcProto.toString;

/** Used to check objects for own properties. */
var _baseIsNative_hasOwnProperty = _baseIsNative_objectProto.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  _baseIsNative_funcToString.call(_baseIsNative_hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!lodash_es_isObject(value) || _isMasked(value)) {
    return false;
  }
  var pattern = lodash_es_isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(_toSource(value));
}

/* harmony default export */ const _baseIsNative = (baseIsNative);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getValue.js
/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

/* harmony default export */ const _getValue = (getValue);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getNative.js



/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = _getValue(object, key);
  return _baseIsNative(value) ? value : undefined;
}

/* harmony default export */ const _getNative = (getNative);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_defineProperty.js


var defineProperty = (function() {
  try {
    var func = _getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

/* harmony default export */ const _defineProperty = (defineProperty);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseAssignValue.js


/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function baseAssignValue(object, key, value) {
  if (key == '__proto__' && _defineProperty) {
    _defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}

/* harmony default export */ const _baseAssignValue = (baseAssignValue);

;// CONCATENATED MODULE: ./node_modules/lodash-es/eq.js
/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}

/* harmony default export */ const lodash_es_eq = (eq);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_assignValue.js



/** Used for built-in method references. */
var _assignValue_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _assignValue_hasOwnProperty = _assignValue_objectProto.hasOwnProperty;

/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignValue(object, key, value) {
  var objValue = object[key];
  if (!(_assignValue_hasOwnProperty.call(object, key) && lodash_es_eq(objValue, value)) ||
      (value === undefined && !(key in object))) {
    _baseAssignValue(object, key, value);
  }
}

/* harmony default export */ const _assignValue = (assignValue);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_copyObject.js



/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */
function copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});

  var index = -1,
      length = props.length;

  while (++index < length) {
    var key = props[index];

    var newValue = customizer
      ? customizer(object[key], source[key], key, object, source)
      : undefined;

    if (newValue === undefined) {
      newValue = source[key];
    }
    if (isNew) {
      _baseAssignValue(object, key, newValue);
    } else {
      _assignValue(object, key, newValue);
    }
  }
  return object;
}

/* harmony default export */ const _copyObject = (copyObject);

;// CONCATENATED MODULE: ./node_modules/lodash-es/identity.js
/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity_identity(value) {
  return value;
}

/* harmony default export */ const lodash_es_identity = (identity_identity);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_apply.js
/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}

/* harmony default export */ const _apply = (apply);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_overRest.js


/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */
function overRest(func, start, transform) {
  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  return function() {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);

    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = transform(array);
    return _apply(func, this, otherArgs);
  };
}

/* harmony default export */ const _overRest = (overRest);

;// CONCATENATED MODULE: ./node_modules/lodash-es/constant.js
/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function() {
    return value;
  };
}

/* harmony default export */ const lodash_es_constant = (constant);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSetToString.js




/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var baseSetToString = !_defineProperty ? lodash_es_identity : function(func, string) {
  return _defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': lodash_es_constant(string),
    'writable': true
  });
};

/* harmony default export */ const _baseSetToString = (baseSetToString);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_shortOut.js
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;

/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */
function shortOut(func) {
  var count = 0,
      lastCalled = 0;

  return function() {
    var stamp = nativeNow(),
        remaining = HOT_SPAN - (stamp - lastCalled);

    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(undefined, arguments);
  };
}

/* harmony default export */ const _shortOut = (shortOut);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_setToString.js



/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var setToString = _shortOut(_baseSetToString);

/* harmony default export */ const _setToString = (setToString);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRest.js




/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  return _setToString(_overRest(func, start, lodash_es_identity), func + '');
}

/* harmony default export */ const _baseRest = (baseRest);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isLength.js
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

/* harmony default export */ const lodash_es_isLength = (isLength);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isArrayLike.js



/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && lodash_es_isLength(value.length) && !lodash_es_isFunction(value);
}

/* harmony default export */ const lodash_es_isArrayLike = (isArrayLike);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isIndex.js
/** Used as references for various `Number` constants. */
var _isIndex_MAX_SAFE_INTEGER = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? _isIndex_MAX_SAFE_INTEGER : length;

  return !!length &&
    (type == 'number' ||
      (type != 'symbol' && reIsUint.test(value))) &&
        (value > -1 && value % 1 == 0 && value < length);
}

/* harmony default export */ const _isIndex = (isIndex);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isIterateeCall.js





/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */
function isIterateeCall(value, index, object) {
  if (!lodash_es_isObject(object)) {
    return false;
  }
  var type = typeof index;
  if (type == 'number'
        ? (lodash_es_isArrayLike(object) && _isIndex(index, object.length))
        : (type == 'string' && index in object)
      ) {
    return lodash_es_eq(object[index], value);
  }
  return false;
}

/* harmony default export */ const _isIterateeCall = (isIterateeCall);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_createAssigner.js



/**
 * Creates a function like `_.assign`.
 *
 * @private
 * @param {Function} assigner The function to assign values.
 * @returns {Function} Returns the new assigner function.
 */
function createAssigner(assigner) {
  return _baseRest(function(object, sources) {
    var index = -1,
        length = sources.length,
        customizer = length > 1 ? sources[length - 1] : undefined,
        guard = length > 2 ? sources[2] : undefined;

    customizer = (assigner.length > 3 && typeof customizer == 'function')
      ? (length--, customizer)
      : undefined;

    if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? undefined : customizer;
      length = 1;
    }
    object = Object(object);
    while (++index < length) {
      var source = sources[index];
      if (source) {
        assigner(object, source, index, customizer);
      }
    }
    return object;
  });
}

/* harmony default export */ const _createAssigner = (createAssigner);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isPrototype.js
/** Used for built-in method references. */
var _isPrototype_objectProto = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = (typeof Ctor == 'function' && Ctor.prototype) || _isPrototype_objectProto;

  return value === proto;
}

/* harmony default export */ const _isPrototype = (isPrototype);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTimes.js
/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}

/* harmony default export */ const _baseTimes = (baseTimes);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isObjectLike.js
/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

/* harmony default export */ const lodash_es_isObjectLike = (isObjectLike);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsArguments.js



/** `Object#toString` result references. */
var argsTag = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments(value) {
  return lodash_es_isObjectLike(value) && _baseGetTag(value) == argsTag;
}

/* harmony default export */ const _baseIsArguments = (baseIsArguments);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isArguments.js



/** Used for built-in method references. */
var isArguments_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var isArguments_hasOwnProperty = isArguments_objectProto.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable = isArguments_objectProto.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
  return lodash_es_isObjectLike(value) && isArguments_hasOwnProperty.call(value, 'callee') &&
    !propertyIsEnumerable.call(value, 'callee');
};

/* harmony default export */ const lodash_es_isArguments = (isArguments);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isArray.js
/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

/* harmony default export */ const lodash_es_isArray = (isArray);

// EXTERNAL MODULE: ./node_modules/lodash-es/isBuffer.js + 1 modules
var isBuffer = __webpack_require__(4002);
;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsTypedArray.js




/** `Object#toString` result references. */
var _baseIsTypedArray_argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    _baseIsTypedArray_funcTag = '[object Function]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    weakMapTag = '[object WeakMap]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[_baseIsTypedArray_argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[_baseIsTypedArray_funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray(value) {
  return lodash_es_isObjectLike(value) &&
    lodash_es_isLength(value.length) && !!typedArrayTags[_baseGetTag(value)];
}

/* harmony default export */ const _baseIsTypedArray = (baseIsTypedArray);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUnary.js
/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}

/* harmony default export */ const _baseUnary = (baseUnary);

// EXTERNAL MODULE: ./node_modules/lodash-es/_nodeUtil.js
var _nodeUtil = __webpack_require__(9730);
;// CONCATENATED MODULE: ./node_modules/lodash-es/isTypedArray.js




/* Node.js helper references. */
var nodeIsTypedArray = _nodeUtil/* default */.Z && _nodeUtil/* default.isTypedArray */.Z.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;

/* harmony default export */ const lodash_es_isTypedArray = (isTypedArray);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayLikeKeys.js







/** Used for built-in method references. */
var _arrayLikeKeys_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _arrayLikeKeys_hasOwnProperty = _arrayLikeKeys_objectProto.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  var isArr = lodash_es_isArray(value),
      isArg = !isArr && lodash_es_isArguments(value),
      isBuff = !isArr && !isArg && (0,isBuffer/* default */.Z)(value),
      isType = !isArr && !isArg && !isBuff && lodash_es_isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? _baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || _arrayLikeKeys_hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (
           // Safari 9 has enumerable `arguments.length` in strict mode.
           key == 'length' ||
           // Node.js 0.10 has enumerable non-index properties on buffers.
           (isBuff && (key == 'offset' || key == 'parent')) ||
           // PhantomJS 2 has enumerable non-index properties on typed arrays.
           (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
           // Skip index properties.
           _isIndex(key, length)
        ))) {
      result.push(key);
    }
  }
  return result;
}

/* harmony default export */ const _arrayLikeKeys = (arrayLikeKeys);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_overArg.js
/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}

/* harmony default export */ const _overArg = (overArg);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeKeys.js


/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = _overArg(Object.keys, Object);

/* harmony default export */ const _nativeKeys = (nativeKeys);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseKeys.js



/** Used for built-in method references. */
var _baseKeys_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _baseKeys_hasOwnProperty = _baseKeys_objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!_isPrototype(object)) {
    return _nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (_baseKeys_hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}

/* harmony default export */ const _baseKeys = (baseKeys);

;// CONCATENATED MODULE: ./node_modules/lodash-es/keys.js




/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return lodash_es_isArrayLike(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}

/* harmony default export */ const lodash_es_keys = (keys);

;// CONCATENATED MODULE: ./node_modules/lodash-es/assign.js







/** Used for built-in method references. */
var assign_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var assign_hasOwnProperty = assign_objectProto.hasOwnProperty;

/**
 * Assigns own enumerable string keyed properties of source objects to the
 * destination object. Source objects are applied from left to right.
 * Subsequent sources overwrite property assignments of previous sources.
 *
 * **Note:** This method mutates `object` and is loosely based on
 * [`Object.assign`](https://mdn.io/Object/assign).
 *
 * @static
 * @memberOf _
 * @since 0.10.0
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.assignIn
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * function Bar() {
 *   this.c = 3;
 * }
 *
 * Foo.prototype.b = 2;
 * Bar.prototype.d = 4;
 *
 * _.assign({ 'a': 0 }, new Foo, new Bar);
 * // => { 'a': 1, 'c': 3 }
 */
var assign_assign = _createAssigner(function(object, source) {
  if (_isPrototype(source) || lodash_es_isArrayLike(source)) {
    _copyObject(source, lodash_es_keys(source), object);
    return;
  }
  for (var key in source) {
    if (assign_hasOwnProperty.call(source, key)) {
      _assignValue(object, key, source[key]);
    }
  }
});

/* harmony default export */ const lodash_es_assign = (assign_assign);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseClamp.js
/**
 * The base implementation of `_.clamp` which doesn't coerce arguments.
 *
 * @private
 * @param {number} number The number to clamp.
 * @param {number} [lower] The lower bound.
 * @param {number} upper The upper bound.
 * @returns {number} Returns the clamped number.
 */
function baseClamp(number, lower, upper) {
  if (number === number) {
    if (upper !== undefined) {
      number = number <= upper ? number : upper;
    }
    if (lower !== undefined) {
      number = number >= lower ? number : lower;
    }
  }
  return number;
}

/* harmony default export */ const _baseClamp = (baseClamp);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_copyArray.js
/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
      length = source.length;

  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}

/* harmony default export */ const _copyArray = (copyArray);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseRandom.js
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeFloor = Math.floor,
    nativeRandom = Math.random;

/**
 * The base implementation of `_.random` without support for returning
 * floating-point numbers.
 *
 * @private
 * @param {number} lower The lower bound.
 * @param {number} upper The upper bound.
 * @returns {number} Returns the random number.
 */
function baseRandom(lower, upper) {
  return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}

/* harmony default export */ const _baseRandom = (baseRandom);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_shuffleSelf.js


/**
 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
 *
 * @private
 * @param {Array} array The array to shuffle.
 * @param {number} [size=array.length] The size of `array`.
 * @returns {Array} Returns `array`.
 */
function shuffleSelf(array, size) {
  var index = -1,
      length = array.length,
      lastIndex = length - 1;

  size = size === undefined ? length : size;
  while (++index < size) {
    var rand = _baseRandom(index, lastIndex),
        value = array[rand];

    array[rand] = array[index];
    array[index] = value;
  }
  array.length = size;
  return array;
}

/* harmony default export */ const _shuffleSelf = (shuffleSelf);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arraySampleSize.js




/**
 * A specialized version of `_.sampleSize` for arrays.
 *
 * @private
 * @param {Array} array The array to sample.
 * @param {number} n The number of elements to sample.
 * @returns {Array} Returns the random elements.
 */
function arraySampleSize(array, n) {
  return _shuffleSelf(_copyArray(array), _baseClamp(n, 0, array.length));
}

/* harmony default export */ const _arraySampleSize = (arraySampleSize);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayMap.js
/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}

/* harmony default export */ const _arrayMap = (arrayMap);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseValues.js


/**
 * The base implementation of `_.values` and `_.valuesIn` which creates an
 * array of `object` property values corresponding to the property names
 * of `props`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array} props The property names to get values for.
 * @returns {Object} Returns the array of property values.
 */
function baseValues(object, props) {
  return _arrayMap(props, function(key) {
    return object[key];
  });
}

/* harmony default export */ const _baseValues = (baseValues);

;// CONCATENATED MODULE: ./node_modules/lodash-es/values.js



/**
 * Creates an array of the own enumerable string keyed property values of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property values.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.values(new Foo);
 * // => [1, 2] (iteration order is not guaranteed)
 *
 * _.values('hi');
 * // => ['h', 'i']
 */
function values(object) {
  return object == null ? [] : _baseValues(object, lodash_es_keys(object));
}

/* harmony default export */ const lodash_es_values = (values);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseSampleSize.js




/**
 * The base implementation of `_.sampleSize` without param guards.
 *
 * @private
 * @param {Array|Object} collection The collection to sample.
 * @param {number} n The number of elements to sample.
 * @returns {Array} Returns the random elements.
 */
function baseSampleSize(collection, n) {
  var array = lodash_es_values(collection);
  return _shuffleSelf(array, _baseClamp(n, 0, array.length));
}

/* harmony default export */ const _baseSampleSize = (baseSampleSize);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_trimmedEndIndex.js
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;

/**
 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
 * character of `string`.
 *
 * @private
 * @param {string} string The string to inspect.
 * @returns {number} Returns the index of the last non-whitespace character.
 */
function trimmedEndIndex(string) {
  var index = string.length;

  while (index-- && reWhitespace.test(string.charAt(index))) {}
  return index;
}

/* harmony default export */ const _trimmedEndIndex = (trimmedEndIndex);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseTrim.js


/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;

/**
 * The base implementation of `_.trim`.
 *
 * @private
 * @param {string} string The string to trim.
 * @returns {string} Returns the trimmed string.
 */
function baseTrim(string) {
  return string
    ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
    : string;
}

/* harmony default export */ const _baseTrim = (baseTrim);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isSymbol.js



/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (lodash_es_isObjectLike(value) && _baseGetTag(value) == symbolTag);
}

/* harmony default export */ const lodash_es_isSymbol = (isSymbol);

;// CONCATENATED MODULE: ./node_modules/lodash-es/toNumber.js




/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (lodash_es_isSymbol(value)) {
    return NAN;
  }
  if (lodash_es_isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = lodash_es_isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = _baseTrim(value);
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

/* harmony default export */ const lodash_es_toNumber = (toNumber);

;// CONCATENATED MODULE: ./node_modules/lodash-es/toFinite.js


/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_INTEGER = 1.7976931348623157e+308;

/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = lodash_es_toNumber(value);
  if (value === INFINITY || value === -INFINITY) {
    var sign = (value < 0 ? -1 : 1);
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}

/* harmony default export */ const lodash_es_toFinite = (toFinite);

;// CONCATENATED MODULE: ./node_modules/lodash-es/toInteger.js


/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */
function toInteger(value) {
  var result = lodash_es_toFinite(value),
      remainder = result % 1;

  return result === result ? (remainder ? result - remainder : result) : 0;
}

/* harmony default export */ const lodash_es_toInteger = (toInteger);

;// CONCATENATED MODULE: ./node_modules/lodash-es/sampleSize.js






/**
 * Gets `n` random elements at unique keys from `collection` up to the
 * size of `collection`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Collection
 * @param {Array|Object} collection The collection to sample.
 * @param {number} [n=1] The number of elements to sample.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {Array} Returns the random elements.
 * @example
 *
 * _.sampleSize([1, 2, 3], 2);
 * // => [3, 1]
 *
 * _.sampleSize([1, 2, 3], 4);
 * // => [2, 3, 1]
 */
function sampleSize(collection, n, guard) {
  if ((guard ? _isIterateeCall(collection, n, guard) : n === undefined)) {
    n = 1;
  } else {
    n = lodash_es_toInteger(n);
  }
  var func = lodash_es_isArray(collection) ? _arraySampleSize : _baseSampleSize;
  return func(collection, n);
}

/* harmony default export */ const lodash_es_sampleSize = (sampleSize);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheClear.js
/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

/* harmony default export */ const _listCacheClear = (listCacheClear);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_assocIndexOf.js


/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (lodash_es_eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}

/* harmony default export */ const _assocIndexOf = (assocIndexOf);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheDelete.js


/** Used for built-in method references. */
var arrayProto = Array.prototype;

/** Built-in value references. */
var splice = arrayProto.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = _assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}

/* harmony default export */ const _listCacheDelete = (listCacheDelete);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheGet.js


/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = _assocIndexOf(data, key);

  return index < 0 ? undefined : data[index][1];
}

/* harmony default export */ const _listCacheGet = (listCacheGet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheHas.js


/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return _assocIndexOf(this.__data__, key) > -1;
}

/* harmony default export */ const _listCacheHas = (listCacheHas);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_listCacheSet.js


/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = _assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}

/* harmony default export */ const _listCacheSet = (listCacheSet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_ListCache.js






/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;

/* harmony default export */ const _ListCache = (ListCache);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackClear.js


/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new _ListCache;
  this.size = 0;
}

/* harmony default export */ const _stackClear = (stackClear);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackDelete.js
/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);

  this.size = data.size;
  return result;
}

/* harmony default export */ const _stackDelete = (stackDelete);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackGet.js
/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

/* harmony default export */ const _stackGet = (stackGet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackHas.js
/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

/* harmony default export */ const _stackHas = (stackHas);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_Map.js



/* Built-in method references that are verified to be native. */
var _Map_Map = _getNative(_root/* default */.Z, 'Map');

/* harmony default export */ const _Map = (_Map_Map);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_nativeCreate.js


/* Built-in method references that are verified to be native. */
var nativeCreate = _getNative(Object, 'create');

/* harmony default export */ const _nativeCreate = (nativeCreate);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashClear.js


/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
  this.size = 0;
}

/* harmony default export */ const _hashClear = (hashClear);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashDelete.js
/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

/* harmony default export */ const _hashDelete = (hashDelete);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashGet.js


/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var _hashGet_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _hashGet_hasOwnProperty = _hashGet_objectProto.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (_nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return _hashGet_hasOwnProperty.call(data, key) ? data[key] : undefined;
}

/* harmony default export */ const _hashGet = (hashGet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashHas.js


/** Used for built-in method references. */
var _hashHas_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _hashHas_hasOwnProperty = _hashHas_objectProto.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return _nativeCreate ? (data[key] !== undefined) : _hashHas_hasOwnProperty.call(data, key);
}

/* harmony default export */ const _hashHas = (hashHas);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_hashSet.js


/** Used to stand-in for `undefined` hash values. */
var _hashSet_HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = (_nativeCreate && value === undefined) ? _hashSet_HASH_UNDEFINED : value;
  return this;
}

/* harmony default export */ const _hashSet = (hashSet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_Hash.js






/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;

/* harmony default export */ const _Hash = (Hash);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheClear.js




/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new _Hash,
    'map': new (_Map || _ListCache),
    'string': new _Hash
  };
}

/* harmony default export */ const _mapCacheClear = (mapCacheClear);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isKeyable.js
/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}

/* harmony default export */ const _isKeyable = (isKeyable);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getMapData.js


/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return _isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}

/* harmony default export */ const _getMapData = (getMapData);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheDelete.js


/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  var result = _getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

/* harmony default export */ const _mapCacheDelete = (mapCacheDelete);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheGet.js


/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return _getMapData(this, key).get(key);
}

/* harmony default export */ const _mapCacheGet = (mapCacheGet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheHas.js


/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return _getMapData(this, key).has(key);
}

/* harmony default export */ const _mapCacheHas = (mapCacheHas);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapCacheSet.js


/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  var data = _getMapData(this, key),
      size = data.size;

  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

/* harmony default export */ const _mapCacheSet = (mapCacheSet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_MapCache.js






/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;

/* harmony default export */ const _MapCache = (MapCache);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_stackSet.js




/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof _ListCache) {
    var pairs = data.__data__;
    if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new _MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}

/* harmony default export */ const _stackSet = (stackSet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_Stack.js







/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  var data = this.__data__ = new _ListCache(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;

/* harmony default export */ const _Stack = (Stack);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheAdd.js
/** Used to stand-in for `undefined` hash values. */
var _setCacheAdd_HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, _setCacheAdd_HASH_UNDEFINED);
  return this;
}

/* harmony default export */ const _setCacheAdd = (setCacheAdd);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_setCacheHas.js
/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}

/* harmony default export */ const _setCacheHas = (setCacheHas);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_SetCache.js




/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;

  this.__data__ = new _MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}

// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;

/* harmony default export */ const _SetCache = (SetCache);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arraySome.js
/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}

/* harmony default export */ const _arraySome = (arraySome);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_cacheHas.js
/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}

/* harmony default export */ const _cacheHas = (cacheHas);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalArrays.js




/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Check that cyclic values are equal.
  var arrStacked = stack.get(array);
  var othStacked = stack.get(other);
  if (arrStacked && othStacked) {
    return arrStacked == other && othStacked == array;
  }
  var index = -1,
      result = true,
      seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined;

  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, arrValue, index, other, array, stack)
        : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!_arraySome(other, function(othValue, othIndex) {
            if (!_cacheHas(seen, othIndex) &&
                (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
        result = false;
        break;
      }
    } else if (!(
          arrValue === othValue ||
            equalFunc(arrValue, othValue, bitmask, customizer, stack)
        )) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}

/* harmony default export */ const _equalArrays = (equalArrays);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_Uint8Array.js


/** Built-in value references. */
var _Uint8Array_Uint8Array = _root/* default.Uint8Array */.Z.Uint8Array;

/* harmony default export */ const _Uint8Array = (_Uint8Array_Uint8Array);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_mapToArray.js
/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);

  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}

/* harmony default export */ const _mapToArray = (mapToArray);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_setToArray.js
/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);

  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}

/* harmony default export */ const _setToArray = (setToArray);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalByTag.js







/** Used to compose bitmasks for value comparisons. */
var _equalByTag_COMPARE_PARTIAL_FLAG = 1,
    _equalByTag_COMPARE_UNORDERED_FLAG = 2;

/** `Object#toString` result references. */
var _equalByTag_boolTag = '[object Boolean]',
    _equalByTag_dateTag = '[object Date]',
    _equalByTag_errorTag = '[object Error]',
    _equalByTag_mapTag = '[object Map]',
    _equalByTag_numberTag = '[object Number]',
    _equalByTag_regexpTag = '[object RegExp]',
    _equalByTag_setTag = '[object Set]',
    _equalByTag_stringTag = '[object String]',
    _equalByTag_symbolTag = '[object Symbol]';

var _equalByTag_arrayBufferTag = '[object ArrayBuffer]',
    _equalByTag_dataViewTag = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var symbolProto = _Symbol ? _Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case _equalByTag_dataViewTag:
      if ((object.byteLength != other.byteLength) ||
          (object.byteOffset != other.byteOffset)) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;

    case _equalByTag_arrayBufferTag:
      if ((object.byteLength != other.byteLength) ||
          !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
        return false;
      }
      return true;

    case _equalByTag_boolTag:
    case _equalByTag_dateTag:
    case _equalByTag_numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return lodash_es_eq(+object, +other);

    case _equalByTag_errorTag:
      return object.name == other.name && object.message == other.message;

    case _equalByTag_regexpTag:
    case _equalByTag_stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == (other + '');

    case _equalByTag_mapTag:
      var convert = _mapToArray;

    case _equalByTag_setTag:
      var isPartial = bitmask & _equalByTag_COMPARE_PARTIAL_FLAG;
      convert || (convert = _setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= _equalByTag_COMPARE_UNORDERED_FLAG;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case _equalByTag_symbolTag:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }
  }
  return false;
}

/* harmony default export */ const _equalByTag = (equalByTag);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayPush.js
/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

/* harmony default export */ const _arrayPush = (arrayPush);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGetAllKeys.js



/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return lodash_es_isArray(object) ? result : _arrayPush(result, symbolsFunc(object));
}

/* harmony default export */ const _baseGetAllKeys = (baseGetAllKeys);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayFilter.js
/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}

/* harmony default export */ const _arrayFilter = (arrayFilter);

;// CONCATENATED MODULE: ./node_modules/lodash-es/stubArray.js
/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

/* harmony default export */ const lodash_es_stubArray = (stubArray);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getSymbols.js



/** Used for built-in method references. */
var _getSymbols_objectProto = Object.prototype;

/** Built-in value references. */
var _getSymbols_propertyIsEnumerable = _getSymbols_objectProto.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = !nativeGetSymbols ? lodash_es_stubArray : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return _arrayFilter(nativeGetSymbols(object), function(symbol) {
    return _getSymbols_propertyIsEnumerable.call(object, symbol);
  });
};

/* harmony default export */ const _getSymbols = (getSymbols);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getAllKeys.js




/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return _baseGetAllKeys(object, lodash_es_keys, _getSymbols);
}

/* harmony default export */ const _getAllKeys = (getAllKeys);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_equalObjects.js


/** Used to compose bitmasks for value comparisons. */
var _equalObjects_COMPARE_PARTIAL_FLAG = 1;

/** Used for built-in method references. */
var _equalObjects_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _equalObjects_hasOwnProperty = _equalObjects_objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & _equalObjects_COMPARE_PARTIAL_FLAG,
      objProps = _getAllKeys(object),
      objLength = objProps.length,
      othProps = _getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : _equalObjects_hasOwnProperty.call(other, key))) {
      return false;
    }
  }
  // Check that cyclic values are equal.
  var objStacked = stack.get(object);
  var othStacked = stack.get(other);
  if (objStacked && othStacked) {
    return objStacked == other && othStacked == object;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);

  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, objValue, key, other, object, stack)
        : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined
          ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
          : compared
        )) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor &&
        ('constructor' in object && 'constructor' in other) &&
        !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
          typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}

/* harmony default export */ const _equalObjects = (equalObjects);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_DataView.js



/* Built-in method references that are verified to be native. */
var _DataView_DataView = _getNative(_root/* default */.Z, 'DataView');

/* harmony default export */ const _DataView = (_DataView_DataView);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_Promise.js



/* Built-in method references that are verified to be native. */
var _Promise_Promise = _getNative(_root/* default */.Z, 'Promise');

/* harmony default export */ const _Promise = (_Promise_Promise);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_Set.js



/* Built-in method references that are verified to be native. */
var _Set_Set = _getNative(_root/* default */.Z, 'Set');

/* harmony default export */ const _Set = (_Set_Set);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_WeakMap.js



/* Built-in method references that are verified to be native. */
var WeakMap = _getNative(_root/* default */.Z, 'WeakMap');

/* harmony default export */ const _WeakMap = (WeakMap);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getTag.js








/** `Object#toString` result references. */
var _getTag_mapTag = '[object Map]',
    _getTag_objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    _getTag_setTag = '[object Set]',
    _getTag_weakMapTag = '[object WeakMap]';

var _getTag_dataViewTag = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = _toSource(_DataView),
    mapCtorString = _toSource(_Map),
    promiseCtorString = _toSource(_Promise),
    setCtorString = _toSource(_Set),
    weakMapCtorString = _toSource(_WeakMap);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = _baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != _getTag_dataViewTag) ||
    (_Map && getTag(new _Map) != _getTag_mapTag) ||
    (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
    (_Set && getTag(new _Set) != _getTag_setTag) ||
    (_WeakMap && getTag(new _WeakMap) != _getTag_weakMapTag)) {
  getTag = function(value) {
    var result = _baseGetTag(value),
        Ctor = result == _getTag_objectTag ? value.constructor : undefined,
        ctorString = Ctor ? _toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString: return _getTag_dataViewTag;
        case mapCtorString: return _getTag_mapTag;
        case promiseCtorString: return promiseTag;
        case setCtorString: return _getTag_setTag;
        case weakMapCtorString: return _getTag_weakMapTag;
      }
    }
    return result;
  };
}

/* harmony default export */ const _getTag = (getTag);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqualDeep.js









/** Used to compose bitmasks for value comparisons. */
var _baseIsEqualDeep_COMPARE_PARTIAL_FLAG = 1;

/** `Object#toString` result references. */
var _baseIsEqualDeep_argsTag = '[object Arguments]',
    _baseIsEqualDeep_arrayTag = '[object Array]',
    _baseIsEqualDeep_objectTag = '[object Object]';

/** Used for built-in method references. */
var _baseIsEqualDeep_objectProto = Object.prototype;

/** Used to check objects for own properties. */
var _baseIsEqualDeep_hasOwnProperty = _baseIsEqualDeep_objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = lodash_es_isArray(object),
      othIsArr = lodash_es_isArray(other),
      objTag = objIsArr ? _baseIsEqualDeep_arrayTag : _getTag(object),
      othTag = othIsArr ? _baseIsEqualDeep_arrayTag : _getTag(other);

  objTag = objTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : objTag;
  othTag = othTag == _baseIsEqualDeep_argsTag ? _baseIsEqualDeep_objectTag : othTag;

  var objIsObj = objTag == _baseIsEqualDeep_objectTag,
      othIsObj = othTag == _baseIsEqualDeep_objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && (0,isBuffer/* default */.Z)(object)) {
    if (!(0,isBuffer/* default */.Z)(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new _Stack);
    return (objIsArr || lodash_es_isTypedArray(object))
      ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
      : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & _baseIsEqualDeep_COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && _baseIsEqualDeep_hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && _baseIsEqualDeep_hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;

      stack || (stack = new _Stack);
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new _Stack);
  return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

/* harmony default export */ const _baseIsEqualDeep = (baseIsEqualDeep);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsEqual.js



/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || (!lodash_es_isObjectLike(value) && !lodash_es_isObjectLike(other))) {
    return value !== value && other !== other;
  }
  return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

/* harmony default export */ const _baseIsEqual = (baseIsEqual);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isEqual.js


/**
 * Performs a deep comparison between two values to determine if they are
 * equivalent.
 *
 * **Note:** This method supports comparing arrays, array buffers, booleans,
 * date objects, error objects, maps, numbers, `Object` objects, regexes,
 * sets, strings, symbols, and typed arrays. `Object` objects are compared
 * by their own, not inherited, enumerable properties. Functions and DOM
 * nodes are compared by strict equality, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.isEqual(object, other);
 * // => true
 *
 * object === other;
 * // => false
 */
function isEqual(value, other) {
  return _baseIsEqual(value, other);
}

/* harmony default export */ const lodash_es_isEqual = (isEqual);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsMatch.js



/** Used to compose bitmasks for value comparisons. */
var _baseIsMatch_COMPARE_PARTIAL_FLAG = 1,
    _baseIsMatch_COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */
function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length,
      length = index,
      noCustomizer = !customizer;

  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index--) {
    var data = matchData[index];
    if ((noCustomizer && data[2])
          ? data[1] !== object[data[0]]
          : !(data[0] in object)
        ) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key = data[0],
        objValue = object[key],
        srcValue = data[1];

    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new _Stack;
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }
      if (!(result === undefined
            ? _baseIsEqual(srcValue, objValue, _baseIsMatch_COMPARE_PARTIAL_FLAG | _baseIsMatch_COMPARE_UNORDERED_FLAG, customizer, stack)
            : result
          )) {
        return false;
      }
    }
  }
  return true;
}

/* harmony default export */ const _baseIsMatch = (baseIsMatch);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isStrictComparable.js


/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */
function isStrictComparable(value) {
  return value === value && !lodash_es_isObject(value);
}

/* harmony default export */ const _isStrictComparable = (isStrictComparable);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_getMatchData.js



/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */
function getMatchData(object) {
  var result = lodash_es_keys(object),
      length = result.length;

  while (length--) {
    var key = result[length],
        value = object[key];

    result[length] = [key, value, _isStrictComparable(value)];
  }
  return result;
}

/* harmony default export */ const _getMatchData = (getMatchData);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_matchesStrictComparable.js
/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function matchesStrictComparable(key, srcValue) {
  return function(object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue &&
      (srcValue !== undefined || (key in Object(object)));
  };
}

/* harmony default export */ const _matchesStrictComparable = (matchesStrictComparable);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatches.js




/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatches(source) {
  var matchData = _getMatchData(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }
  return function(object) {
    return object === source || _baseIsMatch(object, source, matchData);
  };
}

/* harmony default export */ const _baseMatches = (baseMatches);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_isKey.js



/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    reIsPlainProp = /^\w*$/;

/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */
function isKey(value, object) {
  if (lodash_es_isArray(value)) {
    return false;
  }
  var type = typeof value;
  if (type == 'number' || type == 'symbol' || type == 'boolean' ||
      value == null || lodash_es_isSymbol(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
    (object != null && value in Object(object));
}

/* harmony default export */ const _isKey = (isKey);

;// CONCATENATED MODULE: ./node_modules/lodash-es/memoize.js


/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function memoize(func, resolver) {
  if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function() {
    var args = arguments,
        key = resolver ? resolver.apply(this, args) : args[0],
        cache = memoized.cache;

    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize.Cache || _MapCache);
  return memoized;
}

// Expose `MapCache`.
memoize.Cache = _MapCache;

/* harmony default export */ const lodash_es_memoize = (memoize);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_memoizeCapped.js


/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped(func) {
  var result = lodash_es_memoize(func, function(key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });

  var cache = result.cache;
  return result;
}

/* harmony default export */ const _memoizeCapped = (memoizeCapped);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_stringToPath.js


/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var stringToPath = _memoizeCapped(function(string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(rePropName, function(match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  });
  return result;
});

/* harmony default export */ const _stringToPath = (stringToPath);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseToString.js





/** Used as references for various `Number` constants. */
var _baseToString_INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var _baseToString_symbolProto = _Symbol ? _Symbol.prototype : undefined,
    symbolToString = _baseToString_symbolProto ? _baseToString_symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (lodash_es_isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return _arrayMap(value, baseToString) + '';
  }
  if (lodash_es_isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -_baseToString_INFINITY) ? '-0' : result;
}

/* harmony default export */ const _baseToString = (baseToString);

;// CONCATENATED MODULE: ./node_modules/lodash-es/toString.js


/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString_toString(value) {
  return value == null ? '' : _baseToString(value);
}

/* harmony default export */ const lodash_es_toString = (toString_toString);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_castPath.js





/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */
function castPath(value, object) {
  if (lodash_es_isArray(value)) {
    return value;
  }
  return _isKey(value, object) ? [value] : _stringToPath(lodash_es_toString(value));
}

/* harmony default export */ const _castPath = (castPath);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_toKey.js


/** Used as references for various `Number` constants. */
var _toKey_INFINITY = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function toKey(value) {
  if (typeof value == 'string' || lodash_es_isSymbol(value)) {
    return value;
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -_toKey_INFINITY) ? '-0' : result;
}

/* harmony default export */ const _toKey = (toKey);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseGet.js



/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */
function baseGet(object, path) {
  path = _castPath(path, object);

  var index = 0,
      length = path.length;

  while (object != null && index < length) {
    object = object[_toKey(path[index++])];
  }
  return (index && index == length) ? object : undefined;
}

/* harmony default export */ const _baseGet = (baseGet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/get.js


/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function get(object, path, defaultValue) {
  var result = object == null ? undefined : _baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

/* harmony default export */ const lodash_es_get = (get);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseHasIn.js
/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}

/* harmony default export */ const _baseHasIn = (baseHasIn);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_hasPath.js







/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */
function hasPath(object, path, hasFunc) {
  path = _castPath(path, object);

  var index = -1,
      length = path.length,
      result = false;

  while (++index < length) {
    var key = _toKey(path[index]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && lodash_es_isLength(length) && _isIndex(key, length) &&
    (lodash_es_isArray(object) || lodash_es_isArguments(object));
}

/* harmony default export */ const _hasPath = (hasPath);

;// CONCATENATED MODULE: ./node_modules/lodash-es/hasIn.js



/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */
function hasIn(object, path) {
  return object != null && _hasPath(object, path, _baseHasIn);
}

/* harmony default export */ const lodash_es_hasIn = (hasIn);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseMatchesProperty.js








/** Used to compose bitmasks for value comparisons. */
var _baseMatchesProperty_COMPARE_PARTIAL_FLAG = 1,
    _baseMatchesProperty_COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatchesProperty(path, srcValue) {
  if (_isKey(path) && _isStrictComparable(srcValue)) {
    return _matchesStrictComparable(_toKey(path), srcValue);
  }
  return function(object) {
    var objValue = lodash_es_get(object, path);
    return (objValue === undefined && objValue === srcValue)
      ? lodash_es_hasIn(object, path)
      : _baseIsEqual(srcValue, objValue, _baseMatchesProperty_COMPARE_PARTIAL_FLAG | _baseMatchesProperty_COMPARE_UNORDERED_FLAG);
  };
}

/* harmony default export */ const _baseMatchesProperty = (baseMatchesProperty);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseProperty.js
/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function baseProperty(key) {
  return function(object) {
    return object == null ? undefined : object[key];
  };
}

/* harmony default export */ const _baseProperty = (baseProperty);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_basePropertyDeep.js


/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyDeep(path) {
  return function(object) {
    return _baseGet(object, path);
  };
}

/* harmony default export */ const _basePropertyDeep = (basePropertyDeep);

;// CONCATENATED MODULE: ./node_modules/lodash-es/property.js





/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */
function property(path) {
  return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}

/* harmony default export */ const lodash_es_property = (property);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIteratee.js






/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */
function baseIteratee(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }
  if (value == null) {
    return lodash_es_identity;
  }
  if (typeof value == 'object') {
    return lodash_es_isArray(value)
      ? _baseMatchesProperty(value[0], value[1])
      : _baseMatches(value);
  }
  return lodash_es_property(value);
}

/* harmony default export */ const _baseIteratee = (baseIteratee);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseFindIndex.js
/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);

  while ((fromRight ? index-- : ++index < length)) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}

/* harmony default export */ const _baseFindIndex = (baseFindIndex);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIsNaN.js
/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}

/* harmony default export */ const _baseIsNaN = (baseIsNaN);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_strictIndexOf.js
/**
 * A specialized version of `_.indexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}

/* harmony default export */ const _strictIndexOf = (strictIndexOf);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseIndexOf.js




/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  return value === value
    ? _strictIndexOf(array, value, fromIndex)
    : _baseFindIndex(array, _baseIsNaN, fromIndex);
}

/* harmony default export */ const _baseIndexOf = (baseIndexOf);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludes.js


/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludes(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && _baseIndexOf(array, value, 0) > -1;
}

/* harmony default export */ const _arrayIncludes = (arrayIncludes);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_arrayIncludesWith.js
/**
 * This function is like `arrayIncludes` except that it accepts a comparator.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @param {Function} comparator The comparator invoked per element.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludesWith(array, value, comparator) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}

/* harmony default export */ const _arrayIncludesWith = (arrayIncludesWith);

;// CONCATENATED MODULE: ./node_modules/lodash-es/noop.js
/**
 * This method returns `undefined`.
 *
 * @static
 * @memberOf _
 * @since 2.3.0
 * @category Util
 * @example
 *
 * _.times(2, _.noop);
 * // => [undefined, undefined]
 */
function noop() {
  // No operation performed.
}

/* harmony default export */ const lodash_es_noop = (noop);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_createSet.js




/** Used as references for various `Number` constants. */
var _createSet_INFINITY = 1 / 0;

/**
 * Creates a set object of `values`.
 *
 * @private
 * @param {Array} values The values to add to the set.
 * @returns {Object} Returns the new set.
 */
var createSet = !(_Set && (1 / _setToArray(new _Set([,-0]))[1]) == _createSet_INFINITY) ? lodash_es_noop : function(values) {
  return new _Set(values);
};

/* harmony default export */ const _createSet = (createSet);

;// CONCATENATED MODULE: ./node_modules/lodash-es/_baseUniq.js







/** Used as the size to enable large array optimizations. */
var _baseUniq_LARGE_ARRAY_SIZE = 200;

/**
 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns the new duplicate free array.
 */
function baseUniq(array, iteratee, comparator) {
  var index = -1,
      includes = _arrayIncludes,
      length = array.length,
      isCommon = true,
      result = [],
      seen = result;

  if (comparator) {
    isCommon = false;
    includes = _arrayIncludesWith;
  }
  else if (length >= _baseUniq_LARGE_ARRAY_SIZE) {
    var set = iteratee ? null : _createSet(array);
    if (set) {
      return _setToArray(set);
    }
    isCommon = false;
    includes = _cacheHas;
    seen = new _SetCache;
  }
  else {
    seen = iteratee ? [] : result;
  }
  outer:
  while (++index < length) {
    var value = array[index],
        computed = iteratee ? iteratee(value) : value;

    value = (comparator || value !== 0) ? value : 0;
    if (isCommon && computed === computed) {
      var seenIndex = seen.length;
      while (seenIndex--) {
        if (seen[seenIndex] === computed) {
          continue outer;
        }
      }
      if (iteratee) {
        seen.push(computed);
      }
      result.push(value);
    }
    else if (!includes(seen, computed, comparator)) {
      if (seen !== result) {
        seen.push(computed);
      }
      result.push(value);
    }
  }
  return result;
}

/* harmony default export */ const _baseUniq = (baseUniq);

;// CONCATENATED MODULE: ./node_modules/lodash-es/uniqBy.js



/**
 * This method is like `_.uniq` except that it accepts `iteratee` which is
 * invoked for each element in `array` to generate the criterion by which
 * uniqueness is computed. The order of result values is determined by the
 * order they occur in the array. The iteratee is invoked with one argument:
 * (value).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Array
 * @param {Array} array The array to inspect.
 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
 * @returns {Array} Returns the new duplicate free array.
 * @example
 *
 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
 * // => [2.1, 1.2]
 *
 * // The `_.property` iteratee shorthand.
 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
 * // => [{ 'x': 1 }, { 'x': 2 }]
 */
function uniqBy(array, iteratee) {
  return (array && array.length) ? _baseUniq(array, _baseIteratee(iteratee, 2)) : [];
}

/* harmony default export */ const lodash_es_uniqBy = (uniqBy);

// EXTERNAL MODULE: ./node_modules/pixi.js/dist/esm/pixi.js + 39 modules
var pixi = __webpack_require__(9618);
;// CONCATENATED MODULE: ./node_modules/d3-color/src/define.js
/* harmony default export */ function src_define(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}

function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

;// CONCATENATED MODULE: ./node_modules/d3-color/src/color.js


function Color() {}

var darker = 0.7;
var brighter = 1 / darker;

var reI = "\\s*([+-]?\\d+)\\s*",
    reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex = /^#([0-9a-f]{3,8})$/,
    reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
    reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
    reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
    reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
    reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
    reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");

var named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

src_define(Color, color, {
  copy: function(channels) {
    return Object.assign(new this.constructor, this, channels);
  },
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: color_formatHex, // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});

function color_formatHex() {
  return this.rgb().formatHex();
}

function color_formatHsl() {
  return hslConvert(this).formatHsl();
}

function color_formatRgb() {
  return this.rgb().formatRgb();
}

function color(format) {
  var m, l;
  format = (format + "").trim().toLowerCase();
  return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
      : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
      : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
      : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
      : null) // invalid hex
      : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
      : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
      : null;
}

function rgbn(n) {
  return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}

function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}

function color_rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

src_define(Rgb, color_rgb, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (-0.5 <= this.r && this.r < 255.5)
        && (-0.5 <= this.g && this.g < 255.5)
        && (-0.5 <= this.b && this.b < 255.5)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex, // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));

function rgb_formatHex() {
  return "#" + hex(this.r) + hex(this.g) + hex(this.b);
}

function rgb_formatRgb() {
  var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
  return (a === 1 ? "rgb(" : "rgba(")
      + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
      + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
      + Math.max(0, Math.min(255, Math.round(this.b) || 0))
      + (a === 1 ? ")" : ", " + a + ")");
}

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}

function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl;
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}

function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

src_define(Hsl, hsl, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "hsl(" : "hsla(")
        + (this.h || 0) + ", "
        + (this.s || 0) * 100 + "%, "
        + (this.l || 0) * 100 + "%"
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

;// CONCATENATED MODULE: ./node_modules/internmap/src/index.js
class InternMap extends Map {
  constructor(entries, key = keyof) {
    super();
    Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});
    if (entries != null) for (const [key, value] of entries) this.set(key, value);
  }
  get(key) {
    return super.get(intern_get(this, key));
  }
  has(key) {
    return super.has(intern_get(this, key));
  }
  set(key, value) {
    return super.set(intern_set(this, key), value);
  }
  delete(key) {
    return super.delete(intern_delete(this, key));
  }
}

class InternSet extends Set {
  constructor(values, key = keyof) {
    super();
    Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});
    if (values != null) for (const value of values) this.add(value);
  }
  has(value) {
    return super.has(intern_get(this, value));
  }
  add(value) {
    return super.add(intern_set(this, value));
  }
  delete(value) {
    return super.delete(intern_delete(this, value));
  }
}

function intern_get({_intern, _key}, value) {
  const key = _key(value);
  return _intern.has(key) ? _intern.get(key) : value;
}

function intern_set({_intern, _key}, value) {
  const key = _key(value);
  if (_intern.has(key)) return _intern.get(key);
  _intern.set(key, value);
  return value;
}

function intern_delete({_intern, _key}, value) {
  const key = _key(value);
  if (_intern.has(key)) {
    value = _intern.get(value);
    _intern.delete(key);
  }
  return value;
}

function keyof(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/identity.js
/* harmony default export */ function src_identity(x) {
  return x;
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/group.js



function group(values, ...keys) {
  return nest(values, src_identity, src_identity, keys);
}

function groups(values, ...keys) {
  return nest(values, Array.from, identity, keys);
}

function rollup(values, reduce, ...keys) {
  return nest(values, identity, reduce, keys);
}

function rollups(values, reduce, ...keys) {
  return nest(values, Array.from, reduce, keys);
}

function index(values, ...keys) {
  return nest(values, identity, unique, keys);
}

function indexes(values, ...keys) {
  return nest(values, Array.from, unique, keys);
}

function unique(values) {
  if (values.length !== 1) throw new Error("duplicate key");
  return values[0];
}

function nest(values, map, reduce, keys) {
  return (function regroup(values, i) {
    if (i >= keys.length) return reduce(values);
    const groups = new InternMap();
    const keyof = keys[i++];
    let index = -1;
    for (const value of values) {
      const key = keyof(value, ++index, values);
      const group = groups.get(key);
      if (group) group.push(value);
      else groups.set(key, [value]);
    }
    for (const [key, values] of groups) {
      groups.set(key, regroup(values, i));
    }
    return map(groups);
  })(values, 0);
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/max.js
function max(values, valueof) {
  let max;
  if (valueof === undefined) {
    for (const value of values) {
      if (value != null
          && (max < value || (max === undefined && value >= value))) {
        max = value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null
          && (max < value || (max === undefined && value >= value))) {
        max = value;
      }
    }
  }
  return max;
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/min.js
function min(values, valueof) {
  let min;
  if (valueof === undefined) {
    for (const value of values) {
      if (value != null
          && (min > value || (min === undefined && value >= value))) {
        min = value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null
          && (min > value || (min === undefined && value >= value))) {
        min = value;
      }
    }
  }
  return min;
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/sum.js
function sum(values, valueof) {
  let sum = 0;
  if (valueof === undefined) {
    for (let value of values) {
      if (value = +value) {
        sum += value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if (value = +valueof(value, ++index, values)) {
        sum += value;
      }
    }
  }
  return sum;
}

;// CONCATENATED MODULE: ./node_modules/bezier-js/src/utils.js


// math-inlining.
const { abs, cos, sin, acos, atan2, sqrt, pow } = Math;

// cube root function yielding real roots
function crt(v) {
  return v < 0 ? -pow(-v, 1 / 3) : pow(v, 1 / 3);
}

// trig constants
const pi = Math.PI,
  tau = 2 * pi,
  quart = pi / 2,
  // float precision significant decimal
  epsilon = 0.000001,
  // extremas used in bbox calculation and similar algorithms
  nMax = Number.MAX_SAFE_INTEGER || 9007199254740991,
  nMin = Number.MIN_SAFE_INTEGER || -9007199254740991,
  // a zero coordinate, which is surprisingly useful
  ZERO = { x: 0, y: 0, z: 0 };

// Bezier utility functions
const utils = {
  // Legendre-Gauss abscissae with n=24 (x_i values, defined at i=n as the roots of the nth order Legendre polynomial Pn(x))
  Tvalues: [
    -0.0640568928626056260850430826247450385909,
    0.0640568928626056260850430826247450385909,
    -0.1911188674736163091586398207570696318404,
    0.1911188674736163091586398207570696318404,
    -0.3150426796961633743867932913198102407864,
    0.3150426796961633743867932913198102407864,
    -0.4337935076260451384870842319133497124524,
    0.4337935076260451384870842319133497124524,
    -0.5454214713888395356583756172183723700107,
    0.5454214713888395356583756172183723700107,
    -0.6480936519369755692524957869107476266696,
    0.6480936519369755692524957869107476266696,
    -0.7401241915785543642438281030999784255232,
    0.7401241915785543642438281030999784255232,
    -0.8200019859739029219539498726697452080761,
    0.8200019859739029219539498726697452080761,
    -0.8864155270044010342131543419821967550873,
    0.8864155270044010342131543419821967550873,
    -0.9382745520027327585236490017087214496548,
    0.9382745520027327585236490017087214496548,
    -0.9747285559713094981983919930081690617411,
    0.9747285559713094981983919930081690617411,
    -0.9951872199970213601799974097007368118745,
    0.9951872199970213601799974097007368118745,
  ],

  // Legendre-Gauss weights with n=24 (w_i values, defined by a function linked to in the Bezier primer article)
  Cvalues: [
    0.1279381953467521569740561652246953718517,
    0.1279381953467521569740561652246953718517,
    0.1258374563468282961213753825111836887264,
    0.1258374563468282961213753825111836887264,
    0.121670472927803391204463153476262425607,
    0.121670472927803391204463153476262425607,
    0.1155056680537256013533444839067835598622,
    0.1155056680537256013533444839067835598622,
    0.1074442701159656347825773424466062227946,
    0.1074442701159656347825773424466062227946,
    0.0976186521041138882698806644642471544279,
    0.0976186521041138882698806644642471544279,
    0.086190161531953275917185202983742667185,
    0.086190161531953275917185202983742667185,
    0.0733464814110803057340336152531165181193,
    0.0733464814110803057340336152531165181193,
    0.0592985849154367807463677585001085845412,
    0.0592985849154367807463677585001085845412,
    0.0442774388174198061686027482113382288593,
    0.0442774388174198061686027482113382288593,
    0.0285313886289336631813078159518782864491,
    0.0285313886289336631813078159518782864491,
    0.0123412297999871995468056670700372915759,
    0.0123412297999871995468056670700372915759,
  ],

  arcfn: function (t, derivativeFn) {
    const d = derivativeFn(t);
    let l = d.x * d.x + d.y * d.y;
    if (typeof d.z !== "undefined") {
      l += d.z * d.z;
    }
    return sqrt(l);
  },

  compute: function (t, points, _3d) {
    // shortcuts
    if (t === 0) {
      points[0].t = 0;
      return points[0];
    }

    const order = points.length - 1;

    if (t === 1) {
      points[order].t = 1;
      return points[order];
    }

    const mt = 1 - t;
    let p = points;

    // constant?
    if (order === 0) {
      points[0].t = t;
      return points[0];
    }

    // linear?
    if (order === 1) {
      const ret = {
        x: mt * p[0].x + t * p[1].x,
        y: mt * p[0].y + t * p[1].y,
        t: t,
      };
      if (_3d) {
        ret.z = mt * p[0].z + t * p[1].z;
      }
      return ret;
    }

    // quadratic/cubic curve?
    if (order < 4) {
      let mt2 = mt * mt,
        t2 = t * t,
        a,
        b,
        c,
        d = 0;
      if (order === 2) {
        p = [p[0], p[1], p[2], ZERO];
        a = mt2;
        b = mt * t * 2;
        c = t2;
      } else if (order === 3) {
        a = mt2 * mt;
        b = mt2 * t * 3;
        c = mt * t2 * 3;
        d = t * t2;
      }
      const ret = {
        x: a * p[0].x + b * p[1].x + c * p[2].x + d * p[3].x,
        y: a * p[0].y + b * p[1].y + c * p[2].y + d * p[3].y,
        t: t,
      };
      if (_3d) {
        ret.z = a * p[0].z + b * p[1].z + c * p[2].z + d * p[3].z;
      }
      return ret;
    }

    // higher order curves: use de Casteljau's computation
    const dCpts = JSON.parse(JSON.stringify(points));
    while (dCpts.length > 1) {
      for (let i = 0; i < dCpts.length - 1; i++) {
        dCpts[i] = {
          x: dCpts[i].x + (dCpts[i + 1].x - dCpts[i].x) * t,
          y: dCpts[i].y + (dCpts[i + 1].y - dCpts[i].y) * t,
        };
        if (typeof dCpts[i].z !== "undefined") {
          dCpts[i] = dCpts[i].z + (dCpts[i + 1].z - dCpts[i].z) * t;
        }
      }
      dCpts.splice(dCpts.length - 1, 1);
    }
    dCpts[0].t = t;
    return dCpts[0];
  },

  computeWithRatios: function (t, points, ratios, _3d) {
    const mt = 1 - t,
      r = ratios,
      p = points;

    let f1 = r[0],
      f2 = r[1],
      f3 = r[2],
      f4 = r[3],
      d;

    // spec for linear
    f1 *= mt;
    f2 *= t;

    if (p.length === 2) {
      d = f1 + f2;
      return {
        x: (f1 * p[0].x + f2 * p[1].x) / d,
        y: (f1 * p[0].y + f2 * p[1].y) / d,
        z: !_3d ? false : (f1 * p[0].z + f2 * p[1].z) / d,
        t: t,
      };
    }

    // upgrade to quadratic
    f1 *= mt;
    f2 *= 2 * mt;
    f3 *= t * t;

    if (p.length === 3) {
      d = f1 + f2 + f3;
      return {
        x: (f1 * p[0].x + f2 * p[1].x + f3 * p[2].x) / d,
        y: (f1 * p[0].y + f2 * p[1].y + f3 * p[2].y) / d,
        z: !_3d ? false : (f1 * p[0].z + f2 * p[1].z + f3 * p[2].z) / d,
        t: t,
      };
    }

    // upgrade to cubic
    f1 *= mt;
    f2 *= 1.5 * mt;
    f3 *= 3 * mt;
    f4 *= t * t * t;

    if (p.length === 4) {
      d = f1 + f2 + f3 + f4;
      return {
        x: (f1 * p[0].x + f2 * p[1].x + f3 * p[2].x + f4 * p[3].x) / d,
        y: (f1 * p[0].y + f2 * p[1].y + f3 * p[2].y + f4 * p[3].y) / d,
        z: !_3d
          ? false
          : (f1 * p[0].z + f2 * p[1].z + f3 * p[2].z + f4 * p[3].z) / d,
        t: t,
      };
    }
  },

  derive: function (points, _3d) {
    const dpoints = [];
    for (let p = points, d = p.length, c = d - 1; d > 1; d--, c--) {
      const list = [];
      for (let j = 0, dpt; j < c; j++) {
        dpt = {
          x: c * (p[j + 1].x - p[j].x),
          y: c * (p[j + 1].y - p[j].y),
        };
        if (_3d) {
          dpt.z = c * (p[j + 1].z - p[j].z);
        }
        list.push(dpt);
      }
      dpoints.push(list);
      p = list;
    }
    return dpoints;
  },

  between: function (v, m, M) {
    return (
      (m <= v && v <= M) ||
      utils.approximately(v, m) ||
      utils.approximately(v, M)
    );
  },

  approximately: function (a, b, precision) {
    return abs(a - b) <= (precision || epsilon);
  },

  length: function (derivativeFn) {
    const z = 0.5,
      len = utils.Tvalues.length;

    let sum = 0;

    for (let i = 0, t; i < len; i++) {
      t = z * utils.Tvalues[i] + z;
      sum += utils.Cvalues[i] * utils.arcfn(t, derivativeFn);
    }
    return z * sum;
  },

  map: function (v, ds, de, ts, te) {
    const d1 = de - ds,
      d2 = te - ts,
      v2 = v - ds,
      r = v2 / d1;
    return ts + d2 * r;
  },

  lerp: function (r, v1, v2) {
    const ret = {
      x: v1.x + r * (v2.x - v1.x),
      y: v1.y + r * (v2.y - v1.y),
    };
    if (!!v1.z && !!v2.z) {
      ret.z = v1.z + r * (v2.z - v1.z);
    }
    return ret;
  },

  pointToString: function (p) {
    let s = p.x + "/" + p.y;
    if (typeof p.z !== "undefined") {
      s += "/" + p.z;
    }
    return s;
  },

  pointsToString: function (points) {
    return "[" + points.map(utils.pointToString).join(", ") + "]";
  },

  copy: function (obj) {
    return JSON.parse(JSON.stringify(obj));
  },

  angle: function (o, v1, v2) {
    const dx1 = v1.x - o.x,
      dy1 = v1.y - o.y,
      dx2 = v2.x - o.x,
      dy2 = v2.y - o.y,
      cross = dx1 * dy2 - dy1 * dx2,
      dot = dx1 * dx2 + dy1 * dy2;
    return atan2(cross, dot);
  },

  // round as string, to avoid rounding errors
  round: function (v, d) {
    const s = "" + v;
    const pos = s.indexOf(".");
    return parseFloat(s.substring(0, pos + 1 + d));
  },

  dist: function (p1, p2) {
    const dx = p1.x - p2.x,
      dy = p1.y - p2.y;
    return sqrt(dx * dx + dy * dy);
  },

  closest: function (LUT, point) {
    let mdist = pow(2, 63),
      mpos,
      d;
    LUT.forEach(function (p, idx) {
      d = utils.dist(point, p);
      if (d < mdist) {
        mdist = d;
        mpos = idx;
      }
    });
    return { mdist: mdist, mpos: mpos };
  },

  abcratio: function (t, n) {
    // see ratio(t) note on http://pomax.github.io/bezierinfo/#abc
    if (n !== 2 && n !== 3) {
      return false;
    }
    if (typeof t === "undefined") {
      t = 0.5;
    } else if (t === 0 || t === 1) {
      return t;
    }
    const bottom = pow(t, n) + pow(1 - t, n),
      top = bottom - 1;
    return abs(top / bottom);
  },

  projectionratio: function (t, n) {
    // see u(t) note on http://pomax.github.io/bezierinfo/#abc
    if (n !== 2 && n !== 3) {
      return false;
    }
    if (typeof t === "undefined") {
      t = 0.5;
    } else if (t === 0 || t === 1) {
      return t;
    }
    const top = pow(1 - t, n),
      bottom = pow(t, n) + top;
    return top / bottom;
  },

  lli8: function (x1, y1, x2, y2, x3, y3, x4, y4) {
    const nx =
        (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
      ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
      d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
    if (d == 0) {
      return false;
    }
    return { x: nx / d, y: ny / d };
  },

  lli4: function (p1, p2, p3, p4) {
    const x1 = p1.x,
      y1 = p1.y,
      x2 = p2.x,
      y2 = p2.y,
      x3 = p3.x,
      y3 = p3.y,
      x4 = p4.x,
      y4 = p4.y;
    return utils.lli8(x1, y1, x2, y2, x3, y3, x4, y4);
  },

  lli: function (v1, v2) {
    return utils.lli4(v1, v1.c, v2, v2.c);
  },

  makeline: function (p1, p2) {
    const x1 = p1.x,
      y1 = p1.y,
      x2 = p2.x,
      y2 = p2.y,
      dx = (x2 - x1) / 3,
      dy = (y2 - y1) / 3;
    return new Bezier(
      x1,
      y1,
      x1 + dx,
      y1 + dy,
      x1 + 2 * dx,
      y1 + 2 * dy,
      x2,
      y2
    );
  },

  findbbox: function (sections) {
    let mx = nMax,
      my = nMax,
      MX = nMin,
      MY = nMin;
    sections.forEach(function (s) {
      const bbox = s.bbox();
      if (mx > bbox.x.min) mx = bbox.x.min;
      if (my > bbox.y.min) my = bbox.y.min;
      if (MX < bbox.x.max) MX = bbox.x.max;
      if (MY < bbox.y.max) MY = bbox.y.max;
    });
    return {
      x: { min: mx, mid: (mx + MX) / 2, max: MX, size: MX - mx },
      y: { min: my, mid: (my + MY) / 2, max: MY, size: MY - my },
    };
  },

  shapeintersections: function (
    s1,
    bbox1,
    s2,
    bbox2,
    curveIntersectionThreshold
  ) {
    if (!utils.bboxoverlap(bbox1, bbox2)) return [];
    const intersections = [];
    const a1 = [s1.startcap, s1.forward, s1.back, s1.endcap];
    const a2 = [s2.startcap, s2.forward, s2.back, s2.endcap];
    a1.forEach(function (l1) {
      if (l1.virtual) return;
      a2.forEach(function (l2) {
        if (l2.virtual) return;
        const iss = l1.intersects(l2, curveIntersectionThreshold);
        if (iss.length > 0) {
          iss.c1 = l1;
          iss.c2 = l2;
          iss.s1 = s1;
          iss.s2 = s2;
          intersections.push(iss);
        }
      });
    });
    return intersections;
  },

  makeshape: function (forward, back, curveIntersectionThreshold) {
    const bpl = back.points.length;
    const fpl = forward.points.length;
    const start = utils.makeline(back.points[bpl - 1], forward.points[0]);
    const end = utils.makeline(forward.points[fpl - 1], back.points[0]);
    const shape = {
      startcap: start,
      forward: forward,
      back: back,
      endcap: end,
      bbox: utils.findbbox([start, forward, back, end]),
    };
    shape.intersections = function (s2) {
      return utils.shapeintersections(
        shape,
        shape.bbox,
        s2,
        s2.bbox,
        curveIntersectionThreshold
      );
    };
    return shape;
  },

  getminmax: function (curve, d, list) {
    if (!list) return { min: 0, max: 0 };
    let min = nMax,
      max = nMin,
      t,
      c;
    if (list.indexOf(0) === -1) {
      list = [0].concat(list);
    }
    if (list.indexOf(1) === -1) {
      list.push(1);
    }
    for (let i = 0, len = list.length; i < len; i++) {
      t = list[i];
      c = curve.get(t);
      if (c[d] < min) {
        min = c[d];
      }
      if (c[d] > max) {
        max = c[d];
      }
    }
    return { min: min, mid: (min + max) / 2, max: max, size: max - min };
  },

  align: function (points, line) {
    const tx = line.p1.x,
      ty = line.p1.y,
      a = -atan2(line.p2.y - ty, line.p2.x - tx),
      d = function (v) {
        return {
          x: (v.x - tx) * cos(a) - (v.y - ty) * sin(a),
          y: (v.x - tx) * sin(a) + (v.y - ty) * cos(a),
        };
      };
    return points.map(d);
  },

  roots: function (points, line) {
    line = line || { p1: { x: 0, y: 0 }, p2: { x: 1, y: 0 } };

    const order = points.length - 1;
    const aligned = utils.align(points, line);
    const reduce = function (t) {
      return 0 <= t && t <= 1;
    };

    if (order === 2) {
      const a = aligned[0].y,
        b = aligned[1].y,
        c = aligned[2].y,
        d = a - 2 * b + c;
      if (d !== 0) {
        const m1 = -sqrt(b * b - a * c),
          m2 = -a + b,
          v1 = -(m1 + m2) / d,
          v2 = -(-m1 + m2) / d;
        return [v1, v2].filter(reduce);
      } else if (b !== c && d === 0) {
        return [(2 * b - c) / (2 * b - 2 * c)].filter(reduce);
      }
      return [];
    }

    // see http://www.trans4mind.com/personal_development/mathematics/polynomials/cubicAlgebra.htm
    const pa = aligned[0].y,
      pb = aligned[1].y,
      pc = aligned[2].y,
      pd = aligned[3].y;

    let d = -pa + 3 * pb - 3 * pc + pd,
      a = 3 * pa - 6 * pb + 3 * pc,
      b = -3 * pa + 3 * pb,
      c = pa;

    if (utils.approximately(d, 0)) {
      // this is not a cubic curve.
      if (utils.approximately(a, 0)) {
        // in fact, this is not a quadratic curve either.
        if (utils.approximately(b, 0)) {
          // in fact in fact, there are no solutions.
          return [];
        }
        // linear solution:
        return [-c / b].filter(reduce);
      }
      // quadratic solution:
      const q = sqrt(b * b - 4 * a * c),
        a2 = 2 * a;
      return [(q - b) / a2, (-b - q) / a2].filter(reduce);
    }

    // at this point, we know we need a cubic solution:

    a /= d;
    b /= d;
    c /= d;

    const p = (3 * b - a * a) / 3,
      p3 = p / 3,
      q = (2 * a * a * a - 9 * a * b + 27 * c) / 27,
      q2 = q / 2,
      discriminant = q2 * q2 + p3 * p3 * p3;

    let u1, v1, x1, x2, x3;
    if (discriminant < 0) {
      const mp3 = -p / 3,
        mp33 = mp3 * mp3 * mp3,
        r = sqrt(mp33),
        t = -q / (2 * r),
        cosphi = t < -1 ? -1 : t > 1 ? 1 : t,
        phi = acos(cosphi),
        crtr = crt(r),
        t1 = 2 * crtr;
      x1 = t1 * cos(phi / 3) - a / 3;
      x2 = t1 * cos((phi + tau) / 3) - a / 3;
      x3 = t1 * cos((phi + 2 * tau) / 3) - a / 3;
      return [x1, x2, x3].filter(reduce);
    } else if (discriminant === 0) {
      u1 = q2 < 0 ? crt(-q2) : -crt(q2);
      x1 = 2 * u1 - a / 3;
      x2 = -u1 - a / 3;
      return [x1, x2].filter(reduce);
    } else {
      const sd = sqrt(discriminant);
      u1 = crt(-q2 + sd);
      v1 = crt(q2 + sd);
      return [u1 - v1 - a / 3].filter(reduce);
    }
  },

  droots: function (p) {
    // quadratic roots are easy
    if (p.length === 3) {
      const a = p[0],
        b = p[1],
        c = p[2],
        d = a - 2 * b + c;
      if (d !== 0) {
        const m1 = -sqrt(b * b - a * c),
          m2 = -a + b,
          v1 = -(m1 + m2) / d,
          v2 = -(-m1 + m2) / d;
        return [v1, v2];
      } else if (b !== c && d === 0) {
        return [(2 * b - c) / (2 * (b - c))];
      }
      return [];
    }

    // linear roots are even easier
    if (p.length === 2) {
      const a = p[0],
        b = p[1];
      if (a !== b) {
        return [a / (a - b)];
      }
      return [];
    }

    return [];
  },

  curvature: function (t, d1, d2, _3d, kOnly) {
    let num,
      dnm,
      adk,
      dk,
      k = 0,
      r = 0;

    //
    // We're using the following formula for curvature:
    //
    //              x'y" - y'x"
    //   k(t) = ------------------
    //           (x'² + y'²)^(3/2)
    //
    // from https://en.wikipedia.org/wiki/Radius_of_curvature#Definition
    //
    // With it corresponding 3D counterpart:
    //
    //          sqrt( (y'z" - y"z')² + (z'x" - z"x')² + (x'y" - x"y')²)
    //   k(t) = -------------------------------------------------------
    //                     (x'² + y'² + z'²)^(3/2)
    //

    const d = utils.compute(t, d1);
    const dd = utils.compute(t, d2);
    const qdsum = d.x * d.x + d.y * d.y;

    if (_3d) {
      num = sqrt(
        pow(d.y * dd.z - dd.y * d.z, 2) +
          pow(d.z * dd.x - dd.z * d.x, 2) +
          pow(d.x * dd.y - dd.x * d.y, 2)
      );
      dnm = pow(qdsum + d.z * d.z, 3 / 2);
    } else {
      num = d.x * dd.y - d.y * dd.x;
      dnm = pow(qdsum, 3 / 2);
    }

    if (num === 0 || dnm === 0) {
      return { k: 0, r: 0 };
    }

    k = num / dnm;
    r = dnm / num;

    // We're also computing the derivative of kappa, because
    // there is value in knowing the rate of change for the
    // curvature along the curve. And we're just going to
    // ballpark it based on an epsilon.
    if (!kOnly) {
      // compute k'(t) based on the interval before, and after it,
      // to at least try to not introduce forward/backward pass bias.
      const pk = utils.curvature(t - 0.001, d1, d2, _3d, true).k;
      const nk = utils.curvature(t + 0.001, d1, d2, _3d, true).k;
      dk = (nk - k + (k - pk)) / 2;
      adk = (abs(nk - k) + abs(k - pk)) / 2;
    }

    return { k: k, r: r, dk: dk, adk: adk };
  },

  inflections: function (points) {
    if (points.length < 4) return [];

    // FIXME: TODO: add in inflection abstraction for quartic+ curves?

    const p = utils.align(points, { p1: points[0], p2: points.slice(-1)[0] }),
      a = p[2].x * p[1].y,
      b = p[3].x * p[1].y,
      c = p[1].x * p[2].y,
      d = p[3].x * p[2].y,
      v1 = 18 * (-3 * a + 2 * b + 3 * c - d),
      v2 = 18 * (3 * a - b - 3 * c),
      v3 = 18 * (c - a);

    if (utils.approximately(v1, 0)) {
      if (!utils.approximately(v2, 0)) {
        let t = -v3 / v2;
        if (0 <= t && t <= 1) return [t];
      }
      return [];
    }

    const trm = v2 * v2 - 4 * v1 * v3,
      sq = Math.sqrt(trm),
      d2 = 2 * v1;

    if (utils.approximately(d2, 0)) return [];

    return [(sq - v2) / d2, -(v2 + sq) / d2].filter(function (r) {
      return 0 <= r && r <= 1;
    });
  },

  bboxoverlap: function (b1, b2) {
    const dims = ["x", "y"],
      len = dims.length;

    for (let i = 0, dim, l, t, d; i < len; i++) {
      dim = dims[i];
      l = b1[dim].mid;
      t = b2[dim].mid;
      d = (b1[dim].size + b2[dim].size) / 2;
      if (abs(l - t) >= d) return false;
    }
    return true;
  },

  expandbox: function (bbox, _bbox) {
    if (_bbox.x.min < bbox.x.min) {
      bbox.x.min = _bbox.x.min;
    }
    if (_bbox.y.min < bbox.y.min) {
      bbox.y.min = _bbox.y.min;
    }
    if (_bbox.z && _bbox.z.min < bbox.z.min) {
      bbox.z.min = _bbox.z.min;
    }
    if (_bbox.x.max > bbox.x.max) {
      bbox.x.max = _bbox.x.max;
    }
    if (_bbox.y.max > bbox.y.max) {
      bbox.y.max = _bbox.y.max;
    }
    if (_bbox.z && _bbox.z.max > bbox.z.max) {
      bbox.z.max = _bbox.z.max;
    }
    bbox.x.mid = (bbox.x.min + bbox.x.max) / 2;
    bbox.y.mid = (bbox.y.min + bbox.y.max) / 2;
    if (bbox.z) {
      bbox.z.mid = (bbox.z.min + bbox.z.max) / 2;
    }
    bbox.x.size = bbox.x.max - bbox.x.min;
    bbox.y.size = bbox.y.max - bbox.y.min;
    if (bbox.z) {
      bbox.z.size = bbox.z.max - bbox.z.min;
    }
  },

  pairiteration: function (c1, c2, curveIntersectionThreshold) {
    const c1b = c1.bbox(),
      c2b = c2.bbox(),
      r = 100000,
      threshold = curveIntersectionThreshold || 0.5;

    if (
      c1b.x.size + c1b.y.size < threshold &&
      c2b.x.size + c2b.y.size < threshold
    ) {
      return [
        (((r * (c1._t1 + c1._t2)) / 2) | 0) / r +
          "/" +
          (((r * (c2._t1 + c2._t2)) / 2) | 0) / r,
      ];
    }

    let cc1 = c1.split(0.5),
      cc2 = c2.split(0.5),
      pairs = [
        { left: cc1.left, right: cc2.left },
        { left: cc1.left, right: cc2.right },
        { left: cc1.right, right: cc2.right },
        { left: cc1.right, right: cc2.left },
      ];

    pairs = pairs.filter(function (pair) {
      return utils.bboxoverlap(pair.left.bbox(), pair.right.bbox());
    });

    let results = [];

    if (pairs.length === 0) return results;

    pairs.forEach(function (pair) {
      results = results.concat(
        utils.pairiteration(pair.left, pair.right, threshold)
      );
    });

    results = results.filter(function (v, i) {
      return results.indexOf(v) === i;
    });

    return results;
  },

  getccenter: function (p1, p2, p3) {
    const dx1 = p2.x - p1.x,
      dy1 = p2.y - p1.y,
      dx2 = p3.x - p2.x,
      dy2 = p3.y - p2.y,
      dx1p = dx1 * cos(quart) - dy1 * sin(quart),
      dy1p = dx1 * sin(quart) + dy1 * cos(quart),
      dx2p = dx2 * cos(quart) - dy2 * sin(quart),
      dy2p = dx2 * sin(quart) + dy2 * cos(quart),
      // chord midpoints
      mx1 = (p1.x + p2.x) / 2,
      my1 = (p1.y + p2.y) / 2,
      mx2 = (p2.x + p3.x) / 2,
      my2 = (p2.y + p3.y) / 2,
      // midpoint offsets
      mx1n = mx1 + dx1p,
      my1n = my1 + dy1p,
      mx2n = mx2 + dx2p,
      my2n = my2 + dy2p,
      // intersection of these lines:
      arc = utils.lli8(mx1, my1, mx1n, my1n, mx2, my2, mx2n, my2n),
      r = utils.dist(arc, p1);

    // arc start/end values, over mid point:
    let s = atan2(p1.y - arc.y, p1.x - arc.x),
      m = atan2(p2.y - arc.y, p2.x - arc.x),
      e = atan2(p3.y - arc.y, p3.x - arc.x),
      _;

    // determine arc direction (cw/ccw correction)
    if (s < e) {
      // if s<m<e, arc(s, e)
      // if m<s<e, arc(e, s + tau)
      // if s<e<m, arc(e, s + tau)
      if (s > m || m > e) {
        s += tau;
      }
      if (s > e) {
        _ = e;
        e = s;
        s = _;
      }
    } else {
      // if e<m<s, arc(e, s)
      // if m<e<s, arc(s, e + tau)
      // if e<s<m, arc(s, e + tau)
      if (e < m && m < s) {
        _ = e;
        e = s;
        s = _;
      } else {
        e += tau;
      }
    }
    // assign and done.
    arc.s = s;
    arc.e = e;
    arc.r = r;
    return arc;
  },

  numberSort: function (a, b) {
    return a - b;
  },
};



;// CONCATENATED MODULE: ./node_modules/bezier-js/src/poly-bezier.js


/**
 * Poly Bezier
 * @param {[type]} curves [description]
 */
class PolyBezier {
  constructor(curves) {
    this.curves = [];
    this._3d = false;
    if (!!curves) {
      this.curves = curves;
      this._3d = this.curves[0]._3d;
    }
  }

  valueOf() {
    return this.toString();
  }

  toString() {
    return (
      "[" +
      this.curves
        .map(function (curve) {
          return utils.pointsToString(curve.points);
        })
        .join(", ") +
      "]"
    );
  }

  addCurve(curve) {
    this.curves.push(curve);
    this._3d = this._3d || curve._3d;
  }

  length() {
    return this.curves
      .map(function (v) {
        return v.length();
      })
      .reduce(function (a, b) {
        return a + b;
      });
  }

  curve(idx) {
    return this.curves[idx];
  }

  bbox() {
    const c = this.curves;
    var bbox = c[0].bbox();
    for (var i = 1; i < c.length; i++) {
      utils.expandbox(bbox, c[i].bbox());
    }
    return bbox;
  }

  offset(d) {
    const offset = [];
    this.curves.forEach(function (v) {
      offset.push(...v.offset(d));
    });
    return new PolyBezier(offset);
  }
}



;// CONCATENATED MODULE: ./node_modules/bezier-js/src/bezier.js
/**
  A javascript Bezier curve library by Pomax.

  Based on http://pomax.github.io/bezierinfo

  This code is MIT licensed.
**/




// math-inlining.
const { abs: bezier_abs, min: bezier_min, max: bezier_max, cos: bezier_cos, sin: bezier_sin, acos: bezier_acos, sqrt: bezier_sqrt } = Math;
const bezier_pi = Math.PI;
// a zero coordinate, which is surprisingly useful
const bezier_ZERO = { x: 0, y: 0, z: 0 };

/**
 * Bezier curve constructor.
 *
 * ...docs pending...
 */
class Bezier {
  constructor(coords) {
    let args =
      coords && coords.forEach ? coords : Array.from(arguments).slice();
    let coordlen = false;

    if (typeof args[0] === "object") {
      coordlen = args.length;
      const newargs = [];
      args.forEach(function (point) {
        ["x", "y", "z"].forEach(function (d) {
          if (typeof point[d] !== "undefined") {
            newargs.push(point[d]);
          }
        });
      });
      args = newargs;
    }

    let higher = false;
    const len = args.length;

    if (coordlen) {
      if (coordlen > 4) {
        if (arguments.length !== 1) {
          throw new Error(
            "Only new Bezier(point[]) is accepted for 4th and higher order curves"
          );
        }
        higher = true;
      }
    } else {
      if (len !== 6 && len !== 8 && len !== 9 && len !== 12) {
        if (arguments.length !== 1) {
          throw new Error(
            "Only new Bezier(point[]) is accepted for 4th and higher order curves"
          );
        }
      }
    }

    const _3d = (this._3d =
      (!higher && (len === 9 || len === 12)) ||
      (coords && coords[0] && typeof coords[0].z !== "undefined"));

    const points = (this.points = []);
    for (let idx = 0, step = _3d ? 3 : 2; idx < len; idx += step) {
      var point = {
        x: args[idx],
        y: args[idx + 1],
      };
      if (_3d) {
        point.z = args[idx + 2];
      }
      points.push(point);
    }
    const order = (this.order = points.length - 1);

    const dims = (this.dims = ["x", "y"]);
    if (_3d) dims.push("z");
    this.dimlen = dims.length;

    const aligned = utils.align(points, { p1: points[0], p2: points[order] });
    this._linear = !aligned.some((p) => bezier_abs(p.y) > 0.0001);

    this._lut = [];

    this._t1 = 0;
    this._t2 = 1;
    this.update();
  }

  static quadraticFromPoints(p1, p2, p3, t) {
    if (typeof t === "undefined") {
      t = 0.5;
    }
    // shortcuts, although they're really dumb
    if (t === 0) {
      return new Bezier(p2, p2, p3);
    }
    if (t === 1) {
      return new Bezier(p1, p2, p2);
    }
    // real fitting.
    const abc = Bezier.getABC(2, p1, p2, p3, t);
    return new Bezier(p1, abc.A, p3);
  }

  static cubicFromPoints(S, B, E, t, d1) {
    if (typeof t === "undefined") {
      t = 0.5;
    }
    const abc = Bezier.getABC(3, S, B, E, t);
    if (typeof d1 === "undefined") {
      d1 = utils.dist(B, abc.C);
    }
    const d2 = (d1 * (1 - t)) / t;

    const selen = utils.dist(S, E),
      lx = (E.x - S.x) / selen,
      ly = (E.y - S.y) / selen,
      bx1 = d1 * lx,
      by1 = d1 * ly,
      bx2 = d2 * lx,
      by2 = d2 * ly;
    // derivation of new hull coordinates
    const e1 = { x: B.x - bx1, y: B.y - by1 },
      e2 = { x: B.x + bx2, y: B.y + by2 },
      A = abc.A,
      v1 = { x: A.x + (e1.x - A.x) / (1 - t), y: A.y + (e1.y - A.y) / (1 - t) },
      v2 = { x: A.x + (e2.x - A.x) / t, y: A.y + (e2.y - A.y) / t },
      nc1 = { x: S.x + (v1.x - S.x) / t, y: S.y + (v1.y - S.y) / t },
      nc2 = {
        x: E.x + (v2.x - E.x) / (1 - t),
        y: E.y + (v2.y - E.y) / (1 - t),
      };
    // ...done
    return new Bezier(S, nc1, nc2, E);
  }

  static getUtils() {
    return utils;
  }

  getUtils() {
    return Bezier.getUtils();
  }

  static get PolyBezier() {
    return PolyBezier;
  }

  valueOf() {
    return this.toString();
  }

  toString() {
    return utils.pointsToString(this.points);
  }

  toSVG() {
    if (this._3d) return false;
    const p = this.points,
      x = p[0].x,
      y = p[0].y,
      s = ["M", x, y, this.order === 2 ? "Q" : "C"];
    for (let i = 1, last = p.length; i < last; i++) {
      s.push(p[i].x);
      s.push(p[i].y);
    }
    return s.join(" ");
  }

  setRatios(ratios) {
    if (ratios.length !== this.points.length) {
      throw new Error("incorrect number of ratio values");
    }
    this.ratios = ratios;
    this._lut = []; //  invalidate any precomputed LUT
  }

  verify() {
    const print = this.coordDigest();
    if (print !== this._print) {
      this._print = print;
      this.update();
    }
  }

  coordDigest() {
    return this.points
      .map(function (c, pos) {
        return "" + pos + c.x + c.y + (c.z ? c.z : 0);
      })
      .join("");
  }

  update() {
    // invalidate any precomputed LUT
    this._lut = [];
    this.dpoints = utils.derive(this.points, this._3d);
    this.computedirection();
  }

  computedirection() {
    const points = this.points;
    const angle = utils.angle(points[0], points[this.order], points[1]);
    this.clockwise = angle > 0;
  }

  length() {
    return utils.length(this.derivative.bind(this));
  }

  static getABC(order = 2, S, B, E, t = 0.5) {
    const u = utils.projectionratio(t, order),
      um = 1 - u,
      C = {
        x: u * S.x + um * E.x,
        y: u * S.y + um * E.y,
      },
      s = utils.abcratio(t, order),
      A = {
        x: B.x + (B.x - C.x) / s,
        y: B.y + (B.y - C.y) / s,
      };
    return { A, B, C, S, E };
  }

  getABC(t, B) {
    B = B || this.get(t);
    let S = this.points[0];
    let E = this.points[this.order];
    return Bezier.getABC(this.order, S, B, E, t);
  }

  getLUT(steps) {
    this.verify();
    steps = steps || 100;
    if (this._lut.length === steps) {
      return this._lut;
    }
    this._lut = [];
    // We want a range from 0 to 1 inclusive, so
    // we decrement and then use <= rather than <:
    steps--;
    for (let i = 0, p, t; i < steps; i++) {
      t = i / (steps - 1);
      p = this.compute(t);
      p.t = t;
      this._lut.push(p);
    }
    return this._lut;
  }

  on(point, error) {
    error = error || 5;
    const lut = this.getLUT(),
      hits = [];
    for (let i = 0, c, t = 0; i < lut.length; i++) {
      c = lut[i];
      if (utils.dist(c, point) < error) {
        hits.push(c);
        t += i / lut.length;
      }
    }
    if (!hits.length) return false;
    return (t /= hits.length);
  }

  project(point) {
    // step 1: coarse check
    const LUT = this.getLUT(),
      l = LUT.length - 1,
      closest = utils.closest(LUT, point),
      mpos = closest.mpos,
      t1 = (mpos - 1) / l,
      t2 = (mpos + 1) / l,
      step = 0.1 / l;

    // step 2: fine check
    let mdist = closest.mdist,
      t = t1,
      ft = t,
      p;
    mdist += 1;
    for (let d; t < t2 + step; t += step) {
      p = this.compute(t);
      d = utils.dist(point, p);
      if (d < mdist) {
        mdist = d;
        ft = t;
      }
    }
    ft = ft < 0 ? 0 : ft > 1 ? 1 : ft;
    p = this.compute(ft);
    p.t = ft;
    p.d = mdist;
    return p;
  }

  get(t) {
    return this.compute(t);
  }

  point(idx) {
    return this.points[idx];
  }

  compute(t) {
    if (this.ratios) {
      return utils.computeWithRatios(t, this.points, this.ratios, this._3d);
    }
    return utils.compute(t, this.points, this._3d, this.ratios);
  }

  raise() {
    const p = this.points,
      np = [p[0]],
      k = p.length;
    for (let i = 1, pi, pim; i < k; i++) {
      pi = p[i];
      pim = p[i - 1];
      np[i] = {
        x: ((k - i) / k) * pi.x + (i / k) * pim.x,
        y: ((k - i) / k) * pi.y + (i / k) * pim.y,
      };
    }
    np[k] = p[k - 1];
    return new Bezier(np);
  }

  derivative(t) {
    return utils.compute(t, this.dpoints[0]);
  }

  dderivative(t) {
    return utils.compute(t, this.dpoints[1]);
  }

  align() {
    let p = this.points;
    return new Bezier(utils.align(p, { p1: p[0], p2: p[p.length - 1] }));
  }

  curvature(t) {
    return utils.curvature(t, this.dpoints[0], this.dpoints[1], this._3d);
  }

  inflections() {
    return utils.inflections(this.points);
  }

  normal(t) {
    return this._3d ? this.__normal3(t) : this.__normal2(t);
  }

  __normal2(t) {
    const d = this.derivative(t);
    const q = bezier_sqrt(d.x * d.x + d.y * d.y);
    return { x: -d.y / q, y: d.x / q };
  }

  __normal3(t) {
    // see http://stackoverflow.com/questions/25453159
    const r1 = this.derivative(t),
      r2 = this.derivative(t + 0.01),
      q1 = bezier_sqrt(r1.x * r1.x + r1.y * r1.y + r1.z * r1.z),
      q2 = bezier_sqrt(r2.x * r2.x + r2.y * r2.y + r2.z * r2.z);
    r1.x /= q1;
    r1.y /= q1;
    r1.z /= q1;
    r2.x /= q2;
    r2.y /= q2;
    r2.z /= q2;
    // cross product
    const c = {
      x: r2.y * r1.z - r2.z * r1.y,
      y: r2.z * r1.x - r2.x * r1.z,
      z: r2.x * r1.y - r2.y * r1.x,
    };
    const m = bezier_sqrt(c.x * c.x + c.y * c.y + c.z * c.z);
    c.x /= m;
    c.y /= m;
    c.z /= m;
    // rotation matrix
    const R = [
      c.x * c.x,
      c.x * c.y - c.z,
      c.x * c.z + c.y,
      c.x * c.y + c.z,
      c.y * c.y,
      c.y * c.z - c.x,
      c.x * c.z - c.y,
      c.y * c.z + c.x,
      c.z * c.z,
    ];
    // normal vector:
    const n = {
      x: R[0] * r1.x + R[1] * r1.y + R[2] * r1.z,
      y: R[3] * r1.x + R[4] * r1.y + R[5] * r1.z,
      z: R[6] * r1.x + R[7] * r1.y + R[8] * r1.z,
    };
    return n;
  }

  hull(t) {
    let p = this.points,
      _p = [],
      q = [],
      idx = 0;
    q[idx++] = p[0];
    q[idx++] = p[1];
    q[idx++] = p[2];
    if (this.order === 3) {
      q[idx++] = p[3];
    }
    // we lerp between all points at each iteration, until we have 1 point left.
    while (p.length > 1) {
      _p = [];
      for (let i = 0, pt, l = p.length - 1; i < l; i++) {
        pt = utils.lerp(t, p[i], p[i + 1]);
        q[idx++] = pt;
        _p.push(pt);
      }
      p = _p;
    }
    return q;
  }

  split(t1, t2) {
    // shortcuts
    if (t1 === 0 && !!t2) {
      return this.split(t2).left;
    }
    if (t2 === 1) {
      return this.split(t1).right;
    }

    // no shortcut: use "de Casteljau" iteration.
    const q = this.hull(t1);
    const result = {
      left:
        this.order === 2
          ? new Bezier([q[0], q[3], q[5]])
          : new Bezier([q[0], q[4], q[7], q[9]]),
      right:
        this.order === 2
          ? new Bezier([q[5], q[4], q[2]])
          : new Bezier([q[9], q[8], q[6], q[3]]),
      span: q,
    };

    // make sure we bind _t1/_t2 information!
    result.left._t1 = utils.map(0, 0, 1, this._t1, this._t2);
    result.left._t2 = utils.map(t1, 0, 1, this._t1, this._t2);
    result.right._t1 = utils.map(t1, 0, 1, this._t1, this._t2);
    result.right._t2 = utils.map(1, 0, 1, this._t1, this._t2);

    // if we have no t2, we're done
    if (!t2) {
      return result;
    }

    // if we have a t2, split again:
    t2 = utils.map(t2, t1, 1, 0, 1);
    return result.right.split(t2).left;
  }

  extrema() {
    const result = {};
    let roots = [];

    this.dims.forEach(
      function (dim) {
        let mfn = function (v) {
          return v[dim];
        };
        let p = this.dpoints[0].map(mfn);
        result[dim] = utils.droots(p);
        if (this.order === 3) {
          p = this.dpoints[1].map(mfn);
          result[dim] = result[dim].concat(utils.droots(p));
        }
        result[dim] = result[dim].filter(function (t) {
          return t >= 0 && t <= 1;
        });
        roots = roots.concat(result[dim].sort(utils.numberSort));
      }.bind(this)
    );

    result.values = roots.sort(utils.numberSort).filter(function (v, idx) {
      return roots.indexOf(v) === idx;
    });

    return result;
  }

  bbox() {
    const extrema = this.extrema(),
      result = {};
    this.dims.forEach(
      function (d) {
        result[d] = utils.getminmax(this, d, extrema[d]);
      }.bind(this)
    );
    return result;
  }

  overlaps(curve) {
    const lbbox = this.bbox(),
      tbbox = curve.bbox();
    return utils.bboxoverlap(lbbox, tbbox);
  }

  offset(t, d) {
    if (typeof d !== "undefined") {
      const c = this.get(t),
        n = this.normal(t);
      const ret = {
        c: c,
        n: n,
        x: c.x + n.x * d,
        y: c.y + n.y * d,
      };
      if (this._3d) {
        ret.z = c.z + n.z * d;
      }
      return ret;
    }
    if (this._linear) {
      const nv = this.normal(0),
        coords = this.points.map(function (p) {
          const ret = {
            x: p.x + t * nv.x,
            y: p.y + t * nv.y,
          };
          if (p.z && nv.z) {
            ret.z = p.z + t * nv.z;
          }
          return ret;
        });
      return [new Bezier(coords)];
    }
    return this.reduce().map(function (s) {
      if (s._linear) {
        return s.offset(t)[0];
      }
      return s.scale(t);
    });
  }

  simple() {
    if (this.order === 3) {
      const a1 = utils.angle(this.points[0], this.points[3], this.points[1]);
      const a2 = utils.angle(this.points[0], this.points[3], this.points[2]);
      if ((a1 > 0 && a2 < 0) || (a1 < 0 && a2 > 0)) return false;
    }
    const n1 = this.normal(0);
    const n2 = this.normal(1);
    let s = n1.x * n2.x + n1.y * n2.y;
    if (this._3d) {
      s += n1.z * n2.z;
    }
    return bezier_abs(bezier_acos(s)) < bezier_pi / 3;
  }

  reduce() {
    // TODO: examine these var types in more detail...
    let i,
      t1 = 0,
      t2 = 0,
      step = 0.01,
      segment,
      pass1 = [],
      pass2 = [];
    // first pass: split on extrema
    let extrema = this.extrema().values;
    if (extrema.indexOf(0) === -1) {
      extrema = [0].concat(extrema);
    }
    if (extrema.indexOf(1) === -1) {
      extrema.push(1);
    }

    for (t1 = extrema[0], i = 1; i < extrema.length; i++) {
      t2 = extrema[i];
      segment = this.split(t1, t2);
      segment._t1 = t1;
      segment._t2 = t2;
      pass1.push(segment);
      t1 = t2;
    }

    // second pass: further reduce these segments to simple segments
    pass1.forEach(function (p1) {
      t1 = 0;
      t2 = 0;
      while (t2 <= 1) {
        for (t2 = t1 + step; t2 <= 1 + step; t2 += step) {
          segment = p1.split(t1, t2);
          if (!segment.simple()) {
            t2 -= step;
            if (bezier_abs(t1 - t2) < step) {
              // we can never form a reduction
              return [];
            }
            segment = p1.split(t1, t2);
            segment._t1 = utils.map(t1, 0, 1, p1._t1, p1._t2);
            segment._t2 = utils.map(t2, 0, 1, p1._t1, p1._t2);
            pass2.push(segment);
            t1 = t2;
            break;
          }
        }
      }
      if (t1 < 1) {
        segment = p1.split(t1, 1);
        segment._t1 = utils.map(t1, 0, 1, p1._t1, p1._t2);
        segment._t2 = p1._t2;
        pass2.push(segment);
      }
    });
    return pass2;
  }

  scale(d) {
    const order = this.order;
    let distanceFn = false;
    if (typeof d === "function") {
      distanceFn = d;
    }
    if (distanceFn && order === 2) {
      return this.raise().scale(distanceFn);
    }

    // TODO: add special handling for degenerate (=linear) curves.
    const clockwise = this.clockwise;
    const r1 = distanceFn ? distanceFn(0) : d;
    const r2 = distanceFn ? distanceFn(1) : d;
    const v = [this.offset(0, 10), this.offset(1, 10)];
    const points = this.points;
    const np = [];
    const o = utils.lli4(v[0], v[0].c, v[1], v[1].c);

    if (!o) {
      throw new Error("cannot scale this curve. Try reducing it first.");
    }
    // move all points by distance 'd' wrt the origin 'o'

    // move end points by fixed distance along normal.
    [0, 1].forEach(function (t) {
      const p = (np[t * order] = utils.copy(points[t * order]));
      p.x += (t ? r2 : r1) * v[t].n.x;
      p.y += (t ? r2 : r1) * v[t].n.y;
    });

    if (!distanceFn) {
      // move control points to lie on the intersection of the offset
      // derivative vector, and the origin-through-control vector
      [0, 1].forEach((t) => {
        if (order === 2 && !!t) return;
        const p = np[t * order];
        const d = this.derivative(t);
        const p2 = { x: p.x + d.x, y: p.y + d.y };
        np[t + 1] = utils.lli4(p, p2, o, points[t + 1]);
      });
      return new Bezier(np);
    }

    // move control points by "however much necessary to
    // ensure the correct tangent to endpoint".
    [0, 1].forEach(function (t) {
      if (order === 2 && !!t) return;
      var p = points[t + 1];
      var ov = {
        x: p.x - o.x,
        y: p.y - o.y,
      };
      var rc = distanceFn ? distanceFn((t + 1) / order) : d;
      if (distanceFn && !clockwise) rc = -rc;
      var m = bezier_sqrt(ov.x * ov.x + ov.y * ov.y);
      ov.x /= m;
      ov.y /= m;
      np[t + 1] = {
        x: p.x + rc * ov.x,
        y: p.y + rc * ov.y,
      };
    });
    return new Bezier(np);
  }

  outline(d1, d2, d3, d4) {
    d2 = typeof d2 === "undefined" ? d1 : d2;
    const reduced = this.reduce(),
      len = reduced.length,
      fcurves = [];

    let bcurves = [],
      p,
      alen = 0,
      tlen = this.length();

    const graduated = typeof d3 !== "undefined" && typeof d4 !== "undefined";

    function linearDistanceFunction(s, e, tlen, alen, slen) {
      return function (v) {
        const f1 = alen / tlen,
          f2 = (alen + slen) / tlen,
          d = e - s;
        return utils.map(v, 0, 1, s + f1 * d, s + f2 * d);
      };
    }

    // form curve oulines
    reduced.forEach(function (segment) {
      const slen = segment.length();
      if (graduated) {
        fcurves.push(
          segment.scale(linearDistanceFunction(d1, d3, tlen, alen, slen))
        );
        bcurves.push(
          segment.scale(linearDistanceFunction(-d2, -d4, tlen, alen, slen))
        );
      } else {
        fcurves.push(segment.scale(d1));
        bcurves.push(segment.scale(-d2));
      }
      alen += slen;
    });

    // reverse the "return" outline
    bcurves = bcurves
      .map(function (s) {
        p = s.points;
        if (p[3]) {
          s.points = [p[3], p[2], p[1], p[0]];
        } else {
          s.points = [p[2], p[1], p[0]];
        }
        return s;
      })
      .reverse();

    // form the endcaps as lines
    const fs = fcurves[0].points[0],
      fe = fcurves[len - 1].points[fcurves[len - 1].points.length - 1],
      bs = bcurves[len - 1].points[bcurves[len - 1].points.length - 1],
      be = bcurves[0].points[0],
      ls = utils.makeline(bs, fs),
      le = utils.makeline(fe, be),
      segments = [ls].concat(fcurves).concat([le]).concat(bcurves),
      slen = segments.length;

    return new PolyBezier(segments);
  }

  outlineshapes(d1, d2, curveIntersectionThreshold) {
    d2 = d2 || d1;
    const outline = this.outline(d1, d2).curves;
    const shapes = [];
    for (let i = 1, len = outline.length; i < len / 2; i++) {
      const shape = utils.makeshape(
        outline[i],
        outline[len - i],
        curveIntersectionThreshold
      );
      shape.startcap.virtual = i > 1;
      shape.endcap.virtual = i < len / 2 - 1;
      shapes.push(shape);
    }
    return shapes;
  }

  intersects(curve, curveIntersectionThreshold) {
    if (!curve) return this.selfintersects(curveIntersectionThreshold);
    if (curve.p1 && curve.p2) {
      return this.lineIntersects(curve);
    }
    if (curve instanceof Bezier) {
      curve = curve.reduce();
    }
    return this.curveintersects(
      this.reduce(),
      curve,
      curveIntersectionThreshold
    );
  }

  lineIntersects(line) {
    const mx = bezier_min(line.p1.x, line.p2.x),
      my = bezier_min(line.p1.y, line.p2.y),
      MX = bezier_max(line.p1.x, line.p2.x),
      MY = bezier_max(line.p1.y, line.p2.y);
    return utils.roots(this.points, line).filter((t) => {
      var p = this.get(t);
      return utils.between(p.x, mx, MX) && utils.between(p.y, my, MY);
    });
  }

  selfintersects(curveIntersectionThreshold) {
    // "simple" curves cannot intersect with their direct
    // neighbour, so for each segment X we check whether
    // it intersects [0:x-2][x+2:last].

    const reduced = this.reduce(),
      len = reduced.length - 2,
      results = [];

    for (let i = 0, result, left, right; i < len; i++) {
      left = reduced.slice(i, i + 1);
      right = reduced.slice(i + 2);
      result = this.curveintersects(left, right, curveIntersectionThreshold);
      results.push(...result);
    }
    return results;
  }

  curveintersects(c1, c2, curveIntersectionThreshold) {
    const pairs = [];
    // step 1: pair off any overlapping segments
    c1.forEach(function (l) {
      c2.forEach(function (r) {
        if (l.overlaps(r)) {
          pairs.push({ left: l, right: r });
        }
      });
    });
    // step 2: for each pairing, run through the convergence algorithm.
    let intersections = [];
    pairs.forEach(function (pair) {
      const result = utils.pairiteration(
        pair.left,
        pair.right,
        curveIntersectionThreshold
      );
      if (result.length > 0) {
        intersections = intersections.concat(result);
      }
    });
    return intersections;
  }

  arcs(errorThreshold) {
    errorThreshold = errorThreshold || 0.5;
    return this._iterate(errorThreshold, []);
  }

  _error(pc, np1, s, e) {
    const q = (e - s) / 4,
      c1 = this.get(s + q),
      c2 = this.get(e - q),
      ref = utils.dist(pc, np1),
      d1 = utils.dist(pc, c1),
      d2 = utils.dist(pc, c2);
    return bezier_abs(d1 - ref) + bezier_abs(d2 - ref);
  }

  _iterate(errorThreshold, circles) {
    let t_s = 0,
      t_e = 1,
      safety;
    // we do a binary search to find the "good `t` closest to no-longer-good"
    do {
      safety = 0;

      // step 1: start with the maximum possible arc
      t_e = 1;

      // points:
      let np1 = this.get(t_s),
        np2,
        np3,
        arc,
        prev_arc;

      // booleans:
      let curr_good = false,
        prev_good = false,
        done;

      // numbers:
      let t_m = t_e,
        prev_e = 1,
        step = 0;

      // step 2: find the best possible arc
      do {
        prev_good = curr_good;
        prev_arc = arc;
        t_m = (t_s + t_e) / 2;
        step++;

        np2 = this.get(t_m);
        np3 = this.get(t_e);

        arc = utils.getccenter(np1, np2, np3);

        //also save the t values
        arc.interval = {
          start: t_s,
          end: t_e,
        };

        let error = this._error(arc, np1, t_s, t_e);
        curr_good = error <= errorThreshold;

        done = prev_good && !curr_good;
        if (!done) prev_e = t_e;

        // this arc is fine: we can move 'e' up to see if we can find a wider arc
        if (curr_good) {
          // if e is already at max, then we're done for this arc.
          if (t_e >= 1) {
            // make sure we cap at t=1
            arc.interval.end = prev_e = 1;
            prev_arc = arc;
            // if we capped the arc segment to t=1 we also need to make sure that
            // the arc's end angle is correct with respect to the bezier end point.
            if (t_e > 1) {
              let d = {
                x: arc.x + arc.r * bezier_cos(arc.e),
                y: arc.y + arc.r * bezier_sin(arc.e),
              };
              arc.e += utils.angle({ x: arc.x, y: arc.y }, d, this.get(1));
            }
            break;
          }
          // if not, move it up by half the iteration distance
          t_e = t_e + (t_e - t_s) / 2;
        } else {
          // this is a bad arc: we need to move 'e' down to find a good arc
          t_e = t_m;
        }
      } while (!done && safety++ < 100);

      if (safety >= 100) {
        break;
      }

      // console.log("L835: [F] arc found", t_s, prev_e, prev_arc.x, prev_arc.y, prev_arc.s, prev_arc.e);

      prev_arc = prev_arc ? prev_arc : arc;
      circles.push(prev_arc);
      t_s = prev_e;
    } while (t_e < 1);
    return circles;
  }
}



;// CONCATENATED MODULE: ./node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50),
    e5 = Math.sqrt(10),
    e2 = Math.sqrt(2);

/* harmony default export */ function ticks(start, stop, count) {
  var reverse,
      i = -1,
      n,
      ticks,
      step;

  stop = +stop, start = +start, count = +count;
  if (start === stop && count > 0) return [start];
  if (reverse = stop < start) n = start, start = stop, stop = n;
  if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];

  if (step > 0) {
    let r0 = Math.round(start / step), r1 = Math.round(stop / step);
    if (r0 * step < start) ++r0;
    if (r1 * step > stop) --r1;
    ticks = new Array(n = r1 - r0 + 1);
    while (++i < n) ticks[i] = (r0 + i) * step;
  } else {
    step = -step;
    let r0 = Math.round(start * step), r1 = Math.round(stop * step);
    if (r0 / step < start) ++r0;
    if (r1 / step > stop) --r1;
    ticks = new Array(n = r1 - r0 + 1);
    while (++i < n) ticks[i] = (r0 + i) / step;
  }

  if (reverse) ticks.reverse();

  return ticks;
}

function tickIncrement(start, stop, count) {
  var step = (stop - start) / Math.max(0, count),
      power = Math.floor(Math.log(step) / Math.LN10),
      error = step / Math.pow(10, power);
  return power >= 0
      ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
      : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}

function tickStep(start, stop, count) {
  var step0 = Math.abs(stop - start) / Math.max(0, count),
      step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
      error = step0 / step1;
  if (error >= e10) step1 *= 10;
  else if (error >= e5) step1 *= 5;
  else if (error >= e2) step1 *= 2;
  return stop < start ? -step1 : step1;
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/ascending.js
/* harmony default export */ function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/bisector.js


/* harmony default export */ function bisector(f) {
  let delta = f;
  let compare = f;

  if (f.length === 1) {
    delta = (d, x) => f(d) - x;
    compare = ascendingComparator(f);
  }

  function left(a, x, lo, hi) {
    if (lo == null) lo = 0;
    if (hi == null) hi = a.length;
    while (lo < hi) {
      const mid = (lo + hi) >>> 1;
      if (compare(a[mid], x) < 0) lo = mid + 1;
      else hi = mid;
    }
    return lo;
  }

  function right(a, x, lo, hi) {
    if (lo == null) lo = 0;
    if (hi == null) hi = a.length;
    while (lo < hi) {
      const mid = (lo + hi) >>> 1;
      if (compare(a[mid], x) > 0) hi = mid;
      else lo = mid + 1;
    }
    return lo;
  }

  function center(a, x, lo, hi) {
    if (lo == null) lo = 0;
    if (hi == null) hi = a.length;
    const i = left(a, x, lo, hi - 1);
    return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;
  }

  return {left, center, right};
}

function ascendingComparator(f) {
  return (d, x) => ascending(f(d), x);
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/number.js
/* harmony default export */ function number(x) {
  return x === null ? NaN : +x;
}

function* numbers(values, valueof) {
  if (valueof === undefined) {
    for (let value of values) {
      if (value != null && (value = +value) >= value) {
        yield value;
      }
    }
  } else {
    let index = -1;
    for (let value of values) {
      if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
        yield value;
      }
    }
  }
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/bisect.js




const ascendingBisect = bisector(ascending);
const bisectRight = ascendingBisect.right;
const bisectLeft = ascendingBisect.left;
const bisectCenter = bisector(number).center;
/* harmony default export */ const bisect = (bisectRight);

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/basis.js
function basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0
      + (4 - 6 * t2 + 3 * t3) * v1
      + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
      + t3 * v3) / 6;
}

/* harmony default export */ function src_basis(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
        v1 = values[i],
        v2 = values[i + 1],
        v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
        v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/basisClosed.js


/* harmony default export */ function basisClosed(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
        v0 = values[(i + n - 1) % n],
        v1 = values[i % n],
        v2 = values[(i + 1) % n],
        v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/constant.js
/* harmony default export */ const src_constant = (x => () => x);

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/color.js


function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function hue(a, b) {
  var d = b - a;
  return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : src_constant(isNaN(a) ? b : a);
}

function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : src_constant(isNaN(a) ? b : a);
  };
}

function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : src_constant(isNaN(a) ? b : a);
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/rgb.js





/* harmony default export */ const rgb = ((function rgbGamma(y) {
  var color = gamma(y);

  function rgb(start, end) {
    var r = color((start = color_rgb(start)).r, (end = color_rgb(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb.gamma = rgbGamma;

  return rgb;
})(1));

function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length,
        r = new Array(n),
        g = new Array(n),
        b = new Array(n),
        i, color;
    for (i = 0; i < n; ++i) {
      color = color_rgb(colors[i]);
      r[i] = color.r || 0;
      g[i] = color.g || 0;
      b[i] = color.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color.opacity = 1;
    return function(t) {
      color.r = r(t);
      color.g = g(t);
      color.b = b(t);
      return color + "";
    };
  };
}

var rgbBasis = rgbSpline(src_basis);
var rgbBasisClosed = rgbSpline(basisClosed);

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/array.js



/* harmony default export */ function array(a, b) {
  return (isNumberArray(b) ? numberArray : genericArray)(a, b);
}

function genericArray(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/date.js
/* harmony default export */ function date(a, b) {
  var d = new Date;
  return a = +a, b = +b, function(t) {
    return d.setTime(a * (1 - t) + b * t), d;
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/number.js
/* harmony default export */ function src_number(a, b) {
  return a = +a, b = +b, function(t) {
    return a * (1 - t) + b * t;
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/object.js


/* harmony default export */ function object(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = value(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/string.js


var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    reB = new RegExp(reA.source, "g");

function zero(b) {
  return function() {
    return b;
  };
}

function one(b) {
  return function(t) {
    return b(t) + "";
  };
}

/* harmony default export */ function string(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = reA.exec(a))
      && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: src_number(am, bm)});
    }
    bi = reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? one(q[0].x)
      : zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/numberArray.js
/* harmony default export */ function src_numberArray(a, b) {
  if (!b) b = [];
  var n = a ? Math.min(b.length, a.length) : 0,
      c = b.slice(),
      i;
  return function(t) {
    for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
    return c;
  };
}

function numberArray_isNumberArray(x) {
  return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/value.js










/* harmony default export */ function value(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? src_constant(b)
      : (t === "number" ? src_number
      : t === "string" ? ((c = color(b)) ? (b = c, rgb) : string)
      : b instanceof color ? rgb
      : b instanceof Date ? date
      : numberArray_isNumberArray(b) ? src_numberArray
      : Array.isArray(b) ? genericArray
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
      : src_number)(a, b);
}

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/round.js
/* harmony default export */ function round(a, b) {
  return a = +a, b = +b, function(t) {
    return Math.round(a * (1 - t) + b * t);
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/constant.js
function constants(x) {
  return function() {
    return x;
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/number.js
function number_number(x) {
  return +x;
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/continuous.js





var unit = [0, 1];

function continuous_identity(x) {
  return x;
}

function normalize(a, b) {
  return (b -= (a = +a))
      ? function(x) { return (x - a) / b; }
      : constants(isNaN(b) ? NaN : 0.5);
}

function clamper(a, b) {
  var t;
  if (a > b) t = a, a = b, b = t;
  return function(x) { return Math.max(a, Math.min(b, x)); };
}

// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].
function bimap(domain, range, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
  if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
  else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x) { return r0(d0(x)); };
}

function polymap(domain, range, interpolate) {
  var j = Math.min(domain.length, range.length) - 1,
      d = new Array(j),
      r = new Array(j),
      i = -1;

  // Reverse descending domains.
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range = range.slice().reverse();
  }

  while (++i < j) {
    d[i] = normalize(domain[i], domain[i + 1]);
    r[i] = interpolate(range[i], range[i + 1]);
  }

  return function(x) {
    var i = bisect(domain, x, 1, j) - 1;
    return r[i](d[i](x));
  };
}

function copy(source, target) {
  return target
      .domain(source.domain())
      .range(source.range())
      .interpolate(source.interpolate())
      .clamp(source.clamp())
      .unknown(source.unknown());
}

function transformer() {
  var domain = unit,
      range = unit,
      interpolate = value,
      transform,
      untransform,
      unknown,
      clamp = continuous_identity,
      piecewise,
      output,
      input;

  function rescale() {
    var n = Math.min(domain.length, range.length);
    if (clamp !== continuous_identity) clamp = clamper(domain[0], domain[n - 1]);
    piecewise = n > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }

  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));
  }

  scale.invert = function(y) {
    return clamp(untransform((input || (input = piecewise(range, domain.map(transform), src_number)))(y)));
  };

  scale.domain = function(_) {
    return arguments.length ? (domain = Array.from(_, number_number), rescale()) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return range = Array.from(_), interpolate = round, rescale();
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = _ ? true : continuous_identity, rescale()) : clamp !== continuous_identity;
  };

  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  return function(t, u) {
    transform = t, untransform = u;
    return rescale();
  };
}

function continuous() {
  return transformer()(continuous_identity, continuous_identity);
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/init.js
function initRange(domain, range) {
  switch (arguments.length) {
    case 0: break;
    case 1: this.range(domain); break;
    default: this.range(range).domain(domain); break;
  }
  return this;
}

function init_initInterpolator(domain, interpolator) {
  switch (arguments.length) {
    case 0: break;
    case 1: {
      if (typeof domain === "function") this.interpolator(domain);
      else this.range(domain);
      break;
    }
    default: {
      this.domain(domain);
      if (typeof interpolator === "function") this.interpolator(interpolator);
      else this.range(interpolator);
      break;
    }
  }
  return this;
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;

function formatSpecifier(specifier) {
  if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  return new FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}

formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof

function FormatSpecifier(specifier) {
  this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
  this.align = specifier.align === undefined ? ">" : specifier.align + "";
  this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === undefined ? undefined : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === undefined ? "" : specifier.type + "";
}

FormatSpecifier.prototype.toString = function() {
  return this.fill
      + this.align
      + this.sign
      + this.symbol
      + (this.zero ? "0" : "")
      + (this.width === undefined ? "" : Math.max(1, this.width | 0))
      + (this.comma ? "," : "")
      + (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
      + (this.trim ? "~" : "")
      + this.type;
};

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatDecimal.js
/* harmony default export */ function formatDecimal(x) {
  return Math.abs(x = Math.round(x)) >= 1e21
      ? x.toLocaleString("en").replace(/,/g, "")
      : x.toString(10);
}

// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimalParts(1.23) returns ["123", 0].
function formatDecimalParts(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  var i, coefficient = x.slice(0, i);

  // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/exponent.js


/* harmony default export */ function exponent(x) {
  return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/precisionPrefix.js


/* harmony default export */ function precisionPrefix(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatGroup.js
/* harmony default export */ function formatGroup(grouping, thousands) {
  return function(value, width) {
    var i = value.length,
        t = [],
        j = 0,
        g = grouping[0],
        length = 0;

    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }

    return t.reverse().join(thousands);
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ function formatNumerals(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ function formatTrim(s) {
  out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s[i]) {
      case ".": i0 = i1 = i; break;
      case "0": if (i0 === 0) i0 = i; i1 = i; break;
      default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatPrefixAuto.js


var prefixExponent;

/* harmony default export */ function formatPrefixAuto(x, p) {
  var d = formatDecimalParts(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1],
      i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
      n = coefficient.length;
  return i === n ? coefficient
      : i > n ? coefficient + new Array(i - n + 1).join("0")
      : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
      : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatRounded.js


/* harmony default export */ function formatRounded(x, p) {
  var d = formatDecimalParts(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
      : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
      : coefficient + new Array(exponent - coefficient.length + 2).join("0");
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTypes.js




/* harmony default export */ const formatTypes = ({
  "%": (x, p) => (x * 100).toFixed(p),
  "b": (x) => Math.round(x).toString(2),
  "c": (x) => x + "",
  "d": formatDecimal,
  "e": (x, p) => x.toExponential(p),
  "f": (x, p) => x.toFixed(p),
  "g": (x, p) => x.toPrecision(p),
  "o": (x) => Math.round(x).toString(8),
  "p": (x, p) => formatRounded(x * 100, p),
  "r": formatRounded,
  "s": formatPrefixAuto,
  "X": (x) => Math.round(x).toString(16).toUpperCase(),
  "x": (x) => Math.round(x).toString(16)
});

;// CONCATENATED MODULE: ./node_modules/d3-format/src/identity.js
/* harmony default export */ function d3_format_src_identity(x) {
  return x;
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/locale.js









var map = Array.prototype.map,
    prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];

/* harmony default export */ function locale(locale) {
  var group = locale.grouping === undefined || locale.thousands === undefined ? d3_format_src_identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + ""),
      currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
      currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
      decimal = locale.decimal === undefined ? "." : locale.decimal + "",
      numerals = locale.numerals === undefined ? d3_format_src_identity : formatNumerals(map.call(locale.numerals, String)),
      percent = locale.percent === undefined ? "%" : locale.percent + "",
      minus = locale.minus === undefined ? "−" : locale.minus + "",
      nan = locale.nan === undefined ? "NaN" : locale.nan + "";

  function newFormat(specifier) {
    specifier = formatSpecifier(specifier);

    var fill = specifier.fill,
        align = specifier.align,
        sign = specifier.sign,
        symbol = specifier.symbol,
        zero = specifier.zero,
        width = specifier.width,
        comma = specifier.comma,
        precision = specifier.precision,
        trim = specifier.trim,
        type = specifier.type;

    // The "n" type is an alias for ",g".
    if (type === "n") comma = true, type = "g";

    // The "" type, and any invalid type, is an alias for ".12~g".
    else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";

    // If zero fill is specified, padding goes after sign and before digits.
    if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";

    // Compute the prefix and suffix.
    // For SI-prefix, the suffix is lazily computed.
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
        suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";

    // What format function should we use?
    // Is this an integer type?
    // Can this type generate exponential notation?
    var formatType = formatTypes[type],
        maybeSuffix = /[defgprs%]/.test(type);

    // Set the default precision if not specified,
    // or clamp the specified precision to the supported range.
    // For significant precision, it must be in [1, 21].
    // For fixed precision, it must be in [0, 20].
    precision = precision === undefined ? 6
        : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
        : Math.max(0, Math.min(20, precision));

    function format(value) {
      var valuePrefix = prefix,
          valueSuffix = suffix,
          i, n, c;

      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;

        // Determine the sign. -0 is not less than 0, but 1 / -0 is!
        var valueNegative = value < 0 || 1 / value < 0;

        // Perform the initial formatting.
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);

        // Trim insignificant zeros.
        if (trim) value = formatTrim(value);

        // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
        if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;

        // Compute the prefix and suffix.
        valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");

        // Break the formatted value into the integer “value” part that can be
        // grouped, and fractional or exponential “suffix” part that is not.
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }

      // If the fill character is not "0", grouping is applied before padding.
      if (comma && !zero) value = group(value, Infinity);

      // Compute the padding.
      var length = valuePrefix.length + value.length + valueSuffix.length,
          padding = length < width ? new Array(width - length + 1).join(fill) : "";

      // If the fill character is "0", grouping is applied after padding.
      if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";

      // Reconstruct the final output based on the desired alignment.
      switch (align) {
        case "<": value = valuePrefix + value + valueSuffix + padding; break;
        case "=": value = valuePrefix + padding + value + valueSuffix; break;
        case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
        default: value = padding + valuePrefix + value + valueSuffix; break;
      }

      return numerals(value);
    }

    format.toString = function() {
      return specifier + "";
    };

    return format;
  }

  function formatPrefix(specifier, value) {
    var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
        e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,
        k = Math.pow(10, -e),
        prefix = prefixes[8 + e / 3];
    return function(value) {
      return f(k * value) + prefix;
    };
  }

  return {
    format: newFormat,
    formatPrefix: formatPrefix
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/defaultLocale.js


var defaultLocale_locale;
var format;
var formatPrefix;

defaultLocale({
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});

function defaultLocale(definition) {
  defaultLocale_locale = locale(definition);
  format = defaultLocale_locale.format;
  formatPrefix = defaultLocale_locale.formatPrefix;
  return defaultLocale_locale;
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/precisionRound.js


/* harmony default export */ function precisionRound(step, max) {
  step = Math.abs(step), max = Math.abs(max) - step;
  return Math.max(0, exponent(max) - exponent(step)) + 1;
}

;// CONCATENATED MODULE: ./node_modules/d3-format/src/precisionFixed.js


/* harmony default export */ function precisionFixed(step) {
  return Math.max(0, -exponent(Math.abs(step)));
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/tickFormat.js



function tickFormat(start, stop, count, specifier) {
  var step = tickStep(start, stop, count),
      precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format(specifier);
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/linear.js





function linearish(scale) {
  var domain = scale.domain;

  scale.ticks = function(count) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  };

  scale.tickFormat = function(count, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
  };

  scale.nice = function(count) {
    if (count == null) count = 10;

    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;

    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    
    while (maxIter-- > 0) {
      step = tickIncrement(start, stop, count);
      if (step === prestep) {
        d[i0] = start
        d[i1] = stop
        return domain(d);
      } else if (step > 0) {
        start = Math.floor(start / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start = Math.ceil(start * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }

    return scale;
  };

  return scale;
}

function linear_linear() {
  var scale = continuous();

  scale.copy = function() {
    return copy(scale, linear_linear());
  };

  initRange.apply(scale, arguments);

  return linearish(scale);
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/sequential.js








function sequential_transformer() {
  var x0 = 0,
      x1 = 1,
      t0,
      t1,
      k10,
      transform,
      interpolator = continuous_identity,
      clamp = false,
      unknown;

  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));
  }

  scale.domain = function(_) {
    return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale) : clamp;
  };

  scale.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale) : interpolator;
  };

  function range(interpolate) {
    return function(_) {
      var r0, r1;
      return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];
    };
  }

  scale.range = range(value);

  scale.rangeRound = range(round);

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  return function(t) {
    transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);
    return scale;
  };
}

function sequential_copy(source, target) {
  return target
      .domain(source.domain())
      .interpolator(source.interpolator())
      .clamp(source.clamp())
      .unknown(source.unknown());
}

function sequential() {
  var scale = linearish(sequential_transformer()(continuous_identity));

  scale.copy = function() {
    return sequential_copy(scale, sequential());
  };

  return init_initInterpolator.apply(scale, arguments);
}

function sequentialLog() {
  var scale = loggish(sequential_transformer()).domain([1, 10]);

  scale.copy = function() {
    return sequential_copy(scale, sequentialLog()).base(scale.base());
  };

  return initInterpolator.apply(scale, arguments);
}

function sequentialSymlog() {
  var scale = symlogish(sequential_transformer());

  scale.copy = function() {
    return sequential_copy(scale, sequentialSymlog()).constant(scale.constant());
  };

  return initInterpolator.apply(scale, arguments);
}

function sequentialPow() {
  var scale = powish(sequential_transformer());

  scale.copy = function() {
    return sequential_copy(scale, sequentialPow()).exponent(scale.exponent());
  };

  return initInterpolator.apply(scale, arguments);
}

function sequentialSqrt() {
  return sequentialPow.apply(null, arguments).exponent(0.5);
}

;// CONCATENATED MODULE: ./node_modules/d3-array/src/range.js
/* harmony default export */ function range(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;

  var i = -1,
      n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
      range = new Array(n);

  while (++i < n) {
    range[i] = start + i * step;
  }

  return range;
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/ordinal.js


const implicit = Symbol("implicit");

function ordinal() {
  var index = new Map(),
      domain = [],
      range = [],
      unknown = implicit;

  function scale(d) {
    var key = d + "", i = index.get(key);
    if (!i) {
      if (unknown !== implicit) return unknown;
      index.set(key, i = domain.push(d));
    }
    return range[(i - 1) % range.length];
  }

  scale.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [], index = new Map();
    for (const value of _) {
      const key = value + "";
      if (index.has(key)) continue;
      index.set(key, domain.push(value));
    }
    return scale;
  };

  scale.range = function(_) {
    return arguments.length ? (range = Array.from(_), scale) : range.slice();
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return ordinal(domain, range).unknown(unknown);
  };

  initRange.apply(scale, arguments);

  return scale;
}

;// CONCATENATED MODULE: ./node_modules/d3-scale/src/band.js




function band() {
  var scale = ordinal().unknown(undefined),
      domain = scale.domain,
      ordinalRange = scale.range,
      r0 = 0,
      r1 = 1,
      step,
      bandwidth,
      round = false,
      paddingInner = 0,
      paddingOuter = 0,
      align = 0.5;

  delete scale.unknown;

  function rescale() {
    var n = domain().length,
        reverse = r1 < r0,
        start = reverse ? r1 : r0,
        stop = reverse ? r0 : r1;
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round) step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = range(n).map(function(i) { return start + step * i; });
    return ordinalRange(reverse ? values.reverse() : values);
  }

  scale.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };

  scale.range = function(_) {
    return arguments.length ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };

  scale.rangeRound = function(_) {
    return [r0, r1] = _, r0 = +r0, r1 = +r1, round = true, rescale();
  };

  scale.bandwidth = function() {
    return bandwidth;
  };

  scale.step = function() {
    return step;
  };

  scale.round = function(_) {
    return arguments.length ? (round = !!_, rescale()) : round;
  };

  scale.padding = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
  };

  scale.paddingInner = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
  };

  scale.paddingOuter = function(_) {
    return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
  };

  scale.align = function(_) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
  };

  scale.copy = function() {
    return band(domain(), [r0, r1])
        .round(round)
        .paddingInner(paddingInner)
        .paddingOuter(paddingOuter)
        .align(align);
  };

  return initRange.apply(rescale(), arguments);
}

function pointish(scale) {
  var copy = scale.copy;

  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  delete scale.paddingOuter;

  scale.copy = function() {
    return pointish(copy());
  };

  return scale;
}

function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/colors.js
/* harmony default export */ function colors(specifier) {
  var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;
  while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6);
  return colors;
}

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-multi/viridis.js


function ramp(range) {
  var n = range.length;
  return function(t) {
    return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
}

/* harmony default export */ const viridis = (ramp(colors("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")));

var magma = ramp(colors("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf"));

var inferno = ramp(colors("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4"));

var plasma = ramp(colors("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/ramp.js


/* harmony default export */ const src_ramp = (scheme => rgbBasis(scheme[scheme.length - 1]));

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-single/Greys.js



var scheme = new Array(3).concat(
  "f0f0f0bdbdbd636363",
  "f7f7f7cccccc969696525252",
  "f7f7f7cccccc969696636363252525",
  "f7f7f7d9d9d9bdbdbd969696636363252525",
  "f7f7f7d9d9d9bdbdbd969696737373525252252525",
  "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525",
  "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000"
).map(colors);

/* harmony default export */ const Greys = (src_ramp(scheme));

;// CONCATENATED MODULE: ./node_modules/d3-color/src/math.js
const radians = Math.PI / 180;
const degrees = 180 / Math.PI;

;// CONCATENATED MODULE: ./node_modules/d3-color/src/cubehelix.js




var A = -0.14861,
    B = +1.78277,
    C = -0.29227,
    D = -0.90649,
    E = +1.97294,
    ED = E * D,
    EB = E * B,
    BC_DA = B * C - D * A;

function cubehelixConvert(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
      bl = b - l,
      k = (E * (g - l) - C * bl) / D,
      s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function cubehelix_cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

src_define(Cubehelix, cubehelix_cubehelix, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * radians,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new Rgb(
      255 * (l + a * (A * cosh + B * sinh)),
      255 * (l + a * (C * cosh + D * sinh)),
      255 * (l + a * (E * cosh)),
      this.opacity
    );
  }
}));

;// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/cubehelix.js



function cubehelix(hue) {
  return (function cubehelixGamma(y) {
    y = +y;

    function cubehelix(start, end) {
      var h = hue((start = cubehelix_cubehelix(start)).h, (end = cubehelix_cubehelix(end)).h),
          s = nogamma(start.s, end.s),
          l = nogamma(start.l, end.l),
          opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.s = s(t);
        start.l = l(Math.pow(t, y));
        start.opacity = opacity(t);
        return start + "";
      };
    }

    cubehelix.gamma = cubehelixGamma;

    return cubehelix;
  })(1);
}

/* harmony default export */ const src_cubehelix = (cubehelix(hue));
var cubehelixLong = cubehelix(nogamma);

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-multi/rainbow.js



var warm = cubehelixLong(cubehelix_cubehelix(-100, 0.75, 0.35), cubehelix_cubehelix(80, 1.50, 0.8));

var cool = cubehelixLong(cubehelix_cubehelix(260, 0.75, 0.35), cubehelix_cubehelix(80, 1.50, 0.8));

var c = cubehelix_cubehelix();

/* harmony default export */ function rainbow(t) {
  if (t < 0 || t > 1) t -= Math.floor(t);
  var ts = Math.abs(t - 0.5);
  c.h = 360 * t - 100;
  c.s = 1.5 - 1.5 * ts;
  c.l = 0.8 - 0.9 * ts;
  return c + "";
}

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/diverging/Spectral.js



var Spectral_scheme = new Array(3).concat(
  "fc8d59ffffbf99d594",
  "d7191cfdae61abdda42b83ba",
  "d7191cfdae61ffffbfabdda42b83ba",
  "d53e4ffc8d59fee08be6f59899d5943288bd",
  "d53e4ffc8d59fee08bffffbfe6f59899d5943288bd",
  "d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd",
  "d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd",
  "9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2",
  "9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2"
).map(colors);

/* harmony default export */ const Spectral = (src_ramp(Spectral_scheme));

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-multi/cividis.js
/* harmony default export */ function cividis(t) {
  t = Math.max(0, Math.min(1, t));
  return "rgb("
      + Math.max(0, Math.min(255, Math.round(-4.54 - t * (35.34 - t * (2381.73 - t * (6402.7 - t * (7024.72 - t * 2710.57))))))) + ", "
      + Math.max(0, Math.min(255, Math.round(32.49 + t * (170.73 + t * (52.82 - t * (131.46 - t * (176.58 - t * 67.37))))))) + ", "
      + Math.max(0, Math.min(255, Math.round(81.24 + t * (442.36 - t * (2482.43 - t * (6167.24 - t * (6614.94 - t * 2475.67)))))))
      + ")";
}

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-multi/BuPu.js



var BuPu_scheme = new Array(3).concat(
  "e0ecf49ebcda8856a7",
  "edf8fbb3cde38c96c688419d",
  "edf8fbb3cde38c96c68856a7810f7c",
  "edf8fbbfd3e69ebcda8c96c68856a7810f7c",
  "edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b",
  "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b",
  "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b"
).map(colors);

/* harmony default export */ const BuPu = (src_ramp(BuPu_scheme));

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/diverging/RdBu.js



var RdBu_scheme = new Array(3).concat(
  "ef8a62f7f7f767a9cf",
  "ca0020f4a58292c5de0571b0",
  "ca0020f4a582f7f7f792c5de0571b0",
  "b2182bef8a62fddbc7d1e5f067a9cf2166ac",
  "b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac",
  "b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac",
  "b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac",
  "67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061",
  "67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061"
).map(colors);

/* harmony default export */ const RdBu = (src_ramp(RdBu_scheme));

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-multi/YlOrBr.js



var YlOrBr_scheme = new Array(3).concat(
  "fff7bcfec44fd95f0e",
  "ffffd4fed98efe9929cc4c02",
  "ffffd4fed98efe9929d95f0e993404",
  "ffffd4fee391fec44ffe9929d95f0e993404",
  "ffffd4fee391fec44ffe9929ec7014cc4c028c2d04",
  "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04",
  "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506"
).map(colors);

/* harmony default export */ const YlOrBr = (src_ramp(YlOrBr_scheme));

;// CONCATENATED MODULE: ./node_modules/d3-scale-chromatic/src/sequential-multi/RdPu.js



var RdPu_scheme = new Array(3).concat(
  "fde0ddfa9fb5c51b8a",
  "feebe2fbb4b9f768a1ae017e",
  "feebe2fbb4b9f768a1c51b8a7a0177",
  "feebe2fcc5c0fa9fb5f768a1c51b8a7a0177",
  "feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177",
  "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177",
  "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a"
).map(colors);

/* harmony default export */ const RdPu = (src_ramp(RdPu_scheme));

;// CONCATENATED MODULE: ./node_modules/higlass-register/src/index.js
window.higlassTracks = window.higlassTracks || {};
window.higlassTracksByType = window.higlassTracksByType || {};
window.higlassDataFetchersByType = window.higlassDataFetchersByType || {};

const getRandomName = () => Math.random().toString(36).substring(2, 8);

const registerTrack = (trackDef, { force = false } = {}) => {
  // The following is only needed for backward compatibility
  let name = getRandomName();
  while (window.higlassTracks[name]) {
    name = getRandomName();
  }

  trackDef.name = name;
  window.higlassTracks[trackDef.name] = trackDef;
  // backward compatibility: end

  if (window.higlassTracksByType[trackDef.config.type] && !force) {
    // eslint-disable-next-line
    console.warn(
      `A track with the same type (${trackDef.config.type}) was already ` +
      'registered. To override it, set force to true.',
    );
  } else {
    window.higlassTracksByType[trackDef.config.type] = trackDef;
  }
};

const registerDataFetcher = (dataFetcherDef, { force = false } = {}) => {
  if (window.higlassDataFetchersByType[dataFetcherDef.config.type] && !force) {
    // eslint-disable-next-line
    console.warn(
      `A data fetcher with the same type (${dataFetcherDef.config.type}) was already ` +
      'registered. To override it, set force to true.',
    );
  } else {
    window.higlassDataFetchersByType[dataFetcherDef.config.type] = dataFetcherDef;
  }
};

const register = (definition, options = {}) => {
  const { pluginType = 'track' } = options;
  if (pluginType === 'track') {
    registerTrack(definition, options);
  } else if (pluginType === 'dataFetcher') {
    registerDataFetcher(definition, options);
  }
};

/* harmony default export */ const src = (register);

// EXTERNAL MODULE: ./node_modules/higlass-text/node_modules/slugid/index.js
var slugid = __webpack_require__(1722);
;// CONCATENATED MODULE: ./node_modules/higlass-text/es/EmptyDataFetcher.js
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var EmptyDataFetcher = function () {
  function EmptyDataFetcher(dataConfig) {
    _classCallCheck(this, EmptyDataFetcher);

    this.dataConfig = dataConfig;
  }

  _createClass(EmptyDataFetcher, [{
    key: "tilesetInfo",
    value: function tilesetInfo(callback) {
      this.tilesetInfoLoading = false;

      // Dummy values - not actually used
      var TILE_SIZE = 1024;
      var MAX_ZOOM = 22;

      var retVal = {
        tile_size: TILE_SIZE,
        bins_per_dimension: TILE_SIZE,
        max_zoom: MAX_ZOOM,
        max_width: TILE_SIZE * Math.pow(2, MAX_ZOOM),
        min_pos: [0],
        max_pos: [3000000000]
      };

      if (callback) {
        callback(retVal);
      }

      return retVal;
    }
  }, {
    key: "fetchTilesDebounced",
    value: function fetchTilesDebounced(receivedTiles, tileIds) {
      var tiles = {};
      return tiles;
    }
  }, {
    key: "tile",
    value: function tile(z, x) {
      return this.tilesetInfo().then(function (tsInfo) {
        return [];
      });
    }
  }]);

  return EmptyDataFetcher;
}();

/* harmony default export */ const es_EmptyDataFetcher = (EmptyDataFetcher);
;// CONCATENATED MODULE: ./node_modules/higlass-text/es/TextTrack.js
var TextTrack_createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

function TextTrack_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }




var TextTrack = function TextTrack(HGC) {
  for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }

  // Services
  var tileProxy = HGC.services.tileProxy;

  // Utils

  var colorToHex = HGC.utils.colorToHex;

  var TextTrackClass = function (_HGC$tracks$BedLikeTr) {
    _inherits(TextTrackClass, _HGC$tracks$BedLikeTr);

    function TextTrackClass(context, options) {
      TextTrack_classCallCheck(this, TextTrackClass);

      context.dataFetcher = new es_EmptyDataFetcher(context.dataConfig);

      var _this = _possibleConstructorReturn(this, (TextTrackClass.__proto__ || Object.getPrototypeOf(TextTrackClass)).call(this, context, options));

      var animate = context.animate;

      _this.animate = animate;

      _this.isTrackShownVertically = context.definition.position === "left" || context.definition.position === "right";

      _this.options = options;
      _this.initOptions();
      return _this;
    }

    TextTrack_createClass(TextTrackClass, [{
      key: "initTile",
      value: function initTile(tile) {}
    }, {
      key: "initOptions",
      value: function initOptions() {
        this.fontSize = +this.options.fontSize;

        this.colors = {};
        this.colors["textColor"] = colorToHex(this.options.textColor);
        this.colors["black"] = colorToHex("#000000");
        this.colors["white"] = colorToHex("#ffffff");
        this.colors["lightgrey"] = colorToHex("#ededed");

        this.text = this.options.text;

        this.textOptions = {
          fontSize: this.fontSize + "px",
          fontFamily: this.options.fontFamily,
          fontWeight: this.options.fontWeight,
          fill: this.colors["textColor"]
        };
      }
    }, {
      key: "drawTile",
      value: function drawTile() {}

      /*
       * Redraw the track because the options
       * changed
       */

    }, {
      key: "rerender",
      value: function rerender(options, force) {
        var strOptions = JSON.stringify(options);
        if (!force && strOptions === this.prevOptions) return;

        this.options = options;
        this.initOptions();

        this.prevOptions = strOptions;

        this.renderText();

        requestAnimationFrame(this.animate);
      }
    }, {
      key: "drawTile",
      value: function drawTile(tile) {}
    }, {
      key: "renderTile",
      value: function renderTile(tile) {}
    }, {
      key: "draw",
      value: function draw() {}
    }, {
      key: "renderText",
      value: function renderText() {
        this.pForeground.clear();
        this.pForeground.removeChildren();

        var text = new HGC.libraries.PIXI.Text(this.text, this.textOptions);
        text.interactive = true;
        text.anchor.x = 0;
        text.anchor.y = 0;
        text.visible = true;
        text.y = this.options.offsetY;

        var margin = 5;
        text.x = margin;

        if (!this.isTrackShownVertically) {
          if (this.options.align === "left") {
            text.anchor.x = 0;
            text.x = margin;
            this.svgAnchor = "start";
          } else if (this.options.align === "middle") {
            text.anchor.x = 0.5;
            text.x = this.dimensions[0] / 2;
            this.svgAnchor = "middle";
          } else if (this.options.align === "right") {
            text.anchor.x = 1;
            text.x = this.dimensions[0] - margin;
            this.svgAnchor = "end";
          }
        } else {
          if (this.options.align === "right") {
            text.anchor.x = 1;
            text.scale.x *= -1;
            this.svgAnchor = "end";
          } else if (this.options.align === "middle") {
            text.anchor.x = 0.5;
            text.scale.x *= -1;
            text.x = this.dimensions[0] / 2;
            this.svgAnchor = "middle";
          } else if (this.options.align === "left") {
            text.anchor.x = 0;
            text.scale.x *= -1;
            text.x = this.dimensions[0] - margin;
            this.svgAnchor = "start";
          }
        }

        this.svgX = text.x;

        this.pForeground.addChild(text);
      }
    }, {
      key: "zoomedY",
      value: function zoomedY(yPos, kMultiplier) {}
    }, {
      key: "movedY",
      value: function movedY(dY) {}

      /** cleanup */

    }, {
      key: "destroyTile",
      value: function destroyTile(tile) {
        tile.graphics.destroy();
        tile = null;
      }
    }, {
      key: "setDimensions",
      value: function setDimensions(newDimensions) {
        _get(TextTrackClass.prototype.__proto__ || Object.getPrototypeOf(TextTrackClass.prototype), "setDimensions", this).call(this, newDimensions);
        // We have to rerender here, otherwise it does not fire at all sometimes
        this.rerender(this.options, false);
      }
    }, {
      key: "getMouseOverHtml",
      value: function getMouseOverHtml(trackX, trackY) {}
    }, {
      key: "exportSVG",
      value: function exportSVG() {
        var track = null;
        var base = null;

        base = document.createElement("g");
        track = base;

        var clipPathId = slugid.nice();

        var gClipPath = document.createElement("g");
        gClipPath.setAttribute("style", "clip-path:url(#" + clipPathId + ");");

        track.appendChild(gClipPath);

        // define the clipping area as a polygon defined by the track's
        // dimensions on the canvas
        var clipPath = document.createElementNS("http://www.w3.org/2000/svg", "clipPath");
        clipPath.setAttribute("id", clipPathId);
        track.appendChild(clipPath);

        var clipPolygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
        clipPath.appendChild(clipPolygon);

        clipPolygon.setAttribute("points", this.position[0] + "," + this.position[1] + " " + (this.position[0] + this.dimensions[0] + "," + this.position[1] + " ") + (this.position[0] + this.dimensions[0] + "," + (this.position[1] + this.dimensions[1]) + " ") + (this.position[0] + "," + (this.position[1] + this.dimensions[1]) + " "));

        var output = document.createElement("g");

        output.setAttribute("transform", "translate(" + this.position[0] + "," + this.position[1] + ")");

        gClipPath.appendChild(output);

        // Background
        var gBackground = document.createElement("g");
        var rBackground = document.createElement("path");
        var dBackground = "M 0 0 H " + this.dimensions[0] + " V " + this.dimensions[1] + " H 0 Z";
        rBackground.setAttribute("d", dBackground);
        rBackground.setAttribute("fill", this.options.backgroundColor);
        rBackground.setAttribute("opacity", "1");
        gBackground.appendChild(rBackground);
        output.appendChild(gBackground);

        // Text
        var gText = document.createElement("g");
        var t = document.createElement("text");
        t.setAttribute("text-anchor", this.svgAnchor);
        t.setAttribute("font-family", this.options.fontFamily);
        t.setAttribute("font-size", this.fontSize + "px");
        //t.setAttribute("alignment-baseline", "top");
        t.setAttribute("font-weight", this.options.fontWeight);

        gText.setAttribute("transform", "scale(1,1)");

        t.setAttribute("fill", this.options.textColor);
        t.innerHTML = this.options.text;

        var scalefactor = this.isTrackShownVertically ? -1 : 1;

        gText.appendChild(t);
        gText.setAttribute("transform", "translate(" + this.svgX + "," + (this.options.offsetY + this.fontSize) + ")scale(" + scalefactor + ",1)");
        output.appendChild(gText);

        return [base, base];
      }
    }]);

    return TextTrackClass;
  }(HGC.tracks.BedLikeTrack);

  return new (Function.prototype.bind.apply(TextTrackClass, [null].concat(args)))();
};

var icon = '<svg width="20" height="20" xmlns="http://www.w3.org/2000/svg"><path fill="#fff" d="M-1-1h22v22H-1z"/><g><path stroke="#007fff" stroke-width="1.5" fill="#007fff" d="M-.667-.091h5v20.167h-5z"/><path stroke-width="1.5" stroke="#e8e500" fill="#e8e500" d="M5.667.242h5v20.167h-5z"/><path stroke-width="1.5" stroke="#ff0038" fill="#ff0038" d="M15.833.076h5v20.167h-5z"/><path stroke="green" stroke-width="1.5" fill="green" d="M10.833-.258H14.5v20.167h-3.667z"/></g></svg>';

// default
TextTrack.config = {
  type: "text",
  datatype: ["bedlike"],
  local: false,
  orientation: "1d-horizontal",
  thumbnail: new DOMParser().parseFromString(icon, "text/xml").documentElement,
  availableOptions: ["backgroundColor", "textColor", "fontSize", "fontWeight", "offsetY", "align", "text"],
  defaultOptions: {
    backgroundColor: "#ededed",
    textColor: "#333333",
    fontSize: 14,
    fontFamily: "Arial",
    fontWeight: "normal",
    align: "left",
    offsetY: 0,
    text: ""
  }
};

/* harmony default export */ const es_TextTrack = (TextTrack);
;// CONCATENATED MODULE: ./node_modules/higlass-text/es/index.js



// EXTERNAL MODULE: ./node_modules/rbush/rbush.min.js
var rbush_min = __webpack_require__(2582);
var rbush_min_default = /*#__PURE__*/__webpack_require__.n(rbush_min);
;// CONCATENATED MODULE: ./node_modules/d3-path/src/path.js
const path_pi = Math.PI,
    path_tau = 2 * path_pi,
    path_epsilon = 1e-6,
    tauEpsilon = path_tau - path_epsilon;

function Path() {
  this._x0 = this._y0 = // start of current subpath
  this._x1 = this._y1 = null; // end of current subpath
  this._ = "";
}

function path() {
  return new Path;
}

Path.prototype = path.prototype = {
  constructor: Path,
  moveTo: function(x, y) {
    this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
  },
  closePath: function() {
    if (this._x1 !== null) {
      this._x1 = this._x0, this._y1 = this._y0;
      this._ += "Z";
    }
  },
  lineTo: function(x, y) {
    this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  quadraticCurveTo: function(x1, y1, x, y) {
    this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  bezierCurveTo: function(x1, y1, x2, y2, x, y) {
    this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
  },
  arcTo: function(x1, y1, x2, y2, r) {
    x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
    var x0 = this._x1,
        y0 = this._y1,
        x21 = x2 - x1,
        y21 = y2 - y1,
        x01 = x0 - x1,
        y01 = y0 - y1,
        l01_2 = x01 * x01 + y01 * y01;

    // Is the radius negative? Error.
    if (r < 0) throw new Error("negative radius: " + r);

    // Is this path empty? Move to (x1,y1).
    if (this._x1 === null) {
      this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
    }

    // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
    else if (!(l01_2 > path_epsilon));

    // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
    // Equivalently, is (x1,y1) coincident with (x2,y2)?
    // Or, is the radius zero? Line to (x1,y1).
    else if (!(Math.abs(y01 * x21 - y21 * x01) > path_epsilon) || !r) {
      this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
    }

    // Otherwise, draw an arc!
    else {
      var x20 = x2 - x0,
          y20 = y2 - y0,
          l21_2 = x21 * x21 + y21 * y21,
          l20_2 = x20 * x20 + y20 * y20,
          l21 = Math.sqrt(l21_2),
          l01 = Math.sqrt(l01_2),
          l = r * Math.tan((path_pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
          t01 = l / l01,
          t21 = l / l21;

      // If the start tangent is not coincident with (x0,y0), line to.
      if (Math.abs(t01 - 1) > path_epsilon) {
        this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
      }

      this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
    }
  },
  arc: function(x, y, r, a0, a1, ccw) {
    x = +x, y = +y, r = +r, ccw = !!ccw;
    var dx = r * Math.cos(a0),
        dy = r * Math.sin(a0),
        x0 = x + dx,
        y0 = y + dy,
        cw = 1 ^ ccw,
        da = ccw ? a0 - a1 : a1 - a0;

    // Is the radius negative? Error.
    if (r < 0) throw new Error("negative radius: " + r);

    // Is this path empty? Move to (x0,y0).
    if (this._x1 === null) {
      this._ += "M" + x0 + "," + y0;
    }

    // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
    else if (Math.abs(this._x1 - x0) > path_epsilon || Math.abs(this._y1 - y0) > path_epsilon) {
      this._ += "L" + x0 + "," + y0;
    }

    // Is this arc empty? We’re done.
    if (!r) return;

    // Does the angle go the wrong way? Flip the direction.
    if (da < 0) da = da % path_tau + path_tau;

    // Is this a complete circle? Draw two arcs to complete the circle.
    if (da > tauEpsilon) {
      this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
    }

    // Is this arc non-empty? Draw an arc!
    else if (da > path_epsilon) {
      this._ += "A" + r + "," + r + ",0," + (+(da >= path_pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
    }
  },
  rect: function(x, y, w, h) {
    this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z";
  },
  toString: function() {
    return this._;
  }
};

/* harmony default export */ const src_path = (path);

;// CONCATENATED MODULE: ./node_modules/d3-shape/src/constant.js
/* harmony default export */ function d3_shape_src_constant(x) {
  return function constant() {
    return x;
  };
}

;// CONCATENATED MODULE: ./node_modules/d3-shape/src/math.js
var math_abs = Math.abs;
var math_atan2 = Math.atan2;
var math_cos = Math.cos;
var math_max = Math.max;
var math_min = Math.min;
var math_sin = Math.sin;
var math_sqrt = Math.sqrt;

var math_epsilon = 1e-12;
var math_pi = Math.PI;
var halfPi = math_pi / 2;
var math_tau = 2 * math_pi;

function math_acos(x) {
  return x > 1 ? 0 : x < -1 ? math_pi : Math.acos(x);
}

function asin(x) {
  return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);
}

;// CONCATENATED MODULE: ./node_modules/d3-shape/src/arc.js




function arcInnerRadius(d) {
  return d.innerRadius;
}

function arcOuterRadius(d) {
  return d.outerRadius;
}

function arcStartAngle(d) {
  return d.startAngle;
}

function arcEndAngle(d) {
  return d.endAngle;
}

function arcPadAngle(d) {
  return d && d.padAngle; // Note: optional!
}

function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  var x10 = x1 - x0, y10 = y1 - y0,
      x32 = x3 - x2, y32 = y3 - y2,
      t = y32 * x10 - x32 * y10;
  if (t * t < math_epsilon) return;
  t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  return [x0 + t * x10, y0 + t * y10];
}

// Compute perpendicular offset line of length rc.
// http://mathworld.wolfram.com/Circle-LineIntersection.html
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
  var x01 = x0 - x1,
      y01 = y0 - y1,
      lo = (cw ? rc : -rc) / math_sqrt(x01 * x01 + y01 * y01),
      ox = lo * y01,
      oy = -lo * x01,
      x11 = x0 + ox,
      y11 = y0 + oy,
      x10 = x1 + ox,
      y10 = y1 + oy,
      x00 = (x11 + x10) / 2,
      y00 = (y11 + y10) / 2,
      dx = x10 - x11,
      dy = y10 - y11,
      d2 = dx * dx + dy * dy,
      r = r1 - rc,
      D = x11 * y10 - x10 * y11,
      d = (dy < 0 ? -1 : 1) * math_sqrt(math_max(0, r * r * d2 - D * D)),
      cx0 = (D * dy - dx * d) / d2,
      cy0 = (-D * dx - dy * d) / d2,
      cx1 = (D * dy + dx * d) / d2,
      cy1 = (-D * dx + dy * d) / d2,
      dx0 = cx0 - x00,
      dy0 = cy0 - y00,
      dx1 = cx1 - x00,
      dy1 = cy1 - y00;

  // Pick the closer of the two intersection points.
  // TODO Is there a faster way to determine which intersection to use?
  if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;

  return {
    cx: cx0,
    cy: cy0,
    x01: -ox,
    y01: -oy,
    x11: cx0 * (r1 / r - 1),
    y11: cy0 * (r1 / r - 1)
  };
}

/* harmony default export */ function arc() {
  var innerRadius = arcInnerRadius,
      outerRadius = arcOuterRadius,
      cornerRadius = d3_shape_src_constant(0),
      padRadius = null,
      startAngle = arcStartAngle,
      endAngle = arcEndAngle,
      padAngle = arcPadAngle,
      context = null;

  function arc() {
    var buffer,
        r,
        r0 = +innerRadius.apply(this, arguments),
        r1 = +outerRadius.apply(this, arguments),
        a0 = startAngle.apply(this, arguments) - halfPi,
        a1 = endAngle.apply(this, arguments) - halfPi,
        da = math_abs(a1 - a0),
        cw = a1 > a0;

    if (!context) context = buffer = src_path();

    // Ensure that the outer radius is always larger than the inner radius.
    if (r1 < r0) r = r1, r1 = r0, r0 = r;

    // Is it a point?
    if (!(r1 > math_epsilon)) context.moveTo(0, 0);

    // Or is it a circle or annulus?
    else if (da > math_tau - math_epsilon) {
      context.moveTo(r1 * math_cos(a0), r1 * math_sin(a0));
      context.arc(0, 0, r1, a0, a1, !cw);
      if (r0 > math_epsilon) {
        context.moveTo(r0 * math_cos(a1), r0 * math_sin(a1));
        context.arc(0, 0, r0, a1, a0, cw);
      }
    }

    // Or is it a circular or annular sector?
    else {
      var a01 = a0,
          a11 = a1,
          a00 = a0,
          a10 = a1,
          da0 = da,
          da1 = da,
          ap = padAngle.apply(this, arguments) / 2,
          rp = (ap > math_epsilon) && (padRadius ? +padRadius.apply(this, arguments) : math_sqrt(r0 * r0 + r1 * r1)),
          rc = math_min(math_abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),
          rc0 = rc,
          rc1 = rc,
          t0,
          t1;

      // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
      if (rp > math_epsilon) {
        var p0 = asin(rp / r0 * math_sin(ap)),
            p1 = asin(rp / r1 * math_sin(ap));
        if ((da0 -= p0 * 2) > math_epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;
        else da0 = 0, a00 = a10 = (a0 + a1) / 2;
        if ((da1 -= p1 * 2) > math_epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;
        else da1 = 0, a01 = a11 = (a0 + a1) / 2;
      }

      var x01 = r1 * math_cos(a01),
          y01 = r1 * math_sin(a01),
          x10 = r0 * math_cos(a10),
          y10 = r0 * math_sin(a10);

      // Apply rounded corners?
      if (rc > math_epsilon) {
        var x11 = r1 * math_cos(a11),
            y11 = r1 * math_sin(a11),
            x00 = r0 * math_cos(a00),
            y00 = r0 * math_sin(a00),
            oc;

        // Restrict the corner radius according to the sector angle.
        if (da < math_pi && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
          var ax = x01 - oc[0],
              ay = y01 - oc[1],
              bx = x11 - oc[0],
              by = y11 - oc[1],
              kc = 1 / math_sin(math_acos((ax * bx + ay * by) / (math_sqrt(ax * ax + ay * ay) * math_sqrt(bx * bx + by * by))) / 2),
              lc = math_sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = math_min(rc, (r0 - lc) / (kc - 1));
          rc1 = math_min(rc, (r1 - lc) / (kc + 1));
        }
      }

      // Is the sector collapsed to a line?
      if (!(da1 > math_epsilon)) context.moveTo(x01, y01);

      // Does the sector’s outer ring have rounded corners?
      else if (rc1 > math_epsilon) {
        t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
        t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);

        context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, math_atan2(t0.y01, t0.x01), math_atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc1, math_atan2(t0.y01, t0.x01), math_atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r1, math_atan2(t0.cy + t0.y11, t0.cx + t0.x11), math_atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
          context.arc(t1.cx, t1.cy, rc1, math_atan2(t1.y11, t1.x11), math_atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the outer ring just a circular arc?
      else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);

      // Is there no inner ring, and it’s a circular sector?
      // Or perhaps it’s an annular sector collapsed due to padding?
      if (!(r0 > math_epsilon) || !(da0 > math_epsilon)) context.lineTo(x10, y10);

      // Does the sector’s inner ring (or point) have rounded corners?
      else if (rc0 > math_epsilon) {
        t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
        t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);

        context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);

        // Have the corners merged?
        if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, math_atan2(t0.y01, t0.x01), math_atan2(t1.y01, t1.x01), !cw);

        // Otherwise, draw the two corners and the ring.
        else {
          context.arc(t0.cx, t0.cy, rc0, math_atan2(t0.y01, t0.x01), math_atan2(t0.y11, t0.x11), !cw);
          context.arc(0, 0, r0, math_atan2(t0.cy + t0.y11, t0.cx + t0.x11), math_atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
          context.arc(t1.cx, t1.cy, rc0, math_atan2(t1.y11, t1.x11), math_atan2(t1.y01, t1.x01), !cw);
        }
      }

      // Or is the inner ring just a circular arc?
      else context.arc(0, 0, r0, a10, a00, cw);
    }

    context.closePath();

    if (buffer) return context = null, buffer + "" || null;
  }

  arc.centroid = function() {
    var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,
        a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - math_pi / 2;
    return [math_cos(a) * r, math_sin(a) * r];
  };

  arc.innerRadius = function(_) {
    return arguments.length ? (innerRadius = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : innerRadius;
  };

  arc.outerRadius = function(_) {
    return arguments.length ? (outerRadius = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : outerRadius;
  };

  arc.cornerRadius = function(_) {
    return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : cornerRadius;
  };

  arc.padRadius = function(_) {
    return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : padRadius;
  };

  arc.startAngle = function(_) {
    return arguments.length ? (startAngle = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : startAngle;
  };

  arc.endAngle = function(_) {
    return arguments.length ? (endAngle = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : endAngle;
  };

  arc.padAngle = function(_) {
    return arguments.length ? (padAngle = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : padAngle;
  };

  arc.context = function(_) {
    return arguments.length ? ((context = _ == null ? null : _), arc) : context;
  };

  return arc;
}

;// CONCATENATED MODULE: ./node_modules/d3-dsv/src/dsv.js
var EOL = {},
    EOF = {},
    QUOTE = 34,
    NEWLINE = 10,
    RETURN = 13;

function objectConverter(columns) {
  return new Function("d", "return {" + columns.map(function(name, i) {
    return JSON.stringify(name) + ": d[" + i + "] || \"\"";
  }).join(",") + "}");
}

function customConverter(columns, f) {
  var object = objectConverter(columns);
  return function(row, i) {
    return f(object(row), i, columns);
  };
}

// Compute unique columns in order of discovery.
function inferColumns(rows) {
  var columnSet = Object.create(null),
      columns = [];

  rows.forEach(function(row) {
    for (var column in row) {
      if (!(column in columnSet)) {
        columns.push(columnSet[column] = column);
      }
    }
  });

  return columns;
}

function pad(value, width) {
  var s = value + "", length = s.length;
  return length < width ? new Array(width - length + 1).join(0) + s : s;
}

function formatYear(year) {
  return year < 0 ? "-" + pad(-year, 6)
    : year > 9999 ? "+" + pad(year, 6)
    : pad(year, 4);
}

function formatDate(date) {
  var hours = date.getUTCHours(),
      minutes = date.getUTCMinutes(),
      seconds = date.getUTCSeconds(),
      milliseconds = date.getUTCMilliseconds();
  return isNaN(date) ? "Invalid Date"
      : formatYear(date.getUTCFullYear(), 4) + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2)
      + (milliseconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "." + pad(milliseconds, 3) + "Z"
      : seconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "Z"
      : minutes || hours ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + "Z"
      : "");
}

/* harmony default export */ function dsv(delimiter) {
  var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
      DELIMITER = delimiter.charCodeAt(0);

  function parse(text, f) {
    var convert, columns, rows = parseRows(text, function(row, i) {
      if (convert) return convert(row, i - 1);
      columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
    });
    rows.columns = columns || [];
    return rows;
  }

  function parseRows(text, f) {
    var rows = [], // output rows
        N = text.length,
        I = 0, // current character index
        n = 0, // current line number
        t, // current token
        eof = N <= 0, // current token followed by EOF?
        eol = false; // current token followed by EOL?

    // Strip the trailing newline.
    if (text.charCodeAt(N - 1) === NEWLINE) --N;
    if (text.charCodeAt(N - 1) === RETURN) --N;

    function token() {
      if (eof) return EOF;
      if (eol) return eol = false, EOL;

      // Unescape quotes.
      var i, j = I, c;
      if (text.charCodeAt(j) === QUOTE) {
        while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);
        if ((i = I) >= N) eof = true;
        else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;
        else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
        return text.slice(j + 1, i - 1).replace(/""/g, "\"");
      }

      // Find next delimiter or newline.
      while (I < N) {
        if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
        else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
        else if (c !== DELIMITER) continue;
        return text.slice(j, i);
      }

      // Return last token before EOF.
      return eof = true, text.slice(j, N);
    }

    while ((t = token()) !== EOF) {
      var row = [];
      while (t !== EOL && t !== EOF) row.push(t), t = token();
      if (f && (row = f(row, n++)) == null) continue;
      rows.push(row);
    }

    return rows;
  }

  function preformatBody(rows, columns) {
    return rows.map(function(row) {
      return columns.map(function(column) {
        return formatValue(row[column]);
      }).join(delimiter);
    });
  }

  function format(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");
  }

  function formatBody(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return preformatBody(rows, columns).join("\n");
  }

  function formatRows(rows) {
    return rows.map(formatRow).join("\n");
  }

  function formatRow(row) {
    return row.map(formatValue).join(delimiter);
  }

  function formatValue(value) {
    return value == null ? ""
        : value instanceof Date ? formatDate(value)
        : reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\""
        : value;
  }

  return {
    parse: parse,
    parseRows: parseRows,
    format: format,
    formatBody: formatBody,
    formatRows: formatRows,
    formatRow: formatRow,
    formatValue: formatValue
  };
}

// EXTERNAL MODULE: ./node_modules/buffer/index.js
var buffer = __webpack_require__(8764);
;// CONCATENATED MODULE: ./node_modules/fflate/esm/browser.js
// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
// https://tools.ietf.org/html/rfc1951
// You may also wish to take a look at the guide I made about this program:
// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
// Some of the following code is similar to that of UZIP.js:
// https://github.com/photopea/UZIP.js
// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
// is better for memory in most engines (I *think*).
var ch2 = {};
var wk = (function (c, id, msg, transfer, cb) {
    var w = new Worker(ch2[id] || (ch2[id] = URL.createObjectURL(new Blob([
        c + ';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'
    ], { type: 'text/javascript' }))));
    w.onmessage = function (e) {
        var d = e.data, ed = d.$e$;
        if (ed) {
            var err = new Error(ed[0]);
            err['code'] = ed[1];
            err.stack = ed[2];
            cb(err, null);
        }
        else
            cb(null, d);
    };
    w.postMessage(msg, transfer);
    return w;
});

// aliases for shorter compressed code (most minifers don't do this)
var u8 = Uint8Array, u16 = Uint16Array, u32 = Uint32Array;
// fixed length extra bits
var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
// fixed distance extra bits
// see fleb note
var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
// code length index map
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
// get base, reverse index map from extra bits
var freb = function (eb, start) {
    var b = new u16(31);
    for (var i = 0; i < 31; ++i) {
        b[i] = start += 1 << eb[i - 1];
    }
    // numbers here are at max 18 bits
    var r = new u32(b[30]);
    for (var i = 1; i < 30; ++i) {
        for (var j = b[i]; j < b[i + 1]; ++j) {
            r[j] = ((j - b[i]) << 5) | i;
        }
    }
    return [b, r];
};
var _a = freb(fleb, 2), fl = _a[0], revfl = _a[1];
// we can ignore the fact that the other numbers are wrong; they never happen anyway
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0), fd = _b[0], revfd = _b[1];
// map of value to reverse (assuming 16 bits)
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
    // reverse table algorithm from SO
    var x = ((i & 0xAAAA) >>> 1) | ((i & 0x5555) << 1);
    x = ((x & 0xCCCC) >>> 2) | ((x & 0x3333) << 2);
    x = ((x & 0xF0F0) >>> 4) | ((x & 0x0F0F) << 4);
    rev[i] = (((x & 0xFF00) >>> 8) | ((x & 0x00FF) << 8)) >>> 1;
}
// create huffman tree from u8 "map": index -> code length for code index
// mb (max bits) must be at most 15
// TODO: optimize/split up?
var hMap = (function (cd, mb, r) {
    var s = cd.length;
    // index
    var i = 0;
    // u16 "map": index -> # of codes with bit length = index
    var l = new u16(mb);
    // length of cd must be 288 (total # of codes)
    for (; i < s; ++i) {
        if (cd[i])
            ++l[cd[i] - 1];
    }
    // u16 "map": index -> minimum code for bit length = index
    var le = new u16(mb);
    for (i = 0; i < mb; ++i) {
        le[i] = (le[i - 1] + l[i - 1]) << 1;
    }
    var co;
    if (r) {
        // u16 "map": index -> number of actual bits, symbol for code
        co = new u16(1 << mb);
        // bits to remove for reverser
        var rvb = 15 - mb;
        for (i = 0; i < s; ++i) {
            // ignore 0 lengths
            if (cd[i]) {
                // num encoding both symbol and bits read
                var sv = (i << 4) | cd[i];
                // free bits
                var r_1 = mb - cd[i];
                // start value
                var v = le[cd[i] - 1]++ << r_1;
                // m is end value
                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
                    // every 16 bit value starting with the code yields the same result
                    co[rev[v] >>> rvb] = sv;
                }
            }
        }
    }
    else {
        co = new u16(s);
        for (i = 0; i < s; ++i) {
            if (cd[i]) {
                co[i] = rev[le[cd[i] - 1]++] >>> (15 - cd[i]);
            }
        }
    }
    return co;
});
// fixed length tree
var flt = new u8(288);
for (var i = 0; i < 144; ++i)
    flt[i] = 8;
for (var i = 144; i < 256; ++i)
    flt[i] = 9;
for (var i = 256; i < 280; ++i)
    flt[i] = 7;
for (var i = 280; i < 288; ++i)
    flt[i] = 8;
// fixed distance tree
var fdt = new u8(32);
for (var i = 0; i < 32; ++i)
    fdt[i] = 5;
// fixed length map
var flm = /*#__PURE__*/ (/* unused pure expression or super */ null && (hMap(flt, 9, 0))), flrm = /*#__PURE__*/ hMap(flt, 9, 1);
// fixed distance map
var fdm = /*#__PURE__*/ (/* unused pure expression or super */ null && (hMap(fdt, 5, 0))), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
// find max of array
var browser_max = function (a) {
    var m = a[0];
    for (var i = 1; i < a.length; ++i) {
        if (a[i] > m)
            m = a[i];
    }
    return m;
};
// read d, starting at bit p and mask with m
var bits = function (d, p, m) {
    var o = (p / 8) | 0;
    return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
};
// read d, starting at bit p continuing for at least 16 bits
var bits16 = function (d, p) {
    var o = (p / 8) | 0;
    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
};
// get end of byte
var shft = function (p) { return ((p + 7) / 8) | 0; };
// typed array slice - allows garbage collector to free original reference,
// while being more compatible than .slice
var slc = function (v, s, e) {
    if (s == null || s < 0)
        s = 0;
    if (e == null || e > v.length)
        e = v.length;
    // can't use .constructor in case user-supplied
    var n = new (v.BYTES_PER_ELEMENT == 2 ? u16 : v.BYTES_PER_ELEMENT == 4 ? u32 : u8)(e - s);
    n.set(v.subarray(s, e));
    return n;
};
/**
 * Codes for errors generated within this library
 */
var FlateErrorCode = {
    UnexpectedEOF: 0,
    InvalidBlockType: 1,
    InvalidLengthLiteral: 2,
    InvalidDistance: 3,
    StreamFinished: 4,
    NoStreamHandler: 5,
    InvalidHeader: 6,
    NoCallback: 7,
    InvalidUTF8: 8,
    ExtraFieldTooLong: 9,
    InvalidDate: 10,
    FilenameTooLong: 11,
    StreamFinishing: 12,
    InvalidZipData: 13,
    UnknownCompressionMethod: 14
};
// error codes
var ec = [
    'unexpected EOF',
    'invalid block type',
    'invalid length/literal',
    'invalid distance',
    'stream finished',
    'no stream handler',
    ,
    'no callback',
    'invalid UTF-8 data',
    'extra field too long',
    'date not in range 1980-2099',
    'filename too long',
    'stream finishing',
    'invalid zip data'
    // determined by unknown compression method
];
;
var err = function (ind, msg, nt) {
    var e = new Error(msg || ec[ind]);
    e.code = ind;
    if (Error.captureStackTrace)
        Error.captureStackTrace(e, err);
    if (!nt)
        throw e;
    return e;
};
// expands raw DEFLATE data
var inflt = function (dat, buf, st) {
    // source length
    var sl = dat.length;
    if (!sl || (st && st.f && !st.l))
        return buf || new u8(0);
    // have to estimate size
    var noBuf = !buf || st;
    // no state
    var noSt = !st || st.i;
    if (!st)
        st = {};
    // Assumes roughly 33% compression ratio average
    if (!buf)
        buf = new u8(sl * 3);
    // ensure buffer can fit at least l elements
    var cbuf = function (l) {
        var bl = buf.length;
        // need to increase size to fit
        if (l > bl) {
            // Double or set to necessary, whichever is greater
            var nbuf = new u8(Math.max(bl * 2, l));
            nbuf.set(buf);
            buf = nbuf;
        }
    };
    //  last chunk         bitpos           bytes
    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
    // total bits
    var tbts = sl * 8;
    do {
        if (!lm) {
            // BFINAL - this is only 1 when last chunk is next
            final = bits(dat, pos, 1);
            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
            var type = bits(dat, pos + 1, 3);
            pos += 3;
            if (!type) {
                // go to end of byte boundary
                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
                if (t > sl) {
                    if (noSt)
                        err(0);
                    break;
                }
                // ensure size
                if (noBuf)
                    cbuf(bt + l);
                // Copy over uncompressed data
                buf.set(dat.subarray(s, t), bt);
                // Get new bitpos, update byte count
                st.b = bt += l, st.p = pos = t * 8, st.f = final;
                continue;
            }
            else if (type == 1)
                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
            else if (type == 2) {
                //  literal                            lengths
                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
                var tl = hLit + bits(dat, pos + 5, 31) + 1;
                pos += 14;
                // length+distance tree
                var ldt = new u8(tl);
                // code length tree
                var clt = new u8(19);
                for (var i = 0; i < hcLen; ++i) {
                    // use index map to get real code
                    clt[clim[i]] = bits(dat, pos + i * 3, 7);
                }
                pos += hcLen * 3;
                // code lengths bits
                var clb = browser_max(clt), clbmsk = (1 << clb) - 1;
                // code lengths map
                var clm = hMap(clt, clb, 1);
                for (var i = 0; i < tl;) {
                    var r = clm[bits(dat, pos, clbmsk)];
                    // bits read
                    pos += r & 15;
                    // symbol
                    var s = r >>> 4;
                    // code length to copy
                    if (s < 16) {
                        ldt[i++] = s;
                    }
                    else {
                        //  copy   count
                        var c = 0, n = 0;
                        if (s == 16)
                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
                        else if (s == 17)
                            n = 3 + bits(dat, pos, 7), pos += 3;
                        else if (s == 18)
                            n = 11 + bits(dat, pos, 127), pos += 7;
                        while (n--)
                            ldt[i++] = c;
                    }
                }
                //    length tree                 distance tree
                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
                // max length bits
                lbt = browser_max(lt);
                // max dist bits
                dbt = browser_max(dt);
                lm = hMap(lt, lbt, 1);
                dm = hMap(dt, dbt, 1);
            }
            else
                err(1);
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
        }
        // Make sure the buffer can hold this + the largest possible addition
        // Maximum chunk size (practically, theoretically infinite) is 2^17;
        if (noBuf)
            cbuf(bt + 131072);
        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
        var lpos = pos;
        for (;; lpos = pos) {
            // bits read, code
            var c = lm[bits16(dat, pos) & lms], sym = c >>> 4;
            pos += c & 15;
            if (pos > tbts) {
                if (noSt)
                    err(0);
                break;
            }
            if (!c)
                err(2);
            if (sym < 256)
                buf[bt++] = sym;
            else if (sym == 256) {
                lpos = pos, lm = null;
                break;
            }
            else {
                var add = sym - 254;
                // no extra bits needed if less
                if (sym > 264) {
                    // index
                    var i = sym - 257, b = fleb[i];
                    add = bits(dat, pos, (1 << b) - 1) + fl[i];
                    pos += b;
                }
                // dist
                var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4;
                if (!d)
                    err(3);
                pos += d & 15;
                var dt = fd[dsym];
                if (dsym > 3) {
                    var b = fdeb[dsym];
                    dt += bits16(dat, pos) & ((1 << b) - 1), pos += b;
                }
                if (pos > tbts) {
                    if (noSt)
                        err(0);
                    break;
                }
                if (noBuf)
                    cbuf(bt + 131072);
                var end = bt + add;
                for (; bt < end; bt += 4) {
                    buf[bt] = buf[bt - dt];
                    buf[bt + 1] = buf[bt + 1 - dt];
                    buf[bt + 2] = buf[bt + 2 - dt];
                    buf[bt + 3] = buf[bt + 3 - dt];
                }
                bt = end;
            }
        }
        st.l = lm, st.p = lpos, st.b = bt, st.f = final;
        if (lm)
            final = 1, st.m = lbt, st.d = dm, st.n = dbt;
    } while (!final);
    return bt == buf.length ? buf : slc(buf, 0, bt);
};
// starting at p, write the minimum number of bits that can hold v to d
var wbits = function (d, p, v) {
    v <<= p & 7;
    var o = (p / 8) | 0;
    d[o] |= v;
    d[o + 1] |= v >>> 8;
};
// starting at p, write the minimum number of bits (>8) that can hold v to d
var wbits16 = function (d, p, v) {
    v <<= p & 7;
    var o = (p / 8) | 0;
    d[o] |= v;
    d[o + 1] |= v >>> 8;
    d[o + 2] |= v >>> 16;
};
// creates code lengths from a frequency table
var hTree = function (d, mb) {
    // Need extra info to make a tree
    var t = [];
    for (var i = 0; i < d.length; ++i) {
        if (d[i])
            t.push({ s: i, f: d[i] });
    }
    var s = t.length;
    var t2 = t.slice();
    if (!s)
        return [et, 0];
    if (s == 1) {
        var v = new u8(t[0].s + 1);
        v[t[0].s] = 1;
        return [v, 1];
    }
    t.sort(function (a, b) { return a.f - b.f; });
    // after i2 reaches last ind, will be stopped
    // freq must be greater than largest possible number of symbols
    t.push({ s: -1, f: 25001 });
    var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
    t[0] = { s: -1, f: l.f + r.f, l: l, r: r };
    // efficient algorithm from UZIP.js
    // i0 is lookbehind, i2 is lookahead - after processing two low-freq
    // symbols that combined have high freq, will start processing i2 (high-freq,
    // non-composite) symbols instead
    // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
    while (i1 != s - 1) {
        l = t[t[i0].f < t[i2].f ? i0++ : i2++];
        r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
        t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };
    }
    var maxSym = t2[0].s;
    for (var i = 1; i < s; ++i) {
        if (t2[i].s > maxSym)
            maxSym = t2[i].s;
    }
    // code lengths
    var tr = new u16(maxSym + 1);
    // max bits in tree
    var mbt = ln(t[i1 - 1], tr, 0);
    if (mbt > mb) {
        // more algorithms from UZIP.js
        // TODO: find out how this code works (debt)
        //  ind    debt
        var i = 0, dt = 0;
        //    left            cost
        var lft = mbt - mb, cst = 1 << lft;
        t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });
        for (; i < s; ++i) {
            var i2_1 = t2[i].s;
            if (tr[i2_1] > mb) {
                dt += cst - (1 << (mbt - tr[i2_1]));
                tr[i2_1] = mb;
            }
            else
                break;
        }
        dt >>>= lft;
        while (dt > 0) {
            var i2_2 = t2[i].s;
            if (tr[i2_2] < mb)
                dt -= 1 << (mb - tr[i2_2]++ - 1);
            else
                ++i;
        }
        for (; i >= 0 && dt; --i) {
            var i2_3 = t2[i].s;
            if (tr[i2_3] == mb) {
                --tr[i2_3];
                ++dt;
            }
        }
        mbt = mb;
    }
    return [new u8(tr), mbt];
};
// get the max length and assign length codes
var ln = function (n, l, d) {
    return n.s == -1
        ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))
        : (l[n.s] = d);
};
// length codes generation
var lc = function (c) {
    var s = c.length;
    // Note that the semicolon was intentional
    while (s && !c[--s])
        ;
    var cl = new u16(++s);
    //  ind      num         streak
    var cli = 0, cln = c[0], cls = 1;
    var w = function (v) { cl[cli++] = v; };
    for (var i = 1; i <= s; ++i) {
        if (c[i] == cln && i != s)
            ++cls;
        else {
            if (!cln && cls > 2) {
                for (; cls > 138; cls -= 138)
                    w(32754);
                if (cls > 2) {
                    w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);
                    cls = 0;
                }
            }
            else if (cls > 3) {
                w(cln), --cls;
                for (; cls > 6; cls -= 6)
                    w(8304);
                if (cls > 2)
                    w(((cls - 3) << 5) | 8208), cls = 0;
            }
            while (cls--)
                w(cln);
            cls = 1;
            cln = c[i];
        }
    }
    return [cl.subarray(0, cli), s];
};
// calculate the length of output from tree, code lengths
var clen = function (cf, cl) {
    var l = 0;
    for (var i = 0; i < cl.length; ++i)
        l += cf[i] * cl[i];
    return l;
};
// writes a fixed block
// returns the new bit pos
var wfblk = function (out, pos, dat) {
    // no need to write 00 as type: TypedArray defaults to 0
    var s = dat.length;
    var o = shft(pos + 2);
    out[o] = s & 255;
    out[o + 1] = s >>> 8;
    out[o + 2] = out[o] ^ 255;
    out[o + 3] = out[o + 1] ^ 255;
    for (var i = 0; i < s; ++i)
        out[o + i + 4] = dat[i];
    return (o + 4 + s) * 8;
};
// writes a block
var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
    wbits(out, p++, final);
    ++lf[256];
    var _a = hTree(lf, 15), dlt = _a[0], mlb = _a[1];
    var _b = hTree(df, 15), ddt = _b[0], mdb = _b[1];
    var _c = lc(dlt), lclt = _c[0], nlc = _c[1];
    var _d = lc(ddt), lcdt = _d[0], ndc = _d[1];
    var lcfreq = new u16(19);
    for (var i = 0; i < lclt.length; ++i)
        lcfreq[lclt[i] & 31]++;
    for (var i = 0; i < lcdt.length; ++i)
        lcfreq[lcdt[i] & 31]++;
    var _e = hTree(lcfreq, 7), lct = _e[0], mlcb = _e[1];
    var nlcc = 19;
    for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
        ;
    var flen = (bl + 5) << 3;
    var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
    var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]);
    if (flen <= ftlen && flen <= dtlen)
        return wfblk(out, p, dat.subarray(bs, bs + bl));
    var lm, ll, dm, dl;
    wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
    if (dtlen < ftlen) {
        lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
        var llm = hMap(lct, mlcb, 0);
        wbits(out, p, nlc - 257);
        wbits(out, p + 5, ndc - 1);
        wbits(out, p + 10, nlcc - 4);
        p += 14;
        for (var i = 0; i < nlcc; ++i)
            wbits(out, p + 3 * i, lct[clim[i]]);
        p += 3 * nlcc;
        var lcts = [lclt, lcdt];
        for (var it = 0; it < 2; ++it) {
            var clct = lcts[it];
            for (var i = 0; i < clct.length; ++i) {
                var len = clct[i] & 31;
                wbits(out, p, llm[len]), p += lct[len];
                if (len > 15)
                    wbits(out, p, (clct[i] >>> 5) & 127), p += clct[i] >>> 12;
            }
        }
    }
    else {
        lm = flm, ll = flt, dm = fdm, dl = fdt;
    }
    for (var i = 0; i < li; ++i) {
        if (syms[i] > 255) {
            var len = (syms[i] >>> 18) & 31;
            wbits16(out, p, lm[len + 257]), p += ll[len + 257];
            if (len > 7)
                wbits(out, p, (syms[i] >>> 23) & 31), p += fleb[len];
            var dst = syms[i] & 31;
            wbits16(out, p, dm[dst]), p += dl[dst];
            if (dst > 3)
                wbits16(out, p, (syms[i] >>> 5) & 8191), p += fdeb[dst];
        }
        else {
            wbits16(out, p, lm[syms[i]]), p += ll[syms[i]];
        }
    }
    wbits16(out, p, lm[256]);
    return p + ll[256];
};
// deflate options (nice << 13) | chain
var deo = /*#__PURE__*/ new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
// empty
var et = /*#__PURE__*/ new u8(0);
// compresses data into a raw DEFLATE buffer
var dflt = function (dat, lvl, plvl, pre, post, lst) {
    var s = dat.length;
    var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
    // writing to this writes to the output buffer
    var w = o.subarray(pre, o.length - post);
    var pos = 0;
    if (!lvl || s < 8) {
        for (var i = 0; i <= s; i += 65535) {
            // end
            var e = i + 65535;
            if (e >= s) {
                // write final block
                w[pos >> 3] = lst;
            }
            pos = wfblk(w, pos + 1, dat.subarray(i, e));
        }
    }
    else {
        var opt = deo[lvl - 1];
        var n = opt >>> 13, c = opt & 8191;
        var msk_1 = (1 << plvl) - 1;
        //    prev 2-byte val map    curr 2-byte val map
        var prev = new u16(32768), head = new u16(msk_1 + 1);
        var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
        var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };
        // 24576 is an arbitrary number of maximum symbols per block
        // 424 buffer for last block
        var syms = new u32(25000);
        // length/literal freq   distance freq
        var lf = new u16(288), df = new u16(32);
        //  l/lcnt  exbits  index  l/lind  waitdx  bitpos
        var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0;
        for (; i < s; ++i) {
            // hash value
            // deopt when i > s - 3 - at end, deopt acceptable
            var hv = hsh(i);
            // index mod 32768    previous index mod
            var imod = i & 32767, pimod = head[hv];
            prev[imod] = pimod;
            head[hv] = imod;
            // We always should modify head and prev, but only add symbols if
            // this data is not yet processed ("wait" for wait index)
            if (wi <= i) {
                // bytes remaining
                var rem = s - i;
                if ((lc_1 > 7000 || li > 24576) && rem > 423) {
                    pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
                    li = lc_1 = eb = 0, bs = i;
                    for (var j = 0; j < 286; ++j)
                        lf[j] = 0;
                    for (var j = 0; j < 30; ++j)
                        df[j] = 0;
                }
                //  len    dist   chain
                var l = 2, d = 0, ch_1 = c, dif = (imod - pimod) & 32767;
                if (rem > 2 && hv == hsh(i - dif)) {
                    var maxn = Math.min(n, rem) - 1;
                    var maxd = Math.min(32767, i);
                    // max possible length
                    // not capped at dif because decompressors implement "rolling" index population
                    var ml = Math.min(258, rem);
                    while (dif <= maxd && --ch_1 && imod != pimod) {
                        if (dat[i + l] == dat[i + l - dif]) {
                            var nl = 0;
                            for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
                                ;
                            if (nl > l) {
                                l = nl, d = dif;
                                // break out early when we reach "nice" (we are satisfied enough)
                                if (nl > maxn)
                                    break;
                                // now, find the rarest 2-byte sequence within this
                                // length of literals and search for that instead.
                                // Much faster than just using the start
                                var mmd = Math.min(dif, nl - 2);
                                var md = 0;
                                for (var j = 0; j < mmd; ++j) {
                                    var ti = (i - dif + j + 32768) & 32767;
                                    var pti = prev[ti];
                                    var cd = (ti - pti + 32768) & 32767;
                                    if (cd > md)
                                        md = cd, pimod = ti;
                                }
                            }
                        }
                        // check the previous match
                        imod = pimod, pimod = prev[imod];
                        dif += (imod - pimod + 32768) & 32767;
                    }
                }
                // d will be nonzero only when a match was found
                if (d) {
                    // store both dist and len data in one Uint32
                    // Make sure this is recognized as a len/dist with 28th bit (2^28)
                    syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];
                    var lin = revfl[l] & 31, din = revfd[d] & 31;
                    eb += fleb[lin] + fdeb[din];
                    ++lf[257 + lin];
                    ++df[din];
                    wi = i + l;
                    ++lc_1;
                }
                else {
                    syms[li++] = dat[i];
                    ++lf[dat[i]];
                }
            }
        }
        pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
        // this is the easiest way to avoid needing to maintain state
        if (!lst && pos & 7)
            pos = wfblk(w, pos + 1, et);
    }
    return slc(o, 0, pre + shft(pos) + post);
};
// CRC32 table
var crct = /*#__PURE__*/ (/* unused pure expression or super */ null && ((function () {
    var t = new Int32Array(256);
    for (var i = 0; i < 256; ++i) {
        var c = i, k = 9;
        while (--k)
            c = ((c & 1) && -306674912) ^ (c >>> 1);
        t[i] = c;
    }
    return t;
})()));
// CRC32
var crc = function () {
    var c = -1;
    return {
        p: function (d) {
            // closures have awful performance
            var cr = c;
            for (var i = 0; i < d.length; ++i)
                cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);
            c = cr;
        },
        d: function () { return ~c; }
    };
};
// Alder32
var adler = function () {
    var a = 1, b = 0;
    return {
        p: function (d) {
            // closures have awful performance
            var n = a, m = b;
            var l = d.length | 0;
            for (var i = 0; i != l;) {
                var e = Math.min(i + 2655, l);
                for (; i < e; ++i)
                    m += n += d[i];
                n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
            }
            a = n, b = m;
        },
        d: function () {
            a %= 65521, b %= 65521;
            return (a & 255) << 24 | (a >>> 8) << 16 | (b & 255) << 8 | (b >>> 8);
        }
    };
};
;
// deflate with opts
var dopt = function (dat, opt, pre, post, st) {
    return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : (12 + opt.mem), pre, post, !st);
};
// Walmart object spread
var mrg = function (a, b) {
    var o = {};
    for (var k in a)
        o[k] = a[k];
    for (var k in b)
        o[k] = b[k];
    return o;
};
// worker clone
// This is possibly the craziest part of the entire codebase, despite how simple it may seem.
// The only parameter to this function is a closure that returns an array of variables outside of the function scope.
// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.
// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).
// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.
// This took me three weeks to figure out how to do.
var wcln = function (fn, fnStr, td) {
    var dt = fn();
    var st = fn.toString();
    var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(',');
    for (var i = 0; i < dt.length; ++i) {
        var v = dt[i], k = ks[i];
        if (typeof v == 'function') {
            fnStr += ';' + k + '=';
            var st_1 = v.toString();
            if (v.prototype) {
                // for global objects
                if (st_1.indexOf('[native code]') != -1) {
                    var spInd = st_1.indexOf(' ', 8) + 1;
                    fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));
                }
                else {
                    fnStr += st_1;
                    for (var t in v.prototype)
                        fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
                }
            }
            else
                fnStr += st_1;
        }
        else
            td[k] = v;
    }
    return [fnStr, td];
};
var ch = (/* unused pure expression or super */ null && ([]));
// clone bufs
var cbfs = function (v) {
    var tl = [];
    for (var k in v) {
        if (v[k].buffer) {
            tl.push((v[k] = new v[k].constructor(v[k])).buffer);
        }
    }
    return tl;
};
// use a worker to execute code
var wrkr = function (fns, init, id, cb) {
    var _a;
    if (!ch[id]) {
        var fnStr = '', td_1 = {}, m = fns.length - 1;
        for (var i = 0; i < m; ++i)
            _a = wcln(fns[i], fnStr, td_1), fnStr = _a[0], td_1 = _a[1];
        ch[id] = wcln(fns[m], fnStr, td_1);
    }
    var td = mrg({}, ch[id][1]);
    return wk(ch[id][0] + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);
};
// base async inflate fn
var bInflt = function () { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, browser_max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gu8]; };
var bDflt = function () { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };
// gzip extra
var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };
// gunzip extra
var guze = function () { return [gzs, gzl]; };
// zlib extra
var zle = function () { return [zlh, wbytes, adler]; };
// unzlib extra
var zule = function () { return [zlv]; };
// post buf
var pbf = function (msg) { return postMessage(msg, [msg.buffer]); };
// get u8
var gu8 = function (o) { return o && o.size && new u8(o.size); };
// async helper
var cbify = function (dat, opts, fns, init, id, cb) {
    var w = wrkr(fns, init, id, function (err, dat) {
        w.terminate();
        cb(err, dat);
    });
    w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);
    return function () { w.terminate(); };
};
// auto stream
var astrm = function (strm) {
    strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };
    return function (ev) { return strm.push(ev.data[0], ev.data[1]); };
};
// async stream attach
var astrmify = function (fns, strm, opts, init, id) {
    var t;
    var w = wrkr(fns, init, id, function (err, dat) {
        if (err)
            w.terminate(), strm.ondata.call(strm, err);
        else {
            if (dat[1])
                w.terminate();
            strm.ondata.call(strm, err, dat[0], dat[1]);
        }
    });
    w.postMessage(opts);
    strm.push = function (d, f) {
        if (!strm.ondata)
            err(5);
        if (t)
            strm.ondata(err(4, 0, 1), null, !!f);
        w.postMessage([d, t = f], [d.buffer]);
    };
    strm.terminate = function () { w.terminate(); };
};
// read 2 bytes
var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };
// read 4 bytes
var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };
var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };
// write bytes
var wbytes = function (d, b, v) {
    for (; v; ++b)
        d[b] = v, v >>>= 8;
};
// gzip header
var gzh = function (c, o) {
    var fn = o.filename;
    c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix
    if (o.mtime != 0)
        wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));
    if (fn) {
        c[3] = 8;
        for (var i = 0; i <= fn.length; ++i)
            c[i + 10] = fn.charCodeAt(i);
    }
};
// gzip footer: -8 to -4 = CRC, -4 to -0 is length
// gzip start
var gzs = function (d) {
    if (d[0] != 31 || d[1] != 139 || d[2] != 8)
        err(6, 'invalid gzip data');
    var flg = d[3];
    var st = 10;
    if (flg & 4)
        st += d[10] | (d[11] << 8) + 2;
    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
        ;
    return st + (flg & 2);
};
// gzip length
var gzl = function (d) {
    var l = d.length;
    return ((d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16) | (d[l - 1] << 24)) >>> 0;
};
// gzip header length
var gzhl = function (o) { return 10 + ((o.filename && (o.filename.length + 1)) || 0); };
// zlib header
var zlh = function (c, o) {
    var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
    c[0] = 120, c[1] = (fl << 6) | (fl ? (32 - 2 * fl) : 1);
};
// zlib valid
var zlv = function (d) {
    if ((d[0] & 15) != 8 || (d[0] >>> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
        err(6, 'invalid zlib data');
    if (d[1] & 32)
        err(6, 'invalid zlib data: preset dictionaries not supported');
};
function AsyncCmpStrm(opts, cb) {
    if (!cb && typeof opts == 'function')
        cb = opts, opts = {};
    this.ondata = cb;
    return opts;
}
// zlib footer: -4 to -0 is Adler32
/**
 * Streaming DEFLATE compression
 */
var Deflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function Deflate(opts, cb) {
        if (!cb && typeof opts == 'function')
            cb = opts, opts = {};
        this.ondata = cb;
        this.o = opts || {};
    }
    Deflate.prototype.p = function (c, f) {
        this.ondata(dopt(c, this.o, 0, 0, !f), f);
    };
    /**
     * Pushes a chunk to be deflated
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Deflate.prototype.push = function (chunk, final) {
        if (!this.ondata)
            err(5);
        if (this.d)
            err(4);
        this.d = final;
        this.p(chunk, final || false);
    };
    return Deflate;
}())));

/**
 * Asynchronous streaming DEFLATE compression
 */
var AsyncDeflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function AsyncDeflate(opts, cb) {
        astrmify([
            bDflt,
            function () { return [astrm, Deflate]; }
        ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
            var strm = new Deflate(ev.data);
            onmessage = astrm(strm);
        }, 6);
    }
    return AsyncDeflate;
}())));

function deflate(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return cbify(data, opts, [
        bDflt,
    ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);
}
/**
 * Compresses data with DEFLATE without any wrapper
 * @param data The data to compress
 * @param opts The compression options
 * @returns The deflated version of the data
 */
function deflateSync(data, opts) {
    return dopt(data, opts || {}, 0, 0);
}
/**
 * Streaming DEFLATE decompression
 */
var Inflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates an inflation stream
     * @param cb The callback to call whenever data is inflated
     */
    function Inflate(cb) {
        this.s = {};
        this.p = new u8(0);
        this.ondata = cb;
    }
    Inflate.prototype.e = function (c) {
        if (!this.ondata)
            err(5);
        if (this.d)
            err(4);
        var l = this.p.length;
        var n = new u8(l + c.length);
        n.set(this.p), n.set(c, l), this.p = n;
    };
    Inflate.prototype.c = function (final) {
        this.d = this.s.i = final || false;
        var bts = this.s.b;
        var dt = inflt(this.p, this.o, this.s);
        this.ondata(slc(dt, bts, this.s.b), this.d);
        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
        this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;
    };
    /**
     * Pushes a chunk to be inflated
     * @param chunk The chunk to push
     * @param final Whether this is the final chunk
     */
    Inflate.prototype.push = function (chunk, final) {
        this.e(chunk), this.c(final);
    };
    return Inflate;
}())));

/**
 * Asynchronous streaming DEFLATE decompression
 */
var AsyncInflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates an asynchronous inflation stream
     * @param cb The callback to call whenever data is deflated
     */
    function AsyncInflate(cb) {
        this.ondata = cb;
        astrmify([
            bInflt,
            function () { return [astrm, Inflate]; }
        ], this, 0, function () {
            var strm = new Inflate();
            onmessage = astrm(strm);
        }, 7);
    }
    return AsyncInflate;
}())));

function inflate(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return cbify(data, opts, [
        bInflt
    ], function (ev) { return pbf(inflateSync(ev.data[0], gu8(ev.data[1]))); }, 1, cb);
}
/**
 * Expands DEFLATE data with no wrapper
 * @param data The data to decompress
 * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
 * @returns The decompressed version of the data
 */
function inflateSync(data, out) {
    return inflt(data, out);
}
// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.
/**
 * Streaming GZIP compression
 */
var Gzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function Gzip(opts, cb) {
        this.c = crc();
        this.l = 0;
        this.v = 1;
        Deflate.call(this, opts, cb);
    }
    /**
     * Pushes a chunk to be GZIPped
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Gzip.prototype.push = function (chunk, final) {
        Deflate.prototype.push.call(this, chunk, final);
    };
    Gzip.prototype.p = function (c, f) {
        this.c.p(c);
        this.l += c.length;
        var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f);
        if (this.v)
            gzh(raw, this.o), this.v = 0;
        if (f)
            wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);
        this.ondata(raw, f);
    };
    return Gzip;
}())));

/**
 * Asynchronous streaming GZIP compression
 */
var AsyncGzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function AsyncGzip(opts, cb) {
        astrmify([
            bDflt,
            gze,
            function () { return [astrm, Deflate, Gzip]; }
        ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
            var strm = new Gzip(ev.data);
            onmessage = astrm(strm);
        }, 8);
    }
    return AsyncGzip;
}())));

function gzip(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return cbify(data, opts, [
        bDflt,
        gze,
        function () { return [gzipSync]; }
    ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);
}
/**
 * Compresses data with GZIP
 * @param data The data to compress
 * @param opts The compression options
 * @returns The gzipped version of the data
 */
function gzipSync(data, opts) {
    if (!opts)
        opts = {};
    var c = crc(), l = data.length;
    c.p(data);
    var d = dopt(data, opts, gzhl(opts), 8), s = d.length;
    return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;
}
/**
 * Streaming GZIP decompression
 */
var Gunzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a GUNZIP stream
     * @param cb The callback to call whenever data is inflated
     */
    function Gunzip(cb) {
        this.v = 1;
        Inflate.call(this, cb);
    }
    /**
     * Pushes a chunk to be GUNZIPped
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Gunzip.prototype.push = function (chunk, final) {
        Inflate.prototype.e.call(this, chunk);
        if (this.v) {
            var s = this.p.length > 3 ? gzs(this.p) : 4;
            if (s >= this.p.length && !final)
                return;
            this.p = this.p.subarray(s), this.v = 0;
        }
        if (final) {
            if (this.p.length < 8)
                err(6, 'invalid gzip data');
            this.p = this.p.subarray(0, -8);
        }
        // necessary to prevent TS from using the closure value
        // This allows for workerization to function correctly
        Inflate.prototype.c.call(this, final);
    };
    return Gunzip;
}())));

/**
 * Asynchronous streaming GZIP decompression
 */
var AsyncGunzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates an asynchronous GUNZIP stream
     * @param cb The callback to call whenever data is deflated
     */
    function AsyncGunzip(cb) {
        this.ondata = cb;
        astrmify([
            bInflt,
            guze,
            function () { return [astrm, Inflate, Gunzip]; }
        ], this, 0, function () {
            var strm = new Gunzip();
            onmessage = astrm(strm);
        }, 9);
    }
    return AsyncGunzip;
}())));

function gunzip(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return cbify(data, opts, [
        bInflt,
        guze,
        function () { return [gunzipSync]; }
    ], function (ev) { return pbf(gunzipSync(ev.data[0])); }, 3, cb);
}
/**
 * Expands GZIP data
 * @param data The data to decompress
 * @param out Where to write the data. GZIP already encodes the output size, so providing this doesn't save memory.
 * @returns The decompressed version of the data
 */
function gunzipSync(data, out) {
    return inflt(data.subarray(gzs(data), -8), out || new u8(gzl(data)));
}
/**
 * Streaming Zlib compression
 */
var Zlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function Zlib(opts, cb) {
        this.c = adler();
        this.v = 1;
        Deflate.call(this, opts, cb);
    }
    /**
     * Pushes a chunk to be zlibbed
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Zlib.prototype.push = function (chunk, final) {
        Deflate.prototype.push.call(this, chunk, final);
    };
    Zlib.prototype.p = function (c, f) {
        this.c.p(c);
        var raw = dopt(c, this.o, this.v && 2, f && 4, !f);
        if (this.v)
            zlh(raw, this.o), this.v = 0;
        if (f)
            wbytes(raw, raw.length - 4, this.c.d());
        this.ondata(raw, f);
    };
    return Zlib;
}())));

/**
 * Asynchronous streaming Zlib compression
 */
var AsyncZlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function AsyncZlib(opts, cb) {
        astrmify([
            bDflt,
            zle,
            function () { return [astrm, Deflate, Zlib]; }
        ], this, AsyncCmpStrm.call(this, opts, cb), function (ev) {
            var strm = new Zlib(ev.data);
            onmessage = astrm(strm);
        }, 10);
    }
    return AsyncZlib;
}())));

function zlib(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return cbify(data, opts, [
        bDflt,
        zle,
        function () { return [zlibSync]; }
    ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);
}
/**
 * Compress data with Zlib
 * @param data The data to compress
 * @param opts The compression options
 * @returns The zlib-compressed version of the data
 */
function zlibSync(data, opts) {
    if (!opts)
        opts = {};
    var a = adler();
    a.p(data);
    var d = dopt(data, opts, 2, 4);
    return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
}
/**
 * Streaming Zlib decompression
 */
var Unzlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a Zlib decompression stream
     * @param cb The callback to call whenever data is inflated
     */
    function Unzlib(cb) {
        this.v = 1;
        Inflate.call(this, cb);
    }
    /**
     * Pushes a chunk to be unzlibbed
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Unzlib.prototype.push = function (chunk, final) {
        Inflate.prototype.e.call(this, chunk);
        if (this.v) {
            if (this.p.length < 2 && !final)
                return;
            this.p = this.p.subarray(2), this.v = 0;
        }
        if (final) {
            if (this.p.length < 4)
                err(6, 'invalid zlib data');
            this.p = this.p.subarray(0, -4);
        }
        // necessary to prevent TS from using the closure value
        // This allows for workerization to function correctly
        Inflate.prototype.c.call(this, final);
    };
    return Unzlib;
}())));

/**
 * Asynchronous streaming Zlib decompression
 */
var AsyncUnzlib = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates an asynchronous Zlib decompression stream
     * @param cb The callback to call whenever data is deflated
     */
    function AsyncUnzlib(cb) {
        this.ondata = cb;
        astrmify([
            bInflt,
            zule,
            function () { return [astrm, Inflate, Unzlib]; }
        ], this, 0, function () {
            var strm = new Unzlib();
            onmessage = astrm(strm);
        }, 11);
    }
    return AsyncUnzlib;
}())));

function unzlib(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return cbify(data, opts, [
        bInflt,
        zule,
        function () { return [unzlibSync]; }
    ], function (ev) { return pbf(unzlibSync(ev.data[0], gu8(ev.data[1]))); }, 5, cb);
}
/**
 * Expands Zlib data
 * @param data The data to decompress
 * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
 * @returns The decompressed version of the data
 */
function unzlibSync(data, out) {
    return inflt((zlv(data), data.subarray(2, -4)), out);
}
// Default algorithm for compression (used because having a known output size allows faster decompression)

// Default algorithm for compression (used because having a known output size allows faster decompression)

/**
 * Streaming GZIP, Zlib, or raw DEFLATE decompression
 */
var Decompress = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a decompression stream
     * @param cb The callback to call whenever data is decompressed
     */
    function Decompress(cb) {
        this.G = Gunzip;
        this.I = Inflate;
        this.Z = Unzlib;
        this.ondata = cb;
    }
    /**
     * Pushes a chunk to be decompressed
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Decompress.prototype.push = function (chunk, final) {
        if (!this.ondata)
            err(5);
        if (!this.s) {
            if (this.p && this.p.length) {
                var n = new u8(this.p.length + chunk.length);
                n.set(this.p), n.set(chunk, this.p.length);
            }
            else
                this.p = chunk;
            if (this.p.length > 2) {
                var _this_1 = this;
                var cb = function () { _this_1.ondata.apply(_this_1, arguments); };
                this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)
                    ? new this.G(cb)
                    : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))
                        ? new this.I(cb)
                        : new this.Z(cb);
                this.s.push(this.p, final);
                this.p = null;
            }
        }
        else
            this.s.push(chunk, final);
    };
    return Decompress;
}())));

/**
 * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression
 */
var AsyncDecompress = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
   * Creates an asynchronous decompression stream
   * @param cb The callback to call whenever data is decompressed
   */
    function AsyncDecompress(cb) {
        this.G = AsyncGunzip;
        this.I = AsyncInflate;
        this.Z = AsyncUnzlib;
        this.ondata = cb;
    }
    /**
     * Pushes a chunk to be decompressed
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    AsyncDecompress.prototype.push = function (chunk, final) {
        Decompress.prototype.push.call(this, chunk, final);
    };
    return AsyncDecompress;
}())));

function decompress(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    return (data[0] == 31 && data[1] == 139 && data[2] == 8)
        ? gunzip(data, opts, cb)
        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
            ? inflate(data, opts, cb)
            : unzlib(data, opts, cb);
}
/**
 * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
 * @param data The data to decompress
 * @param out Where to write the data. Saves memory if you know the decompressed size and provide an output buffer of that length.
 * @returns The decompressed version of the data
 */
function decompressSync(data, out) {
    return (data[0] == 31 && data[1] == 139 && data[2] == 8)
        ? gunzipSync(data, out)
        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))
            ? inflateSync(data, out)
            : unzlibSync(data, out);
}
// flatten a directory structure
var fltn = function (d, p, t, o) {
    for (var k in d) {
        var val = d[k], n = p + k, op = o;
        if (Array.isArray(val))
            op = mrg(o, val[1]), val = val[0];
        if (val instanceof u8)
            t[n] = [val, op];
        else {
            t[n += '/'] = [new u8(0), op];
            fltn(val, n, t, o);
        }
    }
};
// text encoder
var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();
// text decoder
var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
// text decoder stream
var tds = 0;
try {
    td.decode(et, { stream: true });
    tds = 1;
}
catch (e) { }
// decode UTF8
var dutf8 = function (d) {
    for (var r = '', i = 0;;) {
        var c = d[i++];
        var eb = (c > 127) + (c > 223) + (c > 239);
        if (i + eb > d.length)
            return [r, slc(d, i - 1)];
        if (!eb)
            r += String.fromCharCode(c);
        else if (eb == 3) {
            c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,
                r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));
        }
        else if (eb & 1)
            r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));
        else
            r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));
    }
};
/**
 * Streaming UTF-8 decoding
 */
var DecodeUTF8 = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a UTF-8 decoding stream
     * @param cb The callback to call whenever data is decoded
     */
    function DecodeUTF8(cb) {
        this.ondata = cb;
        if (tds)
            this.t = new TextDecoder();
        else
            this.p = et;
    }
    /**
     * Pushes a chunk to be decoded from UTF-8 binary
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    DecodeUTF8.prototype.push = function (chunk, final) {
        if (!this.ondata)
            err(5);
        final = !!final;
        if (this.t) {
            this.ondata(this.t.decode(chunk, { stream: true }), final);
            if (final) {
                if (this.t.decode().length)
                    err(8);
                this.t = null;
            }
            return;
        }
        if (!this.p)
            err(4);
        var dat = new u8(this.p.length + chunk.length);
        dat.set(this.p);
        dat.set(chunk, this.p.length);
        var _a = dutf8(dat), ch = _a[0], np = _a[1];
        if (final) {
            if (np.length)
                err(8);
            this.p = null;
        }
        else
            this.p = np;
        this.ondata(ch, final);
    };
    return DecodeUTF8;
}())));

/**
 * Streaming UTF-8 encoding
 */
var EncodeUTF8 = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a UTF-8 decoding stream
     * @param cb The callback to call whenever data is encoded
     */
    function EncodeUTF8(cb) {
        this.ondata = cb;
    }
    /**
     * Pushes a chunk to be encoded to UTF-8
     * @param chunk The string data to push
     * @param final Whether this is the last chunk
     */
    EncodeUTF8.prototype.push = function (chunk, final) {
        if (!this.ondata)
            err(5);
        if (this.d)
            err(4);
        this.ondata(strToU8(chunk), this.d = final || false);
    };
    return EncodeUTF8;
}())));

/**
 * Converts a string into a Uint8Array for use with compression/decompression methods
 * @param str The string to encode
 * @param latin1 Whether or not to interpret the data as Latin-1. This should
 *               not need to be true unless decoding a binary string.
 * @returns The string encoded in UTF-8/Latin-1 binary
 */
function strToU8(str, latin1) {
    if (latin1) {
        var ar_1 = new u8(str.length);
        for (var i = 0; i < str.length; ++i)
            ar_1[i] = str.charCodeAt(i);
        return ar_1;
    }
    if (te)
        return te.encode(str);
    var l = str.length;
    var ar = new u8(str.length + (str.length >> 1));
    var ai = 0;
    var w = function (v) { ar[ai++] = v; };
    for (var i = 0; i < l; ++i) {
        if (ai + 5 > ar.length) {
            var n = new u8(ai + 8 + ((l - i) << 1));
            n.set(ar);
            ar = n;
        }
        var c = str.charCodeAt(i);
        if (c < 128 || latin1)
            w(c);
        else if (c < 2048)
            w(192 | (c >> 6)), w(128 | (c & 63));
        else if (c > 55295 && c < 57344)
            c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),
                w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
        else
            w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));
    }
    return slc(ar, 0, ai);
}
/**
 * Converts a Uint8Array to a string
 * @param dat The data to decode to string
 * @param latin1 Whether or not to interpret the data as Latin-1. This should
 *               not need to be true unless encoding to binary string.
 * @returns The original UTF-8/Latin-1 string
 */
function strFromU8(dat, latin1) {
    if (latin1) {
        var r = '';
        for (var i = 0; i < dat.length; i += 16384)
            r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));
        return r;
    }
    else if (td)
        return td.decode(dat);
    else {
        var _a = dutf8(dat), out = _a[0], ext = _a[1];
        if (ext.length)
            err(8);
        return out;
    }
}
;
// deflate bit flag
var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };
// skip local zip header
var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };
// read zip header
var zh = function (d, b, z) {
    var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20);
    var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2];
    return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off];
};
// read zip64 extra field
var z64e = function (d, b) {
    for (; b2(d, b) != 1; b += 4 + b2(d, b + 2))
        ;
    return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)];
};
// extra field length
var exfl = function (ex) {
    var le = 0;
    if (ex) {
        for (var k in ex) {
            var l = ex[k].length;
            if (l > 65535)
                err(9);
            le += l + 4;
        }
    }
    return le;
};
// write zip header
var wzh = function (d, b, f, fn, u, c, ce, co) {
    var fl = fn.length, ex = f.extra, col = co && co.length;
    var exl = exfl(ex);
    wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;
    if (ce != null)
        d[b++] = 20, d[b++] = f.os;
    d[b] = 20, b += 2; // spec compliance? what's that?
    d[b++] = (f.flag << 1) | (c == null && 8), d[b++] = u && 8;
    d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
    var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
    if (y < 0 || y > 119)
        err(10);
    wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >>> 1)), b += 4;
    if (c != null) {
        wbytes(d, b, f.crc);
        wbytes(d, b + 4, c);
        wbytes(d, b + 8, f.size);
    }
    wbytes(d, b + 12, fl);
    wbytes(d, b + 14, exl), b += 16;
    if (ce != null) {
        wbytes(d, b, col);
        wbytes(d, b + 6, f.attrs);
        wbytes(d, b + 10, ce), b += 14;
    }
    d.set(fn, b);
    b += fl;
    if (exl) {
        for (var k in ex) {
            var exf = ex[k], l = exf.length;
            wbytes(d, b, +k);
            wbytes(d, b + 2, l);
            d.set(exf, b + 4), b += 4 + l;
        }
    }
    if (col)
        d.set(co, b), b += col;
    return b;
};
// write zip footer (end of central directory)
var wzf = function (o, b, c, d, e) {
    wbytes(o, b, 0x6054B50); // skip disk
    wbytes(o, b + 8, c);
    wbytes(o, b + 10, c);
    wbytes(o, b + 12, d);
    wbytes(o, b + 16, e);
};
/**
 * A pass-through stream to keep data uncompressed in a ZIP archive.
 */
var ZipPassThrough = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a pass-through stream that can be added to ZIP archives
     * @param filename The filename to associate with this data stream
     */
    function ZipPassThrough(filename) {
        this.filename = filename;
        this.c = crc();
        this.size = 0;
        this.compression = 0;
    }
    /**
     * Processes a chunk and pushes to the output stream. You can override this
     * method in a subclass for custom behavior, but by default this passes
     * the data through. You must call this.ondata(err, chunk, final) at some
     * point in this method.
     * @param chunk The chunk to process
     * @param final Whether this is the last chunk
     */
    ZipPassThrough.prototype.process = function (chunk, final) {
        this.ondata(null, chunk, final);
    };
    /**
     * Pushes a chunk to be added. If you are subclassing this with a custom
     * compression algorithm, note that you must push data from the source
     * file only, pre-compression.
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    ZipPassThrough.prototype.push = function (chunk, final) {
        if (!this.ondata)
            err(5);
        this.c.p(chunk);
        this.size += chunk.length;
        if (final)
            this.crc = this.c.d();
        this.process(chunk, final || false);
    };
    return ZipPassThrough;
}())));

// I don't extend because TypeScript extension adds 1kB of runtime bloat
/**
 * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate
 * for better performance
 */
var ZipDeflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a DEFLATE stream that can be added to ZIP archives
     * @param filename The filename to associate with this data stream
     * @param opts The compression options
     */
    function ZipDeflate(filename, opts) {
        var _this_1 = this;
        if (!opts)
            opts = {};
        ZipPassThrough.call(this, filename);
        this.d = new Deflate(opts, function (dat, final) {
            _this_1.ondata(null, dat, final);
        });
        this.compression = 8;
        this.flag = dbf(opts.level);
    }
    ZipDeflate.prototype.process = function (chunk, final) {
        try {
            this.d.push(chunk, final);
        }
        catch (e) {
            this.ondata(e, null, final);
        }
    };
    /**
     * Pushes a chunk to be deflated
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    ZipDeflate.prototype.push = function (chunk, final) {
        ZipPassThrough.prototype.push.call(this, chunk, final);
    };
    return ZipDeflate;
}())));

/**
 * Asynchronous streaming DEFLATE compression for ZIP archives
 */
var AsyncZipDeflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a DEFLATE stream that can be added to ZIP archives
     * @param filename The filename to associate with this data stream
     * @param opts The compression options
     */
    function AsyncZipDeflate(filename, opts) {
        var _this_1 = this;
        if (!opts)
            opts = {};
        ZipPassThrough.call(this, filename);
        this.d = new AsyncDeflate(opts, function (err, dat, final) {
            _this_1.ondata(err, dat, final);
        });
        this.compression = 8;
        this.flag = dbf(opts.level);
        this.terminate = this.d.terminate;
    }
    AsyncZipDeflate.prototype.process = function (chunk, final) {
        this.d.push(chunk, final);
    };
    /**
     * Pushes a chunk to be deflated
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    AsyncZipDeflate.prototype.push = function (chunk, final) {
        ZipPassThrough.prototype.push.call(this, chunk, final);
    };
    return AsyncZipDeflate;
}())));

// TODO: Better tree shaking
/**
 * A zippable archive to which files can incrementally be added
 */
var Zip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates an empty ZIP archive to which files can be added
     * @param cb The callback to call whenever data for the generated ZIP archive
     *           is available
     */
    function Zip(cb) {
        this.ondata = cb;
        this.u = [];
        this.d = 1;
    }
    /**
     * Adds a file to the ZIP archive
     * @param file The file stream to add
     */
    Zip.prototype.add = function (file) {
        var _this_1 = this;
        if (!this.ondata)
            err(5);
        // finishing or finished
        if (this.d & 2)
            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);
        else {
            var f = strToU8(file.filename), fl_1 = f.length;
            var com = file.comment, o = com && strToU8(com);
            var u = fl_1 != file.filename.length || (o && (com.length != o.length));
            var hl_1 = fl_1 + exfl(file.extra) + 30;
            if (fl_1 > 65535)
                this.ondata(err(11, 0, 1), null, false);
            var header = new u8(hl_1);
            wzh(header, 0, file, f, u);
            var chks_1 = [header];
            var pAll_1 = function () {
                for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {
                    var chk = chks_2[_i];
                    _this_1.ondata(null, chk, false);
                }
                chks_1 = [];
            };
            var tr_1 = this.d;
            this.d = 0;
            var ind_1 = this.u.length;
            var uf_1 = mrg(file, {
                f: f,
                u: u,
                o: o,
                t: function () {
                    if (file.terminate)
                        file.terminate();
                },
                r: function () {
                    pAll_1();
                    if (tr_1) {
                        var nxt = _this_1.u[ind_1 + 1];
                        if (nxt)
                            nxt.r();
                        else
                            _this_1.d = 1;
                    }
                    tr_1 = 1;
                }
            });
            var cl_1 = 0;
            file.ondata = function (err, dat, final) {
                if (err) {
                    _this_1.ondata(err, dat, final);
                    _this_1.terminate();
                }
                else {
                    cl_1 += dat.length;
                    chks_1.push(dat);
                    if (final) {
                        var dd = new u8(16);
                        wbytes(dd, 0, 0x8074B50);
                        wbytes(dd, 4, file.crc);
                        wbytes(dd, 8, cl_1);
                        wbytes(dd, 12, file.size);
                        chks_1.push(dd);
                        uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;
                        if (tr_1)
                            uf_1.r();
                        tr_1 = 1;
                    }
                    else if (tr_1)
                        pAll_1();
                }
            };
            this.u.push(uf_1);
        }
    };
    /**
     * Ends the process of adding files and prepares to emit the final chunks.
     * This *must* be called after adding all desired files for the resulting
     * ZIP file to work properly.
     */
    Zip.prototype.end = function () {
        var _this_1 = this;
        if (this.d & 2) {
            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);
            return;
        }
        if (this.d)
            this.e();
        else
            this.u.push({
                r: function () {
                    if (!(_this_1.d & 1))
                        return;
                    _this_1.u.splice(-1, 1);
                    _this_1.e();
                },
                t: function () { }
            });
        this.d = 3;
    };
    Zip.prototype.e = function () {
        var bt = 0, l = 0, tl = 0;
        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
            var f = _a[_i];
            tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);
        }
        var out = new u8(tl + 22);
        for (var _b = 0, _c = this.u; _b < _c.length; _b++) {
            var f = _c[_b];
            wzh(out, bt, f, f.f, f.u, f.c, l, f.o);
            bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;
        }
        wzf(out, bt, this.u.length, tl, l);
        this.ondata(null, out, true);
        this.d = 2;
    };
    /**
     * A method to terminate any internal workers used by the stream. Subsequent
     * calls to add() will fail.
     */
    Zip.prototype.terminate = function () {
        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {
            var f = _a[_i];
            f.t();
        }
        this.d = 2;
    };
    return Zip;
}())));

function zip(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    var r = {};
    fltn(data, '', r, opts);
    var k = Object.keys(r);
    var lft = k.length, o = 0, tot = 0;
    var slft = lft, files = new Array(lft);
    var term = [];
    var tAll = function () {
        for (var i = 0; i < term.length; ++i)
            term[i]();
    };
    var cbd = function (a, b) {
        mt(function () { cb(a, b); });
    };
    mt(function () { cbd = cb; });
    var cbf = function () {
        var out = new u8(tot + 22), oe = o, cdl = tot - o;
        tot = 0;
        for (var i = 0; i < slft; ++i) {
            var f = files[i];
            try {
                var l = f.c.length;
                wzh(out, tot, f, f.f, f.u, l);
                var badd = 30 + f.f.length + exfl(f.extra);
                var loc = tot + badd;
                out.set(f.c, loc);
                wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;
            }
            catch (e) {
                return cbd(e, null);
            }
        }
        wzf(out, o, files.length, cdl, oe);
        cbd(null, out);
    };
    if (!lft)
        cbf();
    var _loop_1 = function (i) {
        var fn = k[i];
        var _a = r[fn], file = _a[0], p = _a[1];
        var c = crc(), size = file.length;
        c.p(file);
        var f = strToU8(fn), s = f.length;
        var com = p.comment, m = com && strToU8(com), ms = m && m.length;
        var exl = exfl(p.extra);
        var compression = p.level == 0 ? 0 : 8;
        var cbl = function (e, d) {
            if (e) {
                tAll();
                cbd(e, null);
            }
            else {
                var l = d.length;
                files[i] = mrg(p, {
                    size: size,
                    crc: c.d(),
                    c: d,
                    f: f,
                    m: m,
                    u: s != fn.length || (m && (com.length != ms)),
                    compression: compression
                });
                o += 30 + s + exl + l;
                tot += 76 + 2 * (s + exl) + (ms || 0) + l;
                if (!--lft)
                    cbf();
            }
        };
        if (s > 65535)
            cbl(err(11, 0, 1), null);
        if (!compression)
            cbl(null, file);
        else if (size < 160000) {
            try {
                cbl(null, deflateSync(file, p));
            }
            catch (e) {
                cbl(e, null);
            }
        }
        else
            term.push(deflate(file, p, cbl));
    };
    // Cannot use lft because it can decrease
    for (var i = 0; i < slft; ++i) {
        _loop_1(i);
    }
    return tAll;
}
/**
 * Synchronously creates a ZIP file. Prefer using `zip` for better performance
 * with more than one file.
 * @param data The directory structure for the ZIP archive
 * @param opts The main options, merged with per-file options
 * @returns The generated ZIP archive
 */
function zipSync(data, opts) {
    if (!opts)
        opts = {};
    var r = {};
    var files = [];
    fltn(data, '', r, opts);
    var o = 0;
    var tot = 0;
    for (var fn in r) {
        var _a = r[fn], file = _a[0], p = _a[1];
        var compression = p.level == 0 ? 0 : 8;
        var f = strToU8(fn), s = f.length;
        var com = p.comment, m = com && strToU8(com), ms = m && m.length;
        var exl = exfl(p.extra);
        if (s > 65535)
            err(11);
        var d = compression ? deflateSync(file, p) : file, l = d.length;
        var c = crc();
        c.p(file);
        files.push(mrg(p, {
            size: file.length,
            crc: c.d(),
            c: d,
            f: f,
            m: m,
            u: s != fn.length || (m && (com.length != ms)),
            o: o,
            compression: compression
        }));
        o += 30 + s + exl + l;
        tot += 76 + 2 * (s + exl) + (ms || 0) + l;
    }
    var out = new u8(tot + 22), oe = o, cdl = tot - o;
    for (var i = 0; i < files.length; ++i) {
        var f = files[i];
        wzh(out, f.o, f, f.f, f.u, f.c.length);
        var badd = 30 + f.f.length + exfl(f.extra);
        out.set(f.c, f.o + badd);
        wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
    }
    wzf(out, o, files.length, cdl, oe);
    return out;
}
/**
 * Streaming pass-through decompression for ZIP archives
 */
var UnzipPassThrough = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    function UnzipPassThrough() {
    }
    UnzipPassThrough.prototype.push = function (data, final) {
        this.ondata(null, data, final);
    };
    UnzipPassThrough.compression = 0;
    return UnzipPassThrough;
}())));

/**
 * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for
 * better performance.
 */
var UnzipInflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a DEFLATE decompression that can be used in ZIP archives
     */
    function UnzipInflate() {
        var _this_1 = this;
        this.i = new Inflate(function (dat, final) {
            _this_1.ondata(null, dat, final);
        });
    }
    UnzipInflate.prototype.push = function (data, final) {
        try {
            this.i.push(data, final);
        }
        catch (e) {
            this.ondata(e, null, final);
        }
    };
    UnzipInflate.compression = 8;
    return UnzipInflate;
}())));

/**
 * Asynchronous streaming DEFLATE decompression for ZIP archives
 */
var AsyncUnzipInflate = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a DEFLATE decompression that can be used in ZIP archives
     */
    function AsyncUnzipInflate(_, sz) {
        var _this_1 = this;
        if (sz < 320000) {
            this.i = new Inflate(function (dat, final) {
                _this_1.ondata(null, dat, final);
            });
        }
        else {
            this.i = new AsyncInflate(function (err, dat, final) {
                _this_1.ondata(err, dat, final);
            });
            this.terminate = this.i.terminate;
        }
    }
    AsyncUnzipInflate.prototype.push = function (data, final) {
        if (this.i.terminate)
            data = slc(data, 0);
        this.i.push(data, final);
    };
    AsyncUnzipInflate.compression = 8;
    return AsyncUnzipInflate;
}())));

/**
 * A ZIP archive decompression stream that emits files as they are discovered
 */
var Unzip = /*#__PURE__*/ ((/* unused pure expression or super */ null && (function () {
    /**
     * Creates a ZIP decompression stream
     * @param cb The callback to call whenever a file in the ZIP archive is found
     */
    function Unzip(cb) {
        this.onfile = cb;
        this.k = [];
        this.o = {
            0: UnzipPassThrough
        };
        this.p = et;
    }
    /**
     * Pushes a chunk to be unzipped
     * @param chunk The chunk to push
     * @param final Whether this is the last chunk
     */
    Unzip.prototype.push = function (chunk, final) {
        var _this_1 = this;
        if (!this.onfile)
            err(5);
        if (!this.p)
            err(4);
        if (this.c > 0) {
            var len = Math.min(this.c, chunk.length);
            var toAdd = chunk.subarray(0, len);
            this.c -= len;
            if (this.d)
                this.d.push(toAdd, !this.c);
            else
                this.k[0].push(toAdd);
            chunk = chunk.subarray(len);
            if (chunk.length)
                return this.push(chunk, final);
        }
        else {
            var f = 0, i = 0, is = void 0, buf = void 0;
            if (!this.p.length)
                buf = chunk;
            else if (!chunk.length)
                buf = this.p;
            else {
                buf = new u8(this.p.length + chunk.length);
                buf.set(this.p), buf.set(chunk, this.p.length);
            }
            var l = buf.length, oc = this.c, add = oc && this.d;
            var _loop_2 = function () {
                var _a;
                var sig = b4(buf, i);
                if (sig == 0x4034B50) {
                    f = 1, is = i;
                    this_1.d = null;
                    this_1.c = 0;
                    var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);
                    if (l > i + 30 + fnl + es) {
                        var chks_3 = [];
                        this_1.k.unshift(chks_3);
                        f = 2;
                        var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22);
                        var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);
                        if (sc_1 == 4294967295) {
                            _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1];
                        }
                        else if (dd)
                            sc_1 = -1;
                        i += es;
                        this_1.c = sc_1;
                        var d_1;
                        var file_1 = {
                            name: fn_1,
                            compression: cmp_1,
                            start: function () {
                                if (!file_1.ondata)
                                    err(5);
                                if (!sc_1)
                                    file_1.ondata(null, et, true);
                                else {
                                    var ctr = _this_1.o[cmp_1];
                                    if (!ctr)
                                        file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);
                                    d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);
                                    d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };
                                    for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {
                                        var dat = chks_4[_i];
                                        d_1.push(dat, false);
                                    }
                                    if (_this_1.k[0] == chks_3 && _this_1.c)
                                        _this_1.d = d_1;
                                    else
                                        d_1.push(et, true);
                                }
                            },
                            terminate: function () {
                                if (d_1 && d_1.terminate)
                                    d_1.terminate();
                            }
                        };
                        if (sc_1 >= 0)
                            file_1.size = sc_1, file_1.originalSize = su_1;
                        this_1.onfile(file_1);
                    }
                    return "break";
                }
                else if (oc) {
                    if (sig == 0x8074B50) {
                        is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;
                        return "break";
                    }
                    else if (sig == 0x2014B50) {
                        is = i -= 4, f = 3, this_1.c = 0;
                        return "break";
                    }
                }
            };
            var this_1 = this;
            for (; i < l - 4; ++i) {
                var state_1 = _loop_2();
                if (state_1 === "break")
                    break;
            }
            this.p = et;
            if (oc < 0) {
                var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);
                if (add)
                    add.push(dat, !!f);
                else
                    this.k[+(f == 2)].push(dat);
            }
            if (f & 2)
                return this.push(buf.subarray(i), final);
            this.p = buf.subarray(i);
        }
        if (final) {
            if (this.c)
                err(13);
            this.p = null;
        }
    };
    /**
     * Registers a decoder with the stream, allowing for files compressed with
     * the compression type provided to be expanded correctly
     * @param decoder The decoder constructor
     */
    Unzip.prototype.register = function (decoder) {
        this.o[decoder.compression] = decoder;
    };
    return Unzip;
}())));

var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };
function unzip(data, opts, cb) {
    if (!cb)
        cb = opts, opts = {};
    if (typeof cb != 'function')
        err(7);
    var term = [];
    var tAll = function () {
        for (var i = 0; i < term.length; ++i)
            term[i]();
    };
    var files = {};
    var cbd = function (a, b) {
        mt(function () { cb(a, b); });
    };
    mt(function () { cbd = cb; });
    var e = data.length - 22;
    for (; b4(data, e) != 0x6054B50; --e) {
        if (!e || data.length - e > 65558) {
            cbd(err(13, 0, 1), null);
            return tAll;
        }
    }
    ;
    var lft = b2(data, e + 8);
    if (lft) {
        var c = lft;
        var o = b4(data, e + 16);
        var z = o == 4294967295;
        if (z) {
            e = b4(data, e - 12);
            if (b4(data, e) != 0x6064B50) {
                cbd(err(13, 0, 1), null);
                return tAll;
            }
            c = lft = b4(data, e + 32);
            o = b4(data, e + 48);
        }
        var fltr = opts && opts.filter;
        var _loop_3 = function (i) {
            var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
            o = no;
            var cbl = function (e, d) {
                if (e) {
                    tAll();
                    cbd(e, null);
                }
                else {
                    if (d)
                        files[fn] = d;
                    if (!--lft)
                        cbd(null, files);
                }
            };
            if (!fltr || fltr({
                name: fn,
                size: sc,
                originalSize: su,
                compression: c_1
            })) {
                if (!c_1)
                    cbl(null, slc(data, b, b + sc));
                else if (c_1 == 8) {
                    var infl = data.subarray(b, b + sc);
                    if (sc < 320000) {
                        try {
                            cbl(null, inflateSync(infl, new u8(su)));
                        }
                        catch (e) {
                            cbl(e, null);
                        }
                    }
                    else
                        term.push(inflate(infl, { size: su }, cbl));
                }
                else
                    cbl(err(14, 'unknown compression type ' + c_1, 1), null);
            }
            else
                cbl(null, null);
        };
        for (var i = 0; i < c; ++i) {
            _loop_3(i);
        }
    }
    else
        cbd(null, {});
    return tAll;
}
/**
 * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better
 * performance with more than one file.
 * @param data The raw compressed ZIP file
 * @param opts The ZIP extraction options
 * @returns The decompressed files
 */
function unzipSync(data, opts) {
    var files = {};
    var e = data.length - 22;
    for (; b4(data, e) != 0x6054B50; --e) {
        if (!e || data.length - e > 65558)
            err(13);
    }
    ;
    var c = b2(data, e + 8);
    if (!c)
        return {};
    var o = b4(data, e + 16);
    var z = o == 4294967295;
    if (z) {
        e = b4(data, e - 12);
        if (b4(data, e) != 0x6064B50)
            err(13);
        c = b4(data, e + 32);
        o = b4(data, e + 48);
    }
    var fltr = opts && opts.filter;
    for (var i = 0; i < c; ++i) {
        var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);
        o = no;
        if (!fltr || fltr({
            name: fn,
            size: sc,
            originalSize: su,
            compression: c_2
        })) {
            if (!c_2)
                files[fn] = slc(data, b, b + sc);
            else if (c_2 == 8)
                files[fn] = inflateSync(data.subarray(b, b + sc), new u8(su));
            else
                err(14, 'unknown compression type ' + c_2);
        }
    }
    return files;
}

// EXTERNAL MODULE: consume shared module (default) generic-filehandle@^2.2.1 (strict) (fallback: ./node_modules/generic-filehandle/dist/index.js)
var index_js_ = __webpack_require__(2493);
var index_js_default = /*#__PURE__*/__webpack_require__.n(index_js_);
// EXTERNAL MODULE: ./node_modules/pubsub-js/src/pubsub.js
var pubsub = __webpack_require__(1798);
var pubsub_default = /*#__PURE__*/__webpack_require__.n(pubsub);
;// CONCATENATED MODULE: ./node_modules/gosling-theme/dist/gosling-theme.es.js
const gosling_theme_es_t=["#E79F00","#029F73","#0072B2","#CB7AA7","#D45E00","#57B4E9","#EFE441"],o={color:gosling_theme_es_t[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:gosling_theme_es_t,quantitativeSizeRange:[2,6]},e={base:"light",root:{background:"white",titleColor:"black",titleBackgroundColor:"transparent",titleFontSize:18,titleFontFamily:"Arial",titleAlign:"left",titleFontWeight:"bold",subtitleColor:"gray",subtitleBackgroundColor:"transparent",subtitleFontSize:16,subtitleFontFamily:"Arial",subtitleFontWeight:"normal",subtitleAlign:"left",showMousePosition:!0,mousePositionColor:"#000000"},track:{background:"transparent",alternatingBackground:"transparent",titleColor:"black",titleBackground:"white",titleFontSize:12,titleAlign:"left",outline:"black",outlineWidth:1},legend:{position:"top",background:"white",backgroundOpacity:.7,labelColor:"black",labelFontSize:12,labelFontWeight:"normal",labelFontFamily:"Arial",backgroundStroke:"#DBDBDB",tickColor:"black"},axis:{tickColor:"black",labelColor:"black",labelFontSize:12,labelFontWeight:"normal",labelFontFamily:"Arial",baselineColor:"black",gridColor:"#E3E3E3",gridStrokeWidth:1,gridStrokeType:"solid",gridStrokeDash:[4,4]},markCommon:{...o},point:{...o,size:3},rect:{...o},triangle:{...o},area:{...o},line:{...o},bar:{...o},rule:{...o,strokeWidth:1},link:{...o,strokeWidth:1},text:{...o,textAnchor:"middle",textFontWeight:"normal"},brush:{...o,color:"gray",opacity:.3,stroke:"black",strokeWidth:1}},gosling_theme_es_i=["#E79F00","#029F73","#0072B2","#CB7AA7","#D45E00","#57B4E9","#EFE441"],l={...{color:gosling_theme_es_i[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:gosling_theme_es_i,quantitativeSizeRange:[2,6]},stroke:"white"},r={base:"dark",root:{background:"black",titleColor:"white",subtitleColor:"lightgray",mousePositionColor:"#FFFFFF",showMousePosition:!0},track:{titleColor:"white",titleBackground:"black",outline:"white",outlineWidth:1},legend:{background:"black",backgroundOpacity:.7,labelColor:"white",backgroundStroke:"#DBDBDB",tickColor:"white"},axis:{tickColor:"white",labelColor:"white",baselineColor:"white",gridColor:"gray",gridStrokeWidth:1},markCommon:{...l},point:{...l,size:3},rect:{...l},triangle:{...l},area:{...l},line:{...l},bar:{...l},rule:{...l,strokeWidth:1},link:{...l,strokeWidth:1},text:{...l,textAnchor:"middle",textFontWeight:"normal"},brush:{...l,color:"lightgray",opacity:.3,stroke:"white",strokeWidth:1}},a=["#D19000","#008F67","#005F96","#B86E97","#B55100","#4793BF","#C9C03"],n={color:a[0],size:1,stroke:"#3C3C3C",strokeWidth:0,opacity:1,nominalColorRange:a,quantitativeSizeRange:[2,6]},k={base:"warm",root:{background:"#FFF8E8",titleColor:"#3C3C3C",subtitleColor:"gray",showMousePosition:!0,mousePositionColor:"#3C3C3C"},track:{titleColor:"#3C3C3C",titleBackground:"#FFF8E8",outline:"#3C3C3C",outlineWidth:1},legend:{background:"#FFF8E8",backgroundOpacity:.7,labelColor:"#3C3C3C",backgroundStroke:"#3C3C3C",tickColor:"3C3C3C"},axis:{tickColor:"#3C3C3C",labelColor:"#3C3C3C",baselineColor:"#3C3C3C",gridColor:"#E3E3E3",gridStrokeWidth:1},markCommon:{...n},point:{...n,size:3},rect:{...n},triangle:{...n},area:{...n},line:{...n},bar:{...n},rule:{...n,strokeWidth:1},link:{...n,strokeWidth:1},text:{...n,textAnchor:"middle",textFontWeight:"normal"},brush:{...n,color:"lightgray",opacity:.3,stroke:"#3C3C3C",strokeWidth:1}},b=["#F66A62","#05B230","#5692FF","#D764D6","#86E9D4","#6E6AD7","#FFFB00"],gosling_theme_es_c={color:b[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:b,quantitativeSizeRange:[2,6]},g={base:"ggplot",root:{background:"white",titleColor:"black",titleFontSize:18,titleFontFamily:"Helvetica",titleAlign:"middle",titleFontWeight:"bold",titleBackgroundColor:"white",subtitleColor:"gray",subtitleFontSize:14,subtitleFontFamily:"Helvetica",subtitleAlign:"middle",subtitleFontWeight:"light",subtitleBackgroundColor:"white",showMousePosition:!0,mousePositionColor:"black"},track:{background:"#e8e8e8",alternatingBackground:"#d1d1d1",titleColor:"black",titleBackground:"white",outline:"black",outlineWidth:2},legend:{position:"right",background:"#e8e8e8",backgroundOpacity:1,labelColor:"black",backgroundStroke:"#e8e8e8",tickColor:"white"},axis:{tickColor:"white",labelColor:"black",baselineColor:"#e8e8e8",gridColor:"white",gridStrokeWidth:2},markCommon:{...gosling_theme_es_c},point:{...gosling_theme_es_c,size:3},rect:{...gosling_theme_es_c},triangle:{...gosling_theme_es_c},area:{...gosling_theme_es_c},line:{...gosling_theme_es_c},bar:{...gosling_theme_es_c},rule:{...gosling_theme_es_c,strokeWidth:1},link:{...gosling_theme_es_c,strokeWidth:1},text:{...gosling_theme_es_c,textAnchor:"middle",textFontWeight:"bold"},brush:{...gosling_theme_es_c,color:"black",opacity:.3,stroke:"black",strokeWidth:1}},s=["#37E649","#ED2D44","#AEAFEA","#EBAEAE","#CE7B3D","#8743E0","#5233F0"],d={color:s[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:s,quantitativeSizeRange:[2,6]},gosling_theme_es_C={base:"igv",root:{background:"white",titleColor:"white",titleAlign:"left",titleFontWeight:"bold",titleBackgroundColor:"#5f5f5f",subtitleColor:"#3b3b3b",subtitleAlign:"left",subtitleFontWeight:"bold",subtitleBackgroundColor:"#c4c4c4",showMousePosition:!0,mousePositionColor:"black"},track:{background:"white",alternatingBackground:"#e8e8e8",titleColor:"white",titleBackground:"#5F5F5F",outline:"#5F5F5F",outlineWidth:1},legend:{position:"top",background:"white",backgroundOpacity:1,labelColor:"black",backgroundStroke:"black",tickColor:"black"},axis:{tickColor:"black",labelColor:"black",baselineColor:"white",gridColor:"transparent",gridStrokeWidth:0},markCommon:{...d},point:{...d,size:3},rect:{...d},triangle:{...d},area:{...d},line:{...d},bar:{...d},rule:{...d,strokeWidth:1},link:{...d,strokeWidth:1},text:{...d,textAnchor:"middle",textFontWeight:"bold"},brush:{...d,color:"white",opacity:.3,stroke:"black",strokeWidth:1}},u=["#CD9B1D","#8A668B","#40E0D0","#FF6969","#666666","#FAC902","#FE0000","#CC96CD","#D9D9D9"],h={color:u[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:u,quantitativeSizeRange:[2,6]},F={base:"ensembl",root:{background:"white",titleColor:"#494949",titleFontSize:24,titleFontFamily:"GGX88",titleAlign:"left",titleFontWeight:"bold",titleBackgroundColor:"white",subtitleColor:"white",subtitleFontSize:19,subtitleFontFamily:"GGX88",subtitleAlign:"left",subtitleFontWeight:"normal",subtitleBackgroundColor:"#7B8BAF",mousePositionColor:"#FE0000",showMousePosition:!0},track:{background:"white",alternatingBackground:"#fffdf7",titleColor:"black",titleBackground:"white",titleFontSize:"normal",titleAlign:"left",outline:"#7B8BAF",outlineWidth:2},legend:{position:"middle",tickColor:"black",labelColor:"black",labelFontWeight:"normal",labelFontFamily:"GGX88",background:"white",backgroundOpacity:2,backgroundStroke:"lightgray"},axis:{tickColor:"black",labelColor:"black",labelFontFamily:"GGX88",baselineColor:"black",gridColor:"#7B8BAF",gridStrokeWidth:2},markCommon:{...h},point:{...h,size:3},rect:{...h},triangle:{...h},area:{...h},line:{...h},bar:{...h},rule:{...h,strokeWidth:1},link:{...h,strokeWidth:1},text:{...h,textAnchor:"middle",textFontWeight:"normal"},brush:{...h,color:"gray",opacity:.3,stroke:"black",strokeWidth:1}},gosling_theme_es_A=["#3A62FE","#F85353","#3A62FE","#F85353","#DCA326","#03BF06","#BABABA"],m={color:gosling_theme_es_A[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:gosling_theme_es_A,quantitativeSizeRange:[2,6]},W={base:"jbrowse",root:{background:"white",titleColor:"white",titleFontSize:20,titleFontFamily:"Roboto",titleAlign:"middle",titleFontWeight:"normal",titleBackgroundColor:"#0b243f",subtitleColor:"white",subtitleFontSize:18,subtitleFontFamily:"Roboto",subtitleAlign:"middle",subtitleFontWeight:"normal",subtitleBackgroundColor:"#732162",showMousePosition:!0,mousePositionColor:"#000000"},track:{background:"white",alternatingBackground:"white",titleAlign:"middle",titleColor:"white",titleBackground:"#0B243F",outline:"black",outlineWidth:1},legend:{position:"top",background:"white",backgroundOpacity:.7,labelColor:"#DCA326",labelFontWeight:"bold",labelFontFamily:"Roboto",backgroundStroke:"#black",tickColor:"black"},axis:{tickColor:"black",labelColor:"#DCA326",labelFontWeight:"bold",labelFontFamily:"Roboto",baselineColor:"black",gridColor:"#c5d5d9",gridStrokeWidth:1},markCommon:{...m},point:{...m,size:3},rect:{...m},triangle:{...m},area:{...m},line:{...m},bar:{...m},rule:{...m,strokeWidth:1},link:{...m,strokeWidth:1},text:{...m,textAnchor:"middle",textFontWeight:"normal"},brush:{...m,color:"#c5d5d9",opacity:.3,stroke:"black",strokeWidth:1}},gosling_theme_es_B=["#3A5FCD","#FFA54E","#8FBC8F","#B6709B","#EE6A50","#CCB79E","#DADA8F","#00CDCC","#EED5D2","#CD8EDD","#9ACD31","#D1BEA8","#FFB6C0"],w={color:gosling_theme_es_B[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:gosling_theme_es_B,quantitativeSizeRange:[2,6]},y={base:"ucsc",root:{background:"white",titleColor:"white",titleFontSize:22,titleAlign:"middle",titleFontWeight:"bold",titleBackgroundColor:"#00457c",subtitleColor:"black",subtitleAlign:"middle",subtitleFontWeight:"bold",subtitleBackgroundColor:"white",showMousePosition:!0,mousePositionColor:"#FE0000"},track:{background:"white",alternatingBackground:"#e3f7fc",titleColor:"#3A5FCD",titleBackground:"white",outline:"black",outlineWidth:1},legend:{position:"top",background:"white",backgroundOpacity:.7,labelColor:"black",labelFontWeight:"bold",backgroundStroke:"#DBDBDB",tickColor:"black"},axis:{tickColor:"black",labelColor:"#3A5FCD",labelFontWeight:"bold",baselineColor:"black",gridColor:"#E3E3E3",gridStrokeWidth:1},markCommon:{...w},point:{...w,size:3},rect:{...w},triangle:{...w},area:{...w},line:{...w},bar:{...w},rule:{...w,strokeWidth:1},link:{...w,strokeWidth:1},text:{...w,textAnchor:"middle",textFontWeight:"normal"},brush:{...w,color:"gray",opacity:.3,stroke:"black",strokeWidth:1}},p=["#6E12AC","#15C250","#E70FB1","#FF8E55","#A3B8F3","#DE5E59","#77AAAA","#F5CCCA"],gosling_theme_es_E={color:p[0],size:1,stroke:"black",strokeWidth:0,opacity:1,nominalColorRange:p,quantitativeSizeRange:[2,6]},S={base:"washu",root:{background:"white",titleColor:"gray",titleAlign:"left",titleFontWeight:"normal",titleBackgroundColor:"white",subtitleColor:"lightgray",subtitleAlign:"left",subtitleFontWeight:"light",subtitleBackgroundColor:"white",showMousePosition:!0,mousePositionColor:"#000000"},track:{background:"white",titleColor:"gray",titleBackground:"white",titleAlign:"left",outline:"gray",outlineWidth:1},legend:{position:"left",background:"white",backgroundOpacity:.5,labelColor:"gray",labelFontWeight:"light",backgroundStroke:"#DBDBDB",tickColor:"gray"},axis:{tickColor:"lightgray",labelColor:"gray",labelFontWeight:"light",baselineColor:"gray",gridColor:"transparent",gridStrokeWidth:0},markCommon:{...gosling_theme_es_E},point:{...gosling_theme_es_E,size:3},rect:{...gosling_theme_es_E},triangle:{...gosling_theme_es_E},area:{...gosling_theme_es_E},line:{...gosling_theme_es_E},bar:{...gosling_theme_es_E},rule:{...gosling_theme_es_E,strokeWidth:1},link:{...gosling_theme_es_E,strokeWidth:1},text:{...gosling_theme_es_E,textAnchor:"middle",textFontWeight:"normal"},brush:{...gosling_theme_es_E,color:"gray",opacity:.3,stroke:"gray",strokeWidth:1}},z=["#ED7D31","#4472C4","#FFC207","#76AE4F","#9E480E","#A5A5A5","#4472C4","#264378","#76AE4F","#5B9CD5"],gosling_theme_es_D={color:z[0],size:1,stroke:"#5A5A5A",strokeWidth:0,opacity:1,nominalColorRange:z,quantitativeSizeRange:[2,6]},gosling_theme_es_x={base:"excel",root:{background:"white",titleColor:"#5A5A5A",titleFontSize:30,titleFontFamily:"Calibri",titleAlign:"middle",titleFontWeight:"bold",titleBackgroundColor:"white",subtitleColor:"#5A5A5A",subtitleFontSize:22,subtitleFontFamily:"Calibri",subtitleAlign:"middle",subtitleFontWeight:"bold",subtitleBackgroundColor:"white",showMousePosition:!0,mousePositionColor:"#000000"},track:{background:"white",alternatingBackground:"#f5f5f5",titleColor:"#5A5A5A",titleBackground:"white",outline:"#5A5A5A",outlineWidth:1},legend:{position:"right",tickColor:"#5A5A5A",labelColor:"#5A5A5A",labelFontSize:12,labelFontWeight:"bold",labelFontFamily:"Calibri",background:"white",backgroundOpacity:.7,backgroundStroke:"#5A5A5A"},axis:{tickColor:"#5A5A5A",labelColor:"#5A5A5A",labelFontFamily:"Calibri",baselineColor:"#5A5A5A",gridColor:"#5A5A5A",gridStrokeWidth:1},markCommon:{...gosling_theme_es_D},point:{...gosling_theme_es_D,size:3},rect:{...gosling_theme_es_D},triangle:{...gosling_theme_es_D},area:{...gosling_theme_es_D},line:{...gosling_theme_es_D},bar:{...gosling_theme_es_D},rule:{...gosling_theme_es_D,strokeWidth:1},link:{...gosling_theme_es_D,strokeWidth:1},text:{...gosling_theme_es_D,textAnchor:"middle",textFontWeight:"normal"},brush:{...gosling_theme_es_D,color:"#5A5A5A",opacity:.3,stroke:"#5A5A5A",strokeWidth:1}},f=["#4185f4","#DB4437","#F4B400","#0D9D58","#AA30C3","#FF6E02","#CBC74C"],R={color:f[0],size:2,stroke:"black",strokeWidth:.3,opacity:1,nominalColorRange:f,quantitativeSizeRange:[2,6]},P={light:e,dark:r,warm:k,ggplot:g,igv:gosling_theme_es_C,ensembl:F,jbrowse:W,ucsc:y,washu:S,excel:gosling_theme_es_x,google:{base:"google",root:{background:"white",titleColor:"#454545",titleFontSize:20,titleFontFamily:"Arial",titleAlign:"left",titleFontWeight:"normal",titleBackgroundColor:"white",subtitleColor:"#7d7d7d",subtitleFontSize:16,subtitleFontFamily:"Arial",subtitleAlign:"left",subtitleFontWeight:"light",subtitleBackgroundColor:"white",showMousePosition:!0,mousePositionColor:"#000000"},track:{background:"white",alternatingBackground:"#f5f5f5",titleColor:"#e8e8e8",titleBackground:"white",titleFontSize:12,titleAlign:"left",outline:"black",outlineWidth:1},legend:{position:"right",background:"white",backgroundOpacity:1,labelColor:"black",labelFontSize:12,labelFontWeight:"normal",labelFontFamily:"Arial",backgroundStroke:"black",tickColor:"black"},axis:{labelFontSize:12,labelFontWeight:"normal",labelFontFamily:"Arial",tickColor:"black",labelColor:"black",baselineColor:"black",gridColor:"black",gridStrokeWidth:1},markCommon:{...R},point:{...R,size:3},rect:{...R},triangle:{...R},area:{...R},line:{...R},bar:{...R},rule:{...R,strokeWidth:1},link:{...R,strokeWidth:1},text:{...R,textAnchor:"middle",textFontWeight:"normal"},brush:{...R,color:"#999999",opacity:.3,stroke:"black",strokeWidth:.7}}};function v(t){return-1!==Object.keys(P).indexOf(t)}function O(t){return v(t)?P[t]:P.light}
//# sourceMappingURL=gosling-theme.es.js.map

// EXTERNAL MODULE: ./node_modules/threads/dist/index.js
var dist = __webpack_require__(3734);
var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
;// CONCATENATED MODULE: ./node_modules/threads/index.mjs


const registerSerializer = (dist_default()).registerSerializer
const spawn = (dist_default()).spawn
const BlobWorker = (dist_default()).BlobWorker
const DefaultSerializer = (dist_default()).DefaultSerializer
const Pool = (dist_default()).Pool
const Thread = (dist_default()).Thread
const Transfer = (dist_default()).Transfer
const threads_Worker = (dist_default()).Worker

// EXTERNAL MODULE: consume shared module (default) react@^17.0.1 (singleton)
var consume_shared_module_default_react_17_0_singleton_ = __webpack_require__(6271);
var consume_shared_module_default_react_17_0_singleton_default = /*#__PURE__*/__webpack_require__.n(consume_shared_module_default_react_17_0_singleton_);
// EXTERNAL MODULE: consume shared module (default) react-dom@^17.0.1 (singleton)
var consume_shared_module_default_react_dom_17_0_singleton_ = __webpack_require__(4456);
var consume_shared_module_default_react_dom_17_0_singleton_default = /*#__PURE__*/__webpack_require__.n(consume_shared_module_default_react_dom_17_0_singleton_);
// EXTERNAL MODULE: ./node_modules/higlass/dist/hglib.js
var hglib = __webpack_require__(7949);
;// CONCATENATED MODULE: ./node_modules/gosling.js/dist/gosling.es.js





















const name$1 = "gosling.js";
const author = "Sehi L'Yi";
const version$1 = "0.9.16";
const license = "MIT";
const repository = {
  type: "git",
  url: "https://github.com/gosling-lang/gosling.js"
};
const homepage = "https://gosling-lang.github.io/gosling.js/";
const main = "dist/gosling.js";
const gosling_es_module = "dist/gosling.es.js";
const types = "dist/src/index.d.ts";
const files = [
  "dist"
];
const gosling_es_exports = {
  ".": "./dist/gosling.es.js",
  "./embed": "./dist/embed/index.js"
};
const scripts = {
  start: "vite --mode editor",
  "start-embed": "vite",
  build: "run-p build-types build-lib",
  "build-lib": "vite build --mode lib && node scripts/build-umd && node scripts/build-embed",
  "build-types": "tsc --emitDeclarationOnly",
  "build-editor": "vite build",
  preview: "vite preview",
  test: "jest editor/ src/",
  changelog: "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
  format: "eslint src/ editor/ --fix && prettier 'editor/**/*.css' --write",
  schema: "ts-json-schema-generator -p src/index.ts -f tsconfig.json -t GoslingSpec --no-type-check --no-ref-encode > schema/gosling.schema.json",
  "schema-higlass": "ts-json-schema-generator -p src/index.ts -f tsconfig.json -t HiGlassSpec --no-type-check --no-ref-encode > schema/higlass.schema.json",
  "schema-theme": "ts-json-schema-generator -p src/index.ts -f tsconfig.json -t Theme --no-type-check --no-ref-encode > schema/theme.schema.json",
  "schema-template": "ts-json-schema-generator -p src/index.ts -f tsconfig.json -t TemplateTrackDef --no-type-check --no-ref-encode > schema/template.schema.json",
  "schema-versioning": "mkdir -p schema/history/$npm_package_version && cp schema/gosling.schema.json schema/history/$npm_package_version/gosling$npm_package_version.schema.json && cp src/core/gosling.schema.ts schema/history/$npm_package_version/gosling$npm_package_version.schema.ts",
  predeploy: 'yarn build-editor; echo "gosling.js.org" >> build/CNAME',
  deploy: "gh-pages -d build"
};
const peerDependencies = {
  "pixi.js": "^6.0.4",
  react: "16.13.1",
  "react-dom": "16.13.1"
};
const sideEffect = false;
const dependencies$1 = {
  "@gmod/bam": "^1.1.8",
  "@gmod/bbi": "^1.0.30",
  "@types/bezier-js": "^4.1.0",
  "@types/d3": "^7.0.0",
  "@types/lodash": "^4.14.151",
  "@types/node": "^12.0.0",
  "@types/rbush": "^3.0.0",
  "@types/uuid": "^8.3.1",
  "bezier-js": "4.0.3",
  buffer: "^6.0.3",
  "d3-array": "^2.5.1",
  "d3-color": "^2.0.0",
  "d3-dsv": "^2.0.0",
  "d3-scale": "^3.2.1",
  "d3-scale-chromatic": "^2.0.0",
  "d3-shape": "^2.0.0",
  fflate: "^0.7.1",
  "generic-filehandle": "^2.2.1",
  "gosling-theme": "^0.0.10",
  higlass: "^1.11.8",
  "higlass-register": "^0.3.0",
  "higlass-text": "^0.1.1",
  "json-stringify-pretty-compact": "^2.0.0",
  jspdf: "^2.3.1",
  "lodash-es": "^4.17.21",
  mixwith: "^0.1.1",
  "pubsub-js": "^1.9.3",
  rbush: "^3.0.1",
  "react-grid-layout": "^1.2.5",
  threads: "^1.6.4",
  uuid: "^8.3.2"
};
const devDependencies = {
  "@babel/core": "^7.11.1",
  "@commitlint/cli": "^11.0.0",
  "@commitlint/config-conventional": "^11.0.0",
  "@testing-library/jest-dom": "^5.11.3",
  "@testing-library/react": "^10.4.8",
  "@testing-library/user-event": "^12.1.1",
  "@types/d3-drag": "1",
  "@types/d3-selection": "1",
  "@types/jest": "^26.0.10",
  "@types/lodash-es": "^4.17.5",
  "@types/pubsub-js": "^1.8.2",
  "@types/qs": "^6.9.5",
  "@types/react": "^16.9.46",
  "@types/react-dom": "^16.9.8",
  "@types/react-resize-detector": "^4.2.0",
  "@types/react-router-dom": "^5.1.6",
  "@typescript-eslint/eslint-plugin": "^4.8.1",
  "@typescript-eslint/parser": "^4.8.1",
  "@vitejs/plugin-react-refresh": "^1.3.6",
  ajv: "^6.12.2",
  "babel-jest": "^26.3.0",
  canvas: "^2.6.1",
  "conventional-changelog-cli": "^2.1.1",
  "cross-fetch": "^3.0.6",
  "d3-drag": "^1",
  "d3-selection": "^1",
  documentation: "^13.0.2",
  esbuild: "^0.12.25",
  eslint: "^7.6.0",
  "eslint-config-prettier": "^6.11.0",
  "eslint-plugin-jest": "^23.20.0",
  "eslint-plugin-prettier": "^3.1.4",
  "eslint-plugin-react": "^7.20.6",
  "fetch-jsonp": "^1.1.3",
  "gh-pages": "^3.1.0",
  "git-branch-is": "^4.0.0",
  husky: "^4.2.5",
  jest: "^26.4.0",
  "jest-canvas-mock": "^2.3.0",
  "jest-raw-loader": "^1.0.1",
  jsoncrush: "^1.1.6",
  "npm-run-all": "^4.1.5",
  "pixi.js": "^6.0.4",
  prettier: "^2.0.5",
  qs: "^6.9.4",
  react: "16.13.1",
  "react-dom": "16.13.1",
  "react-markdown": "^5.0.3",
  "react-monaco-editor": "^0.45.0",
  "react-resize-detector": "^4.2.3",
  "react-router-dom": "^5.2.0",
  "react-split-pane": "^0.1.91",
  "remark-gfm": "^1.0.0",
  "strip-json-comments": "^3.1.1",
  "ts-jest": "^26.2.0",
  "ts-json-schema-generator": "^0.75.0",
  typescript: "~4.1.2",
  vite: "^2.5.10"
};
const resolutions = {
  slugid: "^3.0.0"
};
const browserslist = {
  production: [
    ">0.2%",
    "not dead",
    "not op_mini all"
  ],
  development: [
    "last 1 chrome version",
    "last 1 firefox version",
    "last 1 safari version"
  ]
};
const jest = {
  moduleNameMapper: {
    inline$: "jest-raw-loader",
    "^lodash-es$": "lodash"
  },
  setupFiles: [
    "jest-canvas-mock"
  ],
  preset: "ts-jest",
  verbose: true,
  moduleFileExtensions: [
    "js",
    "ts"
  ],
  coverageDirectory: "./coverage/",
  collectCoverage: true,
  collectCoverageFrom: [
    "**/src/**/*.{js,ts}",
    "!**/node_modules/**",
    "!**/coverage/**",
    "!**/public/**",
    "!**/dist/**",
    "!**/editor/**",
    "!**/deprecated/**"
  ],
  coverageReporters: [
    "lcov",
    "text"
  ]
};
const husky = {
  hooks: {
    "pre-commit": "yarn changelog && yarn schema && yarn schema-higlass && yarn schema-theme && yarn schema-template && yarn format && git add .",
    "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
  }
};
var pkg = {
  name: name$1,
  author,
  version: version$1,
  license,
  repository,
  homepage,
  main,
  module: gosling_es_module,
  types,
  files,
  exports: gosling_es_exports,
  scripts,
  peerDependencies,
  sideEffect,
  dependencies: dependencies$1,
  devDependencies,
  resolutions,
  browserslist,
  jest,
  husky
};
const $ref$2 = "#/definitions/GoslingSpec";
const $schema$4 = "http://json-schema.org/draft-07/schema#";
const definitions$3 = {
  Aggregate: {
    "enum": [
      "max",
      "min",
      "mean",
      "bin",
      "count"
    ],
    type: "string"
  },
  Assembly: {
    "enum": [
      "hg38",
      "hg19",
      "hg18",
      "hg17",
      "hg16",
      "mm10",
      "mm9",
      "unknown"
    ],
    type: "string"
  },
  AxisPosition: {
    "enum": [
      "none",
      "top",
      "bottom",
      "left",
      "right"
    ],
    type: "string"
  },
  BAMData: {
    additionalProperties: false,
    description: "Binary Alignment Map (BAM) is the comprehensive raw data of genome sequencing; it consists of the lossless, compressed binary representation of the Sequence Alignment Map-files.",
    properties: {
      extractJunction: {
        description: "Determine whether to extract exon-to-exon junctions. __Default__: `false`",
        type: "boolean"
      },
      indexUrl: {
        description: "URL link to the index file of the BAM file",
        type: "string"
      },
      junctionMinCoverage: {
        description: "Determine the threshold of coverage when extracting exon-to-exon junctions. __Default__: `1`",
        type: "number"
      },
      loadMates: {
        description: "Load mates that are located in the same chromosome. __Default__: `false`",
        type: "boolean"
      },
      maxInsertSize: {
        description: "Determines the threshold of insert sizes for determining the structural variants. __Default__: `5000`",
        type: "number"
      },
      type: {
        "const": "bam",
        type: "string"
      },
      url: {
        description: "URL link to the BAM data file",
        type: "string"
      }
    },
    required: [
      "type",
      "url",
      "indexUrl"
    ],
    type: "object"
  },
  BEDDBData: {
    additionalProperties: false,
    description: "Regular BED or similar files can be pre-aggregated for the scalable data exploration. Find our more about this format at [HiGlass Docs](https://docs.higlass.io/data_preparation.html#bed-files).",
    properties: {
      exonIntervalFields: {
        description: "experimental",
        items: [
          {
            additionalProperties: false,
            properties: {
              index: {
                type: "number"
              },
              name: {
                type: "string"
              }
            },
            required: [
              "index",
              "name"
            ],
            type: "object"
          },
          {
            additionalProperties: false,
            properties: {
              index: {
                type: "number"
              },
              name: {
                type: "string"
              }
            },
            required: [
              "index",
              "name"
            ],
            type: "object"
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      },
      genomicFields: {
        description: "Specify the name of genomic data fields.",
        items: {
          additionalProperties: false,
          properties: {
            index: {
              type: "number"
            },
            name: {
              type: "string"
            }
          },
          required: [
            "index",
            "name"
          ],
          type: "object"
        },
        type: "array"
      },
      type: {
        "const": "beddb",
        type: "string"
      },
      url: {
        description: "Specify the URL address of the data file.",
        type: "string"
      },
      valueFields: {
        description: "Specify the column indexes, field names, and field types.",
        items: {
          additionalProperties: false,
          properties: {
            index: {
              type: "number"
            },
            name: {
              type: "string"
            },
            type: {
              "enum": [
                "nominal",
                "quantitative"
              ],
              type: "string"
            }
          },
          required: [
            "index",
            "name",
            "type"
          ],
          type: "object"
        },
        type: "array"
      }
    },
    required: [
      "type",
      "url",
      "genomicFields"
    ],
    type: "object"
  },
  BIGWIGData: {
    additionalProperties: false,
    properties: {
      aggregation: {
        $ref: "#/definitions/BinAggregate",
        description: 'Determine aggregation function to apply within bins. __Default__: `"mean"`'
      },
      binSize: {
        description: "Binning the genomic interval in tiles (unit size: 256).",
        type: "number"
      },
      column: {
        description: "Assign a field name of the middle position of genomic intervals.",
        type: "string"
      },
      end: {
        description: "Assign a field name of the end position of genomic intervals.",
        type: "string"
      },
      start: {
        description: "Assign a field name of the start position of genomic intervals.",
        type: "string"
      },
      type: {
        "const": "bigwig",
        type: "string"
      },
      url: {
        description: "Specify the URL address of the data file.",
        type: "string"
      },
      value: {
        description: "Assign a field name of quantitative values.",
        type: "string"
      }
    },
    required: [
      "type",
      "url",
      "column",
      "value"
    ],
    type: "object"
  },
  BinAggregate: {
    "enum": [
      "mean",
      "sum"
    ],
    type: "string"
  },
  CSVData: {
    additionalProperties: false,
    description: 'Any small enough tabular data files, such as tsv, csv, BED, BEDPE, and GFF, can be loaded using "csv" data specification.',
    properties: {
      chromosomeField: {
        description: "Specify the name of chromosome data fields.",
        type: "string"
      },
      chromosomePrefix: {
        description: "experimental",
        type: "string"
      },
      genomicFields: {
        description: "Specify the name of genomic data fields.",
        items: {
          type: "string"
        },
        type: "array"
      },
      genomicFieldsToConvert: {
        description: "experimental",
        items: {
          additionalProperties: false,
          properties: {
            chromosomeField: {
              type: "string"
            },
            genomicFields: {
              items: {
                type: "string"
              },
              type: "array"
            }
          },
          required: [
            "chromosomeField",
            "genomicFields"
          ],
          type: "object"
        },
        type: "array"
      },
      headerNames: {
        description: "Specify the names of data fields if a CSV file is headerless.",
        items: {
          type: "string"
        },
        type: "array"
      },
      longToWideId: {
        description: "experimental",
        type: "string"
      },
      sampleLength: {
        description: "Specify the number of rows loaded from the URL.\n\n__Default:__ `1000`",
        type: "number"
      },
      separator: {
        description: "Specify file separator, __Default:__ ','",
        type: "string"
      },
      type: {
        "const": "csv",
        type: "string"
      },
      url: {
        description: "Specify the URL address of the data file.",
        type: "string"
      }
    },
    required: [
      "type",
      "url"
    ],
    type: "object"
  },
  Channel: {
    anyOf: [
      {
        $ref: "#/definitions/ChannelDeep"
      },
      {
        $ref: "#/definitions/ChannelValue"
      }
    ]
  },
  ChannelDeep: {
    anyOf: [
      {
        $ref: "#/definitions/X"
      },
      {
        $ref: "#/definitions/Y"
      },
      {
        $ref: "#/definitions/Row"
      },
      {
        $ref: "#/definitions/Color"
      },
      {
        $ref: "#/definitions/Size"
      },
      {
        $ref: "#/definitions/Stroke"
      },
      {
        $ref: "#/definitions/StrokeWidth"
      },
      {
        $ref: "#/definitions/Opacity"
      },
      {
        $ref: "#/definitions/Text"
      }
    ]
  },
  ChannelValue: {
    additionalProperties: false,
    properties: {
      value: {
        description: "Assign a constant value for a visual channel.",
        type: [
          "number",
          "string"
        ]
      }
    },
    required: [
      "value"
    ],
    type: "object"
  },
  Chromosome: {
    "enum": [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "10",
      "11",
      "12",
      "13",
      "14",
      "15",
      "16",
      "17",
      "18",
      "19",
      "20",
      "21",
      "22",
      "X",
      "Y",
      "M",
      "chr1",
      "chr2",
      "chr3",
      "chr4",
      "chr5",
      "chr6",
      "chr7",
      "chr8",
      "chr9",
      "chr10",
      "chr11",
      "chr12",
      "chr13",
      "chr14",
      "chr15",
      "chr16",
      "chr17",
      "chr18",
      "chr19",
      "chr20",
      "chr21",
      "chr22",
      "chrX",
      "chrY",
      "chrM"
    ],
    type: "string"
  },
  Color: {
    additionalProperties: false,
    properties: {
      domain: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      legend: {
        description: "Whether to display legend. __Default__: `false`",
        type: "boolean"
      },
      range: {
        $ref: "#/definitions/Range",
        description: "Determine the colors that should be bound to data value. Default properties are determined considering the field type."
      },
      scale: {
        "enum": [
          "linear",
          "log"
        ],
        type: "string"
      },
      type: {
        description: "Specify the data type",
        "enum": [
          "quantitative",
          "nominal"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  CoverageTransform: {
    additionalProperties: false,
    description: "Aggregate rows and calculate coverage",
    properties: {
      endField: {
        type: "string"
      },
      groupField: {
        description: "The name of a nominal field to group rows by in prior to piling-up",
        type: "string"
      },
      newField: {
        type: "string"
      },
      startField: {
        type: "string"
      },
      type: {
        "const": "coverage",
        type: "string"
      }
    },
    required: [
      "type",
      "startField",
      "endField"
    ],
    type: "object"
  },
  DataDeep: {
    anyOf: [
      {
        $ref: "#/definitions/JSONData"
      },
      {
        $ref: "#/definitions/CSVData"
      },
      {
        $ref: "#/definitions/BIGWIGData"
      },
      {
        $ref: "#/definitions/MultivecData"
      },
      {
        $ref: "#/definitions/BEDDBData"
      },
      {
        $ref: "#/definitions/VectorData"
      },
      {
        $ref: "#/definitions/MatrixData"
      },
      {
        $ref: "#/definitions/BAMData"
      }
    ]
  },
  DataTrack: {
    additionalProperties: false,
    description: "Partial specification of `BasicSingleTrack` to use default visual encoding predefined by data type.",
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "data",
      "height",
      "width"
    ],
    type: "object"
  },
  DataTransform: {
    anyOf: [
      {
        $ref: "#/definitions/FilterTransform"
      },
      {
        $ref: "#/definitions/StrConcatTransform"
      },
      {
        $ref: "#/definitions/StrReplaceTransform"
      },
      {
        $ref: "#/definitions/LogTransform"
      },
      {
        $ref: "#/definitions/DisplaceTransform"
      },
      {
        $ref: "#/definitions/ExonSplitTransform"
      },
      {
        $ref: "#/definitions/GenomicLengthTransform"
      },
      {
        $ref: "#/definitions/CoverageTransform"
      },
      {
        $ref: "#/definitions/JSONParseTransform"
      }
    ]
  },
  Datum: {
    additionalProperties: {
      type: [
        "number",
        "string"
      ]
    },
    description: "Values in the form of JSON.",
    type: "object"
  },
  DisplaceTransform: {
    additionalProperties: false,
    properties: {
      boundingBox: {
        additionalProperties: false,
        properties: {
          endField: {
            description: "The name of a quantitative field that represents the end position.",
            type: "string"
          },
          groupField: {
            description: "The name of a nominal field to group rows by in prior to piling-up.",
            type: "string"
          },
          isPaddingBP: {
            description: "Whether to consider `padding` as the bp length.",
            type: "boolean"
          },
          padding: {
            description: "The padding around visual lements. Either px or bp",
            type: "number"
          },
          startField: {
            description: "The name of a quantitative field that represents the start position.",
            type: "string"
          }
        },
        required: [
          "startField",
          "endField"
        ],
        type: "object"
      },
      maxRows: {
        description: "Specify maximum rows to be generated (default has no limit).",
        type: "number"
      },
      method: {
        $ref: "#/definitions/DisplacementType",
        description: "A string that specifies the type of diseplancement."
      },
      newField: {
        type: "string"
      },
      type: {
        "const": "displace",
        type: "string"
      }
    },
    required: [
      "type",
      "boundingBox",
      "method",
      "newField"
    ],
    type: "object"
  },
  Displacement: {
    additionalProperties: false,
    properties: {
      padding: {
        type: "number"
      },
      type: {
        $ref: "#/definitions/DisplacementType"
      }
    },
    required: [
      "type"
    ],
    type: "object"
  },
  DisplacementType: {
    "enum": [
      "pile",
      "spread"
    ],
    type: "string"
  },
  DomainChr: {
    additionalProperties: false,
    properties: {
      chromosome: {
        $ref: "#/definitions/Chromosome"
      }
    },
    required: [
      "chromosome"
    ],
    type: "object"
  },
  DomainChrInterval: {
    additionalProperties: false,
    properties: {
      chromosome: {
        $ref: "#/definitions/Chromosome",
        description: "If specified, only showing a certain interval in a chromosome."
      },
      interval: {
        items: [
          {
            type: "number"
          },
          {
            type: "number"
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      }
    },
    required: [
      "chromosome",
      "interval"
    ],
    type: "object"
  },
  DomainGene: {
    additionalProperties: false,
    properties: {
      gene: {
        anyOf: [
          {
            type: "string"
          },
          {
            items: [
              {
                type: "string"
              },
              {
                type: "string"
              }
            ],
            maxItems: 2,
            minItems: 2,
            type: "array"
          }
        ]
      }
    },
    required: [
      "gene"
    ],
    type: "object"
  },
  DomainInterval: {
    additionalProperties: false,
    properties: {
      interval: {
        items: [
          {
            type: "number"
          },
          {
            type: "number"
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      }
    },
    required: [
      "interval"
    ],
    type: "object"
  },
  ExonSplitTransform: {
    additionalProperties: false,
    properties: {
      fields: {
        items: {
          additionalProperties: false,
          properties: {
            chrField: {
              type: "string"
            },
            field: {
              type: "string"
            },
            newField: {
              type: "string"
            },
            type: {
              $ref: "#/definitions/FieldType"
            }
          },
          required: [
            "field",
            "type",
            "newField",
            "chrField"
          ],
          type: "object"
        },
        type: "array"
      },
      flag: {
        additionalProperties: false,
        properties: {
          field: {
            type: "string"
          },
          value: {
            type: [
              "number",
              "string"
            ]
          }
        },
        required: [
          "field",
          "value"
        ],
        type: "object"
      },
      separator: {
        type: "string"
      },
      type: {
        "const": "exonSplit",
        type: "string"
      }
    },
    required: [
      "type",
      "separator",
      "flag",
      "fields"
    ],
    type: "object"
  },
  FieldType: {
    "enum": [
      "genomic",
      "nominal",
      "quantitative"
    ],
    type: "string"
  },
  FilterTransform: {
    anyOf: [
      {
        $ref: "#/definitions/OneOfFilter"
      },
      {
        $ref: "#/definitions/RangeFilter"
      },
      {
        $ref: "#/definitions/IncludeFilter"
      }
    ]
  },
  FlatTracks: {
    additionalProperties: false,
    properties: {
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      tracks: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "tracks"
    ],
    type: "object"
  },
  GenomicDomain: {
    anyOf: [
      {
        $ref: "#/definitions/DomainInterval"
      },
      {
        $ref: "#/definitions/DomainChrInterval"
      },
      {
        $ref: "#/definitions/DomainChr"
      },
      {
        $ref: "#/definitions/DomainGene"
      }
    ]
  },
  GenomicLengthTransform: {
    additionalProperties: false,
    description: "Calculate genomic length using two genomic fields",
    properties: {
      endField: {
        type: "string"
      },
      newField: {
        type: "string"
      },
      startField: {
        type: "string"
      },
      type: {
        "const": "genomicLength",
        type: "string"
      }
    },
    required: [
      "type",
      "startField",
      "endField",
      "newField"
    ],
    type: "object"
  },
  GoslingSpec: {
    anyOf: [
      {
        $ref: "#/definitions/RootSpecWithSingleView"
      },
      {
        $ref: "#/definitions/RootSpecWithMultipleViews"
      }
    ]
  },
  IncludeFilter: {
    additionalProperties: false,
    properties: {
      field: {
        description: "A filter is applied based on the values of the specified data field",
        type: "string"
      },
      include: {
        description: "Check whether the value includes a substring.",
        type: "string"
      },
      not: {
        description: 'when `{"not": true}`, apply a NOT logical operation to the filter.\n\n__Default:__ `false`',
        type: "boolean"
      },
      type: {
        "const": "filter",
        type: "string"
      }
    },
    required: [
      "field",
      "include",
      "type"
    ],
    type: "object"
  },
  JSONData: {
    additionalProperties: false,
    description: "The JSON data format allows users to include data directly in the Gosling's JSON specification.",
    properties: {
      chromosomeField: {
        description: "Specify the name of chromosome data fields.",
        type: "string"
      },
      genomicFields: {
        description: "Specify the name of genomic data fields.",
        items: {
          type: "string"
        },
        type: "array"
      },
      genomicFieldsToConvert: {
        description: "experimental",
        items: {
          additionalProperties: false,
          properties: {
            chromosomeField: {
              type: "string"
            },
            genomicFields: {
              items: {
                type: "string"
              },
              type: "array"
            }
          },
          required: [
            "chromosomeField",
            "genomicFields"
          ],
          type: "object"
        },
        type: "array"
      },
      sampleLength: {
        description: "Specify the number of rows loaded from the URL.\n\n__Default:__ `1000`",
        type: "number"
      },
      type: {
        "const": "json",
        description: "Define data type.",
        type: "string"
      },
      values: {
        description: "Values in the form of JSON.",
        items: {
          $ref: "#/definitions/Datum"
        },
        type: "array"
      }
    },
    required: [
      "type",
      "values"
    ],
    type: "object"
  },
  JSONParseTransform: {
    additionalProperties: false,
    description: "Parse JSON Object Array and append vertically",
    properties: {
      baseGenomicField: {
        description: "Base genomic position when parsing relative position.",
        type: "string"
      },
      field: {
        description: "The field that contains the JSON object array.",
        type: "string"
      },
      genomicField: {
        description: "Relative genomic position to parse.",
        type: "string"
      },
      genomicLengthField: {
        description: "Length of genomic interval.",
        type: "string"
      },
      type: {
        "const": "subjson",
        type: "string"
      }
    },
    required: [
      "type",
      "field",
      "baseGenomicField",
      "genomicField",
      "genomicLengthField"
    ],
    type: "object"
  },
  Layout: {
    "enum": [
      "linear",
      "circular"
    ],
    type: "string"
  },
  LogBase: {
    anyOf: [
      {
        type: "number"
      },
      {
        "const": "e",
        type: "string"
      }
    ]
  },
  LogTransform: {
    additionalProperties: false,
    properties: {
      base: {
        $ref: "#/definitions/LogBase",
        description: "If not specified, 10 is used."
      },
      field: {
        type: "string"
      },
      newField: {
        description: "If specified, store transformed values in a new field.",
        type: "string"
      },
      type: {
        "const": "log",
        type: "string"
      }
    },
    required: [
      "type",
      "field"
    ],
    type: "object"
  },
  LogicalOperation: {
    "enum": [
      "less-than",
      "lt",
      "LT",
      "greater-than",
      "gt",
      "GT",
      "less-than-or-equal-to",
      "ltet",
      "LTET",
      "greater-than-or-equal-to",
      "gtet",
      "GTET"
    ],
    type: "string"
  },
  Mark: {
    "enum": [
      "point",
      "line",
      "area",
      "bar",
      "rect",
      "text",
      "withinLink",
      "betweenLink",
      "rule",
      "triangleLeft",
      "triangleRight",
      "triangleBottom",
      "brush",
      "header"
    ],
    type: "string"
  },
  MatrixData: {
    additionalProperties: false,
    properties: {
      binSize: {
        description: "Determine the number of nearby cells to aggregate. __Default__: `1`",
        type: "number"
      },
      column: {
        description: "The name of the first genomic field. __Default__: `x`",
        type: "string"
      },
      row: {
        description: "The name of the first genomic field. __Default__: `y`",
        type: "string"
      },
      type: {
        "const": "matrix",
        type: "string"
      },
      url: {
        description: "URL link to the matrix data file",
        type: "string"
      },
      value: {
        description: "The name of the value field. __Default__: `value`",
        type: "string"
      }
    },
    required: [
      "type",
      "url"
    ],
    type: "object"
  },
  MultipleViews: {
    additionalProperties: false,
    properties: {
      arrangement: {
        description: "Specify how multiple views are arranged.",
        "enum": [
          "parallel",
          "serial",
          "horizontal",
          "vertical"
        ],
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      views: {
        description: "An array of view specifications",
        items: {
          anyOf: [
            {
              $ref: "#/definitions/SingleView"
            },
            {
              $ref: "#/definitions/MultipleViews"
            }
          ]
        },
        type: "array"
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "views"
    ],
    type: "object"
  },
  MultivecData: {
    additionalProperties: false,
    description: 'Two-dimensional quantitative values, one axis for genomic coordinate and the other for different samples, can be converted into HiGlass\' `"multivec"` data. For example, multiple BigWig files can be converted into a single multivec file. You can also convert sequence data (FASTA) into this format where rows will be different nucleotide bases (e.g., A, T, G, C) and quantitative values represent the frequency. Find out more about this format at [HiGlass Docs](https://docs.higlass.io/data_preparation.html#multivec-files).',
    properties: {
      aggregation: {
        $ref: "#/definitions/BinAggregate",
        description: 'Determine aggregation function to apply within bins. __Default__: `"mean"`'
      },
      binSize: {
        description: "Binning the genomic interval in tiles (unit size: 256).",
        type: "number"
      },
      categories: {
        description: "assign names of individual samples.",
        items: {
          type: "string"
        },
        type: "array"
      },
      column: {
        description: "Assign a field name of the middle position of genomic intervals.",
        type: "string"
      },
      end: {
        description: "Assign a field name of the end position of genomic intervals.",
        type: "string"
      },
      row: {
        description: "Assign a field name of samples.",
        type: "string"
      },
      start: {
        description: "Assign a field name of the start position of genomic intervals.",
        type: "string"
      },
      type: {
        "const": "multivec",
        type: "string"
      },
      url: {
        description: "Specify the URL address of the data file.",
        type: "string"
      },
      value: {
        description: "Assign a field name of quantitative values.",
        type: "string"
      }
    },
    required: [
      "type",
      "url",
      "column",
      "row",
      "value"
    ],
    type: "object"
  },
  OneOfFilter: {
    additionalProperties: false,
    properties: {
      field: {
        description: "A filter is applied based on the values of the specified data field",
        type: "string"
      },
      not: {
        description: 'when `{"not": true}`, apply a NOT logical operation to the filter.\n\n__Default:__ `false`',
        type: "boolean"
      },
      oneOf: {
        anyOf: [
          {
            items: {
              type: "string"
            },
            type: "array"
          },
          {
            items: {
              type: "number"
            },
            type: "array"
          }
        ],
        description: "Check whether the value is an element in the provided list."
      },
      type: {
        "const": "filter",
        type: "string"
      }
    },
    required: [
      "field",
      "oneOf",
      "type"
    ],
    type: "object"
  },
  Opacity: {
    additionalProperties: false,
    properties: {
      domain: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      range: {
        $ref: "#/definitions/ValueExtent",
        description: "Ranges of visual channel values"
      },
      type: {
        description: "Specify the data type",
        "enum": [
          "quantitative",
          "nominal"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  Orientation: {
    "enum": [
      "horizontal",
      "vertical"
    ],
    type: "string"
  },
  OverlaidTrack: {
    additionalProperties: false,
    description: "Superposing multiple tracks.",
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      color: {
        anyOf: [
          {
            $ref: "#/definitions/Color"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      dataTransform: {
        items: {
          $ref: "#/definitions/DataTransform"
        },
        type: "array"
      },
      displacement: {
        $ref: "#/definitions/Displacement"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      flipY: {
        type: "boolean"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      mark: {
        $ref: "#/definitions/Mark"
      },
      opacity: {
        anyOf: [
          {
            $ref: "#/definitions/Opacity"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlay: {
        items: {
          additionalProperties: false,
          properties: {
            _invalidTrack: {
              description: "internal",
              type: "boolean"
            },
            _renderingId: {
              description: "internal",
              type: "string"
            },
            assembly: {
              $ref: "#/definitions/Assembly",
              description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
            },
            centerRadius: {
              description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
              type: "number"
            },
            color: {
              anyOf: [
                {
                  $ref: "#/definitions/Color"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            data: {
              $ref: "#/definitions/DataDeep"
            },
            dataTransform: {
              items: {
                $ref: "#/definitions/DataTransform"
              },
              type: "array"
            },
            displacement: {
              $ref: "#/definitions/Displacement"
            },
            endAngle: {
              description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
              type: "number"
            },
            flipY: {
              type: "boolean"
            },
            id: {
              type: "string"
            },
            innerRadius: {
              description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
              type: "number"
            },
            linkingId: {
              description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
              type: "string"
            },
            mark: {
              $ref: "#/definitions/Mark"
            },
            opacity: {
              anyOf: [
                {
                  $ref: "#/definitions/Opacity"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            orientation: {
              $ref: "#/definitions/Orientation",
              description: "Specify the orientation."
            },
            outerRadius: {
              description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
              type: "number"
            },
            overlayOnPreviousTrack: {
              type: "boolean"
            },
            overrideTemplate: {
              type: "boolean"
            },
            prerelease: {
              additionalProperties: false,
              description: "internal",
              type: "object"
            },
            row: {
              anyOf: [
                {
                  $ref: "#/definitions/Row"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            size: {
              anyOf: [
                {
                  $ref: "#/definitions/Size"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            spacing: {
              description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
              type: "number"
            },
            startAngle: {
              description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
              type: "number"
            },
            "static": {
              description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
              type: "boolean"
            },
            stretch: {
              type: "boolean"
            },
            stroke: {
              anyOf: [
                {
                  $ref: "#/definitions/Stroke"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            strokeWidth: {
              anyOf: [
                {
                  $ref: "#/definitions/StrokeWidth"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            style: {
              $ref: "#/definitions/Style",
              description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
            },
            text: {
              anyOf: [
                {
                  $ref: "#/definitions/Text"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            tooltip: {
              items: {
                $ref: "#/definitions/Tooltip"
              },
              type: "array"
            },
            visibility: {
              items: {
                $ref: "#/definitions/VisibilityCondition"
              },
              type: "array"
            },
            x: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            x1: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            x1e: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            xAxis: {
              $ref: "#/definitions/AxisPosition",
              description: "not supported"
            },
            xDomain: {
              anyOf: [
                {
                  $ref: "#/definitions/DomainInterval"
                },
                {
                  $ref: "#/definitions/DomainChrInterval"
                },
                {
                  $ref: "#/definitions/DomainChr"
                }
              ],
              description: "Specify the visible region of genomic x-axis"
            },
            xOffset: {
              description: "Specify the x offset of views in the unit of pixels",
              type: "number"
            },
            xe: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            y: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            y1: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            y1e: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            yDomain: {
              anyOf: [
                {
                  $ref: "#/definitions/DomainInterval"
                },
                {
                  $ref: "#/definitions/DomainChrInterval"
                },
                {
                  $ref: "#/definitions/DomainChr"
                }
              ],
              description: "Specify the visible region of genomic y-axis"
            },
            yOffset: {
              description: "Specify the y offset of views in the unit of pixels",
              type: "number"
            },
            ye: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            zoomLimits: {
              $ref: "#/definitions/ZoomLimits"
            }
          },
          type: "object"
        },
        type: "array"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      overrideTemplate: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      row: {
        anyOf: [
          {
            $ref: "#/definitions/Row"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      size: {
        anyOf: [
          {
            $ref: "#/definitions/Size"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      stretch: {
        type: "boolean"
      },
      stroke: {
        anyOf: [
          {
            $ref: "#/definitions/Stroke"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      strokeWidth: {
        anyOf: [
          {
            $ref: "#/definitions/StrokeWidth"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      text: {
        anyOf: [
          {
            $ref: "#/definitions/Text"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      tooltip: {
        items: {
          $ref: "#/definitions/Tooltip"
        },
        type: "array"
      },
      visibility: {
        items: {
          $ref: "#/definitions/VisibilityCondition"
        },
        type: "array"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      x: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1e: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      xe: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1e: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      ye: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "height",
      "overlay",
      "width"
    ],
    type: "object"
  },
  OverlaidTracks: {
    additionalProperties: false,
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      alignment: {
        "const": "overlay",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      color: {
        anyOf: [
          {
            $ref: "#/definitions/Color"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      dataTransform: {
        items: {
          $ref: "#/definitions/DataTransform"
        },
        type: "array"
      },
      displacement: {
        $ref: "#/definitions/Displacement"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      flipY: {
        type: "boolean"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      mark: {
        $ref: "#/definitions/Mark"
      },
      opacity: {
        anyOf: [
          {
            $ref: "#/definitions/Opacity"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      overrideTemplate: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      row: {
        anyOf: [
          {
            $ref: "#/definitions/Row"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      size: {
        anyOf: [
          {
            $ref: "#/definitions/Size"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      stretch: {
        type: "boolean"
      },
      stroke: {
        anyOf: [
          {
            $ref: "#/definitions/Stroke"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      strokeWidth: {
        anyOf: [
          {
            $ref: "#/definitions/StrokeWidth"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      text: {
        anyOf: [
          {
            $ref: "#/definitions/Text"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      tooltip: {
        items: {
          $ref: "#/definitions/Tooltip"
        },
        type: "array"
      },
      tracks: {
        items: {
          $ref: "#/definitions/PartialTrack"
        },
        type: "array"
      },
      visibility: {
        items: {
          $ref: "#/definitions/VisibilityCondition"
        },
        type: "array"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      x: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1e: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      xe: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1e: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      ye: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "alignment",
      "tracks",
      "width",
      "height"
    ],
    type: "object"
  },
  PREDEFINED_COLORS: {
    "enum": [
      "viridis",
      "grey",
      "spectral",
      "warm",
      "cividis",
      "bupu",
      "rdbu",
      "hot",
      "pink"
    ],
    type: "string"
  },
  PartialTrack: {
    additionalProperties: false,
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      color: {
        anyOf: [
          {
            $ref: "#/definitions/Color"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      dataTransform: {
        items: {
          $ref: "#/definitions/DataTransform"
        },
        type: "array"
      },
      displacement: {
        $ref: "#/definitions/Displacement"
      },
      encoding: {
        additionalProperties: {
          $ref: "#/definitions/Channel"
        },
        type: "object"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      flipY: {
        type: "boolean"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      mark: {
        $ref: "#/definitions/Mark"
      },
      opacity: {
        anyOf: [
          {
            $ref: "#/definitions/Opacity"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlay: {
        items: {
          additionalProperties: false,
          properties: {
            _invalidTrack: {
              description: "internal",
              type: "boolean"
            },
            _renderingId: {
              description: "internal",
              type: "string"
            },
            assembly: {
              $ref: "#/definitions/Assembly",
              description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
            },
            centerRadius: {
              description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
              type: "number"
            },
            color: {
              anyOf: [
                {
                  $ref: "#/definitions/Color"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            data: {
              $ref: "#/definitions/DataDeep"
            },
            dataTransform: {
              items: {
                $ref: "#/definitions/DataTransform"
              },
              type: "array"
            },
            displacement: {
              $ref: "#/definitions/Displacement"
            },
            endAngle: {
              description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
              type: "number"
            },
            flipY: {
              type: "boolean"
            },
            id: {
              type: "string"
            },
            innerRadius: {
              description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
              type: "number"
            },
            linkingId: {
              description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
              type: "string"
            },
            mark: {
              $ref: "#/definitions/Mark"
            },
            opacity: {
              anyOf: [
                {
                  $ref: "#/definitions/Opacity"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            orientation: {
              $ref: "#/definitions/Orientation",
              description: "Specify the orientation."
            },
            outerRadius: {
              description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
              type: "number"
            },
            overlayOnPreviousTrack: {
              type: "boolean"
            },
            overrideTemplate: {
              type: "boolean"
            },
            prerelease: {
              additionalProperties: false,
              description: "internal",
              type: "object"
            },
            row: {
              anyOf: [
                {
                  $ref: "#/definitions/Row"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            size: {
              anyOf: [
                {
                  $ref: "#/definitions/Size"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            spacing: {
              description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
              type: "number"
            },
            startAngle: {
              description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
              type: "number"
            },
            "static": {
              description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
              type: "boolean"
            },
            stretch: {
              type: "boolean"
            },
            stroke: {
              anyOf: [
                {
                  $ref: "#/definitions/Stroke"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            strokeWidth: {
              anyOf: [
                {
                  $ref: "#/definitions/StrokeWidth"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            style: {
              $ref: "#/definitions/Style",
              description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
            },
            text: {
              anyOf: [
                {
                  $ref: "#/definitions/Text"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            tooltip: {
              items: {
                $ref: "#/definitions/Tooltip"
              },
              type: "array"
            },
            visibility: {
              items: {
                $ref: "#/definitions/VisibilityCondition"
              },
              type: "array"
            },
            x: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            x1: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            x1e: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            xAxis: {
              $ref: "#/definitions/AxisPosition",
              description: "not supported"
            },
            xDomain: {
              anyOf: [
                {
                  $ref: "#/definitions/DomainInterval"
                },
                {
                  $ref: "#/definitions/DomainChrInterval"
                },
                {
                  $ref: "#/definitions/DomainChr"
                }
              ],
              description: "Specify the visible region of genomic x-axis"
            },
            xOffset: {
              description: "Specify the x offset of views in the unit of pixels",
              type: "number"
            },
            xe: {
              anyOf: [
                {
                  $ref: "#/definitions/X"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            y: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            y1: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            y1e: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            yDomain: {
              anyOf: [
                {
                  $ref: "#/definitions/DomainInterval"
                },
                {
                  $ref: "#/definitions/DomainChrInterval"
                },
                {
                  $ref: "#/definitions/DomainChr"
                }
              ],
              description: "Specify the visible region of genomic y-axis"
            },
            yOffset: {
              description: "Specify the y offset of views in the unit of pixels",
              type: "number"
            },
            ye: {
              anyOf: [
                {
                  $ref: "#/definitions/Y"
                },
                {
                  $ref: "#/definitions/ChannelValue"
                }
              ]
            },
            zoomLimits: {
              $ref: "#/definitions/ZoomLimits"
            }
          },
          type: "object"
        },
        type: "array"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      overrideTemplate: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      row: {
        anyOf: [
          {
            $ref: "#/definitions/Row"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      size: {
        anyOf: [
          {
            $ref: "#/definitions/Size"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      stretch: {
        type: "boolean"
      },
      stroke: {
        anyOf: [
          {
            $ref: "#/definitions/Stroke"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      strokeWidth: {
        anyOf: [
          {
            $ref: "#/definitions/StrokeWidth"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      template: {
        type: "string"
      },
      text: {
        anyOf: [
          {
            $ref: "#/definitions/Text"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      tooltip: {
        items: {
          $ref: "#/definitions/Tooltip"
        },
        type: "array"
      },
      visibility: {
        items: {
          $ref: "#/definitions/VisibilityCondition"
        },
        type: "array"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      x: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1e: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      xe: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1e: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      ye: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    type: "object"
  },
  Range: {
    anyOf: [
      {
        $ref: "#/definitions/ValueExtent"
      },
      {
        $ref: "#/definitions/PREDEFINED_COLORS"
      }
    ]
  },
  RangeFilter: {
    additionalProperties: false,
    properties: {
      field: {
        description: "A filter is applied based on the values of the specified data field",
        type: "string"
      },
      inRange: {
        description: "Check whether the value is in a number range.",
        items: {
          type: "number"
        },
        type: "array"
      },
      not: {
        description: 'when `{"not": true}`, apply a NOT logical operation to the filter.\n\n__Default:__ `false`',
        type: "boolean"
      },
      type: {
        "const": "filter",
        type: "string"
      }
    },
    required: [
      "field",
      "inRange",
      "type"
    ],
    type: "object"
  },
  ResponsiveSize: {
    anyOf: [
      {
        type: "boolean"
      },
      {
        additionalProperties: false,
        properties: {
          height: {
            type: "boolean"
          },
          width: {
            type: "boolean"
          }
        },
        type: "object"
      }
    ]
  },
  RootSpecWithMultipleViews: {
    additionalProperties: false,
    properties: {
      arrangement: {
        description: "Specify how multiple views are arranged.",
        "enum": [
          "parallel",
          "serial",
          "horizontal",
          "vertical"
        ],
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      description: {
        type: "string"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      responsiveSize: {
        $ref: "#/definitions/ResponsiveSize",
        description: "Determine whether to make the size of `GoslingComponent` bound to its parent element. __Default__: `false`"
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      title: {
        type: "string"
      },
      views: {
        description: "An array of view specifications",
        items: {
          anyOf: [
            {
              $ref: "#/definitions/SingleView"
            },
            {
              $ref: "#/definitions/MultipleViews"
            }
          ]
        },
        type: "array"
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "views"
    ],
    type: "object"
  },
  RootSpecWithSingleView: {
    anyOf: [
      {
        additionalProperties: false,
        properties: {
          _invalidTrack: {
            description: "internal",
            type: "boolean"
          },
          _renderingId: {
            description: "internal",
            type: "string"
          },
          alignment: {
            "const": "overlay",
            type: "string"
          },
          assembly: {
            $ref: "#/definitions/Assembly",
            description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
          },
          centerRadius: {
            description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
            type: "number"
          },
          color: {
            anyOf: [
              {
                $ref: "#/definitions/Color"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          data: {
            $ref: "#/definitions/DataDeep"
          },
          dataTransform: {
            items: {
              $ref: "#/definitions/DataTransform"
            },
            type: "array"
          },
          description: {
            type: "string"
          },
          displacement: {
            $ref: "#/definitions/Displacement"
          },
          endAngle: {
            description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
            type: "number"
          },
          flipY: {
            type: "boolean"
          },
          height: {
            description: "Specify the track height in pixels.",
            type: "number"
          },
          id: {
            type: "string"
          },
          innerRadius: {
            description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
            type: "number"
          },
          layout: {
            $ref: "#/definitions/Layout",
            description: "Specify the layout type of all tracks."
          },
          linkingId: {
            description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
            type: "string"
          },
          mark: {
            $ref: "#/definitions/Mark"
          },
          opacity: {
            anyOf: [
              {
                $ref: "#/definitions/Opacity"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          orientation: {
            $ref: "#/definitions/Orientation",
            description: "Specify the orientation."
          },
          outerRadius: {
            description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
            type: "number"
          },
          overlayOnPreviousTrack: {
            type: "boolean"
          },
          overrideTemplate: {
            type: "boolean"
          },
          prerelease: {
            additionalProperties: false,
            description: "internal",
            type: "object"
          },
          responsiveSize: {
            $ref: "#/definitions/ResponsiveSize",
            description: "Determine whether to make the size of `GoslingComponent` bound to its parent element. __Default__: `false`"
          },
          row: {
            anyOf: [
              {
                $ref: "#/definitions/Row"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          size: {
            anyOf: [
              {
                $ref: "#/definitions/Size"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          spacing: {
            description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
            type: "number"
          },
          startAngle: {
            description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
            type: "number"
          },
          "static": {
            description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
            type: "boolean"
          },
          stretch: {
            type: "boolean"
          },
          stroke: {
            anyOf: [
              {
                $ref: "#/definitions/Stroke"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          strokeWidth: {
            anyOf: [
              {
                $ref: "#/definitions/StrokeWidth"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          style: {
            $ref: "#/definitions/Style",
            description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
          },
          subtitle: {
            type: "string"
          },
          text: {
            anyOf: [
              {
                $ref: "#/definitions/Text"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          title: {
            description: "If defined, will show the textual label on the left-top corner of a track.",
            type: "string"
          },
          tooltip: {
            items: {
              $ref: "#/definitions/Tooltip"
            },
            type: "array"
          },
          tracks: {
            items: {
              $ref: "#/definitions/PartialTrack"
            },
            type: "array"
          },
          visibility: {
            items: {
              $ref: "#/definitions/VisibilityCondition"
            },
            type: "array"
          },
          width: {
            description: "Specify the track width in pixels.",
            type: "number"
          },
          x: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          x1: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          x1e: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          xAxis: {
            $ref: "#/definitions/AxisPosition",
            description: "not supported"
          },
          xDomain: {
            anyOf: [
              {
                $ref: "#/definitions/DomainInterval"
              },
              {
                $ref: "#/definitions/DomainChrInterval"
              },
              {
                $ref: "#/definitions/DomainChr"
              }
            ],
            description: "Specify the visible region of genomic x-axis"
          },
          xOffset: {
            description: "Specify the x offset of views in the unit of pixels",
            type: "number"
          },
          xe: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          y: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          y1: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          y1e: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          yDomain: {
            anyOf: [
              {
                $ref: "#/definitions/DomainInterval"
              },
              {
                $ref: "#/definitions/DomainChrInterval"
              },
              {
                $ref: "#/definitions/DomainChr"
              }
            ],
            description: "Specify the visible region of genomic y-axis"
          },
          yOffset: {
            description: "Specify the y offset of views in the unit of pixels",
            type: "number"
          },
          ye: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          zoomLimits: {
            $ref: "#/definitions/ZoomLimits"
          }
        },
        required: [
          "alignment",
          "height",
          "tracks",
          "width"
        ],
        type: "object"
      },
      {
        additionalProperties: false,
        properties: {
          _invalidTrack: {
            description: "internal",
            type: "boolean"
          },
          _renderingId: {
            description: "internal",
            type: "string"
          },
          alignment: {
            "const": "stack",
            type: "string"
          },
          assembly: {
            $ref: "#/definitions/Assembly",
            description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
          },
          centerRadius: {
            description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
            type: "number"
          },
          color: {
            anyOf: [
              {
                $ref: "#/definitions/Color"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          data: {
            $ref: "#/definitions/DataDeep"
          },
          dataTransform: {
            items: {
              $ref: "#/definitions/DataTransform"
            },
            type: "array"
          },
          description: {
            type: "string"
          },
          displacement: {
            $ref: "#/definitions/Displacement"
          },
          endAngle: {
            description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
            type: "number"
          },
          flipY: {
            type: "boolean"
          },
          height: {
            description: "Specify the track height in pixels.",
            type: "number"
          },
          id: {
            type: "string"
          },
          innerRadius: {
            description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
            type: "number"
          },
          layout: {
            $ref: "#/definitions/Layout",
            description: "Specify the layout type of all tracks."
          },
          linkingId: {
            description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
            type: "string"
          },
          mark: {
            $ref: "#/definitions/Mark"
          },
          opacity: {
            anyOf: [
              {
                $ref: "#/definitions/Opacity"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          orientation: {
            $ref: "#/definitions/Orientation",
            description: "Specify the orientation."
          },
          outerRadius: {
            description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
            type: "number"
          },
          overlayOnPreviousTrack: {
            type: "boolean"
          },
          overrideTemplate: {
            type: "boolean"
          },
          prerelease: {
            additionalProperties: false,
            description: "internal",
            type: "object"
          },
          responsiveSize: {
            $ref: "#/definitions/ResponsiveSize",
            description: "Determine whether to make the size of `GoslingComponent` bound to its parent element. __Default__: `false`"
          },
          row: {
            anyOf: [
              {
                $ref: "#/definitions/Row"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          size: {
            anyOf: [
              {
                $ref: "#/definitions/Size"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          spacing: {
            description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
            type: "number"
          },
          startAngle: {
            description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
            type: "number"
          },
          "static": {
            description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
            type: "boolean"
          },
          stretch: {
            type: "boolean"
          },
          stroke: {
            anyOf: [
              {
                $ref: "#/definitions/Stroke"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          strokeWidth: {
            anyOf: [
              {
                $ref: "#/definitions/StrokeWidth"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          style: {
            $ref: "#/definitions/Style",
            description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
          },
          subtitle: {
            type: "string"
          },
          text: {
            anyOf: [
              {
                $ref: "#/definitions/Text"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          title: {
            description: "If defined, will show the textual label on the left-top corner of a track.",
            type: "string"
          },
          tooltip: {
            items: {
              $ref: "#/definitions/Tooltip"
            },
            type: "array"
          },
          tracks: {
            items: {
              anyOf: [
                {
                  $ref: "#/definitions/PartialTrack"
                },
                {
                  $ref: "#/definitions/OverlaidTracks"
                }
              ]
            },
            type: "array"
          },
          visibility: {
            items: {
              $ref: "#/definitions/VisibilityCondition"
            },
            type: "array"
          },
          width: {
            description: "Specify the track width in pixels.",
            type: "number"
          },
          x: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          x1: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          x1e: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          xAxis: {
            $ref: "#/definitions/AxisPosition",
            description: "not supported"
          },
          xDomain: {
            anyOf: [
              {
                $ref: "#/definitions/DomainInterval"
              },
              {
                $ref: "#/definitions/DomainChrInterval"
              },
              {
                $ref: "#/definitions/DomainChr"
              }
            ],
            description: "Specify the visible region of genomic x-axis"
          },
          xOffset: {
            description: "Specify the x offset of views in the unit of pixels",
            type: "number"
          },
          xe: {
            anyOf: [
              {
                $ref: "#/definitions/X"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          y: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          y1: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          y1e: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          yDomain: {
            anyOf: [
              {
                $ref: "#/definitions/DomainInterval"
              },
              {
                $ref: "#/definitions/DomainChrInterval"
              },
              {
                $ref: "#/definitions/DomainChr"
              }
            ],
            description: "Specify the visible region of genomic y-axis"
          },
          yOffset: {
            description: "Specify the y offset of views in the unit of pixels",
            type: "number"
          },
          ye: {
            anyOf: [
              {
                $ref: "#/definitions/Y"
              },
              {
                $ref: "#/definitions/ChannelValue"
              }
            ]
          },
          zoomLimits: {
            $ref: "#/definitions/ZoomLimits"
          }
        },
        required: [
          "tracks"
        ],
        type: "object"
      },
      {
        additionalProperties: false,
        properties: {
          assembly: {
            $ref: "#/definitions/Assembly",
            description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
          },
          centerRadius: {
            description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
            type: "number"
          },
          description: {
            type: "string"
          },
          layout: {
            $ref: "#/definitions/Layout",
            description: "Specify the layout type of all tracks."
          },
          linkingId: {
            description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
            type: "string"
          },
          orientation: {
            $ref: "#/definitions/Orientation",
            description: "Specify the orientation."
          },
          responsiveSize: {
            $ref: "#/definitions/ResponsiveSize",
            description: "Determine whether to make the size of `GoslingComponent` bound to its parent element. __Default__: `false`"
          },
          spacing: {
            description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
            type: "number"
          },
          "static": {
            description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
            type: "boolean"
          },
          style: {
            $ref: "#/definitions/Style",
            description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
          },
          subtitle: {
            type: "string"
          },
          title: {
            type: "string"
          },
          tracks: {
            items: {
              $ref: "#/definitions/Track"
            },
            type: "array"
          },
          xAxis: {
            $ref: "#/definitions/AxisPosition",
            description: "not supported"
          },
          xDomain: {
            anyOf: [
              {
                $ref: "#/definitions/DomainInterval"
              },
              {
                $ref: "#/definitions/DomainChrInterval"
              },
              {
                $ref: "#/definitions/DomainChr"
              }
            ],
            description: "Specify the visible region of genomic x-axis"
          },
          xOffset: {
            description: "Specify the x offset of views in the unit of pixels",
            type: "number"
          },
          yDomain: {
            anyOf: [
              {
                $ref: "#/definitions/DomainInterval"
              },
              {
                $ref: "#/definitions/DomainChrInterval"
              },
              {
                $ref: "#/definitions/DomainChr"
              }
            ],
            description: "Specify the visible region of genomic y-axis"
          },
          yOffset: {
            description: "Specify the y offset of views in the unit of pixels",
            type: "number"
          },
          zoomLimits: {
            $ref: "#/definitions/ZoomLimits"
          }
        },
        required: [
          "tracks"
        ],
        type: "object"
      }
    ]
  },
  Row: {
    additionalProperties: false,
    properties: {
      domain: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      grid: {
        description: "Whether to display grid. __Default__: `false`",
        type: "boolean"
      },
      legend: {
        description: "Whether to display legend. __Default__: `false`",
        type: "boolean"
      },
      padding: {
        description: "Determines the size of inner white spaces on the top and bottom of individiual rows. __Default__: `0`",
        type: "number"
      },
      range: {
        $ref: "#/definitions/ValueExtent",
        description: "Determine the start and end position of rendering area of this track along vertical axis. __Default__: `[0, height]`"
      },
      type: {
        "const": "nominal",
        description: "Specify the data type",
        type: "string"
      }
    },
    type: "object"
  },
  SingleTrack: {
    additionalProperties: false,
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      color: {
        anyOf: [
          {
            $ref: "#/definitions/Color"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      dataTransform: {
        items: {
          $ref: "#/definitions/DataTransform"
        },
        type: "array"
      },
      displacement: {
        $ref: "#/definitions/Displacement"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      flipY: {
        type: "boolean"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      mark: {
        $ref: "#/definitions/Mark"
      },
      opacity: {
        anyOf: [
          {
            $ref: "#/definitions/Opacity"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      overrideTemplate: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      row: {
        anyOf: [
          {
            $ref: "#/definitions/Row"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      size: {
        anyOf: [
          {
            $ref: "#/definitions/Size"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      stretch: {
        type: "boolean"
      },
      stroke: {
        anyOf: [
          {
            $ref: "#/definitions/Stroke"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      strokeWidth: {
        anyOf: [
          {
            $ref: "#/definitions/StrokeWidth"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      text: {
        anyOf: [
          {
            $ref: "#/definitions/Text"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      tooltip: {
        items: {
          $ref: "#/definitions/Tooltip"
        },
        type: "array"
      },
      visibility: {
        items: {
          $ref: "#/definitions/VisibilityCondition"
        },
        type: "array"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      x: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1e: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      xe: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1e: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      ye: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "data",
      "height",
      "mark",
      "width"
    ],
    type: "object"
  },
  SingleView: {
    anyOf: [
      {
        $ref: "#/definitions/OverlaidTracks"
      },
      {
        $ref: "#/definitions/StackedTracks"
      },
      {
        $ref: "#/definitions/FlatTracks"
      }
    ]
  },
  Size: {
    additionalProperties: false,
    properties: {
      domain: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      legend: {
        description: "not supported: Whether to display legend. __Default__: `false`",
        type: "boolean"
      },
      range: {
        $ref: "#/definitions/ValueExtent",
        description: "Ranges of visual channel values"
      },
      type: {
        description: "Specify the data type",
        "enum": [
          "quantitative",
          "nominal"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  SizeVisibilityCondition: {
    additionalProperties: false,
    properties: {
      conditionPadding: {
        description: "Specify the buffer size (in pixel) of width or height when calculating the visibility.\n\n__Default__: `0`",
        type: "number"
      },
      measure: {
        description: "Specify which aspect of the `target` will be compared to the `threshold`.",
        "enum": [
          "width",
          "height"
        ],
        type: "string"
      },
      operation: {
        $ref: "#/definitions/LogicalOperation",
        description: 'A string that pecifies the logical operation to conduct between `threshold` and the `measure` of `target`. Support\n\n- greater than : "greater-than", "gt", "GT"\n\n- less than : "less-than", "lt", "LT"\n\n- greater than or equal to : "greater-than-or-equal-to", "gtet", "GTET"\n\n- less than or equal to : "less-than-or-equal-to", "ltet", "LTET"'
      },
      target: {
        description: "Target specifies the object that you want to compare with the threshold.",
        "enum": [
          "track",
          "mark"
        ],
        type: "string"
      },
      threshold: {
        anyOf: [
          {
            type: "number"
          },
          {
            "const": "|xe-x|",
            type: "string"
          }
        ],
        description: 'Specify the threshold as one of:\n\n- A number representing a fixed threshold in the unit of pixels;\n\n- `"|xe-x|"`, using the distance between `xe` and `x` as threshold'
      },
      transitionPadding: {
        description: "Specify the buffer size (in pixel) of width or height for smooth transition.\n\n__Default__: `0`",
        type: "number"
      }
    },
    required: [
      "measure",
      "operation",
      "target",
      "threshold"
    ],
    type: "object"
  },
  StackedTracks: {
    additionalProperties: false,
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      alignment: {
        "const": "stack",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      color: {
        anyOf: [
          {
            $ref: "#/definitions/Color"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      dataTransform: {
        items: {
          $ref: "#/definitions/DataTransform"
        },
        type: "array"
      },
      displacement: {
        $ref: "#/definitions/Displacement"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      flipY: {
        type: "boolean"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      mark: {
        $ref: "#/definitions/Mark"
      },
      opacity: {
        anyOf: [
          {
            $ref: "#/definitions/Opacity"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      overrideTemplate: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      row: {
        anyOf: [
          {
            $ref: "#/definitions/Row"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      size: {
        anyOf: [
          {
            $ref: "#/definitions/Size"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      stretch: {
        type: "boolean"
      },
      stroke: {
        anyOf: [
          {
            $ref: "#/definitions/Stroke"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      strokeWidth: {
        anyOf: [
          {
            $ref: "#/definitions/StrokeWidth"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      text: {
        anyOf: [
          {
            $ref: "#/definitions/Text"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      tooltip: {
        items: {
          $ref: "#/definitions/Tooltip"
        },
        type: "array"
      },
      tracks: {
        items: {
          anyOf: [
            {
              $ref: "#/definitions/PartialTrack"
            },
            {
              $ref: "#/definitions/OverlaidTracks"
            }
          ]
        },
        type: "array"
      },
      visibility: {
        items: {
          $ref: "#/definitions/VisibilityCondition"
        },
        type: "array"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      x: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      x1e: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      xe: {
        anyOf: [
          {
            $ref: "#/definitions/X"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      y1e: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      ye: {
        anyOf: [
          {
            $ref: "#/definitions/Y"
          },
          {
            $ref: "#/definitions/ChannelValue"
          }
        ]
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "tracks"
    ],
    type: "object"
  },
  StrConcatTransform: {
    additionalProperties: false,
    properties: {
      fields: {
        items: {
          type: "string"
        },
        type: "array"
      },
      newField: {
        type: "string"
      },
      separator: {
        type: "string"
      },
      type: {
        "const": "concat",
        type: "string"
      }
    },
    required: [
      "type",
      "fields",
      "newField",
      "separator"
    ],
    type: "object"
  },
  StrReplaceTransform: {
    additionalProperties: false,
    properties: {
      field: {
        type: "string"
      },
      newField: {
        type: "string"
      },
      replace: {
        items: {
          additionalProperties: false,
          properties: {
            from: {
              type: "string"
            },
            to: {
              type: "string"
            }
          },
          required: [
            "from",
            "to"
          ],
          type: "object"
        },
        type: "array"
      },
      type: {
        "const": "replace",
        type: "string"
      }
    },
    required: [
      "type",
      "field",
      "newField",
      "replace"
    ],
    type: "object"
  },
  Stroke: {
    additionalProperties: false,
    properties: {
      domain: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      range: {
        $ref: "#/definitions/Range",
        description: "Ranges of visual channel values"
      },
      type: {
        description: "Specify the data type",
        "enum": [
          "quantitative",
          "nominal"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  StrokeWidth: {
    additionalProperties: false,
    properties: {
      domain: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      range: {
        $ref: "#/definitions/ValueExtent",
        description: "Ranges of visual channel values"
      },
      type: {
        description: "Specify the data type",
        "enum": [
          "quantitative",
          "nominal"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  Style: {
    additionalProperties: false,
    properties: {
      align: {
        description: "Specify the alignment of marks. This property is currently only supported for `triangle` marks.",
        "enum": [
          "left",
          "right"
        ],
        type: "string"
      },
      background: {
        type: "string"
      },
      backgroundOpacity: {
        type: "number"
      },
      bezierLink: {
        description: "Specify whether to use bezier curves for the `link` marks.",
        type: "boolean"
      },
      curve: {
        description: "Specify the curve of `rule` marks.",
        "enum": [
          "top",
          "bottom",
          "left",
          "right"
        ],
        type: "string"
      },
      dashed: {
        description: "Specify the pattern of dashes and gaps for `rule` marks.",
        items: [
          {
            type: "number"
          },
          {
            type: "number"
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      },
      dx: {
        description: "Offset the position of marks in x direction. This property is currently only supported for `text` marks",
        type: "number"
      },
      dy: {
        description: "Offset the position of marks in y direction. This property is currently only supported for `text` marks.",
        type: "number"
      },
      enableSmoothPath: {
        description: "Whether to enable smooth paths when drawing curves.\n\n__Default__: `false`",
        type: "boolean"
      },
      flatWithinLink: {
        description: "Specify whether to use a flat within-links, such as the one in Sashimi plots. __Default__: `false`",
        type: "boolean"
      },
      inlineLegend: {
        description: "Specify whether to show legend in a single horizontal line?",
        type: "boolean"
      },
      legendTitle: {
        description: "If defined, show legend title on the top or left",
        type: "string"
      },
      linePattern: {
        additionalProperties: false,
        description: "Specify the pattern of dashes and gaps for `rule` marks.",
        properties: {
          size: {
            type: "number"
          },
          type: {
            "enum": [
              "triangleLeft",
              "triangleRight"
            ],
            type: "string"
          }
        },
        required: [
          "type",
          "size"
        ],
        type: "object"
      },
      linkConnectionType: {
        description: 'Specify the connetion type of `betweenLink` marks.\n\n__Default__: `"corner"`',
        "enum": [
          "straight",
          "curve",
          "corner"
        ],
        type: "string"
      },
      outline: {
        type: "string"
      },
      outlineWidth: {
        type: "number"
      },
      textAnchor: {
        description: "Specify the alignment of `text` marks to a given point.",
        "enum": [
          "start",
          "middle",
          "end"
        ],
        type: "string"
      },
      textFontSize: {
        description: "Specify the font size of `text` marks. Can also be specified using the `size` channel option of `text` marks.",
        type: "number"
      },
      textFontWeight: {
        description: "Specify the font weight of `text` marks.",
        "enum": [
          "bold",
          "normal"
        ],
        type: "string"
      },
      textStroke: {
        description: "Specify the stroke of `text` marks. Can also be specified using the `stroke` channel option of `text` marks.",
        type: "string"
      },
      textStrokeWidth: {
        description: "Specify the stroke width of `text` marks. Can also be specified using the `strokeWidth` channel option of `text` marks.",
        type: "number"
      }
    },
    type: "object"
  },
  TemplateTrack: {
    additionalProperties: false,
    description: "Template specification that will be internally converted into `SingleTrack` for rendering.",
    properties: {
      _invalidTrack: {
        description: "internal",
        type: "boolean"
      },
      _renderingId: {
        description: "internal",
        type: "string"
      },
      assembly: {
        $ref: "#/definitions/Assembly",
        description: 'A string that specifies the genome builds to use. Currently support `"hg38"`, `"hg19"`, `"hg18"`, `"hg17"`, `"hg16"`, `"mm10"`, `"mm9"`, and `"unknown"`.\n\n__Note:__: with `"unknown"` assembly, genomic axes do not show chrN: in labels.'
      },
      centerRadius: {
        description: "Proportion of the radius of the center white space.\n\n__Default:__ `0.3`",
        type: "number"
      },
      data: {
        $ref: "#/definitions/DataDeep"
      },
      encoding: {
        additionalProperties: {
          $ref: "#/definitions/Channel"
        },
        type: "object"
      },
      endAngle: {
        description: 'Specify the end angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      height: {
        description: "Specify the track height in pixels.",
        type: "number"
      },
      id: {
        type: "string"
      },
      innerRadius: {
        description: 'Specify the inner radius of tracks when (`{"layout": "circular"}`).',
        type: "number"
      },
      layout: {
        $ref: "#/definitions/Layout",
        description: "Specify the layout type of all tracks."
      },
      linkingId: {
        description: "Specify an ID for [linking multiple views](http://gosling-lang.org/docs/user-interaction#linking-views)",
        type: "string"
      },
      orientation: {
        $ref: "#/definitions/Orientation",
        description: "Specify the orientation."
      },
      outerRadius: {
        description: 'Specify the outer radius of tracks when `{"layout": "circular"}`.',
        type: "number"
      },
      overlayOnPreviousTrack: {
        type: "boolean"
      },
      prerelease: {
        additionalProperties: false,
        description: "internal",
        type: "object"
      },
      spacing: {
        description: '- If `{"layout": "linear"}`, specify the space between tracks in pixels;\n\n- If `{"layout": "circular"}`, specify the space between tracks in percentage ranging from 0 to 100.',
        type: "number"
      },
      startAngle: {
        description: 'Specify the start angle (in the range of [0, 360]) of circular tracks (`{"layout": "circular"}`).',
        type: "number"
      },
      "static": {
        description: "Whether to disable [Zooming and Panning](http://gosling-lang.org/docs/user-interaction#zooming-and-panning), __Default:__ `false`.",
        type: "boolean"
      },
      style: {
        $ref: "#/definitions/Style",
        description: "Define the [style](http://gosling-lang.org/docs/visual-channel#style-related-properties) of multive views. Will be overriden by the style of children elements (e.g., view, track)."
      },
      subtitle: {
        type: "string"
      },
      template: {
        type: "string"
      },
      title: {
        description: "If defined, will show the textual label on the left-top corner of a track.",
        type: "string"
      },
      width: {
        description: "Specify the track width in pixels.",
        type: "number"
      },
      xAxis: {
        $ref: "#/definitions/AxisPosition",
        description: "not supported"
      },
      xDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic x-axis"
      },
      xOffset: {
        description: "Specify the x offset of views in the unit of pixels",
        type: "number"
      },
      yDomain: {
        anyOf: [
          {
            $ref: "#/definitions/DomainInterval"
          },
          {
            $ref: "#/definitions/DomainChrInterval"
          },
          {
            $ref: "#/definitions/DomainChr"
          }
        ],
        description: "Specify the visible region of genomic y-axis"
      },
      yOffset: {
        description: "Specify the y offset of views in the unit of pixels",
        type: "number"
      },
      zoomLimits: {
        $ref: "#/definitions/ZoomLimits"
      }
    },
    required: [
      "data",
      "height",
      "template",
      "width"
    ],
    type: "object"
  },
  Text: {
    additionalProperties: false,
    properties: {
      domain: {
        description: "Values of the data",
        items: {
          type: "string"
        },
        type: "array"
      },
      field: {
        description: "Name of the data field",
        type: "string"
      },
      range: {
        description: "Ranges of visual channel values",
        items: {
          type: "string"
        },
        type: "array"
      },
      type: {
        description: "Specify the data type",
        "enum": [
          "quantitative",
          "nominal"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  Tooltip: {
    additionalProperties: false,
    properties: {
      alt: {
        type: "string"
      },
      field: {
        type: "string"
      },
      format: {
        type: "string"
      },
      type: {
        $ref: "#/definitions/FieldType"
      }
    },
    required: [
      "field",
      "type"
    ],
    type: "object"
  },
  Track: {
    anyOf: [
      {
        $ref: "#/definitions/SingleTrack"
      },
      {
        $ref: "#/definitions/OverlaidTrack"
      },
      {
        $ref: "#/definitions/DataTrack"
      },
      {
        $ref: "#/definitions/TemplateTrack"
      }
    ]
  },
  ValueExtent: {
    anyOf: [
      {
        items: {
          type: "string"
        },
        type: "array"
      },
      {
        items: {
          type: "number"
        },
        type: "array"
      }
    ]
  },
  VectorData: {
    additionalProperties: false,
    description: 'One-dimensional quantitative values along genomic position (e.g., bigwig) can be converted into HiGlass\' `"vector"` format data. Find out more about this format at [HiGlass Docs](https://docs.higlass.io/data_preparation.html#bigwig-files).',
    properties: {
      aggregation: {
        $ref: "#/definitions/BinAggregate",
        description: 'Determine aggregation function to apply within bins. __Default__: `"mean"`'
      },
      binSize: {
        description: "Binning the genomic interval in tiles (unit size: 256).",
        type: "number"
      },
      column: {
        description: "Assign a field name of the middle position of genomic intervals.",
        type: "string"
      },
      end: {
        description: "Assign a field name of the end position of genomic intervals.",
        type: "string"
      },
      start: {
        description: "Assign a field name of the start position of genomic intervals.",
        type: "string"
      },
      type: {
        "const": "vector",
        type: "string"
      },
      url: {
        description: "Specify the URL address of the data file.",
        type: "string"
      },
      value: {
        description: "Assign a field name of quantitative values.",
        type: "string"
      }
    },
    required: [
      "type",
      "url",
      "column",
      "value"
    ],
    type: "object"
  },
  VisibilityCondition: {
    anyOf: [
      {
        $ref: "#/definitions/SizeVisibilityCondition"
      },
      {
        $ref: "#/definitions/ZoomLevelVisibilityCondition"
      }
    ]
  },
  X: {
    additionalProperties: false,
    properties: {
      aggregate: {
        $ref: "#/definitions/Aggregate",
        description: "Specify how to aggregate data. __Default__: `undefined`"
      },
      axis: {
        $ref: "#/definitions/AxisPosition",
        description: "Specify where should the axis be put"
      },
      domain: {
        $ref: "#/definitions/GenomicDomain",
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field.",
        type: "string"
      },
      grid: {
        description: "Whether to display grid. __Default__: `false`",
        type: "boolean"
      },
      legend: {
        description: "Whether to display legend. __Default__: `false`",
        type: "boolean"
      },
      linkingId: {
        description: "Users need to assign a unique linkingId for [linking views](/docs/user-interaction#linking-views) and [Brushing and Linking](/docs/user-interaction#brushing-and-linking)",
        type: "string"
      },
      range: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the visual channel."
      },
      type: {
        "const": "genomic",
        description: "Specify the data type.",
        type: "string"
      }
    },
    type: "object"
  },
  Y: {
    additionalProperties: false,
    properties: {
      aggregate: {
        $ref: "#/definitions/Aggregate",
        description: "Specify how to aggregate data. __Default__: `undefined`"
      },
      axis: {
        $ref: "#/definitions/AxisPosition",
        description: "Specify where should the axis be put"
      },
      baseline: {
        description: "Custom baseline of the y-axis. __Default__: `0`",
        type: [
          "string",
          "number"
        ]
      },
      domain: {
        anyOf: [
          {
            $ref: "#/definitions/ValueExtent"
          },
          {
            $ref: "#/definitions/GenomicDomain"
          }
        ],
        description: "Values of the data"
      },
      field: {
        description: "Name of the data field.",
        type: "string"
      },
      flip: {
        description: "Whether to flip the y-axis. This is done by inverting the `range` property. __Default__: `false`",
        type: "boolean"
      },
      grid: {
        description: "Whether to display grid. __Default__: `false`",
        type: "boolean"
      },
      legend: {
        description: "Whether to display legend. __Default__: `false`",
        type: "boolean"
      },
      linkingId: {
        description: "Users need to assign a unique linkingId for [linking views](/docs/user-interaction#linking-views) and [Brushing and Linking](/docs/user-interaction#brushing-and-linking)",
        type: "string"
      },
      range: {
        $ref: "#/definitions/ValueExtent",
        description: "Values of the visual channel."
      },
      type: {
        description: "Specify the data type.",
        "enum": [
          "quantitative",
          "nominal",
          "genomic"
        ],
        type: "string"
      },
      zeroBaseline: {
        description: "Specify whether to use zero baseline. __Default__: `true`",
        type: "boolean"
      }
    },
    type: "object"
  },
  ZoomLevelVisibilityCondition: {
    additionalProperties: false,
    properties: {
      conditionPadding: {
        description: "Specify the buffer size (in pixel) of width or height when calculating the visibility.\n\n__Default__: `0`",
        type: "number"
      },
      measure: {
        "const": "zoomLevel",
        description: "Specify which aspect of the `target` will be compared to the `threshold`.",
        type: "string"
      },
      operation: {
        $ref: "#/definitions/LogicalOperation",
        description: 'A string that pecifies the logical operation to conduct between `threshold` and the `measure` of `target`. Support\n\n- greater than : "greater-than", "gt", "GT"\n\n- less than : "less-than", "lt", "LT"\n\n- greater than or equal to : "greater-than-or-equal-to", "gtet", "GTET"\n\n- less than or equal to : "less-than-or-equal-to", "ltet", "LTET"'
      },
      target: {
        description: "Target specifies the object that you want to compare with the threshold.",
        "enum": [
          "track",
          "mark"
        ],
        type: "string"
      },
      threshold: {
        description: "Set a threshold in the unit of base pairs (bp)",
        type: "number"
      },
      transitionPadding: {
        description: "Specify the buffer size (in pixel) of width or height for smooth transition.\n\n__Default__: `0`",
        type: "number"
      }
    },
    required: [
      "measure",
      "operation",
      "target",
      "threshold"
    ],
    type: "object"
  },
  ZoomLimits: {
    items: [
      {
        type: [
          "number",
          "null"
        ]
      },
      {
        type: [
          "number",
          "null"
        ]
      }
    ],
    maxItems: 2,
    minItems: 2,
    type: "array"
  }
};
var GoslingSchema = {
  $ref: $ref$2,
  $schema: $schema$4,
  definitions: definitions$3
};
const $ref$1 = "#/definitions/Theme";
const $schema$3 = "http://json-schema.org/draft-07/schema#";
const definitions$2 = {
  AxisStyle: {
    additionalProperties: false,
    properties: {
      baselineColor: {
        type: "string"
      },
      gridColor: {
        type: "string"
      },
      gridStrokeDash: {
        items: [
          {
            type: "number"
          },
          {
            type: "number"
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      },
      gridStrokeType: {
        "enum": [
          "solid",
          "dashed"
        ],
        type: "string"
      },
      gridStrokeWidth: {
        type: "number"
      },
      labelColor: {
        type: "string"
      },
      labelFontFamily: {
        type: "string"
      },
      labelFontSize: {
        type: "number"
      },
      labelFontWeight: {
        "enum": [
          "bold",
          "normal",
          "light"
        ],
        type: "string"
      },
      tickColor: {
        type: "string"
      }
    },
    type: "object"
  },
  LegendStyle: {
    additionalProperties: false,
    properties: {
      background: {
        type: "string"
      },
      backgroundOpacity: {
        type: "number"
      },
      backgroundStroke: {
        type: "string"
      },
      labelColor: {
        type: "string"
      },
      labelFontFamily: {
        type: "string"
      },
      labelFontSize: {
        type: "number"
      },
      labelFontWeight: {
        "enum": [
          "bold",
          "normal",
          "light"
        ],
        type: "string"
      },
      position: {
        "enum": [
          "top",
          "right"
        ],
        type: "string"
      },
      tickColor: {
        type: "string"
      }
    },
    type: "object"
  },
  MarkStyle: {
    additionalProperties: false,
    properties: {
      color: {
        type: "string"
      },
      nominalColorRange: {
        items: {
          type: "string"
        },
        type: "array"
      },
      opacity: {
        type: "number"
      },
      quantitativeSizeRange: {
        items: [
          {
            type: "number"
          },
          {
            type: "number"
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      },
      size: {
        type: "number"
      },
      stroke: {
        type: "string"
      },
      strokeWidth: {
        type: "number"
      }
    },
    type: "object"
  },
  RootStyle: {
    additionalProperties: false,
    properties: {
      background: {
        type: "string"
      },
      mousePositionColor: {
        type: "string"
      },
      showMousePosition: {
        type: "boolean"
      },
      subtitleAlign: {
        "enum": [
          "left",
          "middle",
          "right"
        ],
        type: "string"
      },
      subtitleBackgroundColor: {
        type: "string"
      },
      subtitleColor: {
        type: "string"
      },
      subtitleFontFamily: {
        type: "string"
      },
      subtitleFontSize: {
        type: "number"
      },
      subtitleFontWeight: {
        "enum": [
          "bold",
          "normal",
          "light"
        ],
        type: "string"
      },
      titleAlign: {
        "enum": [
          "left",
          "middle",
          "right"
        ],
        type: "string"
      },
      titleBackgroundColor: {
        type: "string"
      },
      titleColor: {
        type: "string"
      },
      titleFontFamily: {
        type: "string"
      },
      titleFontSize: {
        type: "number"
      },
      titleFontWeight: {
        "enum": [
          "bold",
          "normal",
          "light"
        ],
        type: "string"
      }
    },
    type: "object"
  },
  Theme: {
    anyOf: [
      {
        $ref: "#/definitions/ThemeType"
      },
      {
        $ref: "#/definitions/ThemeDeep"
      }
    ]
  },
  ThemeDeep: {
    additionalProperties: false,
    properties: {
      area: {
        $ref: "#/definitions/MarkStyle"
      },
      axis: {
        $ref: "#/definitions/AxisStyle"
      },
      bar: {
        $ref: "#/definitions/MarkStyle"
      },
      base: {
        $ref: "#/definitions/ThemeType"
      },
      brush: {
        $ref: "#/definitions/MarkStyle"
      },
      legend: {
        $ref: "#/definitions/LegendStyle"
      },
      line: {
        $ref: "#/definitions/MarkStyle"
      },
      link: {
        $ref: "#/definitions/MarkStyle"
      },
      markCommon: {
        $ref: "#/definitions/MarkStyle"
      },
      point: {
        $ref: "#/definitions/MarkStyle"
      },
      rect: {
        $ref: "#/definitions/MarkStyle"
      },
      root: {
        $ref: "#/definitions/RootStyle"
      },
      rule: {
        $ref: "#/definitions/MarkStyle"
      },
      text: {
        additionalProperties: false,
        properties: {
          color: {
            type: "string"
          },
          nominalColorRange: {
            items: {
              type: "string"
            },
            type: "array"
          },
          opacity: {
            type: "number"
          },
          quantitativeSizeRange: {
            items: [
              {
                type: "number"
              },
              {
                type: "number"
              }
            ],
            maxItems: 2,
            minItems: 2,
            type: "array"
          },
          size: {
            type: "number"
          },
          stroke: {
            type: "string"
          },
          strokeWidth: {
            type: "number"
          },
          textAnchor: {
            "enum": [
              "start",
              "middle",
              "end"
            ],
            type: "string"
          },
          textFontWeight: {
            "enum": [
              "bold",
              "normal"
            ],
            type: "string"
          }
        },
        type: "object"
      },
      track: {
        $ref: "#/definitions/TrackStyle"
      },
      triangle: {
        $ref: "#/definitions/MarkStyle"
      }
    },
    required: [
      "base"
    ],
    type: "object"
  },
  ThemeType: {
    "enum": [
      "light",
      "dark",
      "warm",
      "ggplot",
      "igv",
      "ensembl",
      "jbrowse",
      "ucsc",
      "washu",
      "excel",
      "google"
    ],
    type: "string"
  },
  TrackStyle: {
    additionalProperties: false,
    properties: {
      alternatingBackground: {
        type: "string"
      },
      background: {
        type: "string"
      },
      outline: {
        type: "string"
      },
      outlineWidth: {
        type: "number"
      },
      titleAlign: {
        "enum": [
          "left",
          "middle",
          "right"
        ],
        type: "string"
      },
      titleBackground: {
        type: "string"
      },
      titleColor: {
        type: "string"
      },
      titleFontSize: {
        type: "number"
      }
    },
    type: "object"
  }
};
var theme_schema = {
  $ref: $ref$1,
  $schema: $schema$3,
  definitions: definitions$2
};
const DEWFAULT_TITLE_PADDING_ON_TOP_AND_BOTTOM = 6;
const DEFAULT_TRACK_HEIGHT_LINEAR = 180;
const DEFAULT_TRACK_WIDTH_LINEAR = 360;
const DEFAULT_VIEW_SPACING = 10;
const DEFAULT_INNER_RADIUS_PROP = 0.3;
const DEFAULT_CIRCULAR_VIEW_PADDING = 0;
const DEFAULT_BACKUP_COLOR = "gray";
const colorToHex = (colorStr) => {
  let c = color(colorStr);
  if (!c) {
    c = color(DEFAULT_BACKUP_COLOR);
  }
  const hex = pixi.utils.rgb2hex([c.rgb().r / 255, c.rgb().g / 255, c.rgb().b / 255]);
  return hex;
};
const RADIAN_GAP = 0;
function valueToRadian(v, max2, sa, ea, g) {
  const safeVal = Math.max(Math.min(max2, v), 0);
  const gap = g != null ? g : RADIAN_GAP;
  const radExtent = (ea - sa) / 360 * Math.PI * 2 - gap * 2;
  const radStart = sa / 360 * Math.PI * 2;
  return -(radStart + safeVal / max2 * radExtent) - Math.PI / 2 - gap;
}
function cartesianToPolar(x, max2, r, cx, cy, sa, ea) {
  return {
    x: cx + r * Math.cos(valueToRadian(x, max2, sa, ea)),
    y: cy + r * Math.sin(valueToRadian(x, max2, sa, ea))
  };
}
function positionToRadian(x, y, cx, cy) {
  if (cx <= x) {
    return Math.atan((y - cy) / (x - cx));
  } else {
    return Math.atan((y - cy) / (x - cx)) - Math.PI;
  }
}
const TOOLTIP_MOUSEOVER_MARGIN = 1;
function drawPoint(trackInfo, g, model) {
  var _a, _b, _c, _d, _e;
  const spec = model.spec();
  if (!spec.width || !spec.height) {
    console.warn("Size of a track is not properly determined, so visual mark cannot be rendered");
    return;
  }
  const data2 = model.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const zoomLevel = model.getChannelScale("x").invert(trackWidth) - model.getChannelScale("x").invert(0);
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const tcx = trackWidth / 2;
  const tcy = trackHeight / 2;
  const rowCategories = (_e = model.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  rowCategories.forEach((rowCategory) => {
    const rowPosition = model.encodedValue("row", rowCategory);
    data2.filter((d) => !getValueUsingChannel(d, spec.row) || getValueUsingChannel(d, spec.row) === rowCategory).forEach((d) => {
      const cx = model.encodedPIXIProperty("x-center", d);
      const cy = model.encodedPIXIProperty("y-center", d);
      const color2 = model.encodedPIXIProperty("color", d);
      const size = model.encodedPIXIProperty("p-size", d);
      const strokeWidth = model.encodedPIXIProperty("strokeWidth", d);
      const stroke = model.encodedPIXIProperty("stroke", d);
      const opacity = model.encodedPIXIProperty("opacity", d);
      const alphaTransition = model.markVisibility(d, { width: size, zoomLevel });
      const actualOpacity = Math.min(alphaTransition, opacity);
      if (size <= 0.1 || actualOpacity === 0 || cx + size < 0 || cx - size > trackWidth) {
        return;
      }
      g.lineStyle(strokeWidth, colorToHex(stroke), actualOpacity, 1);
      if (circular) {
        const r = trackOuterRadius - (rowPosition + rowHeight - cy) / trackHeight * trackRingSize;
        const pos = cartesianToPolar(cx, trackWidth, r, tcx, tcy, startAngle, endAngle);
        g.beginFill(colorToHex(color2), actualOpacity);
        g.drawCircle(pos.x, pos.y, size);
      } else {
        g.beginFill(colorToHex(color2), actualOpacity);
        g.drawCircle(cx, rowPosition + rowHeight - cy, size);
        if (trackInfo == null ? void 0 : trackInfo.tooltips) {
          const gcy = rowPosition + rowHeight - cy;
          trackInfo.tooltips.push({
            datum: d,
            isMouseOver: (x, y) => Math.sqrt(Math.abs(x - cx) * Math.abs(x - cx) + Math.abs(y - gcy) * Math.abs(y - gcy)) < size + TOOLTIP_MOUSEOVER_MARGIN,
            markInfo: { x: cx, y: rowPosition + rowHeight - cy, width: size, height: size, type: "point" }
          });
        }
      }
    });
  });
}
function pointProperty(model, propertyKey, datum) {
  const xe = model.visualPropertyByChannel("xe", datum);
  const x = model.visualPropertyByChannel("x", datum);
  const size = model.visualPropertyByChannel("size", datum);
  switch (propertyKey) {
    case "x-center":
      return xe ? (xe + x) / 2 : x;
    case "y-center":
      const ye = model.visualPropertyByChannel("ye", datum);
      const y = model.visualPropertyByChannel("y", datum);
      return ye ? (ye + y) / 2 : y;
    case "p-size":
      return xe && model.spec().stretch ? (xe - x) / 2 : size;
    default:
      return void 0;
  }
}
function drawLine(g, tm, tooltips, trackWidth, trackHeight) {
  var _a, _b, _c, _d, _e, _f;
  const spec = tm.spec();
  if (!spec.width || !spec.height) {
    console.warn("Size of a track is not properly determined, so visual mark cannot be rendered");
    return;
  }
  const data2 = tm.data();
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const trackCenterX = trackWidth / 2;
  const trackCenterY = trackHeight / 2;
  const rowCategories = (_e = tm.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const colorCategories = (_f = tm.getChannelDomainArray("color")) != null ? _f : ["___SINGLE_COLOR___"];
  rowCategories.forEach((rowCategory) => {
    const rowPosition = tm.encodedValue("row", rowCategory);
    colorCategories.forEach((colorCategory) => {
      data2.filter((d) => (!getValueUsingChannel(d, spec.row) || getValueUsingChannel(d, spec.row) === rowCategory) && (!getValueUsingChannel(d, spec.color) || getValueUsingChannel(d, spec.color) === colorCategory)).sort((d1, d2) => getValueUsingChannel(d1, spec.x) - getValueUsingChannel(d2, spec.x)).forEach((d, i) => {
        const cx = tm.encodedPIXIProperty("x", d);
        const y = tm.encodedPIXIProperty("y", d);
        const size = tm.encodedPIXIProperty("size", d);
        const color2 = tm.encodedPIXIProperty("color", d);
        const opacity = tm.encodedPIXIProperty("opacity", d);
        g.lineStyle(size, colorToHex(color2), opacity, 0.5);
        if (circular) {
          const r = trackOuterRadius - (rowPosition + rowHeight - y) / trackHeight * trackRingSize;
          const pos = cartesianToPolar(cx, trackWidth, r, trackCenterX, trackCenterY, startAngle, endAngle);
          if (i === 0) {
            g.moveTo(pos.x, pos.y);
          } else {
            g.lineTo(pos.x, pos.y);
          }
        } else {
          if (i === 0) {
            g.moveTo(cx, rowPosition + rowHeight - y);
          } else {
            g.lineTo(cx, rowPosition + rowHeight - y);
          }
          if (spec.tooltip) {
            tooltips.push({
              datum: d,
              isMouseOver: (x, y2) => cx - TOOLTIP_MOUSEOVER_MARGIN < x && x < cx + TOOLTIP_MOUSEOVER_MARGIN && rowPosition - TOOLTIP_MOUSEOVER_MARGIN < y2 && y2 < rowPosition + rowHeight + TOOLTIP_MOUSEOVER_MARGIN,
              markInfo: { x: cx, y, width: TOOLTIP_MOUSEOVER_MARGIN, height: y, type: "line" }
            });
          }
        }
      });
    });
  });
}
function drawBar(trackInfo, tile, model) {
  var _a, _b, _c, _d, _e, _f, _g;
  const spec = model.spec();
  if (!spec.width || !spec.height) {
    console.warn("Size of a track is not properly determined, so visual mark cannot be rendered");
    return;
  }
  const data2 = model.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const tileSize = trackInfo.tilesetInfo.tile_size;
  const { tileX, tileWidth } = trackInfo.getTilePosAndDimensions(tile.gos.zoomLevel, tile.gos.tilePos, tileSize);
  const zoomLevel = model.getChannelScale("x").invert(trackWidth) - model.getChannelScale("x").invert(0);
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const cx = trackWidth / 2;
  const cy = trackHeight / 2;
  const xScale = model.getChannelScale("x");
  const tileUnitWidth = xScale(tileX + tileWidth / tileSize) - xScale(tileX);
  const rowCategories = (_e = model.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const baselineValue = IsChannelDeep(spec.y) ? (_f = spec.y) == null ? void 0 : _f.baseline : void 0;
  const staticBaseY = (_g = model.encodedValue("y", baselineValue)) != null ? _g : 0;
  const g = tile.graphics;
  if (IsStackedMark(spec)) {
    const genomicChannel = model.getGenomicChannel();
    if (!genomicChannel || !genomicChannel.field) {
      console.warn("Genomic field is not provided in the specification");
      return;
    }
    const pivotedData = group(data2, (d) => d[genomicChannel.field]);
    const xKeys = [...pivotedData.keys()];
    xKeys.forEach((k) => {
      var _a2;
      let prevYEnd = 0;
      (_a2 = pivotedData.get(k)) == null ? void 0 : _a2.forEach((d) => {
        const color2 = model.encodedPIXIProperty("color", d);
        const stroke = model.encodedPIXIProperty("stroke", d);
        const strokeWidth = model.encodedPIXIProperty("strokeWidth", d);
        const opacity = model.encodedPIXIProperty("opacity", d);
        const y = model.encodedPIXIProperty("y", d);
        const barWidth = model.encodedPIXIProperty("width", d, { tileUnitWidth });
        const xs = model.encodedPIXIProperty("x-start", d, { markWidth: barWidth });
        const xe = xs + barWidth;
        const alphaTransition = model.markVisibility(d, { width: barWidth, zoomLevel });
        const actualOpacity = Math.min(alphaTransition, opacity);
        if (actualOpacity === 0 || barWidth <= 0 || y <= 0) {
          return;
        }
        g.lineStyle(strokeWidth, colorToHex(stroke), actualOpacity, 0);
        if (circular) {
          const farR = trackOuterRadius - (rowHeight - prevYEnd) / trackHeight * trackRingSize;
          const nearR = trackOuterRadius - (rowHeight - y - prevYEnd) / trackHeight * trackRingSize;
          const sPos = cartesianToPolar(xs, trackWidth, nearR, cx, cy, startAngle, endAngle);
          const startRad = valueToRadian(xs, trackWidth, startAngle, endAngle);
          const endRad = valueToRadian(xs + barWidth, trackWidth, startAngle, endAngle);
          g.beginFill(colorToHex(color2), actualOpacity);
          g.moveTo(sPos.x, sPos.y);
          g.arc(cx, cy, nearR, startRad, endRad, true);
          g.arc(cx, cy, farR, endRad, startRad, false);
          g.closePath();
        } else {
          const ys = rowHeight - y - prevYEnd;
          const barHeight = y;
          g.beginFill(colorToHex(color2), actualOpacity);
          g.drawRect(xs, rowHeight - y - prevYEnd, barWidth, y);
          if (spec.tooltip) {
            trackInfo.tooltips.push({
              datum: d,
              isMouseOver: (x, y2) => xs - TOOLTIP_MOUSEOVER_MARGIN < x && x < xe + TOOLTIP_MOUSEOVER_MARGIN && ys - TOOLTIP_MOUSEOVER_MARGIN < y2 && y2 < ys + barHeight + TOOLTIP_MOUSEOVER_MARGIN,
              markInfo: { x: xs, y: ys, width: barWidth, height: barHeight, type: "bar" }
            });
          }
        }
        prevYEnd += y;
      });
    });
  } else {
    rowCategories.forEach((rowCategory) => {
      const rowPosition = model.encodedValue("row", rowCategory);
      data2.filter((d) => {
        const rowValue = getValueUsingChannel(d, spec.row);
        return !rowValue || rowValue === rowCategory;
      }).forEach((d) => {
        const color2 = model.encodedPIXIProperty("color", d);
        const stroke = model.encodedPIXIProperty("stroke", d);
        const strokeWidth = model.encodedPIXIProperty("strokeWidth", d);
        const opacity = model.encodedPIXIProperty("opacity");
        let y = model.encodedPIXIProperty("y", d);
        let ye = model.encodedPIXIProperty("ye", d);
        if (typeof ye !== "undefined") {
          [y, ye] = [y, ye].sort();
        }
        const barWidth = model.encodedPIXIProperty("width", d, { tileUnitWidth });
        const xLeft = model.encodedPIXIProperty("x-start", d, { markWidth: barWidth });
        const xRight = xLeft + barWidth;
        let yTop, yBottom;
        if (typeof ye === "undefined") {
          yTop = rowPosition + rowHeight - staticBaseY - y;
          yBottom = rowPosition + rowHeight - staticBaseY;
        } else {
          yTop = rowPosition + rowHeight - ye;
          yBottom = rowPosition + rowHeight - y;
        }
        const alphaTransition = model.markVisibility(d, { width: barWidth, zoomLevel });
        const actualOpacity = Math.min(alphaTransition, opacity);
        if (actualOpacity === 0 || barWidth === 0 || y === 0) {
          return;
        }
        g.lineStyle(strokeWidth, colorToHex(stroke), actualOpacity, 0);
        if (circular) {
          const farR = trackOuterRadius - yTop / trackHeight * trackRingSize;
          const nearR = trackOuterRadius - yBottom / trackHeight * trackRingSize;
          const sPos = cartesianToPolar(xLeft, trackWidth, nearR, cx, cy, startAngle, endAngle);
          const startRad = valueToRadian(xLeft, trackWidth, startAngle, endAngle);
          const endRad = valueToRadian(xLeft + barWidth, trackWidth, startAngle, endAngle);
          g.beginFill(colorToHex(color2), actualOpacity);
          g.moveTo(sPos.x, sPos.y);
          g.arc(cx, cy, nearR, startRad, endRad, true);
          g.arc(cx, cy, farR, endRad, startRad, false);
          g.closePath();
        } else {
          g.beginFill(colorToHex(color2), actualOpacity);
          g.drawRect(xLeft, yTop, barWidth, yBottom - yTop);
          if (spec.tooltip) {
            const barHeight = yBottom - yTop;
            trackInfo.tooltips.push({
              datum: d,
              isMouseOver: (x, y2) => xLeft - TOOLTIP_MOUSEOVER_MARGIN < x && x < xRight + TOOLTIP_MOUSEOVER_MARGIN && yTop - TOOLTIP_MOUSEOVER_MARGIN < y2 && y2 < yBottom + TOOLTIP_MOUSEOVER_MARGIN,
              markInfo: { x: xLeft, y: yTop, width: barWidth, height: barHeight, type: "bar" }
            });
          }
        }
      });
    });
  }
}
function barProperty(gm, propertyKey, datum, additionalInfo) {
  const x = gm.visualPropertyByChannel("x", datum);
  const xe = gm.visualPropertyByChannel("xe", datum);
  const size = gm.visualPropertyByChannel("size", datum);
  switch (propertyKey) {
    case "width":
      return size != null ? size : xe ? xe - x : additionalInfo == null ? void 0 : additionalInfo.tileUnitWidth;
    case "x-start":
      if (!(additionalInfo == null ? void 0 : additionalInfo.markWidth)) {
        return void 0;
      }
      return xe ? (x + xe - (additionalInfo == null ? void 0 : additionalInfo.markWidth)) / 2 : x - (additionalInfo == null ? void 0 : additionalInfo.markWidth) / 2;
    default:
      return void 0;
  }
}
function drawArea(HGC, trackInfo, tile, tm) {
  var _a, _b, _c, _d, _e, _f;
  const spec = tm.spec();
  const data2 = tm.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const tileSize = trackInfo.tilesetInfo.tile_size;
  const { tileX } = trackInfo.getTilePosAndDimensions(tile.gos.zoomLevel, tile.gos.tilePos, tileSize);
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const trackCenterX = trackWidth / 2;
  const trackCenterY = trackHeight / 2;
  const xScale = tm.getChannelScale("x");
  const rowCategories = (_e = tm.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const colorCategories = (_f = tm.getChannelDomainArray("color")) != null ? _f : ["___SINGLE_COLOR___"];
  const constantOpacity = tm.encodedPIXIProperty("opacity");
  const constantStrokeWidth = tm.encodedPIXIProperty("strokeWidth");
  const constantStroke = tm.encodedPIXIProperty("stroke");
  const graphics = tile.graphics;
  if (IsStackedMark(spec)) {
    const genomicChannel = tm.getGenomicChannel();
    if (!genomicChannel || !genomicChannel.field) {
      console.warn("Genomic field is not provided in the specification");
      return;
    }
    const pivotedData = group(data2, (d) => d[genomicChannel.field]);
    const genomicPosCategories = [...pivotedData.keys()];
    graphics.lineStyle(constantStrokeWidth, colorToHex(constantStroke), constantOpacity, 1);
    const prevYEndByGPos = {};
    colorCategories.forEach((colorCategory) => {
      const areaPointsTop = [];
      const areaPointsBottom = [];
      genomicPosCategories.forEach((genomicPosCategory, i, array) => {
        var _a2, _b2;
        (_b2 = (_a2 = pivotedData.get(genomicPosCategory)) == null ? void 0 : _a2.filter((d) => getValueUsingChannel(d, spec.color) === colorCategory)) == null ? void 0 : _b2.forEach((d) => {
          const xValue = +genomicPosCategory;
          const cx = xScale(xValue);
          const cy = max([tm.encodedPIXIProperty("y", d), 0]);
          if (circular) {
            if (i === 0) {
              const r = trackOuterRadius - rowHeight / trackHeight * trackRingSize;
              const pos = cartesianToPolar(cx, trackWidth, r, trackCenterX, trackCenterY, startAngle, endAngle);
              areaPointsTop.push([pos.x, pos.y]);
              areaPointsBottom.push([pos.x, pos.y]);
            }
            if (typeof prevYEndByGPos[genomicPosCategory] === "undefined") {
              prevYEndByGPos[genomicPosCategory] = 0;
            }
            const rTop = trackOuterRadius - (rowHeight - cy - prevYEndByGPos[genomicPosCategory]) / trackHeight * trackRingSize;
            const posTop = cartesianToPolar(cx, trackWidth, rTop, trackCenterX, trackCenterY, startAngle, endAngle);
            areaPointsTop.push([posTop.x, posTop.y]);
            const rBot = trackOuterRadius - (rowHeight - prevYEndByGPos[genomicPosCategory]) / trackHeight * trackRingSize;
            const posBot = cartesianToPolar(cx, trackWidth, rBot, trackCenterX, trackCenterY, startAngle, endAngle);
            areaPointsBottom.push([posBot.x, posBot.y]);
            if (i === array.length - 1) {
              const r = trackOuterRadius - rowHeight / trackHeight * trackRingSize;
              const pos = cartesianToPolar(cx, trackWidth, r, trackCenterX, trackCenterY, startAngle, endAngle);
              areaPointsTop.push([pos.x, pos.y]);
              areaPointsBottom.push([pos.x, pos.y]);
            }
          } else {
            if (i === 0) {
              areaPointsTop.push([cx, rowHeight]);
              areaPointsBottom.push([cx, rowHeight]);
            }
            if (typeof prevYEndByGPos[genomicPosCategory] === "undefined") {
              prevYEndByGPos[genomicPosCategory] = 0;
            }
            areaPointsTop.push([cx, rowHeight - cy - prevYEndByGPos[genomicPosCategory]]);
            areaPointsBottom.push([cx, rowHeight - prevYEndByGPos[genomicPosCategory]]);
            if (i === array.length - 1) {
              areaPointsTop.push([cx, rowHeight]);
              areaPointsBottom.push([cx, rowHeight]);
            }
            if (spec.tooltip) {
              const ys = rowHeight - cy - prevYEndByGPos[genomicPosCategory];
              const ye = rowHeight - prevYEndByGPos[genomicPosCategory];
              trackInfo.tooltips.push({
                datum: d,
                isMouseOver: (x, y) => cx - TOOLTIP_MOUSEOVER_MARGIN < x && x < cx + TOOLTIP_MOUSEOVER_MARGIN && ys - TOOLTIP_MOUSEOVER_MARGIN < y && y < ye + TOOLTIP_MOUSEOVER_MARGIN,
                markInfo: { x: cx, y: ys, width: TOOLTIP_MOUSEOVER_MARGIN, height: cy, type: "area" }
              });
            }
          }
          prevYEndByGPos[genomicPosCategory] += cy;
        });
      });
      const color2 = tm.encodedValue("color", colorCategory);
      graphics.beginFill(colorToHex(color2), constantOpacity);
      graphics.drawPolygon([
        ...areaPointsTop.reduce((a, b) => a.concat(b)),
        ...areaPointsBottom.reverse().reduce((a, b) => a.concat(b))
      ]);
      graphics.endFill();
    });
  } else {
    rowCategories.forEach((rowCategory) => {
      const rowPosition = tm.encodedValue("row", rowCategory);
      graphics.lineStyle(constantStrokeWidth, colorToHex(constantStroke), constantOpacity, 0);
      colorCategories.forEach((colorCategory) => {
        const baselinePoints = [];
        const areaPoints = [];
        const baselineR = trackOuterRadius - (rowPosition + rowHeight) / trackHeight * trackRingSize;
        data2.filter((d) => (typeof getValueUsingChannel(d, spec.row) === "undefined" || getValueUsingChannel(d, spec.row) === rowCategory) && (typeof getValueUsingChannel(d, spec.color) === "undefined" || getValueUsingChannel(d, spec.color) === colorCategory)).sort((a, b) => tm.encodedPIXIProperty("x", a) - tm.encodedPIXIProperty("x", b)).forEach((d, i, array) => {
          const cy = min([max([tm.encodedPIXIProperty("y", d), 0]), rowHeight]);
          const cx = tm.encodedPIXIProperty("x", d);
          if (circular) {
            const baselinePos = cartesianToPolar(cx, trackWidth, baselineR, trackCenterX, trackCenterY, startAngle, endAngle);
            baselinePoints.push([baselinePos.x, baselinePos.y]);
            if (i === 0) {
              areaPoints.push(baselinePos.x, baselinePos.y);
            }
            const r = trackOuterRadius - (rowPosition + rowHeight - cy) / trackHeight * trackRingSize;
            const pos = cartesianToPolar(cx, trackWidth, r, trackCenterX, trackCenterY, startAngle, endAngle);
            areaPoints.push(pos.x, pos.y);
            if (i === array.length - 1) {
              const startR = trackOuterRadius - (rowPosition + rowHeight) / trackHeight * trackRingSize;
              const curPos = cartesianToPolar(cx, trackWidth, startR, trackCenterX, trackCenterY, startAngle, endAngle);
              areaPoints.push(curPos.x, curPos.y);
            }
          } else {
            if (i === 0) {
              areaPoints.push(cx, rowPosition + rowHeight);
            }
            areaPoints.push(cx, rowPosition + rowHeight - cy);
            if (i === array.length - 1) {
              const startX = xScale(tileX);
              areaPoints.push(cx, rowPosition + rowHeight);
              areaPoints.push(startX, rowPosition + rowHeight);
            }
            if (spec.tooltip) {
              trackInfo.tooltips.push({
                datum: d,
                isMouseOver: (x, y) => cx - TOOLTIP_MOUSEOVER_MARGIN < x && x < cx + TOOLTIP_MOUSEOVER_MARGIN && rowPosition - TOOLTIP_MOUSEOVER_MARGIN < y && y < rowPosition + rowHeight + TOOLTIP_MOUSEOVER_MARGIN,
                markInfo: { x: cx, y: cy, width: TOOLTIP_MOUSEOVER_MARGIN, height: cy, type: "area" }
              });
            }
          }
        });
        if (circular && baselinePoints.length !== 0) {
          areaPoints.push(...baselinePoints.reverse().reduce((a, b) => a.concat(b)));
        }
        const color2 = tm.encodedValue("color", colorCategory);
        graphics.beginFill(colorToHex(color2), constantOpacity);
        graphics.drawPolygon(areaPoints);
        graphics.endFill();
      });
    });
  }
}
function drawRect(HGC, trackInfo, tile, model) {
  var _a, _b, _c, _d, _e, _f;
  const spec = model.spec();
  const data2 = model.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const tileSize = trackInfo.tilesetInfo.tile_size;
  const { tileX, tileWidth } = trackInfo.getTilePosAndDimensions(tile.gos.zoomLevel, tile.gos.tilePos, tileSize);
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const cx = trackWidth / 2;
  const cy = trackHeight / 2;
  const xScale = trackInfo._xScale;
  const tileUnitWidth = xScale(tileX + tileWidth / tileSize) - xScale(tileX);
  const rowCategories = (_e = model.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const RPAD = IsChannelDeep(spec.row) && spec.row.padding ? spec.row.padding : 0;
  const yCategories = (_f = model.getChannelDomainArray("y")) != null ? _f : ["___SINGLE_Y_POSITION___"];
  const cellHeight = rowHeight / yCategories.length - RPAD * 2;
  const g = tile.graphics;
  data2.forEach((d) => {
    var _a2;
    const rowPosition = model.encodedPIXIProperty("row", d) + RPAD;
    const x = model.encodedPIXIProperty("x", d);
    const color2 = model.encodedPIXIProperty("color", d);
    const stroke = model.encodedPIXIProperty("stroke", d);
    const strokeWidth = model.encodedPIXIProperty("strokeWidth", d);
    const opacity = model.encodedPIXIProperty("opacity", d);
    const rectWidth = model.encodedPIXIProperty("width", d, { markWidth: tileUnitWidth });
    const rectHeight = model.encodedPIXIProperty("height", d, { markHeight: cellHeight });
    const y = model.encodedPIXIProperty("y", d);
    const alphaTransition = model.markVisibility(d, {
      width: rectWidth,
      zoomLevel: trackInfo._xScale.invert(trackWidth) - trackInfo._xScale.invert(0)
    });
    const actualOpacity = Math.min(alphaTransition, opacity);
    if (actualOpacity === 0 || rectHeight === 0 || rectWidth <= 1e-4) {
      return;
    }
    const xs = x;
    const xe = x + rectWidth;
    const absoluteHeight = (_a2 = model.visualPropertyByChannel("size", d)) != null ? _a2 : void 0;
    g.lineStyle(strokeWidth, colorToHex(stroke), actualOpacity, 0.5);
    if (circular) {
      if (xe < 0 || trackWidth < xs) {
        return;
      }
      let farR = trackOuterRadius - (rowPosition + rowHeight - y - rectHeight / 2) / trackHeight * trackRingSize;
      let nearR = trackOuterRadius - (rowPosition + rowHeight - y + rectHeight / 2) / trackHeight * trackRingSize;
      if (absoluteHeight) {
        const midR = trackOuterRadius - (rowPosition + y) / trackHeight * trackRingSize;
        farR = midR - absoluteHeight / 2;
        nearR = midR + absoluteHeight / 2;
      }
      const sPos = cartesianToPolar(xs, trackWidth, nearR, cx, cy, startAngle, endAngle);
      const startRad = valueToRadian(xs, trackWidth, startAngle, endAngle);
      const endRad = valueToRadian(xe, trackWidth, startAngle, endAngle);
      g.beginFill(colorToHex(color2 === "none" ? "white" : color2), color2 === "none" ? 0 : actualOpacity);
      g.moveTo(sPos.x, sPos.y);
      g.arc(cx, cy, nearR, startRad, endRad, true);
      g.arc(cx, cy, farR, endRad, startRad, false);
      g.closePath();
    } else {
      g.beginFill(colorToHex(color2 === "none" ? "white" : color2), color2 === "none" ? 0 : actualOpacity);
      g.drawRect(xs, rowPosition + rowHeight - y - rectHeight / 2, xe - xs, rectHeight);
      if (spec.tooltip) {
        trackInfo.tooltips.push({
          datum: d,
          isMouseOver: (mouseX, mouseY) => xs - TOOLTIP_MOUSEOVER_MARGIN < mouseX && mouseX < xe + TOOLTIP_MOUSEOVER_MARGIN && rowPosition + rowHeight - y - rectHeight / 2 - TOOLTIP_MOUSEOVER_MARGIN < mouseY && mouseY < rowPosition + rowHeight - y + rectHeight / 2 + TOOLTIP_MOUSEOVER_MARGIN,
          markInfo: {
            x: xs,
            y: rowPosition + rowHeight - y - rectHeight / 2,
            width: xe - xs,
            height: rectHeight,
            type: "rect"
          }
        });
      }
    }
  });
}
function rectProperty(gm, propertyKey, datum, additionalInfo) {
  var _a;
  switch (propertyKey) {
    case "width":
      const width = gm.visualPropertyByChannel("xe", datum) ? gm.visualPropertyByChannel("xe", datum) - gm.visualPropertyByChannel("x", datum) : additionalInfo == null ? void 0 : additionalInfo.markWidth;
      return width === 0 ? 0.1 : width;
    case "height":
      return (_a = gm.visualPropertyByChannel("size", datum)) != null ? _a : additionalInfo == null ? void 0 : additionalInfo.markHeight;
    default:
      return void 0;
  }
}
function drawTriangle(g, model, trackWidth, trackHeight) {
  var _a, _b, _c, _d, _e, _f, _g;
  const spec = model.spec();
  if (!spec.width || !spec.height) {
    console.warn("Size of a track is not properly determined, so visual mark cannot be rendered");
    return;
  }
  const data2 = model.data();
  const zoomLevel = model.getChannelScale("x").invert(trackWidth) - model.getChannelScale("x").invert(0);
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const cx = trackWidth / 2;
  const cy = trackHeight / 2;
  const rowCategories = (_e = model.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const yCategories = (_f = model.getChannelDomainArray("y")) != null ? _f : ["___SINGLE_Y___"];
  const triHeight = (_g = model.encodedValue("size")) != null ? _g : circular ? trackRingSize / rowCategories.length / yCategories.length : rowHeight / yCategories.length;
  rowCategories.forEach((rowCategory) => {
    const rowPosition = model.encodedValue("row", rowCategory);
    data2.filter((d) => !getValueUsingChannel(d, spec.row) || getValueUsingChannel(d, spec.row) === rowCategory).forEach((d) => {
      var _a2, _b2, _c2;
      const x = model.encodedPIXIProperty("x", d);
      const xe = model.encodedPIXIProperty("xe", d);
      const markWidth = (_a2 = model.encodedPIXIProperty("size", d)) != null ? _a2 : xe === void 0 ? triHeight : xe - x;
      const y = model.encodedPIXIProperty("y", d);
      const strokeWidth = model.encodedPIXIProperty("strokeWidth", d);
      const stroke = model.encodedPIXIProperty("stroke", d);
      const color2 = model.encodedPIXIProperty("color", d);
      const opacity = model.encodedPIXIProperty("opacity", d);
      if (circular) {
        let x0 = x ? x : xe - markWidth;
        let x1 = xe ? xe : x + markWidth;
        let xm = (x0 + x1) / 2;
        const rm = trackOuterRadius - (rowPosition + rowHeight - y) / trackHeight * trackRingSize;
        const r0 = rm - triHeight / 2;
        const r1 = rm + triHeight / 2;
        if (((_b2 = spec.style) == null ? void 0 : _b2.align) === "right" && !xe) {
          x0 -= markWidth;
          x1 -= markWidth;
          xm -= markWidth;
        }
        let markToPoints = [];
        if (spec.mark === "triangleLeft") {
          const p0 = cartesianToPolar(x1, trackWidth, r0, cx, cy, startAngle, endAngle);
          const p1 = cartesianToPolar(x0, trackWidth, rm, cx, cy, startAngle, endAngle);
          const p2 = cartesianToPolar(x1, trackWidth, r1, cx, cy, startAngle, endAngle);
          const p3 = cartesianToPolar(x1, trackWidth, r0, cx, cy, startAngle, endAngle);
          markToPoints = [p0.x, p0.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y];
        } else if (spec.mark === "triangleRight") {
          const p0 = cartesianToPolar(x0, trackWidth, r0, cx, cy, startAngle, endAngle);
          const p1 = cartesianToPolar(x1, trackWidth, rm, cx, cy, startAngle, endAngle);
          const p2 = cartesianToPolar(x0, trackWidth, r1, cx, cy, startAngle, endAngle);
          const p3 = cartesianToPolar(x0, trackWidth, r0, cx, cy, startAngle, endAngle);
          markToPoints = [p0.x, p0.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y];
        } else if (spec.mark === "triangleBottom") {
          x0 = xm - markWidth / 2;
          x1 = xm + markWidth / 2;
          const p0 = cartesianToPolar(x0, trackWidth, r1, cx, cy, startAngle, endAngle);
          const p1 = cartesianToPolar(x1, trackWidth, r1, cx, cy, startAngle, endAngle);
          const p2 = cartesianToPolar(xm, trackWidth, r0, cx, cy, startAngle, endAngle);
          const p3 = cartesianToPolar(x0, trackWidth, r1, cx, cy, startAngle, endAngle);
          markToPoints = [p0.x, p0.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y];
        }
        const alphaTransition = model.markVisibility(d, { width: x1 - x0, zoomLevel });
        const actualOpacity = Math.min(alphaTransition, opacity);
        g.lineStyle(strokeWidth, colorToHex(stroke), x1 - x0 > 2 ? actualOpacity : 0, 0);
        g.beginFill(colorToHex(color2), actualOpacity);
        g.drawPolygon(markToPoints);
        g.endFill();
      } else {
        let x0 = x ? x : xe - markWidth;
        let x1 = xe ? xe : x + markWidth;
        let xm = x0 + (x1 - x0) / 2;
        const ym = rowPosition + rowHeight - y;
        const y0 = rowPosition + rowHeight - y - triHeight / 2;
        const y1 = rowPosition + rowHeight - y + triHeight / 2;
        if (((_c2 = spec.style) == null ? void 0 : _c2.align) === "right" && !xe) {
          x0 -= markWidth;
          x1 -= markWidth;
          xm -= markWidth;
        }
        const markToPoints = {
          triangleLeft: [x1, y0, x0, ym, x1, y1, x1, y0],
          triangleRight: [x0, y0, x1, ym, x0, y1, x0, y0],
          triangleBottom: [x0, y0, x1, y0, xm, y1, x0, y0]
        }[spec.mark];
        const alphaTransition = model.markVisibility(d, { width: x1 - x0, zoomLevel });
        const actualOpacity = Math.min(alphaTransition, opacity);
        g.lineStyle(strokeWidth, colorToHex(stroke), x1 - x0 > 2 ? actualOpacity : 0, 0.5);
        g.beginFill(colorToHex(color2), actualOpacity);
        g.drawPolygon(markToPoints);
        g.endFill();
      }
    });
  });
}
const TEXT_STYLE_GLOBAL = {
  fontSize: "12px",
  fontFamily: "sans-serif",
  fontWeight: "normal",
  fill: "black",
  background: "white",
  lineJoin: "round",
  stroke: "#ffffff",
  strokeThickness: 0
};
function drawText(HGC, trackInfo, tile, tm) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
  const spec = tm.spec();
  const data2 = tm.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const tcx = trackWidth / 2;
  const tcy = trackHeight / 2;
  const rowCategories = (_e = tm.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const dx = (_g = (_f = spec.style) == null ? void 0 : _f.dx) != null ? _g : 0;
  const dy = (_i = (_h = spec.style) == null ? void 0 : _h.dy) != null ? _i : 0;
  if (IsStackedMark(spec)) {
    if (circular) {
      return;
    }
    const rowGraphics = tile.graphics;
    const genomicChannel = tm.getGenomicChannel();
    if (!genomicChannel || !genomicChannel.field) {
      console.warn("Genomic field is not provided in the specification");
      return;
    }
    const pivotedData = group(data2, (d) => d[genomicChannel.field]);
    const xKeys = [...pivotedData.keys()];
    xKeys.forEach((k) => {
      var _a2;
      let prevYEnd = 0;
      (_a2 = pivotedData.get(k)) == null ? void 0 : _a2.forEach((d) => {
        var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
        const text = tm.encodedPIXIProperty("text", d);
        const color2 = tm.encodedPIXIProperty("color", d);
        const x = tm.encodedPIXIProperty("x", d) + dx;
        const xe = tm.encodedPIXIProperty("xe", d) + dx;
        const cx = tm.encodedPIXIProperty("x-center", d) + dx;
        const y = tm.encodedPIXIProperty("y", d) + dy;
        const size = tm.encodedPIXIProperty("size", d);
        const stroke = tm.encodedPIXIProperty("stroke", d);
        const strokeWidth = tm.encodedPIXIProperty("strokeWidth", d);
        const opacity = tm.encodedPIXIProperty("opacity", d);
        if (cx < 0 || cx > trackWidth) {
          return;
        }
        if (trackInfo.textsBeingUsed > 1e3) {
          return;
        }
        const localTextStyle = {
          ...TEXT_STYLE_GLOBAL,
          fontSize: size != null ? size : ((_a3 = spec.style) == null ? void 0 : _a3.textFontSize) ? `${(_b2 = spec.style) == null ? void 0 : _b2.textFontSize}px` : TEXT_STYLE_GLOBAL.fontSize,
          stroke: (_d2 = stroke != null ? stroke : (_c2 = spec.style) == null ? void 0 : _c2.textStroke) != null ? _d2 : TEXT_STYLE_GLOBAL.stroke,
          strokeThickness: (_f2 = strokeWidth != null ? strokeWidth : (_e2 = spec.style) == null ? void 0 : _e2.textStrokeWidth) != null ? _f2 : TEXT_STYLE_GLOBAL.strokeThickness,
          fontWeight: (_h2 = (_g2 = spec.style) == null ? void 0 : _g2.textFontWeight) != null ? _h2 : TEXT_STYLE_GLOBAL.fontWeight
        };
        const textStyleObj = new HGC.libraries.PIXI.TextStyle(localTextStyle);
        let textGraphic;
        if (trackInfo.textGraphics.length > trackInfo.textsBeingUsed) {
          textGraphic = trackInfo.textGraphics[trackInfo.textsBeingUsed];
          textGraphic.style.fill = color2;
          textGraphic.visible = true;
          textGraphic.text = text;
          textGraphic.alpha = 1;
        } else {
          textGraphic = new HGC.libraries.PIXI.Text(text, {
            ...localTextStyle,
            fill: color2
          });
          trackInfo.textGraphics.push(textGraphic);
        }
        const metric = HGC.libraries.PIXI.TextMetrics.measureText(text, textStyleObj);
        trackInfo.textsBeingUsed++;
        const alphaTransition = tm.markVisibility(d, {
          ...metric,
          zoomLevel: trackInfo._xScale.invert(trackWidth) - trackInfo._xScale.invert(0)
        });
        const actualOpacity = Math.min(alphaTransition, opacity);
        if (!text || actualOpacity === 0) {
          trackInfo.textsBeingUsed--;
          textGraphic.visible = false;
          return;
        }
        textGraphic.alpha = actualOpacity;
        textGraphic.resolution = 8;
        textGraphic.updateText();
        textGraphic.texture.baseTexture.scaleMode = HGC.libraries.PIXI.SCALE_MODES.LINEAR;
        const sprite = new HGC.libraries.PIXI.Sprite(textGraphic.texture);
        sprite.x = x;
        sprite.y = rowHeight - y - prevYEnd;
        sprite.width = xe - x;
        sprite.height = y;
        rowGraphics.addChild(sprite);
        prevYEnd += y;
      });
    });
  } else {
    rowCategories.forEach((rowCategory) => {
      const rowGraphics = tile.graphics;
      const rowPosition = tm.encodedValue("row", rowCategory);
      data2.filter((d) => !getValueUsingChannel(d, spec.row) || getValueUsingChannel(d, spec.row) === rowCategory).forEach((d) => {
        var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j;
        const text = tm.encodedPIXIProperty("text", d);
        const color2 = tm.encodedPIXIProperty("color", d);
        const cx = tm.encodedPIXIProperty("x-center", d) + dx;
        const y = tm.encodedPIXIProperty("y", d) + dy;
        const size = tm.encodedPIXIProperty("size", d);
        const stroke = tm.encodedPIXIProperty("stroke", d);
        const strokeWidth = tm.encodedPIXIProperty("strokeWidth", d);
        const opacity = tm.encodedPIXIProperty("opacity", d);
        if (cx < 0 || cx > trackWidth) {
          return;
        }
        if (trackInfo.textsBeingUsed > 1e3) {
          return;
        }
        const localTextStyle = {
          ...TEXT_STYLE_GLOBAL,
          fontSize: size != null ? size : ((_a2 = spec.style) == null ? void 0 : _a2.textFontSize) ? `${(_b2 = spec.style) == null ? void 0 : _b2.textFontSize}px` : TEXT_STYLE_GLOBAL.fontSize,
          stroke: (_d2 = stroke != null ? stroke : (_c2 = spec.style) == null ? void 0 : _c2.textStroke) != null ? _d2 : TEXT_STYLE_GLOBAL.stroke,
          strokeThickness: (_f2 = strokeWidth != null ? strokeWidth : (_e2 = spec.style) == null ? void 0 : _e2.textStrokeWidth) != null ? _f2 : TEXT_STYLE_GLOBAL.strokeThickness,
          fontWeight: (_h2 = (_g2 = spec.style) == null ? void 0 : _g2.textFontWeight) != null ? _h2 : TEXT_STYLE_GLOBAL.fontWeight
        };
        const textStyleObj = new HGC.libraries.PIXI.TextStyle(localTextStyle);
        let textGraphic;
        if (trackInfo.textGraphics.length > trackInfo.textsBeingUsed) {
          textGraphic = trackInfo.textGraphics[trackInfo.textsBeingUsed];
          textGraphic.style.fill = color2;
          textGraphic.visible = true;
          textGraphic.text = text;
          textGraphic.alpha = 1;
        } else {
          textGraphic = new HGC.libraries.PIXI.Text(text, {
            ...localTextStyle,
            fill: color2
          });
          trackInfo.textGraphics.push(textGraphic);
        }
        const metric = HGC.libraries.PIXI.TextMetrics.measureText(text, textStyleObj);
        trackInfo.textsBeingUsed++;
        const alphaTransition = tm.markVisibility(d, {
          ...metric,
          zoomLevel: trackInfo._xScale.invert(trackWidth) - trackInfo._xScale.invert(0)
        });
        const actualOpacity = Math.min(alphaTransition, opacity);
        if (!text || actualOpacity === 0) {
          trackInfo.textsBeingUsed--;
          textGraphic.visible = false;
          return;
        }
        textGraphic.alpha = actualOpacity;
        textGraphic.anchor.x = !((_i2 = spec.style) == null ? void 0 : _i2.textAnchor) || ((_j = spec.style) == null ? void 0 : _j.textAnchor) === "middle" ? 0.5 : spec.style.textAnchor === "start" ? 0 : 1;
        textGraphic.anchor.y = 0.5;
        if (circular) {
          const r = trackOuterRadius - (rowPosition + rowHeight - y) / trackHeight * trackRingSize;
          const centerPos = cartesianToPolar(cx, trackWidth, r, tcx, tcy, startAngle, endAngle);
          textGraphic.x = centerPos.x;
          textGraphic.y = centerPos.y;
          textGraphic.resolution = 4;
          const txtStyle = new HGC.libraries.PIXI.TextStyle(textStyleObj);
          const metric2 = HGC.libraries.PIXI.TextMetrics.measureText(textGraphic.text, txtStyle);
          const tw = metric2.width / (2 * r * Math.PI) * trackWidth;
          let [minX, maxX] = [cx - tw / 2, cx + tw / 2];
          if (minX < 0) {
            const gap = -minX;
            minX = 0;
            maxX += gap;
          } else if (maxX > trackWidth) {
            const gap = maxX - trackWidth;
            maxX = trackWidth;
            minX -= gap;
          }
          const ropePoints = [];
          for (let i = maxX; i >= minX; i -= tw / 10) {
            const p = cartesianToPolar(i, trackWidth, r, tcx, tcy, startAngle, endAngle);
            ropePoints.push(new HGC.libraries.PIXI.Point(p.x, p.y));
          }
          textGraphic.updateText();
          const rope = new HGC.libraries.PIXI.SimpleRope(textGraphic.texture, ropePoints);
          rope.alpha = actualOpacity;
          rowGraphics.addChild(rope);
        } else {
          textGraphic.position.x = cx;
          textGraphic.position.y = rowPosition + rowHeight - y;
          rowGraphics.addChild(textGraphic);
        }
      });
    });
  }
}
function drawRule(HGC, trackInfo, tile, tm) {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const spec = tm.spec();
  const data2 = tm.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const cx = trackWidth / 2;
  const cy = trackHeight / 2;
  const rowCategories = (_e = tm.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const dashed = (_f = spec.style) == null ? void 0 : _f.dashed;
  const linePattern = (_g = spec.style) == null ? void 0 : _g.linePattern;
  const curved = (_h = spec.style) == null ? void 0 : _h.curve;
  const g = tile.graphics;
  rowCategories.forEach((rowCategory) => {
    const rowPosition = tm.encodedValue("row", rowCategory);
    data2.filter((d) => !getValueUsingChannel(d, spec.row) || getValueUsingChannel(d, spec.row) === rowCategory).forEach((d) => {
      const x = tm.encodedPIXIProperty("x", d);
      const xe = tm.encodedPIXIProperty("xe", d);
      const y = tm.encodedPIXIProperty("y", d);
      const color2 = tm.encodedPIXIProperty("color", d);
      const strokeWidth = tm.encodedPIXIProperty("strokeWidth", d);
      const opacity = tm.encodedPIXIProperty("opacity", d);
      const alphaTransition = tm.markVisibility(d, {
        width: xe - x,
        zoomLevel: trackInfo._xScale.invert(trackWidth) - trackInfo._xScale.invert(0)
      });
      const actualOpacity = Math.min(alphaTransition, opacity);
      g.lineStyle(strokeWidth, colorToHex(color2), actualOpacity, 0.5);
      if (!xe && (!spec.y || !("field" in spec.y))) {
        if (circular) {
          return;
        } else {
          if (dashed) {
            const [dashSize, gapSize] = dashed;
            let curPos = 0;
            do {
              g.moveTo(x, curPos);
              g.lineTo(x, curPos + dashSize);
              curPos += dashSize + gapSize;
            } while (curPos < trackHeight);
          } else {
            g.moveTo(x, 0);
            g.lineTo(x, trackHeight);
          }
        }
      } else if (!xe && y) {
        if (circular) {
          g.lineStyle(strokeWidth, colorToHex(color2), 0, 0.5);
          const midR = trackOuterRadius - (rowPosition + y) / trackHeight * trackRingSize;
          const farR = midR + strokeWidth / 2;
          const nearR = midR - strokeWidth / 2;
          const sPos = cartesianToPolar(0, trackWidth, nearR, cx, cy, startAngle, endAngle);
          const startRad = valueToRadian(0, trackWidth, startAngle, endAngle);
          const endRad = valueToRadian(trackWidth, trackWidth, startAngle, endAngle);
          g.beginFill(colorToHex(color2), actualOpacity);
          g.moveTo(sPos.x, sPos.y);
          g.arc(cx, cy, nearR, startRad, endRad, true);
          g.arc(cx, cy, farR, endRad, startRad, false);
          g.closePath();
        } else {
          if (dashed) {
            const [dashSize, gapSize] = dashed;
            let curPos = 0;
            do {
              g.moveTo(curPos, rowPosition + rowHeight - y);
              g.lineTo(curPos + dashSize, rowPosition + rowHeight - y);
              curPos += dashSize + gapSize;
            } while (curPos < trackWidth);
          } else {
            g.moveTo(0, rowPosition + rowHeight - y);
            g.lineTo(trackWidth, rowPosition + rowHeight - y);
          }
        }
      } else {
        if (circular) {
          if (strokeWidth === 0) {
            return;
          }
          g.lineStyle(strokeWidth, colorToHex(color2), 0, 0.5);
          const midR = trackOuterRadius - (rowPosition + y) / trackHeight * trackRingSize;
          const farR = midR + strokeWidth / 2;
          const nearR = midR - strokeWidth / 2;
          const sPos = cartesianToPolar(x, trackWidth, nearR, cx, cy, startAngle, endAngle);
          const startRad = valueToRadian(x, trackWidth, startAngle, endAngle);
          const endRad = valueToRadian(xe, trackWidth, startAngle, endAngle);
          g.beginFill(colorToHex(color2), actualOpacity);
          g.moveTo(sPos.x, sPos.y);
          g.arc(cx, cy, nearR, startRad, endRad, true);
          g.arc(cx, cy, farR, endRad, startRad, false);
          g.closePath();
        } else if (dashed) {
          const [dashSize, gapSize] = dashed;
          let curPos = x;
          do {
            g.moveTo(curPos, rowPosition + rowHeight - y);
            g.lineTo(curPos + dashSize, rowPosition + rowHeight - y);
            curPos += dashSize + gapSize;
          } while (curPos < xe);
        } else {
          if (curved === void 0) {
            g.moveTo(x, rowPosition + rowHeight - y);
            g.lineTo(xe, rowPosition + rowHeight - y);
          } else if (curved === "top") {
            const CURVE_HEIGHT = 2;
            const xm = x + (xe - x) / 2;
            g.moveTo(x, rowPosition + rowHeight - y + CURVE_HEIGHT / 2);
            g.lineTo(xm, rowPosition + rowHeight - y - CURVE_HEIGHT / 2);
            g.moveTo(xm, rowPosition + rowHeight - y - CURVE_HEIGHT / 2);
            g.lineTo(xe, rowPosition + rowHeight - y + CURVE_HEIGHT / 2);
          }
        }
        if (linePattern && curved === void 0 && !circular) {
          const { type: pType, size: pSize } = linePattern;
          let curPos = Math.max(x, 0);
          g.lineStyle(0);
          const PATTERN_GAP_SIZE = pSize * 2;
          let count2 = 0;
          while (curPos < Math.min(xe, trackWidth) && count2 < 100) {
            const x0 = curPos;
            const x1 = curPos + pSize;
            const ym = rowPosition + rowHeight - y;
            const y0 = ym - pSize / 2;
            const y1 = ym + pSize / 2;
            g.beginFill(colorToHex(color2), actualOpacity);
            g.drawPolygon(pType === "triangleLeft" ? [x1, y0, x0, ym, x1, y1, x1, y0] : [x0, y0, x1, ym, x0, y1, x0, y0]);
            g.endFill();
            curPos += pSize + PATTERN_GAP_SIZE;
            count2++;
          }
        }
      }
    });
  });
}
function drawLink(g, trackInfo, model) {
  var _a, _b, _c, _d, _e;
  const spec = model.spec();
  if (!spec.width || !spec.height) {
    console.warn("Size of a track is not properly determined, so visual mark cannot be rendered");
    return;
  }
  const data2 = model.data();
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const circular = spec.layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const tcx = trackWidth / 2;
  const tcy = trackHeight / 2;
  const rowCategories = (_e = model.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  rowCategories.forEach((rowCategory) => {
    const rowPosition = model.encodedValue("row", rowCategory);
    data2.filter((d) => !getValueUsingChannel(d, spec.row) || getValueUsingChannel(d, spec.row) === rowCategory).forEach((d) => {
      var _a2, _b2, _c2, _d2, _e2;
      let x = model.encodedPIXIProperty("x", d);
      let xe = model.encodedPIXIProperty("xe", d);
      let x1 = model.encodedPIXIProperty("x1", d);
      let x1e = model.encodedPIXIProperty("x1e", d);
      const y = model.encodedPIXIProperty("y", d);
      const stroke = model.encodedPIXIProperty("stroke", d);
      const strokeWidth = model.encodedPIXIProperty("strokeWidth", d);
      const color2 = model.encodedPIXIProperty("color", d);
      const opacity = model.encodedPIXIProperty("opacity", d);
      if (typeof xe !== "undefined") {
        [x, xe] = [x, xe].sort((a, b) => a - b);
      }
      if (typeof x1 !== "undefined" && typeof x1e !== "undefined") {
        [x1, x1e] = [x1, x1e].sort((a, b) => a - b);
      }
      const isBand = typeof xe !== "undefined" && typeof x1 !== "undefined" && typeof x1e !== "undefined" && Math.abs(x - xe) > 0.1 && Math.abs(x1 - x1e) > 0.1;
      if (!isBand && xe === void 0 && !Is2DTrack(spec)) {
        if (x1 === void 0 && x1e === void 0) {
          return;
        }
        xe = x1 !== void 0 ? x1 : x1e;
      }
      if (!isBand && Math.abs(x - xe) <= 0.1 && Math.abs(x1 - x1e) <= 0.1) {
        x = (x + xe) / 2;
        xe = (x1 + x1e) / 2;
      }
      g.lineStyle(strokeWidth, colorToHex(stroke), opacity, 0.5);
      const flipY = IsChannelDeep(spec.y) && spec.y.flip || spec.flipY;
      const baseY = rowPosition + (flipY ? 0 : rowHeight);
      if (isBand) {
        g.beginFill(color2 === "none" ? colorToHex("white") : colorToHex(color2), color2 === "none" ? 0 : opacity);
        let [_x1, _x2, _x3, _x4] = [x, xe, x1, x1e];
        if (spec.mark === "betweenLink") {
          [_x1, _x2] = [_x1, _x2].sort((a, b) => a - b);
          [_x3, _x4] = [_x3, _x4].sort((a, b) => a - b);
        } else {
          [_x1, _x2, _x3, _x4] = [_x1, _x2, _x3, _x4].sort((a, b) => a - b);
        }
        if (_x1 > trackWidth || _x4 < 0 || Math.abs(_x4 - _x1) < 0.5) {
          return;
        }
        if (circular) {
          if (_x1 < 0 || _x4 > trackWidth) {
            return;
          }
          const r = trackOuterRadius - rowPosition / trackHeight * trackRingSize;
          const posX = cartesianToPolar(_x1, trackWidth, r, tcx, tcy, startAngle, endAngle);
          const posXE = cartesianToPolar(_x2, trackWidth, r, tcx, tcy, startAngle, endAngle);
          const posX1 = cartesianToPolar(_x3, trackWidth, r, tcx, tcy, startAngle, endAngle);
          const posX1E = cartesianToPolar(_x4, trackWidth, r, tcx, tcy, startAngle, endAngle);
          g.moveTo(posX.x, posX.y);
          g.bezierCurveTo(tcx, tcy, tcx, tcy, posX1E.x, posX1E.y);
          g.arc(tcx, tcy, trackOuterRadius, positionToRadian(posX1E.x, posX1E.y, tcx, tcy), positionToRadian(posX1.x, posX1.y, tcx, tcy), false);
          g.bezierCurveTo(tcx, tcy, tcx, tcy, posXE.x, posXE.y);
          g.arc(tcx, tcy, trackOuterRadius, positionToRadian(posXE.x, posXE.y, tcx, tcy), positionToRadian(posX.x, posX.y, tcx, tcy), false);
          g.endFill();
        } else {
          if (spec.mark === "betweenLink") {
            g.moveTo(_x1, rowPosition);
            g.lineTo(_x2, rowPosition);
            g.lineTo(_x4, rowPosition + rowHeight);
            g.lineTo(_x3, rowPosition + rowHeight);
            g.lineTo(_x1, rowPosition);
            g.closePath();
            return;
          }
          g.moveTo(_x1, baseY);
          if (!((_a2 = spec.style) == null ? void 0 : _a2.bezierLink)) {
            g.arc((_x1 + _x4) / 2, baseY, (_x4 - _x1) / 2, -Math.PI, Math.PI, false);
            g.arc((_x2 + _x3) / 2, baseY, (_x3 - _x2) / 2, Math.PI, -Math.PI, true);
            g.closePath();
          } else {
            g.lineTo(_x3, rowPosition + rowHeight);
            g.bezierCurveTo(_x3 + (_x2 - _x3) / 3, rowPosition + rowHeight - (_x2 - _x3) / 2, _x3 + (_x2 - _x3) / 3 * 2, rowPosition + rowHeight - (_x2 - _x3) / 2, _x2, rowPosition + rowHeight);
            g.lineTo(_x4, rowPosition + rowHeight);
            g.bezierCurveTo(_x1 + (_x4 - _x1) / 3 * 2, rowPosition + rowHeight - (_x4 - _x1) / 2, _x1 + (_x4 - _x1) / 3, rowPosition + rowHeight - (_x4 - _x1) / 2, _x1, rowPosition + rowHeight);
            g.endFill();
          }
        }
      } else {
        if (Is2DTrack(spec) && spec.mark === "betweenLink") {
          if (((_b2 = spec.style) == null ? void 0 : _b2.linkConnectionType) === "curve") {
            g.moveTo(x, 0);
            g.bezierCurveTo(x / 5 * 4, (rowPosition + rowHeight - y) / 2, x / 2, (rowPosition + rowHeight - y) / 5 * 4, 0, rowPosition + rowHeight - y);
          } else if (((_c2 = spec.style) == null ? void 0 : _c2.linkConnectionType) === "straight") {
            g.moveTo(x, 0);
            g.lineTo(0, rowPosition + rowHeight - y);
          } else {
            g.moveTo(x, 0);
            g.lineTo(x, rowPosition + rowHeight - y);
            g.lineTo(0, rowPosition + rowHeight - y);
          }
          return;
        }
        if (spec.mark === "betweenLink" && circular) {
          let prevX, prevY;
          for (let t = 0; t <= 1; t += 0.02) {
            const logodds = (t2) => Math.log(t2 / (1 - t2));
            const movingRadius = (t2) => trackOuterRadius - 1 / (1 + Math.exp(logodds(t2))) * trackRingSize + 3;
            const getRadian = (t2, s, e) => ((e - s) * t2 + s) / trackWidth;
            const _x = tcx + movingRadius(t) * Math.cos(-getRadian(t, x, xe) * 2 * Math.PI - Math.PI / 2);
            const _y = tcy + movingRadius(t) * Math.sin(-getRadian(t, x, xe) * 2 * Math.PI - Math.PI / 2);
            if (prevX && prevY) {
              g.lineStyle(strokeWidth, colorToHex(stroke), opacity, 0.5);
              g.moveTo(prevX, prevY);
              g.lineTo(_x, _y);
            }
            prevX = _x;
            prevY = _y;
          }
          return;
        }
        if (spec.mark === "betweenLink") {
          g.moveTo(xe, rowPosition + rowHeight);
          g.lineTo(x, rowPosition);
          return;
        }
        const midX = (x + xe) / 2;
        g.beginFill(colorToHex("white"), 0);
        if (circular) {
          if (x < 0 || xe > trackWidth) {
            return;
          }
          const r = trackOuterRadius - rowPosition / trackHeight * trackRingSize;
          const posS = cartesianToPolar(x, trackWidth, r, tcx, tcy, startAngle, endAngle);
          const posE = cartesianToPolar(xe, trackWidth, r, tcx, tcy, startAngle, endAngle);
          const x12 = posS.x;
          const y1 = posS.y;
          const x2 = posS.x;
          const y2 = posS.y;
          const x3 = trackWidth / 2;
          const y3 = trackHeight / 2;
          const x4 = posE.x;
          const y4 = posE.y;
          g.moveTo(x12, y1);
          const bezier = new Bezier(x12, y1, x2, y2, x3, y3, x4, y4);
          const points = bezier.getLUT(14);
          points.forEach((d2) => g.lineTo(d2.x, d2.y));
          const morePoints = bezier.getLUT(1e3);
          if (spec.tooltip) {
            trackInfo.tooltips.push({
              datum: d,
              isMouseOver: (mouseX, mouseY) => morePoints.findIndex((d2) => Math.sqrt((d2.x - mouseX) ** 2 + (d2.y - mouseY) ** 2) < 5) !== -1,
              markInfo: {}
            });
          }
        } else {
          g.moveTo(x, baseY);
          if ((_d2 = spec.style) == null ? void 0 : _d2.bezierLink) {
            const x12 = x;
            const y1 = baseY;
            const x2 = x + (xe - x) / 3;
            const y2 = baseY + Math.max(rowHeight / 2, Math.min(rowHeight, (xe - x) / 2)) * (flipY ? 1 : -1);
            const x3 = x + (xe - x) / 3 * 2;
            const y3 = baseY + Math.max(rowHeight / 2, Math.min(rowHeight, (xe - x) / 2)) * (flipY ? 1 : -1);
            const x4 = xe;
            const y4 = baseY;
            const bezier = new Bezier(x12, y1, x2, y2, x3, y3, x4, y4);
            const points = bezier.getLUT(14);
            points.forEach((d2) => g.lineTo(d2.x, d2.y));
            const morePoints = bezier.getLUT(1e3);
            if (spec.tooltip) {
              trackInfo.tooltips.push({
                datum: d,
                isMouseOver: (mouseX, mouseY) => morePoints.findIndex((d2) => Math.sqrt((d2.x - mouseX) ** 2 + (d2.y - mouseY) ** 2) < 5) !== -1,
                markInfo: {}
              });
            }
          } else if ((_e2 = spec.style) == null ? void 0 : _e2.flatWithinLink) {
            const arcWidth = xe - x;
            const radius = Math.min(10, arcWidth / 2);
            const topY = rowPosition + rowHeight - y;
            if (flipY) {
              g.moveTo(x, baseY);
              g.lineTo(x, topY - radius);
              g.arc(x + radius, topY - radius, radius, -Math.PI, Math.PI / 2, true);
              g.lineTo(xe - radius, topY);
              g.arc(xe - radius, topY - radius, radius, Math.PI / 2, 0, true);
              g.lineTo(xe, baseY);
            } else {
              g.moveTo(x, baseY);
              g.lineTo(x, topY + radius);
              g.arc(x + radius, topY + radius, radius, -Math.PI, -Math.PI / 2);
              g.lineTo(xe - radius, topY);
              g.arc(xe - radius, topY + radius, radius, -Math.PI / 2, 0);
              g.lineTo(xe, baseY);
            }
          } else {
            if (xe < 0 || x > trackWidth) {
              return;
            }
            g.arc(midX, baseY, (xe - x) / 2, -Math.PI, Math.PI);
            g.closePath();
          }
        }
      }
    });
  });
}
function drawGrid(trackInfo, tm, theme) {
  drawYGridQuantitative(trackInfo, tm, theme);
  drawRowGrid(trackInfo, tm, theme);
}
function drawRowGrid(trackInfo, tm, theme) {
  var _a, _b, _c, _d;
  const spec = tm.spec();
  if (!IsChannelDeep(spec.row) || spec.row.grid !== true) {
    return;
  }
  const [trackX, trackY] = trackInfo.position;
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const circular = tm.spec().layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const cx = trackWidth / 2;
  const cy = trackHeight / 2;
  const rowCategories = tm.getChannelDomainArray("row");
  if (!rowCategories) {
    return;
  }
  const rowHeight = trackHeight / rowCategories.length;
  if (circular && trackRingSize <= 20 || !circular && rowHeight <= 20) {
    return;
  }
  const graphics = trackInfo.pBackground;
  const strokeWidth = theme.axis.gridStrokeWidth;
  rowCategories.forEach((rowCategory) => {
    const rowPosition = tm.encodedValue("row", rowCategory);
    if (!circular) {
      graphics.lineStyle(strokeWidth, colorToHex(theme.axis.gridColor), 1, 0.5);
      const y = trackY + rowPosition + rowHeight / 2;
      graphics.moveTo(trackX, y);
      graphics.lineTo(trackX + trackWidth, y);
    } else {
      const y = rowPosition + rowHeight / 2;
      const midR = trackOuterRadius - y / trackHeight * trackRingSize;
      const farR = midR + strokeWidth / 2;
      const nearR = midR - strokeWidth / 2;
      const sPos = cartesianToPolar(0, trackWidth, nearR, cx, cy, startAngle, endAngle);
      const startRad = valueToRadian(0, trackWidth, startAngle, endAngle);
      const endRad = valueToRadian(trackWidth, trackWidth, startAngle, endAngle);
      graphics.lineStyle(strokeWidth, colorToHex("black"), 0, 0.5);
      graphics.beginFill(colorToHex(theme.axis.gridColor), 1);
      graphics.moveTo(trackX + sPos.x, trackY + sPos.y);
      graphics.arc(trackX + cx, trackY + cy, nearR, startRad, endRad, true);
      graphics.arc(trackX + cx, trackY + cy, farR, endRad, startRad, false);
      graphics.closePath();
    }
  });
}
function drawYGridQuantitative(trackInfo, tm, theme) {
  var _a, _b, _c, _d, _e;
  const spec = tm.spec();
  if (!IsChannelDeep(spec.y) || spec.y.grid !== true) {
    return;
  }
  const [trackX, trackY] = trackInfo.position;
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const startX = trackX;
  const endX = trackX + trackWidth;
  const circular = tm.spec().layout === "circular";
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const cx = trackWidth / 2;
  const cy = trackHeight / 2;
  const rowCategories = (_e = tm.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = trackHeight / rowCategories.length;
  const scale = tm.getChannelScale("y");
  const domain = tm.getChannelDomainArray("y");
  if (!scale || !domain) {
    return;
  }
  if (circular && rowHeight / trackHeight * trackRingSize <= 20 || !circular && rowHeight <= 20) {
    return;
  }
  const graphics = trackInfo.pBackground;
  const strokeWidth = theme.axis.gridStrokeWidth;
  rowCategories.forEach((rowCategory) => {
    const rowPosition = tm.encodedValue("row", rowCategory);
    const assignedHeight = circular ? rowHeight / trackHeight * trackRingSize : rowHeight;
    const tickCount = Math.max(Math.ceil(assignedHeight / 40), 1);
    let ticks = scale.ticks(tickCount).filter((v) => domain[0] <= v && v <= domain[1]);
    if (ticks.length === 1) {
      ticks = scale.ticks(tickCount + 1).filter((v) => domain[0] <= v && v <= domain[1]);
    }
    if (!circular) {
      graphics.lineStyle(strokeWidth, colorToHex(theme.axis.gridColor), 1, 0.5);
      ticks.forEach((value) => {
        var _a2;
        const y = trackY + rowPosition + rowHeight - scale(value);
        if (theme.axis.gridStrokeType === "solid") {
          graphics.moveTo(startX, y);
          graphics.lineTo(endX, y);
        } else if (theme.axis.gridStrokeType === "dashed") {
          const [line, gap] = (_a2 = theme.axis.gridStrokeDash) != null ? _a2 : [1, 1];
          for (let i = startX; i < endX; i += line + gap) {
            graphics.moveTo(i, y);
            graphics.lineTo(i + line, y);
          }
        }
      });
    } else {
      ticks.forEach((value) => {
        const y = scale(value);
        const midR = trackOuterRadius - (rowPosition + rowHeight - y) / trackHeight * trackRingSize;
        const farR = midR + strokeWidth / 2;
        const nearR = midR - strokeWidth / 2;
        const sPos = cartesianToPolar(0, trackWidth, nearR, cx, cy, startAngle, endAngle);
        const startRad = valueToRadian(0, trackWidth, startAngle, endAngle);
        const endRad = valueToRadian(trackWidth, trackWidth, startAngle, endAngle);
        graphics.lineStyle(strokeWidth, colorToHex("black"), 0, 0.5);
        graphics.beginFill(colorToHex(theme.axis.gridColor), 1);
        graphics.moveTo(trackX + sPos.x, trackY + sPos.y);
        graphics.arc(trackX + cx, trackY + cy, nearR, startRad, endRad, true);
        graphics.arc(trackX + cx, trackY + cy, farR, endRad, startRad, false);
        graphics.closePath();
      });
    }
  });
}
const DEFAULT_TEXT_STYLE = {
  color: "black",
  size: 10,
  fontFamily: "Arial",
  fontWeight: "normal",
  stroke: "#ffffff",
  strokeThickness: 0
};
function getTextStyle(style = DEFAULT_TEXT_STYLE) {
  var _a, _b, _c, _d, _e, _f;
  return {
    fontSize: `${(_a = style.size) != null ? _a : DEFAULT_TEXT_STYLE.size}px`,
    fontFamily: (_b = style.fontFamily) != null ? _b : DEFAULT_TEXT_STYLE.fontFamily,
    fontWeight: (_c = style.fontWeight) != null ? _c : DEFAULT_TEXT_STYLE.fontWeight,
    fill: (_d = style.color) != null ? _d : DEFAULT_TEXT_STYLE.color,
    background: "white",
    lineJoin: "round",
    stroke: (_e = style.stroke) != null ? _e : DEFAULT_TEXT_STYLE.stroke,
    strokeThickness: (_f = style.strokeThickness) != null ? _f : DEFAULT_TEXT_STYLE.strokeThickness
  };
}
function drawCircularTitle(HGC, trackInfo, tile, gos, theme) {
  var _a, _b, _c;
  const spec = gos.spec();
  const { title: title2 } = spec;
  if (spec.layout !== "circular") {
    return;
  }
  if (!title2) {
    return;
  }
  const [tw, th] = trackInfo.dimensions;
  const trackOuterRadius = (_a = spec.outerRadius) != null ? _a : 300;
  const startAngle = (_b = spec.startAngle) != null ? _b : 0;
  const endAngle = (_c = spec.endAngle) != null ? _c : 360;
  const cx = tw / 2;
  const cy = th / 2;
  const g = tile.graphics;
  const titleR = trackOuterRadius - 1;
  const padding = 1;
  const pos = cartesianToPolar(padding, tw, titleR, cx, cy, startAngle, endAngle);
  const styleConfig = getTextStyle({
    color: theme.track.titleColor,
    size: 12,
    fontFamily: theme.axis.labelFontFamily,
    fontWeight: theme.axis.labelFontWeight
  });
  const textGraphic = new HGC.libraries.PIXI.Text(title2, styleConfig);
  textGraphic.anchor.x = 1;
  textGraphic.anchor.y = 0.5;
  textGraphic.position.x = pos.x;
  textGraphic.position.y = pos.y;
  textGraphic.resolution = 4;
  const txtStyle = new HGC.libraries.PIXI.TextStyle(styleConfig);
  const metric = HGC.libraries.PIXI.TextMetrics.measureText(textGraphic.text, txtStyle);
  const txtWidth = metric.width / (2 * titleR * Math.PI) * tw * 360 / (endAngle - startAngle);
  const scaledStartX = padding;
  const scaledEndX = padding + txtWidth;
  const ropePoints = [];
  for (let i = scaledEndX; i >= scaledStartX; i -= txtWidth / 10) {
    const p = cartesianToPolar(i, tw, titleR - metric.height / 2, cx, cy, startAngle, endAngle);
    ropePoints.push(new HGC.libraries.PIXI.Point(p.x, p.y));
  }
  const startRad = valueToRadian(scaledStartX, tw, startAngle, endAngle);
  const endRad = valueToRadian(scaledEndX + padding, tw, startAngle, endAngle);
  g.lineStyle(1, colorToHex("red"), 0, 0.5);
  g.beginFill(colorToHex(theme.track.titleBackground), 0.5);
  g.moveTo(pos.x, pos.y);
  g.arc(cx, cy, titleR - metric.height, startRad, endRad, true);
  g.arc(cx, cy, titleR, endRad, startRad, false);
  g.closePath();
  textGraphic.updateText();
  const rope = new HGC.libraries.PIXI.SimpleRope(textGraphic.texture, ropePoints);
  g.addChild(rope);
}
function drawChartOutlines(HGC, trackInfo, tm, theme) {
  var _a, _b, _c, _d;
  const g = trackInfo.pBorder;
  const [l, t] = trackInfo.position;
  const [w, h] = trackInfo.dimensions;
  g.lineStyle((_b = (_a = tm.spec().style) == null ? void 0 : _a.outlineWidth) != null ? _b : 1, colorToHex((_d = (_c = tm.spec().style) == null ? void 0 : _c.outline) != null ? _d : theme.track.outline), 1, 0.5);
  g.beginFill(colorToHex("white"), 0);
  g.drawRect(l, t, w, h);
  const x = tm.spec().x;
  g.lineStyle(1, colorToHex(theme.axis.baselineColor), 1, 0.5);
  if (IsChannelDeep(x) && x.axis === "top") {
    g.moveTo(l, t);
    g.lineTo(l + w, t);
  } else if (IsChannelDeep(x) && x.axis === "bottom") {
    g.moveTo(l, t + h);
    g.lineTo(l + w, t + h);
  }
}
function drawColorLegend(HGC, trackInfo, tile, tm, theme) {
  const spec = tm.spec();
  if (!IsChannelDeep(spec.color) || !spec.color.legend) {
    return;
  }
  switch (spec.color.type) {
    case "nominal":
      drawColorLegendCategories(HGC, trackInfo, tile, tm, theme);
      break;
    case "quantitative":
      drawColorLegendQuantitative(HGC, trackInfo, tile, tm, theme);
      break;
  }
}
function drawColorLegendQuantitative(HGC, trackInfo, tile, tm, theme) {
  const spec = tm.spec();
  if (!IsChannelDeep(spec.color) || spec.color.type !== "quantitative" || !spec.color.legend) {
    return;
  }
  const [trackX, trackY] = trackInfo.position;
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const legendWidth = 80;
  const legendHeight = trackHeight - 2 > 110 ? 110 : Math.max(trackHeight - 2, 40 - 2);
  const colorBarDim = {
    top: 10,
    left: 55,
    width: 20,
    height: legendHeight - 20
  };
  const legendX = trackX + trackWidth - legendWidth - 1;
  const legendY = trackY + 1;
  const colorScale = tm.getChannelScale("color");
  const colorDomain = tm.getChannelDomainArray("color");
  if (!colorScale || !colorDomain) {
    return;
  }
  const graphics = trackInfo.pBorder;
  graphics.beginFill(colorToHex(theme.legend.background), theme.legend.backgroundOpacity);
  graphics.lineStyle(1, colorToHex(theme.legend.backgroundStroke), theme.legend.backgroundOpacity, 0);
  graphics.drawRect(legendX, legendY, legendWidth, legendHeight);
  const [startValue, endValue] = colorDomain;
  const extent = endValue - startValue;
  [...Array(colorBarDim.height).keys()].forEach((y) => {
    const value = (colorBarDim.height - y) / colorBarDim.height * extent + startValue;
    graphics.beginFill(colorToHex(colorScale(value)), 1);
    graphics.lineStyle(1, colorToHex(theme.legend.backgroundStroke), 0, 0.5);
    graphics.drawRect(legendX + colorBarDim.left, legendY + colorBarDim.top + y, colorBarDim.width, 1);
  });
  const tickCount = Math.max(Math.ceil(colorBarDim.height / 30), 2);
  let ticks = colorScale.ticks(tickCount).filter((v) => colorDomain[0] <= v && v <= colorDomain[1]);
  if (ticks.length === 1) {
    ticks = colorScale.ticks(tickCount + 1).filter((v) => colorDomain[0] <= v && v <= colorDomain[1]);
  }
  const TICK_STROKE_SIZE = 1;
  graphics.lineStyle(TICK_STROKE_SIZE, colorToHex(theme.legend.tickColor), 1, 0.5);
  const labelTextStyle = getTextStyle({
    color: theme.legend.labelColor,
    size: theme.legend.labelFontSize,
    fontWeight: theme.legend.labelFontWeight,
    fontFamily: theme.legend.labelFontFamily
  });
  const tickEnd = legendX + colorBarDim.left;
  ticks.forEach((value) => {
    let y = legendY + colorBarDim.top + colorBarDim.height - (value - startValue) / extent * colorBarDim.height;
    if (y === legendY + colorBarDim.top) {
      y += TICK_STROKE_SIZE / 2;
    } else if (y === legendY + colorBarDim.top + colorBarDim.height) {
      y -= TICK_STROKE_SIZE / 2;
    }
    graphics.moveTo(tickEnd - 3, y);
    graphics.lineTo(tickEnd, y);
    const textGraphic = new HGC.libraries.PIXI.Text(value, labelTextStyle);
    textGraphic.anchor.x = 1;
    textGraphic.anchor.y = 0.5;
    textGraphic.position.x = tickEnd - 6;
    textGraphic.position.y = y;
    graphics.addChild(textGraphic);
  });
}
function drawColorLegendCategories(HGC, trackInfo, tile, tm, theme) {
  var _a, _b, _c, _d, _e;
  const spec = tm.spec();
  if (!IsChannelDeep(spec.color) || spec.color.type !== "nominal" || !spec.color.legend) {
    return;
  }
  const colorCategories = (_a = tm.getChannelDomainArray("color")) != null ? _a : ["___SINGLE_COLOR___"];
  if (colorCategories.length === 0) {
    return;
  }
  const graphics = trackInfo.pBorder;
  const paddingX = 10;
  const paddingY = 4;
  let cumY = paddingY;
  let maxWidth = 0;
  const recipe = [];
  const labelTextStyle = getTextStyle({
    color: theme.legend.labelColor,
    size: theme.legend.labelFontSize,
    fontWeight: theme.legend.labelFontWeight,
    fontFamily: theme.legend.labelFontFamily
  });
  if ((_b = spec.style) == null ? void 0 : _b.inlineLegend) {
    colorCategories.map((d) => d).reverse().forEach((category) => {
      if (maxWidth > trackInfo.dimensions[0]) {
        return;
      }
      const color2 = tm.encodedValue("color", category);
      const textGraphic = new HGC.libraries.PIXI.Text(category, labelTextStyle);
      textGraphic.anchor.x = 1;
      textGraphic.anchor.y = 0;
      textGraphic.position.x = trackInfo.position[0] + trackInfo.dimensions[0] - maxWidth - paddingX;
      textGraphic.position.y = trackInfo.position[1] + paddingY;
      graphics.addChild(textGraphic);
      const textStyleObj = new HGC.libraries.PIXI.TextStyle(labelTextStyle);
      const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(category, textStyleObj);
      if (cumY < textMetrics.height + paddingY * 3) {
        cumY = textMetrics.height + paddingY * 3;
      }
      recipe.push({
        x: trackInfo.position[0] + trackInfo.dimensions[0] - textMetrics.width - maxWidth - paddingX * 2,
        y: trackInfo.position[1] + paddingY + textMetrics.height / 2,
        color: color2
      });
      maxWidth += textMetrics.width + paddingX * 3;
    });
  } else {
    if ((_c = spec.style) == null ? void 0 : _c.legendTitle) {
      const textGraphic = new HGC.libraries.PIXI.Text((_d = spec.style) == null ? void 0 : _d.legendTitle, {
        ...labelTextStyle,
        fontWeight: "bold"
      });
      textGraphic.anchor.x = 1;
      textGraphic.anchor.y = 0;
      textGraphic.position.x = trackInfo.position[0] + trackInfo.dimensions[0] - paddingX;
      textGraphic.position.y = trackInfo.position[1] + cumY;
      const textStyleObj = new HGC.libraries.PIXI.TextStyle({ ...labelTextStyle, fontWeight: "bold" });
      const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText((_e = spec.style) == null ? void 0 : _e.legendTitle, textStyleObj);
      graphics.addChild(textGraphic);
      cumY += textMetrics.height + paddingY * 2;
    }
    colorCategories.forEach((category) => {
      if (cumY > trackInfo.dimensions[1]) {
        return;
      }
      const color2 = tm.encodedValue("color", category);
      const textGraphic = new HGC.libraries.PIXI.Text(category, labelTextStyle);
      textGraphic.anchor.x = 1;
      textGraphic.anchor.y = 0;
      textGraphic.position.x = trackInfo.position[0] + trackInfo.dimensions[0] - paddingX;
      textGraphic.position.y = trackInfo.position[1] + cumY;
      graphics.addChild(textGraphic);
      const textStyleObj = new HGC.libraries.PIXI.TextStyle(labelTextStyle);
      const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(category, textStyleObj);
      if (maxWidth < textMetrics.width + paddingX * 3) {
        maxWidth = textMetrics.width + paddingX * 3;
      }
      recipe.push({
        x: trackInfo.position[0] + trackInfo.dimensions[0] - textMetrics.width - paddingX * 2,
        y: trackInfo.position[1] + cumY + textMetrics.height / 2,
        color: color2
      });
      cumY += textMetrics.height + paddingY * 2;
    });
  }
  graphics.beginFill(colorToHex(theme.legend.background), theme.legend.backgroundOpacity);
  graphics.lineStyle(1, colorToHex(theme.legend.backgroundStroke), theme.legend.backgroundOpacity, 0);
  graphics.drawRect(trackInfo.position[0] + trackInfo.dimensions[0] - maxWidth - 1, trackInfo.position[1] + 1, maxWidth, cumY - paddingY);
  recipe.forEach((r) => {
    graphics.lineStyle(1, colorToHex("black"), 0, 0);
    graphics.beginFill(colorToHex(r.color), 1);
    graphics.drawCircle(r.x, r.y, 4);
  });
}
function drawRowLegend(HGC, trackInfo, tile, tm, theme) {
  var _a;
  const spec = tm.spec();
  if (!IsChannelDeep(spec.row) || spec.row.type !== "nominal" || !spec.row.legend) {
    return;
  }
  const rowCategories = (_a = tm.getChannelDomainArray("row")) != null ? _a : ["___SINGLE_ROW___"];
  if (rowCategories.length === 0) {
    return;
  }
  const graphics = trackInfo.pBorder;
  const paddingX = 4;
  const paddingY = 2;
  const labelTextStyle = getTextStyle({
    color: theme.legend.labelColor,
    size: theme.legend.labelFontSize,
    fontWeight: theme.legend.labelFontWeight,
    fontFamily: theme.legend.labelFontFamily
  });
  rowCategories.forEach((category) => {
    const rowPosition = tm.encodedValue("row", category);
    const textGraphic = new HGC.libraries.PIXI.Text(category, labelTextStyle);
    textGraphic.anchor.x = 0;
    textGraphic.anchor.y = 0;
    textGraphic.position.x = trackInfo.position[0] + paddingX;
    textGraphic.position.y = trackInfo.position[1] + rowPosition + paddingY;
    graphics.addChild(textGraphic);
    const textStyleObj = new HGC.libraries.PIXI.TextStyle(labelTextStyle);
    const textMetrics = HGC.libraries.PIXI.TextMetrics.measureText(category, textStyleObj);
    graphics.beginFill(colorToHex(theme.legend.background), theme.legend.backgroundOpacity);
    graphics.lineStyle(1, colorToHex(theme.legend.backgroundStroke), 0, 0);
    graphics.drawRect(trackInfo.position[0] + 1, trackInfo.position[1] + rowPosition + 1, textMetrics.width + paddingX * 2, textMetrics.height + paddingY * 2);
  });
}
const EXTENT_TICK_SIZE = 8;
const TICK_SIZE = 6;
function drawLinearYAxis(HGC, trackInfo, tile, gos, theme) {
  var _a;
  const spec = gos.spec();
  const CIRCULAR = spec.layout === "circular";
  const yDomain = gos.getChannelDomainArray("y");
  const yRange = gos.getChannelRangeArray("y");
  if (CIRCULAR) {
    return;
  }
  if (!gos.isShowYAxis() || !yDomain || !yRange) {
    return;
  }
  const [tw, th] = trackInfo.dimensions;
  const [tx, ty] = trackInfo.position;
  const rowCategories = (_a = gos.getChannelDomainArray("row")) != null ? _a : ["___SINGLE_ROW___"];
  const rowHeight = th / rowCategories.length;
  if (rowHeight <= 20) {
    return;
  }
  const yChannel = gos.spec().y;
  const isLeft = IsChannelDeep(yChannel) && "axis" in yChannel && yChannel.axis === "right" ? false : true;
  const yScale = linear_linear().domain(yDomain).range(yRange);
  const graphics = trackInfo.pBorder;
  rowCategories.forEach((category) => {
    const rowPosition = gos.encodedValue("row", category);
    const dx = isLeft ? tx : tx + tw;
    const dy = ty + rowPosition;
    graphics.lineStyle(1, colorToHex(theme.axis.baselineColor), 1, 0.5);
    graphics.moveTo(dx, dy);
    graphics.lineTo(dx, dy + rowHeight);
    const tickCount = Math.max(Math.ceil(rowHeight / 40), 1);
    let ticks = yScale.ticks(tickCount).filter((v) => yDomain[0] <= v && v <= yDomain[1]);
    if (ticks.length === 1) {
      ticks = yScale.ticks(tickCount + 1).filter((v) => yDomain[0] <= v && v <= yDomain[1]);
    }
    graphics.lineStyle(1, colorToHex(theme.axis.tickColor), 1, 0.5);
    let tickEnd = isLeft ? dx + TICK_SIZE : dx - TICK_SIZE;
    ticks.forEach((t) => {
      const y = yScale(t);
      graphics.moveTo(dx, dy + rowHeight - y);
      graphics.lineTo(tickEnd, dy + rowHeight - y);
    });
    tickEnd = isLeft ? dx + EXTENT_TICK_SIZE : dx - EXTENT_TICK_SIZE;
    graphics.moveTo(dx, dy);
    graphics.lineTo(tickEnd, dy);
    graphics.moveTo(dx, dy + rowHeight);
    graphics.lineTo(tickEnd, dy + rowHeight);
    const styleConfig = getTextStyle({
      color: theme.axis.labelColor,
      size: theme.axis.labelFontSize,
      fontFamily: theme.axis.labelFontFamily,
      fontWeight: theme.axis.labelFontWeight
    });
    ticks.forEach((t) => {
      const y = yScale(t);
      tickEnd = isLeft ? dx + TICK_SIZE * 2 : dx - TICK_SIZE * 2;
      const textGraphic = new HGC.libraries.PIXI.Text(t, styleConfig);
      textGraphic.anchor.x = isLeft ? 0 : 1;
      textGraphic.anchor.y = y === 0 ? 0.9 : 0.5;
      textGraphic.position.x = tickEnd;
      textGraphic.position.y = dy + rowHeight - y;
      graphics.addChild(textGraphic);
    });
  });
}
function drawCircularYAxis(HGC, trackInfo, tile, gos, theme) {
  var _a, _b, _c, _d, _e;
  const spec = gos.spec();
  const CIRCULAR = spec.layout === "circular";
  const yDomain = gos.getChannelDomainArray("y");
  const yRange = gos.getChannelRangeArray("y");
  if (!CIRCULAR) {
    return;
  }
  if (!gos.isShowYAxis() || !yDomain || !yRange) {
    return;
  }
  const [tw, th] = trackInfo.dimensions;
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const trackRingSize = trackOuterRadius - trackInnerRadius;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const cx = tw / 2;
  const cy = th / 2;
  const rowCategories = (_e = gos.getChannelDomainArray("row")) != null ? _e : ["___SINGLE_ROW___"];
  const rowHeight = th / rowCategories.length;
  if (rowHeight / th * trackRingSize <= 20) {
    return;
  }
  const yChannel = gos.spec().y;
  const isLeft = IsChannelDeep(yChannel) && "axis" in yChannel && yChannel.axis === "right" ? false : true;
  const yScale = linear_linear().domain(yDomain).range(yRange);
  const graphics = tile.graphics;
  rowCategories.forEach((category) => {
    const rowPosition = gos.encodedValue("row", category);
    const innerR = trackOuterRadius - (rowPosition + rowHeight) / th * trackRingSize;
    const outerR = trackOuterRadius - rowPosition / th * trackRingSize;
    const innerPos = cartesianToPolar(isLeft ? 0 : tw, tw, innerR, cx, cy, startAngle, endAngle);
    const outerPos = cartesianToPolar(isLeft ? 0 : tw, tw, outerR, cx, cy, startAngle, endAngle);
    graphics.lineStyle(1, colorToHex(theme.axis.baselineColor), 1, 0.5);
    graphics.moveTo(innerPos.x, innerPos.y);
    graphics.lineTo(outerPos.x, outerPos.y);
    const SCALED_TICK_SIZE = (r) => TICK_SIZE * tw / 2 / Math.PI / r;
    const SCALED_EXTENT_TICK_SIZE = (r) => EXTENT_TICK_SIZE * tw / 2 / Math.PI / r;
    const axisHeight = rowHeight / th * trackRingSize;
    const tickCount = Math.max(Math.ceil(axisHeight / 40), 1);
    let ticks = yScale.ticks(tickCount).filter((v) => yDomain[0] <= v && v <= yDomain[1]);
    if (ticks.length === 1) {
      ticks = yScale.ticks(tickCount + 1).filter((v) => yDomain[0] <= v && v <= yDomain[1]);
    }
    graphics.lineStyle(1, colorToHex(theme.axis.tickColor), 1, 0.5);
    ticks.forEach((t) => {
      const y = yScale(t);
      const currentR = trackOuterRadius - (rowPosition + rowHeight - y) / th * trackRingSize;
      const scaledStartX = isLeft ? 0 : tw - SCALED_TICK_SIZE(currentR);
      const scaledEndX = isLeft ? SCALED_TICK_SIZE(currentR) : tw;
      const pos = cartesianToPolar(scaledStartX, tw, currentR, cx, cy, startAngle, endAngle);
      const startRad = valueToRadian(scaledStartX, tw, startAngle, endAngle);
      const endRad = valueToRadian(scaledEndX, tw, startAngle, endAngle);
      graphics.moveTo(pos.x, pos.y);
      graphics.arc(cx, cy, currentR, startRad, endRad, true);
      graphics.arc(cx, cy, currentR, endRad, startRad, false);
      graphics.closePath();
    });
    {
      const scaledStartX = isLeft ? 0 : tw - SCALED_EXTENT_TICK_SIZE(trackInnerRadius);
      const scaledEndX = isLeft ? SCALED_EXTENT_TICK_SIZE(trackInnerRadius) : tw;
      const startRad = valueToRadian(scaledStartX, tw, startAngle, endAngle);
      const endRad = valueToRadian(scaledEndX, tw, startAngle, endAngle);
      graphics.moveTo(innerPos.x, innerPos.y);
      graphics.arc(cx, cy, trackInnerRadius, startRad, endRad, true);
      graphics.arc(cx, cy, trackInnerRadius, endRad, startRad, false);
      graphics.closePath();
    }
    {
      const scaledStartX = isLeft ? 0 : tw - SCALED_EXTENT_TICK_SIZE(trackOuterRadius);
      const scaledEndX = isLeft ? SCALED_EXTENT_TICK_SIZE(trackOuterRadius) : tw;
      const startRad = valueToRadian(scaledStartX, tw, startAngle, endAngle);
      const endRad = valueToRadian(scaledEndX, tw, startAngle, endAngle);
      graphics.moveTo(outerPos.x, outerPos.y);
      graphics.arc(cx, cy, trackOuterRadius, startRad, endRad, true);
      graphics.arc(cx, cy, trackOuterRadius, endRad, startRad, false);
      graphics.closePath();
    }
    ticks.forEach((t) => {
      const y = yScale(t);
      const currentR = trackOuterRadius - (rowPosition + rowHeight - y) / th * trackRingSize;
      const pos = cartesianToPolar(SCALED_TICK_SIZE(currentR) * 2, tw, currentR, cx, cy, startAngle, endAngle);
      const styleConfig = getTextStyle({
        color: theme.axis.labelColor,
        size: theme.axis.labelFontSize,
        fontFamily: theme.axis.labelFontFamily,
        fontWeight: theme.axis.labelFontWeight
      });
      const textGraphic = new HGC.libraries.PIXI.Text(t, styleConfig);
      textGraphic.anchor.x = isLeft ? 1 : 0;
      textGraphic.anchor.y = 0.5;
      textGraphic.position.x = pos.x;
      textGraphic.position.y = pos.y;
      textGraphic.resolution = 4;
      const txtStyle = new HGC.libraries.PIXI.TextStyle(styleConfig);
      const metric = HGC.libraries.PIXI.TextMetrics.measureText(textGraphic.text, txtStyle);
      const txtWidth = metric.width / (2 * currentR * Math.PI) * tw * 360 / (endAngle - startAngle);
      const scaledStartX = isLeft ? SCALED_TICK_SIZE(currentR) * 2 : tw - SCALED_TICK_SIZE(currentR) * 2 - txtWidth;
      const scaledEndX = isLeft ? SCALED_TICK_SIZE(currentR) * 2 + txtWidth : tw - SCALED_TICK_SIZE(currentR) * 2;
      const ropePoints = [];
      for (let i = scaledEndX; i >= scaledStartX; i -= txtWidth / 10) {
        const p = cartesianToPolar(i, tw, currentR, cx, cy, startAngle, endAngle);
        ropePoints.push(new HGC.libraries.PIXI.Point(p.x, p.y));
      }
      textGraphic.updateText();
      const rope = new HGC.libraries.PIXI.SimpleRope(textGraphic.texture, ropePoints);
      graphics.addChild(rope);
    });
  });
}
function drawCircularOutlines(HGC, trackInfo, tile, tm, theme) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
  const spec = tm.spec();
  const [l, t] = trackInfo.position;
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  const trackInnerRadius = (_a = spec.innerRadius) != null ? _a : 220;
  const trackOuterRadius = (_b = spec.outerRadius) != null ? _b : 300;
  const startAngle = (_c = spec.startAngle) != null ? _c : 0;
  const endAngle = (_d = spec.endAngle) != null ? _d : 360;
  const cx = l + trackWidth / 2;
  const cy = t + trackHeight / 2;
  const posStartInner = cartesianToPolar(0, trackWidth, trackInnerRadius, cx, cy, startAngle, endAngle);
  const startRad = valueToRadian(0, trackWidth, startAngle, endAngle);
  const endRad = valueToRadian(trackWidth, trackWidth, startAngle, endAngle);
  const g = trackInfo.pBackground;
  if (!(spec.layout === "circular" && spec.mark === "withinLink")) {
    g.lineStyle(((_e = spec.style) == null ? void 0 : _e.outlineWidth) ? ((_f = spec.style) == null ? void 0 : _f.outlineWidth) / 2.5 : 0, colorToHex((_h = (_g = spec.style) == null ? void 0 : _g.outline) != null ? _h : "#DBDBDB"), 1, 1);
    g.beginFill(colorToHex((_j = (_i = tm.spec().style) == null ? void 0 : _i.background) != null ? _j : theme.track.background), (_l = (_k = tm.spec().style) == null ? void 0 : _k.backgroundOpacity) != null ? _l : !theme.track.background || theme.track.background === "transparent" ? 0 : 1);
    g.moveTo(posStartInner.x, posStartInner.y);
    g.arc(cx, cy, trackInnerRadius, startRad, endRad, true);
    g.arc(cx, cy, trackOuterRadius, endRad, startRad, false);
    g.closePath();
  }
  if (IsChannelDeep(spec.x) && spec.x.axis === "top") {
    g.lineStyle(0.5, colorToHex("black"), 0, 0.5);
    g.beginFill(colorToHex("white"), 0);
    g.moveTo(posStartInner.x, posStartInner.y);
    g.arc(cx, cy, trackOuterRadius - 0.5, startRad, endRad, true);
    g.arc(cx, cy, trackOuterRadius, endRad, startRad, false);
    g.closePath();
  }
  g.lineStyle(0.5, colorToHex("black"), 0, 0.5);
  g.beginFill(colorToHex("white"), 0);
  g.moveTo(cx, cy);
  g.arc(cx, cy, trackOuterRadius + 3, startRad, endRad, false);
  g.closePath();
  g.lineStyle(1, colorToHex("#DBDBDB"), 0, 0);
  g.beginFill(colorToHex("white"), 0);
  g.drawCircle(cx, cy, trackInnerRadius - 1);
}
function drawBackground(HGC, trackInfo, tile, tm, theme) {
  var _a, _b, _c, _d, _e, _f;
  const [l, t] = trackInfo.position;
  const [w, h] = trackInfo.dimensions;
  const g = trackInfo.pBackground;
  if (((_a = tm.spec().style) == null ? void 0 : _a.background) || theme.track.background && theme.track.background !== "transparent") {
    g.clear();
    const bg = (_c = (_b = tm.spec().style) == null ? void 0 : _b.background) != null ? _c : theme.track.background;
    const alpha = lodash_es_isUndefined((_d = tm.spec().style) == null ? void 0 : _d.backgroundOpacity) ? 1 : (_e = tm.spec().style) == null ? void 0 : _e.backgroundOpacity;
    g.lineStyle(1, colorToHex("white"), 0, 0);
    g.beginFill(colorToHex(bg), alpha);
    g.drawRect(l, t, w, h);
  }
  if (theme.track.alternatingBackground && theme.track.alternatingBackground !== "transparent") {
    const spec = tm.spec();
    if (!IsChannelDeep(spec.row) || spec.row.type !== "nominal") {
      return;
    }
    const rowCategories = (_f = tm.getChannelDomainArray("row")) != null ? _f : ["___SINGLE_ROW___"];
    if (rowCategories.length === 0) {
      return;
    }
    rowCategories.forEach((category, i) => {
      var _a2, _b2, _c2, _d2;
      if (i % 2 === 0) {
        return;
      }
      const rowPosition = tm.encodedValue("row", category);
      const bg = (_b2 = (_a2 = tm.spec().style) == null ? void 0 : _a2.background) != null ? _b2 : theme.track.alternatingBackground;
      const alpha = lodash_es_isUndefined((_c2 = tm.spec().style) == null ? void 0 : _c2.backgroundOpacity) ? 1 : (_d2 = tm.spec().style) == null ? void 0 : _d2.backgroundOpacity;
      g.lineStyle(1, colorToHex("white"), 0, 0);
      g.beginFill(colorToHex(bg), alpha);
      g.drawRect(trackInfo.position[0], trackInfo.position[1] + rowPosition, w, h / rowCategories.length);
    });
  }
}
const SUPPORTED_CHANNELS = [
  "x",
  "xe",
  "x1",
  "x1e",
  "y",
  "ye",
  "y1",
  "y1e",
  "color",
  "size",
  "row",
  "stroke",
  "strokeWidth",
  "opacity",
  "text"
];
function drawMark(HGC, trackInfo, tile, model) {
  if (!HGC || !trackInfo || !tile) {
    return;
  }
  if (model.spec().mark === "brush") {
    return;
  }
  ["x", "x1", "x1e", "xe"].forEach((d) => {
    model.setChannelScale(d, trackInfo._xScale);
  });
  if (Is2DTrack(model.spec()) || IsVerticalRule(model.spec())) {
    const yScale = trackInfo._yScale.copy();
    yScale.range([yScale.range()[1], yScale.range()[0]]);
    ["y", "y1", "y1e", "ye"].forEach((d) => {
      model.setChannelScale(d, yScale);
    });
  }
  const [trackWidth, trackHeight] = trackInfo.dimensions;
  switch (model.spec().mark) {
    case "point":
      drawPoint(trackInfo, tile.graphics, model);
      break;
    case "bar":
      drawBar(trackInfo, tile, model);
      break;
    case "line":
      drawLine(tile.graphics, model, trackInfo.tooltips, trackWidth, trackHeight);
      break;
    case "area":
      drawArea(HGC, trackInfo, tile, model);
      break;
    case "rect":
      drawRect(HGC, trackInfo, tile, model);
      break;
    case "triangleLeft":
    case "triangleRight":
    case "triangleBottom":
      drawTriangle(tile.graphics, model, trackWidth, trackHeight);
      break;
    case "text":
      drawText(HGC, trackInfo, tile, model);
      break;
    case "rule":
      drawRule(HGC, trackInfo, tile, model);
      break;
    case "betweenLink":
    case "withinLink":
      drawLink(tile.graphics, trackInfo, model);
      break;
    default:
      console.warn("Unsupported mark type");
      break;
  }
}
function drawPreEmbellishment(HGC, trackInfo, tile, model, theme) {
  if (!HGC || !trackInfo || !tile) {
    return;
  }
  if (model.spec().mark === "brush") {
    return;
  }
  trackInfo.pBackground.clear();
  trackInfo.pBackground.removeChildren();
  trackInfo.pBorder.clear();
  trackInfo.pBorder.removeChildren();
  const CIRCULAR = model.spec().layout === "circular";
  ["x", "x1", "x1e", "xe"].forEach((d) => {
    model.setChannelScale(d, trackInfo._xScale);
  });
  if (CIRCULAR) {
    drawCircularOutlines(HGC, trackInfo, tile, model, theme);
  } else {
    drawBackground(HGC, trackInfo, tile, model, theme);
    drawChartOutlines(HGC, trackInfo, model, theme);
  }
  drawGrid(trackInfo, model, theme);
}
function drawPostEmbellishment(HGC, trackInfo, tile, model, theme) {
  if (!HGC || !trackInfo || !tile) {
    return;
  }
  if (model.spec().mark === "brush") {
    return;
  }
  const CIRCULAR = model.spec().layout === "circular";
  ["x", "x1", "x1e", "xe"].forEach((d) => {
    model.setChannelScale(d, trackInfo._xScale);
  });
  if (CIRCULAR) {
    drawCircularYAxis(HGC, trackInfo, tile, model, theme);
    drawCircularTitle(HGC, trackInfo, tile, model, theme);
  } else {
    drawLinearYAxis(HGC, trackInfo, tile, model, theme);
    drawRowLegend(HGC, trackInfo, tile, model, theme);
  }
  drawColorLegend(HGC, trackInfo, tile, model, theme);
}
function resolveSuperposedTracks(track) {
  if (IsDataTrack(track)) {
    return [];
  }
  if (!IsOverlaidTrack(track)) {
    return [track];
  }
  if (track.overlay.length === 0) {
    return [{ ...track, superpose: void 0 }];
  }
  const base = JSON.parse(JSON.stringify(track));
  delete base.overlay;
  const resolved = [];
  track.overlay.forEach((subSpec, i) => {
    const spec = lodash_es_assign(JSON.parse(JSON.stringify(base)), subSpec);
    if (spec.title && i !== 0) {
      delete spec.title;
    }
    resolved.push(spec);
  });
  let xAxisPosition = void 0;
  resolved.forEach((d) => {
    if (IsChannelDeep(d.x) && d.x.axis && !xAxisPosition) {
      xAxisPosition = d.x.axis;
    }
  });
  const corrected = resolved.map((d) => {
    return {
      ...d,
      x: { ...d.x, axis: xAxisPosition }
    };
  });
  return corrected;
}
function spreadTracksByData(tracks) {
  return [].concat(...tracks.map((t) => {
    if (IsDataTrack(t) || !IsOverlaidTrack(t) || t.overlay.length <= 1) {
      return [t];
    }
    if (t.overlay.filter((s) => s.data).length === 0) {
      return [t];
    }
    if (isIdenticalDataSpec([t.data, ...t.overlay.map((s) => s.data)])) {
      return [t];
    }
    const base = JSON.parse(JSON.stringify(t));
    delete base.overlay;
    const spread = [];
    const original = JSON.parse(JSON.stringify(base));
    original.overlay = [];
    t.overlay.forEach((subSpec) => {
      if (!original.data) {
        original.data = subSpec.data;
      }
      if (!subSpec.data || isIdenticalDataSpec([original.data, subSpec.data])) {
        original.overlay.push(subSpec);
        return;
      }
      const spec = lodash_es_assign(JSON.parse(JSON.stringify(base)), subSpec);
      spread.push(spec);
    });
    const output = original.overlay.length > 0 ? [original, ...spread] : spread;
    return output.map((track, i, arr) => {
      const overlayOnPreviousTrack = i !== 0;
      const y = IsSingleTrack(track) && IsChannelDeep(track.y) && !track.y.axis && overlayOnPreviousTrack ? { ...track.y, axis: i === 1 ? "right" : "none" } : IsSingleTrack(track) ? track.y : void 0;
      if (track.title && i !== arr.length - 1 && arr.length !== 1) {
        delete track.title;
      }
      return { ...track, overlayOnPreviousTrack, y };
    });
  }));
}
function isIdenticalDataSpec(specs) {
  if (specs.length === 0) {
    return false;
  }
  const definedSpecs = specs.filter((d) => d);
  if (definedSpecs.length !== specs.length) {
    return false;
  }
  const keys = Object.keys(definedSpecs[0]).sort();
  let isIdentical = true;
  keys.forEach((k) => {
    const uniqueProperties = Array.from(new Set(definedSpecs.map((d) => JSON.stringify(d[k]))));
    if (uniqueProperties.length !== 1) {
      isIdentical = false;
      return;
    }
  });
  return isIdentical;
}
const PREDEFINED_COLOR_STR_MAP = {
  viridis: viridis,
  grey: Greys,
  warm: warm,
  spectral: Spectral,
  cividis: cividis,
  bupu: BuPu,
  rdbu: RdBu,
  hot: YlOrBr,
  pink: RdPu
};
function getHiGlassColorRange(colorStr = "viridis", step = 100) {
  var _a;
  const interpolate = (_a = PREDEFINED_COLOR_STR_MAP[colorStr]) != null ? _a : PREDEFINED_COLOR_STR_MAP["viridis"];
  return [...Array(step)].map((v, i) => interpolate(1 / step * i));
}
function IsFlatTracks(_) {
  return !("alignment" in _) && !_.tracks.find((d) => d.alignment === "overlay" || "tracks" in d);
}
function IsOverlaidTracks(_) {
  return "alignment" in _ && _.alignment === "overlay";
}
function IsStackedTracks(_) {
  return !IsFlatTracks(_) && !IsOverlaidTracks(_);
}
function IsDataTrack(_) {
  return !IsOverlaidTrack(_) && "data" in _ && !("mark" in _);
}
function IsDataTemplate(_) {
  return !!("data" in _ && "overrideTemplate" in _ && _.overrideTemplate);
}
function IsDataDeep(data2) {
  return typeof data2 === "object";
}
function IsDomainChr(domain) {
  return "chromosome" in domain && !("interval" in domain);
}
function IsDomainInterval(domain) {
  return !("chromosome" in domain) && "interval" in domain;
}
function IsDomainChrInterval(domain) {
  return "chromosome" in domain && "interval" in domain;
}
function IsSingleTrack(track) {
  return !("overlay" in track);
}
function IsOverlaidTrack(track) {
  return "overlay" in track;
}
function IsTemplateTrack(track) {
  return "template" in track;
}
function IsVerticalRule(track) {
  return IsSingleTrack(track) && !IsChannelDeep(track.x) && IsChannelDeep(track.y) && track.y.type === "genomic";
}
function Is2DTrack(track) {
  const t = IsSingleTrack(track) ? track : resolveSuperposedTracks(track)[0];
  return IsChannelDeep(t.x) && t.x.type === "genomic" && IsChannelDeep(t.y) && t.y.type === "genomic";
}
function IsHiGlassMatrix(track) {
  return Is2DTrack(track) && track.data.type === "matrix" && (track.mark === "bar" || track.mark === "rect") && track.xe && track.ye;
}
function IsChannelValue(channel) {
  return channel !== null && typeof channel === "object" && "value" in channel;
}
function IsDataDeepTileset(_) {
  return _ !== void 0 && (_.type === "vector" || _.type === "beddb" || _.type === "multivec" || _.type === "bigwig" || _.type === "matrix" || _.type === "bam");
}
function IsChannelDeep(channel) {
  return typeof channel === "object" && !("value" in channel);
}
function IsOneOfFilter(_) {
  return "oneOf" in _;
}
function IsRangeFilter(_) {
  return "inRange" in _;
}
function IsIncludeFilter(_) {
  return "include" in _;
}
function IsDomainArray(domain) {
  return lodash_es_isArray(domain);
}
function IsRangeArray(range2) {
  return lodash_es_isArray(range2);
}
function IsStackedMark(track) {
  return (track.mark === "bar" || track.mark === "area" || track.mark === "text") && IsChannelDeep(track.color) && track.color.type === "nominal" && (!track.row || IsChannelValue(track.row)) && IsChannelDeep(track.y) && track.y.type === "quantitative" && !IsChannelDeep(track.ye);
}
function IsStackedChannel(track, channelKey) {
  const channel = track[channelKey];
  return IsStackedMark(track) && (channelKey === "x" || channelKey === "y") && IsChannelDeep(channel) && channel.type === "quantitative";
}
function getValueUsingChannel(datum, channel) {
  if (IsChannelDeep(channel) && channel.field) {
    return datum[channel == null ? void 0 : channel.field];
  }
  return void 0;
}
function getChannelKeysByAggregateFnc(spec) {
  const keys = [];
  SUPPORTED_CHANNELS.forEach((k) => {
    const c = spec[k];
    if (IsChannelDeep(c) && "aggregate" in c) {
      keys.push(k);
    }
  });
  return keys;
}
function getChannelKeysByType(spec, t) {
  const keys = [];
  SUPPORTED_CHANNELS.forEach((k) => {
    const c = spec[k];
    if (IsChannelDeep(c) && c.type === t) {
      keys.push(k);
    }
  });
  return keys;
}
function IsXAxis(_) {
  if ((IsSingleTrack(_) || IsOverlaidTrack(_)) && IsChannelDeep(_.x) && _.x.axis && _.x.axis !== "none") {
    return true;
  } else if (IsOverlaidTrack(_)) {
    let isFound = false;
    _.overlay.forEach((t) => {
      if (isFound)
        return;
      if (IsChannelDeep(t.x) && t.x.axis && t.x.axis !== "none") {
        isFound = true;
      }
    });
    return isFound;
  }
  return false;
}
function IsYAxis(_) {
  if ((IsSingleTrack(_) || IsOverlaidTrack(_)) && IsChannelDeep(_.y) && _.y.axis && _.y.axis !== "none") {
    return true;
  } else if (IsOverlaidTrack(_)) {
    let isFound = false;
    _.overlay.forEach((t) => {
      if (isFound)
        return;
      if (IsChannelDeep(t.y) && t.y.axis && t.y.axis !== "none") {
        isFound = true;
      }
    });
    return isFound;
  }
  return false;
}
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
  if (!getRandomValues) {
    getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== "undefined" && typeof msCrypto.getRandomValues === "function" && msCrypto.getRandomValues.bind(msCrypto);
    if (!getRandomValues) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues(rnds8);
}
var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
function validate$2(uuid) {
  return typeof uuid === "string" && REGEX.test(uuid);
}
var byteToHex = [];
for (var gosling_es_i = 0; gosling_es_i < 256; ++gosling_es_i) {
  byteToHex.push((gosling_es_i + 256).toString(16).substr(1));
}
function stringify(arr) {
  var offset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
  var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
  if (!validate$2(uuid)) {
    throw TypeError("Stringified UUID is invalid");
  }
  return uuid;
}
var _nodeId;
var _clockseq;
var _lastMSecs = 0;
var _lastNSecs = 0;
function v1(options, buf, offset) {
  var i = buf && offset || 0;
  var b = buf || new Array(16);
  options = options || {};
  var node = options.node || _nodeId;
  var clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq;
  if (node == null || clockseq == null) {
    var seedBytes = options.random || (options.rng || rng)();
    if (node == null) {
      node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
    }
    if (clockseq == null) {
      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
    }
  }
  var msecs = options.msecs !== void 0 ? options.msecs : Date.now();
  var nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1;
  var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
  if (dt < 0 && options.clockseq === void 0) {
    clockseq = clockseq + 1 & 16383;
  }
  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) {
    nsecs = 0;
  }
  if (nsecs >= 1e4) {
    throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
  }
  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;
  msecs += 122192928e5;
  var tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
  b[i++] = tl >>> 24 & 255;
  b[i++] = tl >>> 16 & 255;
  b[i++] = tl >>> 8 & 255;
  b[i++] = tl & 255;
  var tmh = msecs / 4294967296 * 1e4 & 268435455;
  b[i++] = tmh >>> 8 & 255;
  b[i++] = tmh & 255;
  b[i++] = tmh >>> 24 & 15 | 16;
  b[i++] = tmh >>> 16 & 255;
  b[i++] = clockseq >>> 8 | 128;
  b[i++] = clockseq & 255;
  for (var n = 0; n < 6; ++n) {
    b[i + n] = node[n];
  }
  return buf || stringify(b);
}
function parse(uuid) {
  if (!validate$2(uuid)) {
    throw TypeError("Invalid UUID");
  }
  var v;
  var arr = new Uint8Array(16);
  arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v >>> 16 & 255;
  arr[2] = v >>> 8 & 255;
  arr[3] = v & 255;
  arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v & 255;
  arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v & 255;
  arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v & 255;
  arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  arr[11] = v / 4294967296 & 255;
  arr[12] = v >>> 24 & 255;
  arr[13] = v >>> 16 & 255;
  arr[14] = v >>> 8 & 255;
  arr[15] = v & 255;
  return arr;
}
function stringToBytes(str) {
  str = unescape(encodeURIComponent(str));
  var bytes = [];
  for (var i = 0; i < str.length; ++i) {
    bytes.push(str.charCodeAt(i));
  }
  return bytes;
}
var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
var URL$2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
function v35(name2, version2, hashfunc) {
  function generateUUID(value, namespace, buf, offset) {
    if (typeof value === "string") {
      value = stringToBytes(value);
    }
    if (typeof namespace === "string") {
      namespace = parse(namespace);
    }
    if (namespace.length !== 16) {
      throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
    }
    var bytes = new Uint8Array(16 + value.length);
    bytes.set(namespace);
    bytes.set(value, namespace.length);
    bytes = hashfunc(bytes);
    bytes[6] = bytes[6] & 15 | version2;
    bytes[8] = bytes[8] & 63 | 128;
    if (buf) {
      offset = offset || 0;
      for (var i = 0; i < 16; ++i) {
        buf[offset + i] = bytes[i];
      }
      return buf;
    }
    return stringify(bytes);
  }
  try {
    generateUUID.name = name2;
  } catch (err) {
  }
  generateUUID.DNS = DNS;
  generateUUID.URL = URL$2;
  return generateUUID;
}
function md5(bytes) {
  if (typeof bytes === "string") {
    var msg = unescape(encodeURIComponent(bytes));
    bytes = new Uint8Array(msg.length);
    for (var i = 0; i < msg.length; ++i) {
      bytes[i] = msg.charCodeAt(i);
    }
  }
  return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
}
function md5ToHexEncodedArray(input) {
  var output = [];
  var length32 = input.length * 32;
  var hexTab = "0123456789abcdef";
  for (var i = 0; i < length32; i += 8) {
    var x = input[i >> 5] >>> i % 32 & 255;
    var hex = parseInt(hexTab.charAt(x >>> 4 & 15) + hexTab.charAt(x & 15), 16);
    output.push(hex);
  }
  return output;
}
function getOutputLength(inputLength8) {
  return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
}
function wordsToMd5(x, len) {
  x[len >> 5] |= 128 << len % 32;
  x[getOutputLength(len) - 1] = len;
  var a = 1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d = 271733878;
  for (var i = 0; i < x.length; i += 16) {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    a = md5ff(a, b, c, d, x[i], 7, -680876936);
    d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
    c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
    b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
    a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
    d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
    c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
    b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
    a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
    d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
    c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
    b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
    a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
    d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
    c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
    b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
    a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
    d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
    c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
    b = md5gg(b, c, d, a, x[i], 20, -373897302);
    a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
    d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
    c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
    b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
    a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
    d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
    c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
    b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
    a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
    d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
    c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
    b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
    a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
    d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
    c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
    b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
    a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
    d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
    c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
    b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
    a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
    d = md5hh(d, a, b, c, x[i], 11, -358537222);
    c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
    b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
    a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
    d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
    c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
    b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
    a = md5ii(a, b, c, d, x[i], 6, -198630844);
    d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
    c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
    b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
    a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
    d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
    c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
    b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
    a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
    d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
    c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
    b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
    a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
    d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
    c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
    b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
    a = safeAdd(a, olda);
    b = safeAdd(b, oldb);
    c = safeAdd(c, oldc);
    d = safeAdd(d, oldd);
  }
  return [a, b, c, d];
}
function bytesToWords(input) {
  if (input.length === 0) {
    return [];
  }
  var length8 = input.length * 8;
  var output = new Uint32Array(getOutputLength(length8));
  for (var i = 0; i < length8; i += 8) {
    output[i >> 5] |= (input[i / 8] & 255) << i % 32;
  }
  return output;
}
function safeAdd(x, y) {
  var lsw = (x & 65535) + (y & 65535);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return msw << 16 | lsw & 65535;
}
function bitRotateLeft(num, cnt) {
  return num << cnt | num >>> 32 - cnt;
}
function md5cmn(q, a, b, x, s, t) {
  return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
  return md5cmn(b & c | ~b & d, a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
  return md5cmn(b & d | c & ~d, a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
  return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
  return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
v35("v3", 48, md5);
function v4(options, buf, offset) {
  options = options || {};
  var rnds = options.random || (options.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset = offset || 0;
    for (var i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }
    return buf;
  }
  return stringify(rnds);
}
function gosling_es_f(s, x, y, z) {
  switch (s) {
    case 0:
      return x & y ^ ~x & z;
    case 1:
      return x ^ y ^ z;
    case 2:
      return x & y ^ x & z ^ y & z;
    case 3:
      return x ^ y ^ z;
  }
}
function ROTL(x, n) {
  return x << n | x >>> 32 - n;
}
function sha1(bytes) {
  var K = [1518500249, 1859775393, 2400959708, 3395469782];
  var H = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
  if (typeof bytes === "string") {
    var msg = unescape(encodeURIComponent(bytes));
    bytes = [];
    for (var i = 0; i < msg.length; ++i) {
      bytes.push(msg.charCodeAt(i));
    }
  } else if (!Array.isArray(bytes)) {
    bytes = Array.prototype.slice.call(bytes);
  }
  bytes.push(128);
  var l = bytes.length / 4 + 2;
  var N = Math.ceil(l / 16);
  var M = new Array(N);
  for (var _i = 0; _i < N; ++_i) {
    var arr = new Uint32Array(16);
    for (var j = 0; j < 16; ++j) {
      arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
    }
    M[_i] = arr;
  }
  M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  M[N - 1][14] = Math.floor(M[N - 1][14]);
  M[N - 1][15] = (bytes.length - 1) * 8 & 4294967295;
  for (var _i2 = 0; _i2 < N; ++_i2) {
    var W = new Uint32Array(80);
    for (var t = 0; t < 16; ++t) {
      W[t] = M[_i2][t];
    }
    for (var _t = 16; _t < 80; ++_t) {
      W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
    }
    var a = H[0];
    var b = H[1];
    var c = H[2];
    var d = H[3];
    var e = H[4];
    for (var _t2 = 0; _t2 < 80; ++_t2) {
      var s = Math.floor(_t2 / 20);
      var T = ROTL(a, 5) + gosling_es_f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
      e = d;
      d = c;
      c = ROTL(b, 30) >>> 0;
      b = a;
      a = T;
    }
    H[0] = H[0] + a >>> 0;
    H[1] = H[1] + b >>> 0;
    H[2] = H[2] + c >>> 0;
    H[3] = H[3] + d >>> 0;
    H[4] = H[4] + e >>> 0;
  }
  return [H[0] >> 24 & 255, H[0] >> 16 & 255, H[0] >> 8 & 255, H[0] & 255, H[1] >> 24 & 255, H[1] >> 16 & 255, H[1] >> 8 & 255, H[1] & 255, H[2] >> 24 & 255, H[2] >> 16 & 255, H[2] >> 8 & 255, H[2] & 255, H[3] >> 24 & 255, H[3] >> 16 & 255, H[3] >> 8 & 255, H[3] & 255, H[4] >> 24 & 255, H[4] >> 16 & 255, H[4] >> 8 & 255, H[4] & 255];
}
v35("v5", 80, sha1);
function getStyleOverridden(parent, child) {
  const base = parent ? JSON.parse(JSON.stringify(parent)) : {};
  return child ? lodash_es_assign(base, child) : base;
}
function traverseTracks(spec, callback) {
  if ("tracks" in spec) {
    spec.tracks.forEach((t, i, ts) => {
      callback(t, i, ts);
      traverseTracks(t, callback);
    });
  } else if ("views" in spec) {
    spec.views.forEach((view) => traverseTracks(view, callback));
  }
}
function traverseTracksAndViews(spec, callback) {
  if ("tracks" in spec) {
    spec.tracks.forEach((t) => {
      callback(t);
      traverseTracksAndViews(t, callback);
    });
  } else if ("views" in spec) {
    spec.views.forEach((v) => {
      callback(v);
      traverseTracksAndViews(v, callback);
    });
  }
}
function traverseViewArrangements(spec, callback) {
  if ("tracks" in spec)
    ;
  else {
    callback(spec);
    spec.views.forEach((v) => {
      traverseViewArrangements(v, callback);
    });
  }
}
function convertToFlatTracks(spec) {
  if (IsFlatTracks(spec)) {
    const base = JSON.parse(JSON.stringify(spec));
    delete base.tracks;
    return spec.tracks.filter((track) => !track._invalidTrack).map((track) => lodash_es_assign(JSON.parse(JSON.stringify(base)), track));
  }
  const newTracks = [];
  if (IsStackedTracks(spec)) {
    spec.tracks.filter((track) => !track._invalidTrack).map((track) => {
      if ("alignment" in track) {
        newTracks.push({
          ...track,
          overlay: [...track.tracks],
          tracks: void 0,
          alignment: void 0
        });
      } else {
        const base = JSON.parse(JSON.stringify(spec));
        delete base.tracks;
        const newSpec = lodash_es_assign(JSON.parse(JSON.stringify(base)), track);
        newTracks.push(newSpec);
      }
    });
  } else {
    newTracks.push({
      ...spec,
      overlay: [...spec.tracks.filter((track) => !track._invalidTrack)],
      tracks: void 0,
      alignment: void 0
    });
  }
  return JSON.parse(JSON.stringify(newTracks));
}
function traverseToFixSpecDownstream(spec, parentDef) {
  if (parentDef) {
    if (spec.assembly === void 0)
      spec.assembly = parentDef.assembly;
    if (spec.layout === void 0)
      spec.layout = parentDef.layout;
    if (spec.orientation === void 0)
      spec.orientation = parentDef.orientation;
    if (spec.static === void 0)
      spec.static = parentDef.static !== void 0 ? parentDef.static : false;
    if (spec.zoomLimits === void 0)
      spec.zoomLimits = parentDef.zoomLimits;
    if (spec.xDomain === void 0)
      spec.xDomain = parentDef.xDomain;
    if (spec.yDomain === void 0)
      spec.yDomain = parentDef.yDomain;
    if (spec.linkingId === void 0)
      spec.linkingId = parentDef.linkingId;
    if (spec.centerRadius === void 0)
      spec.centerRadius = parentDef.centerRadius;
    if (spec.spacing === void 0 && !("tracks" in spec))
      spec.spacing = parentDef.spacing;
    if (spec.xOffset === void 0)
      spec.xOffset = parentDef.xOffset;
    if (spec.yOffset === void 0)
      spec.yOffset = parentDef.yOffset;
    if ("views" in spec && "arrangement" in parentDef && spec.arrangement === void 0)
      spec.arrangement = parentDef.arrangement;
    spec.style = getStyleOverridden(parentDef.style, spec.style);
  } else {
    if (spec.assembly === void 0)
      spec.assembly = "hg38";
    if (spec.layout === void 0)
      spec.layout = "linear";
    if (spec.orientation === void 0)
      spec.orientation = "horizontal";
    if (spec.static === void 0)
      spec.static = false;
    if (spec.zoomLimits === void 0)
      spec.zoomLimits = [1, null];
    if (spec.centerRadius === void 0)
      spec.centerRadius = DEFAULT_INNER_RADIUS_PROP;
    if (spec.spacing === void 0)
      spec.spacing = DEFAULT_VIEW_SPACING;
    if ("views" in spec && spec.arrangement === void 0)
      spec.arrangement = "vertical";
    if (spec.xOffset === void 0)
      spec.xOffset = 0;
    if (spec.yOffset === void 0)
      spec.yOffset = 0;
  }
  if ("tracks" in spec) {
    let tracks = convertToFlatTracks(spec);
    tracks = spreadTracksByData(tracks);
    const linkID = v4();
    tracks.forEach((track, i, array) => {
      var _a, _b, _c;
      if (!track.width)
        track.width = DEFAULT_TRACK_WIDTH_LINEAR;
      if (!track.height)
        track.height = DEFAULT_TRACK_HEIGHT_LINEAR;
      if ("displacement" in track) {
        if (((_a = track.displacement) == null ? void 0 : _a.type) === "pile" && track.row === void 0 && IsChannelDeep(track.x) && track.x.field && IsChannelDeep(track.xe) && track.xe.field) {
          const newField = v4();
          const startField = track.x.field;
          const endField = track.xe.field;
          const padding = track.displacement.padding;
          const displaceTransform = {
            type: "displace",
            newField,
            boundingBox: { startField, endField, padding },
            method: "pile"
          };
          if (!track.dataTransform) {
            track.dataTransform = [];
          }
          track.dataTransform = [...track.dataTransform, displaceTransform];
          track.row = { field: newField, type: "nominal" };
        } else if (((_b = track.displacement) == null ? void 0 : _b.type) === "spread")
          ;
      }
      if (track.layout)
        track.layout = void 0;
      if (track.zoomLimits)
        track.zoomLimits = void 0;
      if (!track.assembly)
        track.assembly = spec.assembly;
      if (!track.layout)
        track.layout = spec.layout;
      if (!track.orientation)
        track.orientation = spec.orientation;
      if (track.static === void 0)
        track.static = spec.static !== void 0 ? spec.static : false;
      if (!track.zoomLimits)
        track.zoomLimits = spec.zoomLimits;
      track.style = getStyleOverridden(spec.style, track.style);
      if (IsOverlaidTrack(track)) {
        track.overlay.forEach((o) => {
          o.style = getStyleOverridden(track.style, o.style);
        });
      }
      if ((track.layout === "circular" || Is2DTrack(track)) && track.orientation === "vertical") {
        track.orientation = "horizontal";
      }
      if (Is2DTrack(track)) {
        track.layout = "linear";
        if ((IsSingleTrack(track) || IsOverlaidTrack(track)) && IsChannelDeep(track.y) && !track.y.domain) {
          track.y.domain = spec.yDomain;
        } else if (IsOverlaidTrack(track)) {
          track.overlay.forEach((o) => {
            if (IsChannelDeep(o.y) && !o.y.domain) {
              o.y.domain = spec.yDomain;
            }
          });
        }
      }
      if ((IsSingleTrack(track) || IsOverlaidTrack(track)) && IsChannelDeep(track.x) && !track.x.domain) {
        track.x.domain = spec.xDomain;
      } else if (IsOverlaidTrack(track)) {
        track.overlay.forEach((o) => {
          if (IsChannelDeep(o.x) && !o.x.domain) {
            o.x.domain = spec.xDomain;
          }
        });
      }
      if ((IsSingleTrack(track) || IsOverlaidTrack(track)) && IsChannelDeep(track.x) && !track.x.linkingId) {
        track.x.linkingId = (_c = spec.linkingId) != null ? _c : linkID;
      } else if (IsOverlaidTrack(track)) {
        let isAdded = false;
        track.overlay.forEach((o) => {
          var _a2;
          if (isAdded)
            return;
          if (IsChannelDeep(o.x) && !o.x.linkingId) {
            o.x.linkingId = (_a2 = spec.linkingId) != null ? _a2 : linkID;
            isAdded = true;
          }
        });
      }
      if (i === 0) {
        track.overlayOnPreviousTrack = false;
      }
      if (i === 0 || i !== 0 && tracks.slice(0, i).filter((d) => !d.overlayOnPreviousTrack).length === 1 && track.overlayOnPreviousTrack === true) {
        if ((IsSingleTrack(track) || IsOverlaidTrack(track)) && IsChannelDeep(track.x) && !track.x.axis) {
          if (track.orientation === "vertical") {
            track.x.axis = "left";
          } else {
            track.x.axis = "top";
          }
        } else if (IsOverlaidTrack(track)) {
          track.overlay.forEach((o) => {
            if (IsChannelDeep(o.x) && !o.x.axis) {
              if (track.orientation === "vertical") {
                o.x.axis = "left";
              } else {
                o.x.axis = "top";
              }
            }
          });
        }
      }
      if ((IsSingleTrack(track) || IsOverlaidTrack(track)) && IsChannelDeep(track.x) && track.x.axis && track.x.axis !== "none") {
        if (track.orientation === "vertical") {
          if (track.x.axis === "top") {
            track.x.axis = "left";
          } else if (track.x.axis === "bottom") {
            track.x.axis = "right";
          }
        } else {
          if (track.x.axis === "left") {
            track.x.axis = "top";
          } else if (track.x.axis === "right") {
            track.x.axis = "bottom";
          }
        }
      } else if (IsOverlaidTrack(track)) {
        track.overlay.forEach((o) => {
          if (IsChannelDeep(o.x) && o.x.axis && o.x.axis !== "none") {
            if (track.orientation === "vertical") {
              if (o.x.axis === "top") {
                o.x.axis = "left";
              } else if (o.x.axis === "bottom") {
                o.x.axis = "right";
              }
            } else {
              if (o.x.axis === "left") {
                o.x.axis = "top";
              } else if (o.x.axis === "right") {
                o.x.axis = "bottom";
              }
            }
          }
        });
      }
      if (i !== 0 && (i === array.length - 1 && array.slice(0, i + 1).filter((d) => d.overlayOnPreviousTrack).length < i || i !== array.length - 1 && array.slice(i + 1).filter((d) => d.overlayOnPreviousTrack).length === array.length - i - 1 && array.slice(0, i + 1).filter((d) => d.overlayOnPreviousTrack).length < i)) {
        if (IsSingleTrack(track) && track.mark === "withinLink" && track.flipY === void 0) {
          track.flipY = true;
        } else if (IsOverlaidTrack(track)) {
          if (track.mark === "withinLink" && track.flipY === void 0) {
            track.flipY = true;
          }
          track.overlay.forEach((o) => {
            if (o.mark === "withinLink" && o.flipY === void 0) {
              o.flipY = true;
            }
          });
        }
      }
      if (track.overlayOnPreviousTrack && array[i - 1]) {
        track.width = array[i - 1].width;
        track.height = array[i - 1].height;
        track.layout = array[i - 1].layout;
        track.assembly = array[i - 1].assembly;
      }
    });
    spec.tracks = tracks;
  } else {
    spec.views.forEach((v) => {
      traverseToFixSpecDownstream(v, spec);
    });
  }
}
function getVectorTemplate(column, value) {
  return {
    data: {
      type: "vector",
      url: "",
      column,
      value
    },
    mark: "bar",
    x: { field: column, type: "genomic", axis: "top" },
    y: { field: value, type: "quantitative" },
    width: 400,
    height: 100
  };
}
function getMultivecTemplate(row, column, value, categories) {
  return categories && categories.length < 10 ? {
    data: {
      type: "multivec",
      url: "",
      row,
      column,
      value,
      categories
    },
    mark: "bar",
    x: { field: column, type: "genomic", axis: "top" },
    y: { field: value, type: "quantitative" },
    row: { field: row, type: "nominal", legend: true },
    color: { field: row, type: "nominal" },
    width: 400,
    height: 100
  } : {
    data: {
      type: "multivec",
      url: "",
      row,
      column,
      value,
      categories
    },
    mark: "rect",
    x: { field: column, type: "genomic", axis: "top" },
    row: { field: row, type: "nominal", legend: true },
    color: { field: value, type: "quantitative" },
    width: 400,
    height: 100
  };
}
function overrideDataTemplates(spec) {
  traverseTracks(spec, (t, i, ts) => {
    if (!t.data || !IsDataDeepTileset(t.data)) {
      return;
    }
    if ("alignment" in t) {
      return;
    }
    if (!IsDataTemplate(t)) {
      return;
    }
    switch (t.data.type) {
      case "vector":
      case "bigwig":
        ts[i] = lodash_es_assign(getVectorTemplate(t.data.column, t.data.value), t);
        break;
      case "multivec":
        ts[i] = lodash_es_assign(getMultivecTemplate(t.data.row, t.data.column, t.data.value, t.data.categories), t);
        break;
    }
  });
}
const GoslingTemplates = [
  {
    name: "gene",
    channels: [
      { name: "startPosition", type: "genomic", required: true },
      { name: "endPosition", type: "genomic", required: true },
      { name: "strandColor", type: "nominal", required: true },
      { name: "strandRow", type: "nominal", required: true },
      { name: "opacity", type: "value", required: false },
      { name: "geneHeight", type: "value", required: false },
      { name: "geneLabel", type: "nominal", required: true },
      { name: "geneLabelColor", type: "nominal", required: true },
      { name: "geneLabelFontSize", type: "value", required: false },
      { name: "geneLabelStroke", type: "value", required: false },
      { name: "geneLabelStrokeThickness", type: "value", required: false },
      { name: "geneLabelOpacity", type: "value", required: false },
      { name: "type", type: "nominal", required: true }
    ],
    mapping: [
      {
        dataTransform: [
          { type: "filter", base: "type", oneOf: ["gene"] },
          { type: "filter", base: "strandColor", oneOf: ["-"] }
        ],
        mark: "triangleLeft",
        x: { base: "startPosition", type: "genomic" },
        size: { base: "geneHeight", value: 12 },
        row: { base: "strandRow", type: "nominal", domain: ["+", "-"] },
        color: { base: "strandColor", type: "nominal", domain: ["+", "-"], range: ["blue", "red"] },
        opacity: { base: "opacity", value: 0.4 },
        style: { align: "right" }
      },
      {
        dataTransform: [
          { type: "filter", base: "type", oneOf: ["gene"] },
          { type: "filter", base: "strandColor", oneOf: ["+"] }
        ],
        mark: "triangleRight",
        x: { base: "endPosition", type: "genomic" },
        size: { base: "geneHeight", value: 12 },
        row: { base: "strandRow", type: "nominal", domain: ["+", "-"] },
        color: { base: "strandColor", type: "nominal", domain: ["+", "-"], range: ["blue", "red"] },
        opacity: { base: "opacity", value: 0.4 },
        style: { align: "left" }
      },
      {
        dataTransform: [{ type: "filter", base: "type", oneOf: ["exon"] }],
        mark: "rect",
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        size: { base: "geneHeight", value: 12 },
        row: { base: "strandRow", type: "nominal", domain: ["+", "-"] },
        color: { base: "strandColor", type: "nominal", domain: ["+", "-"], range: ["blue", "red"] },
        opacity: { base: "opacity", value: 0.4 }
      },
      {
        dataTransform: [
          { type: "filter", base: "type", oneOf: ["gene"] },
          { type: "filter", base: "strandColor", oneOf: ["+"] }
        ],
        mark: "rect",
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        row: { base: "strandRow", type: "nominal", domain: ["+", "-"] },
        color: { base: "strandColor", type: "nominal", domain: ["+", "-"], range: ["blue", "red"] },
        opacity: { base: "opacity", value: 0.4 },
        size: { value: 3 }
      },
      {
        dataTransform: [
          { type: "filter", base: "type", oneOf: ["gene"] },
          { type: "filter", base: "strandColor", oneOf: ["-"] }
        ],
        mark: "rect",
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        row: { base: "strandRow", type: "nominal", domain: ["+", "-"] },
        color: { base: "strandColor", type: "nominal", domain: ["+", "-"], range: ["blue", "red"] },
        opacity: { base: "opacity", value: 0.4 },
        size: { value: 3 }
      },
      {
        dataTransform: [{ type: "filter", base: "type", oneOf: ["gene"] }],
        mark: "text",
        text: { base: "geneLabel", type: "nominal" },
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        row: { base: "strandRow", type: "nominal", domain: ["+", "-"] },
        color: { base: "geneLabelColor", type: "nominal", domain: ["+", "-"], range: ["blue", "red"] },
        opacity: { base: "opacity", value: 1 },
        size: { base: "geneLabelFontSize", value: 18 },
        stroke: { base: "geneLabelStroke", value: "white" },
        strokeWidth: { base: "geneLabelStrokeThickness", value: 2 },
        visibility: [
          {
            operation: "less-than",
            measure: "width",
            threshold: "|xe-x|",
            transitionPadding: 10,
            target: "mark"
          }
        ]
      }
    ]
  },
  {
    name: "ideogram",
    channels: [
      { name: "startPosition", type: "genomic", required: true },
      { name: "endPosition", type: "genomic", required: true },
      { name: "chrHeight", type: "value", required: false },
      { name: "name", type: "nominal", required: true },
      { name: "stainBackgroundColor", type: "nominal", required: true },
      { name: "stainLabelColor", type: "nominal", required: true },
      { name: "stainStroke", type: "value", required: false },
      { name: "stainStrokeWidth", type: "value", required: false }
    ],
    mapping: [
      {
        mark: "rect",
        dataTransform: [{ type: "filter", base: "stainBackgroundColor", oneOf: ["acen"], not: true }],
        color: {
          base: "stainBackgroundColor",
          type: "nominal",
          domain: ["gneg", "gpos25", "gpos50", "gpos75", "gpos100", "gvar", "acen"],
          range: ["white", "lightgray", "gray", "gray", "black", "#7B9CC8", "#DC4542"]
        },
        size: { base: "chrHeight", value: 18 },
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        stroke: { base: "stainStroke", value: "gray" },
        strokeWidth: { base: "stainStrokeWidth", value: 0.3 }
      },
      {
        mark: "triangleRight",
        dataTransform: [
          { type: "filter", base: "stainBackgroundColor", oneOf: ["acen"] },
          { type: "filter", base: "name", include: "q" }
        ],
        color: {
          base: "stainBackgroundColor",
          type: "nominal",
          domain: ["gneg", "gpos25", "gpos50", "gpos75", "gpos100", "gvar", "acen"],
          range: ["white", "lightgray", "gray", "gray", "black", "#7B9CC8", "#DC4542"]
        },
        size: { base: "chrHeight", value: 18 },
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        stroke: { base: "stainStroke", value: "gray" },
        strokeWidth: { base: "stainStrokeWidth", value: 0.3 }
      },
      {
        mark: "triangleLeft",
        dataTransform: [
          { type: "filter", base: "stainBackgroundColor", oneOf: ["acen"] },
          { type: "filter", base: "name", include: "p" }
        ],
        color: {
          base: "stainBackgroundColor",
          type: "nominal",
          domain: ["gneg", "gpos25", "gpos50", "gpos75", "gpos100", "gvar", "acen"],
          range: ["white", "lightgray", "gray", "gray", "black", "#7B9CC8", "#DC4542"]
        },
        size: { base: "chrHeight", value: 18 },
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        stroke: { base: "stainStroke", value: "gray" },
        strokeWidth: { base: "stainStrokeWidth", value: 0.3 }
      },
      {
        mark: "text",
        dataTransform: [{ type: "filter", base: "stainLabelColor", oneOf: ["acen"], not: true }],
        color: {
          base: "stainLabelColor",
          type: "nominal",
          domain: ["gneg", "gpos25", "gpos50", "gpos75", "gpos100", "gvar"],
          range: ["black", "black", "black", "black", "white", "black"]
        },
        text: { base: "name", type: "nominal" },
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        visibility: [
          {
            operation: "less-than",
            measure: "width",
            threshold: "|xe-x|",
            transitionPadding: 10,
            target: "mark"
          }
        ]
      }
    ]
  },
  {
    name: "sequence",
    channels: [
      { name: "startPosition", type: "genomic", required: true },
      { name: "endPosition", type: "genomic", required: true },
      { name: "barLength", type: "quantitative", required: true },
      { name: "baseBackground", type: "nominal", required: true },
      { name: "baseLabelColor", type: "nominal", required: true },
      { name: "baseLabelFontSize", type: "value", required: false }
    ],
    mapping: [
      {
        mark: "bar",
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        y: { base: "barLength", type: "quantitative", axis: "none" },
        color: { base: "baseBackground", type: "nominal", domain: ["A", "T", "G", "C"] }
      },
      {
        dataTransform: [{ type: "filter", base: "barLength", oneOf: [0], not: true }],
        mark: "text",
        x: { base: "startPosition", type: "genomic" },
        xe: { base: "endPosition", type: "genomic" },
        color: { base: "baseLabelColor", type: "nominal", domain: ["A", "T", "G", "C"], range: ["white"] },
        text: { base: "baseBackground", type: "nominal" },
        size: { base: "baseLabelFontSize", value: 18 },
        visibility: [
          {
            operation: "less-than",
            measure: "width",
            threshold: "|xe-x|",
            transitionPadding: 30,
            target: "mark"
          },
          {
            operation: "LT",
            measure: "zoomLevel",
            threshold: 10,
            target: "track"
          }
        ]
      }
    ]
  }
];
function replaceTrackTemplates(spec, templates) {
  traverseTracks(spec, (t, i, ts) => {
    var _a, _b;
    if (!IsTemplateTrack(t)) {
      return;
    }
    const { template: name2 } = t;
    const templateDef = templates.find((d) => d.name === name2);
    if (!templateDef) {
      t._invalidTrack = true;
      console.warn(`There is no track template named '${name2}'`);
      return;
    }
    let isValid = true;
    templateDef.channels.forEach((d) => {
      if (d.required && (!t.encoding || !(d.name in t.encoding))) {
        isValid = false;
        console.warn(`A template spec ('${name2}') does not contain a required channel, ${d.name}`);
      }
    });
    if (!isValid) {
      t._invalidTrack = true;
      return;
    }
    const viewBase = JSON.parse(JSON.stringify(t));
    if ("encoding" in viewBase) {
      delete viewBase.encoding;
    }
    const convertedView = {
      ...viewBase,
      alignment: "overlay",
      tracks: [],
      width: (_a = t.width) != null ? _a : 100,
      height: (_b = t.height) != null ? _b : 100
    };
    templateDef.mapping.forEach((singleTrackMappingDef) => {
      const convertedTrack = {
        data: t.data,
        mark: singleTrackMappingDef.mark
      };
      const { dataTransform } = singleTrackMappingDef;
      if (dataTransform) {
        dataTransform.map((dataTramsformMap) => {
          const baseChannelName = dataTramsformMap.base;
          if (baseChannelName && t.encoding && baseChannelName in t.encoding && "field" in t.encoding[baseChannelName]) {
            delete dataTramsformMap.base;
            dataTramsformMap.field = t.encoding[baseChannelName].field;
          }
        });
      }
      const encodingSpec = t.encoding;
      if (!encodingSpec) {
        Object.keys(singleTrackMappingDef).filter((k) => k !== "mark").forEach((channelKey) => {
          const channelMap = JSON.parse(JSON.stringify(singleTrackMappingDef[channelKey]));
          if ("base" in channelMap) {
            delete channelMap.base;
          }
          convertedTrack[channelKey] = channelMap;
        });
      } else {
        Object.keys(singleTrackMappingDef).filter((k) => k !== "mark").forEach((channelKey) => {
          const channelMap = JSON.parse(JSON.stringify(singleTrackMappingDef[channelKey]));
          if ("base" in channelMap) {
            const baseChannelName = channelMap.base;
            if (baseChannelName in encodingSpec) {
              const base = JSON.parse(JSON.stringify(encodingSpec[baseChannelName]));
              delete channelMap.base;
              const newChannelSpec = lodash_es_assign(channelMap, JSON.parse(JSON.stringify(base)));
              convertedTrack[channelKey] = newChannelSpec;
            } else {
              delete channelMap.base;
              convertedTrack[channelKey] = channelMap;
            }
          } else {
            convertedTrack[channelKey] = channelMap;
          }
        });
      }
      convertedView.tracks.push(convertedTrack);
    });
    ts[i] = convertedView;
  });
}
function gosling_es_formatDecimal(x) {
  return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10);
}
function gosling_es_formatDecimalParts(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0)
    return null;
  var i, coefficient = x.slice(0, i);
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
}
function gosling_es_exponent(x) {
  return x = gosling_es_formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
}
function gosling_es_formatGroup(grouping, thousands) {
  return function(value, width) {
    var i = value.length, t = [], j = 0, g = grouping[0], length = 0;
    while (i > 0 && g > 0) {
      if (length + g + 1 > width)
        g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width)
        break;
      g = grouping[j = (j + 1) % grouping.length];
    }
    return t.reverse().join(thousands);
  };
}
function gosling_es_formatNumerals(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
}
var gosling_es_re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function gosling_es_formatSpecifier(specifier) {
  if (!(match = gosling_es_re.exec(specifier)))
    throw new Error("invalid format: " + specifier);
  var match;
  return new gosling_es_FormatSpecifier({
    fill: match[1],
    align: match[2],
    sign: match[3],
    symbol: match[4],
    zero: match[5],
    width: match[6],
    comma: match[7],
    precision: match[8] && match[8].slice(1),
    trim: match[9],
    type: match[10]
  });
}
gosling_es_formatSpecifier.prototype = gosling_es_FormatSpecifier.prototype;
function gosling_es_FormatSpecifier(specifier) {
  this.fill = specifier.fill === void 0 ? " " : specifier.fill + "";
  this.align = specifier.align === void 0 ? ">" : specifier.align + "";
  this.sign = specifier.sign === void 0 ? "-" : specifier.sign + "";
  this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + "";
  this.zero = !!specifier.zero;
  this.width = specifier.width === void 0 ? void 0 : +specifier.width;
  this.comma = !!specifier.comma;
  this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision;
  this.trim = !!specifier.trim;
  this.type = specifier.type === void 0 ? "" : specifier.type + "";
}
gosling_es_FormatSpecifier.prototype.toString = function() {
  return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type;
};
function gosling_es_formatTrim(s) {
  out:
    for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
      switch (s[i]) {
        case ".":
          i0 = i1 = i;
          break;
        case "0":
          if (i0 === 0)
            i0 = i;
          i1 = i;
          break;
        default:
          if (!+s[i])
            break out;
          if (i0 > 0)
            i0 = 0;
          break;
      }
    }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}
var gosling_es_prefixExponent;
function gosling_es_formatPrefixAuto(x, p) {
  var d = gosling_es_formatDecimalParts(x, p);
  if (!d)
    return x + "";
  var coefficient = d[0], exponent2 = d[1], i = exponent2 - (gosling_es_prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent2 / 3))) * 3) + 1, n = coefficient.length;
  return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + gosling_es_formatDecimalParts(x, Math.max(0, p + i - 1))[0];
}
function gosling_es_formatRounded(x, p) {
  var d = gosling_es_formatDecimalParts(x, p);
  if (!d)
    return x + "";
  var coefficient = d[0], exponent2 = d[1];
  return exponent2 < 0 ? "0." + new Array(-exponent2).join("0") + coefficient : coefficient.length > exponent2 + 1 ? coefficient.slice(0, exponent2 + 1) + "." + coefficient.slice(exponent2 + 1) : coefficient + new Array(exponent2 - coefficient.length + 2).join("0");
}
var gosling_es_formatTypes = {
  "%": function(x, p) {
    return (x * 100).toFixed(p);
  },
  "b": function(x) {
    return Math.round(x).toString(2);
  },
  "c": function(x) {
    return x + "";
  },
  "d": gosling_es_formatDecimal,
  "e": function(x, p) {
    return x.toExponential(p);
  },
  "f": function(x, p) {
    return x.toFixed(p);
  },
  "g": function(x, p) {
    return x.toPrecision(p);
  },
  "o": function(x) {
    return Math.round(x).toString(8);
  },
  "p": function(x, p) {
    return gosling_es_formatRounded(x * 100, p);
  },
  "r": gosling_es_formatRounded,
  "s": gosling_es_formatPrefixAuto,
  "X": function(x) {
    return Math.round(x).toString(16).toUpperCase();
  },
  "x": function(x) {
    return Math.round(x).toString(16);
  }
};
function identity$1(x) {
  return x;
}
var map$1 = Array.prototype.map, gosling_es_prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function formatLocale(locale2) {
  var group2 = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity$1 : gosling_es_formatGroup(map$1.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity$1 : gosling_es_formatNumerals(map$1.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "-" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + "";
  function newFormat(specifier) {
    specifier = gosling_es_formatSpecifier(specifier);
    var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type2 = specifier.type;
    if (type2 === "n")
      comma = true, type2 = "g";
    else if (!gosling_es_formatTypes[type2])
      precision === void 0 && (precision = 12), trim = true, type2 = "g";
    if (zero || fill === "0" && align === "=")
      zero = true, fill = "0", align = "=";
    var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type2) ? "0" + type2.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type2) ? percent : "";
    var formatType = gosling_es_formatTypes[type2], maybeSuffix = /[defgprs%]/.test(type2);
    precision = precision === void 0 ? 6 : /[gprs]/.test(type2) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
    function format2(value) {
      var valuePrefix = prefix, valueSuffix = suffix, i, n, c;
      if (type2 === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
        if (trim)
          value = gosling_es_formatTrim(value);
        if (valueNegative && +value === 0 && sign !== "+")
          valueNegative = false;
        valuePrefix = (valueNegative ? sign === "(" ? sign : minus : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type2 === "s" ? gosling_es_prefixes[8 + gosling_es_prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }
      if (comma && !zero)
        value = group2(value, Infinity);
      var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : "";
      if (comma && zero)
        value = group2(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
      switch (align) {
        case "<":
          value = valuePrefix + value + valueSuffix + padding;
          break;
        case "=":
          value = valuePrefix + padding + value + valueSuffix;
          break;
        case "^":
          value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
          break;
        default:
          value = padding + valuePrefix + value + valueSuffix;
          break;
      }
      return numerals(value);
    }
    format2.toString = function() {
      return specifier + "";
    };
    return format2;
  }
  function formatPrefix2(specifier, value) {
    var f2 = newFormat((specifier = gosling_es_formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(gosling_es_exponent(value) / 3))) * 3, k = Math.pow(10, -e), prefix = gosling_es_prefixes[8 + e / 3];
    return function(value2) {
      return f2(k * value2) + prefix;
    };
  }
  return {
    format: newFormat,
    formatPrefix: formatPrefix2
  };
}
var gosling_es_locale;
var format$1;
var gosling_es_formatPrefix;
gosling_es_defaultLocale({
  decimal: ".",
  thousands: ",",
  grouping: [3],
  currency: ["$", ""],
  minus: "-"
});
function gosling_es_defaultLocale(definition) {
  gosling_es_locale = formatLocale(definition);
  format$1 = gosling_es_locale.format;
  gosling_es_formatPrefix = gosling_es_locale.formatPrefix;
  return gosling_es_locale;
}
function gosling_es_precisionPrefix(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(gosling_es_exponent(value) / 3))) * 3 - gosling_es_exponent(Math.abs(step)));
}
const CHROM_SIZE_HG38 = {
  chr1: 248956422,
  chr2: 242193529,
  chr3: 198295559,
  chr4: 190214555,
  chr5: 181538259,
  chr6: 170805979,
  chr7: 159345973,
  chr8: 145138636,
  chr9: 138394717,
  chr10: 133797422,
  chr11: 135086622,
  chr12: 133275309,
  chr13: 114364328,
  chr14: 107043718,
  chr15: 101991189,
  chr16: 90338345,
  chr17: 83257441,
  chr18: 80373285,
  chr19: 58617616,
  chr20: 64444167,
  chr21: 46709983,
  chr22: 50818468,
  chrX: 156040895,
  chrY: 57227415
};
const CHROM_SIZE_HG19 = {
  chr1: 249250621,
  chr2: 243199373,
  chr3: 198022430,
  chr4: 191154276,
  chr5: 180915260,
  chr6: 171115067,
  chr7: 159138663,
  chr8: 146364022,
  chr9: 141213431,
  chr10: 135534747,
  chr11: 135006516,
  chr12: 133851895,
  chr13: 115169878,
  chr14: 107349540,
  chr15: 102531392,
  chr16: 90354753,
  chr17: 81195210,
  chr18: 78077248,
  chr19: 59128983,
  chr20: 63025520,
  chr21: 48129895,
  chr22: 51304566,
  chrX: 155270560,
  chrY: 59373566,
  chrM: 16571
};
const CHROM_SIZE_HG18 = {
  chr1: 247249719,
  chr2: 242951149,
  chr3: 199501827,
  chr4: 191273063,
  chr5: 180857866,
  chr6: 170899992,
  chr7: 158821424,
  chr8: 146274826,
  chr9: 140273252,
  chr10: 135374737,
  chr11: 134452384,
  chr12: 132349534,
  chr13: 114142980,
  chr14: 106368585,
  chr15: 100338915,
  chr16: 88827254,
  chr17: 78774742,
  chr18: 76117153,
  chr19: 63811651,
  chr20: 62435964,
  chr21: 46944323,
  chr22: 49691432,
  chrX: 154913754,
  chrY: 57772954,
  chrM: 16571
};
const CHROM_SIZE_HG17 = {
  chr1: 245522847,
  chr2: 243018229,
  chr3: 199505740,
  chr4: 191411218,
  chr5: 180857866,
  chr6: 170975699,
  chr7: 158628139,
  chr8: 146274826,
  chr9: 138429268,
  chr10: 135413628,
  chr11: 134452384,
  chr12: 132449811,
  chr13: 114142980,
  chr14: 106368585,
  chr15: 100338915,
  chr16: 88827254,
  chr17: 78774742,
  chr18: 76117153,
  chr19: 63811651,
  chr20: 62435964,
  chr21: 46944323,
  chr22: 49554710,
  chrX: 154824264,
  chrY: 57701691,
  chrM: 16571
};
const CHROM_SIZE_HG16 = {
  chr1: 246127941,
  chr2: 243615958,
  chr3: 199344050,
  chr4: 191731959,
  chr5: 181034922,
  chr6: 170914576,
  chr7: 158545518,
  chr8: 146308819,
  chr9: 136372045,
  chr10: 135037215,
  chr11: 134482954,
  chr12: 132078379,
  chr13: 113042980,
  chr14: 105311216,
  chr15: 100256656,
  chr16: 90041932,
  chr17: 81860266,
  chr18: 76115139,
  chr19: 63811651,
  chr20: 63741868,
  chr21: 46976097,
  chr22: 49396972,
  chrX: 153692391,
  chrY: 50286555,
  chrM: 16571
};
const CHROM_SIZE_MM10 = {
  chr1: 195471971,
  chr2: 182113224,
  chr3: 160039680,
  chr4: 156508116,
  chr5: 151834684,
  chr6: 149736546,
  chr7: 145441459,
  chr8: 129401213,
  chr9: 124595110,
  chr10: 130694993,
  chr11: 122082543,
  chr12: 120129022,
  chr13: 120421639,
  chr14: 124902244,
  chr15: 104043685,
  chr16: 98207768,
  chr17: 94987271,
  chr18: 90702639,
  chr19: 61431566,
  chrX: 171031299,
  chrY: 91744698,
  chrM: 16299
};
const CHROM_SIZE_MM9 = {
  chr1: 197195432,
  chr2: 181748087,
  chr3: 159599783,
  chr4: 155630120,
  chr5: 152537259,
  chr6: 149517037,
  chr7: 152524553,
  chr8: 131738871,
  chr9: 124076172,
  chr10: 129993255,
  chr11: 121843856,
  chr12: 121257530,
  chr13: 120284312,
  chr14: 125194864,
  chr15: 103494974,
  chr16: 98319150,
  chr17: 95272651,
  chr18: 90772031,
  chr19: 61342430,
  chrX: 166650296,
  chrY: 15902555,
  chrM: 16299
};
function getRelativeGenomicPosition(absPos, assembly) {
  const chrAndRange = Object.entries(GET_CHROM_SIZES(assembly).interval).find((d) => {
    const [, [start, end]] = d;
    return start <= absPos && absPos < end;
  });
  if (!chrAndRange) {
    return `${absPos}`;
  }
  const pos = format$1(",")(absPos - chrAndRange[1][0]);
  return `${chrAndRange[0]}:${pos}`;
}
function GET_CHROM_SIZES(assembly) {
  if (assembly && assembly in CRHOM_SIZES) {
    return CRHOM_SIZES[assembly];
  } else {
    return CRHOM_SIZES.hg38;
  }
}
const basePath = (assembly) => `https://s3.amazonaws.com/gosling-lang.org/data/${assembly}.chrom.sizes`;
const CRHOM_SIZES = Object.freeze({
  hg38: {
    size: CHROM_SIZE_HG38,
    interval: getChromInterval(CHROM_SIZE_HG38),
    total: getChromTotalSize(CHROM_SIZE_HG38),
    path: basePath("hg38")
  },
  hg19: {
    size: CHROM_SIZE_HG19,
    interval: getChromInterval(CHROM_SIZE_HG19),
    total: getChromTotalSize(CHROM_SIZE_HG19),
    path: basePath("hg19")
  },
  hg18: {
    size: CHROM_SIZE_HG18,
    interval: getChromInterval(CHROM_SIZE_HG18),
    total: getChromTotalSize(CHROM_SIZE_HG18),
    path: basePath("hg18")
  },
  hg17: {
    size: CHROM_SIZE_HG17,
    interval: getChromInterval(CHROM_SIZE_HG17),
    total: getChromTotalSize(CHROM_SIZE_HG17),
    path: basePath("hg17")
  },
  hg16: {
    size: CHROM_SIZE_HG16,
    interval: getChromInterval(CHROM_SIZE_HG16),
    total: getChromTotalSize(CHROM_SIZE_HG16),
    path: basePath("hg16")
  },
  mm10: {
    size: CHROM_SIZE_MM10,
    interval: getChromInterval(CHROM_SIZE_MM10),
    total: getChromTotalSize(CHROM_SIZE_MM10),
    path: basePath("mm10")
  },
  mm9: {
    size: CHROM_SIZE_MM9,
    interval: getChromInterval(CHROM_SIZE_MM9),
    total: getChromTotalSize(CHROM_SIZE_MM9),
    path: basePath("mm9")
  },
  unknown: {
    size: { chr: Number.MAX_VALUE },
    interval: { chr: [0, Number.MAX_VALUE] },
    total: Number.MAX_VALUE,
    path: basePath("hg38")
  }
});
function getChromInterval(chromSize) {
  const interval2 = {};
  Object.keys(chromSize).reduce((sum2, k) => {
    interval2[k] = [sum2, sum2 + chromSize[k]];
    return sum2 + chromSize[k];
  }, 0);
  return interval2;
}
function getChromTotalSize(chromSize) {
  return Object.values(chromSize).reduce((sum2, current) => sum2 + current, 0);
}
const TICK_WIDTH = 200;
const TICK_HEIGHT = 6;
const TICK_TEXT_SEPARATION = 2;
const TICK_COLOR = 7829367;
function AxisTrack(HGC, ...args) {
  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }
  const { absToChr, colorToHex: colorToHex2, pixiTextToSvg, showMousePosition, svgLine } = HGC.utils;
  class AxisTrackClass extends HGC.tracks.PixiTrack {
    constructor(params) {
      super(...params);
      const [context2, options] = params;
      const { dataConfig, animate, chromInfoPath, isShowGlobalMousePosition } = context2;
      this.searchField = null;
      this.chromInfo = null;
      this.dataConfig = dataConfig;
      this.allTexts = [];
      this.pTicksCircular = new HGC.libraries.PIXI.Graphics();
      this.pTicks = new HGC.libraries.PIXI.Graphics();
      this.pMain.addChild(this.pTicks);
      this.pMain.addChild(this.pTicksCircular);
      this.gTicks = {};
      this.tickTexts = {};
      this.options = options;
      this.isShowGlobalMousePosition = isShowGlobalMousePosition;
      this.textFontSize = 12;
      this.textFontFamily = "sans-serif";
      this.textFontWeight = "normal";
      this.textFontColor = "#808080";
      this.textStrokeColor = "#ffffff";
      this.pixiTextConfig = getTextStyle({
        size: +this.options.fontSize || this.textFontSize,
        fontFamily: this.options.fontFamily || this.textFontFamily,
        fontWeight: this.options.fontWeight || this.textFontWeight,
        color: this.options.color || this.textFontColor,
        stroke: this.options.stroke || this.textStrokeColor,
        strokeThickness: 2
      });
      this.stroke = colorToHex2(this.pixiTextConfig.stroke);
      this.tickWidth = TICK_WIDTH;
      this.tickHeight = TICK_HEIGHT;
      this.tickTextSeparation = TICK_TEXT_SEPARATION;
      this.tickColor = this.options.tickColor ? colorToHex2(this.options.tickColor) : TICK_COLOR;
      this.animate = animate;
      this.pubSubs = [];
      if (this.options.showMousePosition && !this.hideMousePosition) {
        this.hideMousePosition = showMousePosition(this, this.is2d, this.isShowGlobalMousePosition());
      }
      let chromSizesPath = chromInfoPath;
      if (!chromSizesPath) {
        chromSizesPath = `${dataConfig.server}/chrom-sizes/?id=${dataConfig.tilesetUid}`;
      }
      const assembly = this.options.assembly;
      const chrPositions = {};
      const chromLengths = { ...GET_CHROM_SIZES(assembly).size };
      const cumPositions = [];
      Object.keys(GET_CHROM_SIZES(assembly).size).forEach((k) => {
        chrPositions[k] = { chr: k, pos: GET_CHROM_SIZES(assembly).size[k] };
      });
      Object.keys(GET_CHROM_SIZES(assembly).interval).forEach((k) => {
        cumPositions.push({ chr: k, pos: GET_CHROM_SIZES(assembly).interval[k][0] });
      });
      this.chromInfo = { chrPositions, chromLengths, cumPositions };
      this.rerender(this.options, true);
      this.draw();
      this.animate();
    }
    initBoundsTicks() {
      if (this.pTicks) {
        this.pMain.removeChild(this.pTicks);
        this.pTicks = null;
      }
      if (!this.gBoundTicks) {
        this.gBoundTicks = new HGC.libraries.PIXI.Graphics();
        this.leftBoundTick = new HGC.libraries.PIXI.Text("", this.pixiTextConfig);
        this.rightBoundTick = new HGC.libraries.PIXI.Text("", this.pixiTextConfig);
        this.gBoundTicks.addChild(this.leftBoundTick);
        this.gBoundTicks.addChild(this.rightBoundTick);
        this.pMain.addChild(this.gBoundTicks);
      }
      this.texts = [];
    }
    initChromLabels() {
      if (!this.chromInfo)
        return;
      if (this.gBoundTicks) {
        this.pMain.removeChild(this.gBoundTicks);
        this.gBoundTicks = null;
      }
      if (!this.pTicks) {
        this.pTicks = new HGC.libraries.PIXI.Graphics();
        this.pMain.addChild(this.pTicks);
      }
      this.texts = [];
      this.pTicks.removeChildren();
      this.chromInfo.cumPositions.forEach((info) => {
        const chromName = info.chr;
        this.gTicks[chromName] = new HGC.libraries.PIXI.Graphics();
        if (!this.tickTexts[chromName])
          this.tickTexts[chromName] = [];
        const text = new HGC.libraries.PIXI.Text(chromName, this.pixiTextConfig);
        text.hashValue = Math.random();
        this.pTicks.addChild(text);
        this.pTicks.addChild(this.gTicks[chromName]);
        this.texts.push(text);
      });
    }
    rerender(options, force) {
      const strOptions = JSON.stringify(options);
      if (!force && strOptions === this.prevOptions)
        return;
      this.prevOptions = strOptions;
      this.options = options;
      this.pixiTextConfig.fontSize = +this.options.fontSize ? `${+this.options.fontSize}px` : this.pixiTextConfig.fontSize;
      this.pixiTextConfig.fill = this.options.color || this.pixiTextConfig.fill;
      this.pixiTextConfig.stroke = this.options.stroke || this.pixiTextConfig.stroke;
      this.stroke = colorToHex2(this.pixiTextConfig.stroke);
      this.tickColor = this.options.tickColor ? colorToHex2(this.options.tickColor) : TICK_COLOR;
      if (this.options.tickPositions === "ends" && this.options.layout !== "circular") {
        this.initBoundsTicks();
      } else {
        this.initChromLabels();
      }
      super.rerender(options, force);
      if (this.options.showMousePosition && !this.hideMousePosition) {
        this.hideMousePosition = showMousePosition(this, this.is2d, this.isShowGlobalMousePosition());
      }
      if (!this.options.showMousePosition && this.hideMousePosition) {
        this.hideMousePosition();
        this.hideMousePosition = void 0;
      }
    }
    formatTick(pos) {
      if (isNaN(pos)) {
        return "null";
      }
      const domain = this._xScale.domain();
      const viewWidth = domain[1] - domain[0];
      const p = gosling_es_precisionPrefix(pos, viewWidth);
      const fPlain = format$1(",");
      const fPrecision = gosling_es_formatPrefix(`,.${p}`, viewWidth);
      let f2 = fPlain;
      if (this.options.tickFormat === "si") {
        f2 = fPrecision;
      } else if (this.options.tickFormat === "plain") {
        f2 = fPlain;
      } else if (this.options.tickPositions === "ends") {
        f2 = fPrecision;
      }
      return f2(pos);
    }
    drawBoundsTicks(x1, x2) {
      const graphics = this.gBoundTicks;
      graphics.clear();
      graphics.lineStyle(1, 0);
      const lineYStart = this.options.reverseOrientation ? 0 : this.dimensions[1];
      const lineYEnd = this.options.reverseOrientation ? this.tickHeight : this.dimensions[1] - this.tickHeight;
      graphics.moveTo(1, lineYStart);
      graphics.lineTo(1, lineYEnd);
      graphics.moveTo(this.dimensions[0] - 1, lineYStart);
      graphics.lineTo(this.dimensions[0] - 1, lineYEnd);
      this.leftBoundTick.x = 0;
      this.leftBoundTick.y = this.options.reverseOrientation ? lineYEnd + this.tickTextSeparation : lineYEnd - this.tickTextSeparation;
      this.leftBoundTick.text = this.options.assembly === "unknown" ? `${this.formatTick(x1[1])}` : `${x1[0]}: ${this.formatTick(x1[1])}`;
      this.leftBoundTick.anchor.y = this.options.reverseOrientation ? 0 : 1;
      this.rightBoundTick.x = this.dimensions[0];
      this.rightBoundTick.text = this.options.assembly === "unknown" ? `${this.formatTick(x2[1])}` : `${x2[0]}: ${this.formatTick(x2[1])}`;
      this.rightBoundTick.y = this.options.reverseOrientation ? lineYEnd + this.tickTextSeparation : lineYEnd - this.tickTextSeparation;
      this.rightBoundTick.anchor.y = this.options.reverseOrientation ? 0 : 1;
      this.rightBoundTick.anchor.x = 1;
      if (this.flipText) {
        this.leftBoundTick.scale.x = -1;
        this.leftBoundTick.anchor.x = 1;
        this.rightBoundTick.scale.x = -1;
        this.rightBoundTick.anchor.x = 0;
      }
      this.leftBoundTick.tickLine = [1, this.dimensions[1], 1, this.dimensions[1] - this.tickHeight];
      this.rightBoundTick.tickLine = [
        this.dimensions[0] - 1,
        this.dimensions[1],
        this.dimensions[0] - 1,
        this.dimensions[1] - this.tickHeight
      ];
      this.tickTexts = {};
      this.tickTexts.all = [this.leftBoundTick, this.rightBoundTick];
    }
    drawTicks(cumPos) {
      const graphics = this.gTicks[cumPos.chr];
      graphics.visible = true;
      graphics.clear();
      const chromLen = +this.chromInfo.chromLengths[cumPos.chr];
      const vpLeft = Math.max(this._xScale(cumPos.pos), 0);
      const vpRight = Math.min(this._xScale(cumPos.pos + chromLen), this.dimensions[0]);
      const numTicks = (vpRight - vpLeft) / this.tickWidth;
      const xScale = linear_linear().domain([
        Math.max(1, this._xScale.invert(0) - cumPos.pos),
        Math.min(chromLen, this._xScale.invert(this.dimensions[0]) - cumPos.pos)
      ]).range([vpLeft, vpRight]);
      const ticks = xScale.ticks(numTicks).filter((tick) => Number.isInteger(tick));
      const tickTexts = this.tickTexts[cumPos.chr];
      const tickHeight = this.tickHeight;
      const xPadding = 0;
      let yPadding = tickHeight + this.tickTextSeparation;
      if (this.options.reverseOrientation) {
        yPadding = this.dimensions[1] - yPadding;
      }
      while (tickTexts.length < ticks.length) {
        const newText = new HGC.libraries.PIXI.Text("", this.pixiTextConfig);
        tickTexts.push(newText);
        this.gTicks[cumPos.chr].addChild(newText);
      }
      while (tickTexts.length > ticks.length) {
        const text = tickTexts.pop();
        this.gTicks[cumPos.chr].removeChild(text);
      }
      let i = 0;
      while (i < ticks.length) {
        tickTexts[i].visible = true;
        tickTexts[i].anchor.x = 0.5;
        tickTexts[i].anchor.y = this.options.layout === "circular" ? 0 : this.options.reverseOrientation ? 0 : 1;
        if (this.flipText)
          tickTexts[i].scale.x = -1;
        const chrText = this.options.assembly === "unknown" ? "" : `${cumPos.chr}: `;
        tickTexts[i].text = ticks[i] === 0 ? `${chrText}1` : `${chrText}${this.formatTick(ticks[i])}`;
        const x = this._xScale(cumPos.pos + ticks[i]);
        if (this.options.layout === "circular") {
          const rope = this.addCurvedText(tickTexts[i], x + xPadding);
          this.pTicksCircular.addChild(rope);
        } else {
          tickTexts[i].x = x + xPadding;
          tickTexts[i].y = this.dimensions[1] - yPadding;
          tickTexts[i].tickLine = [x - 1, this.dimensions[1], x - 1, this.dimensions[1] - tickHeight - 1];
          const lineYStart = this.options.reverseOrientation ? 0 : this.dimensions[1];
          const lineYEnd = this.options.reverseOrientation ? tickHeight : this.dimensions[1] - tickHeight;
          graphics.lineStyle(1, this.tickColor);
          graphics.moveTo(x, lineYStart);
          graphics.lineTo(x, lineYEnd);
        }
        i += 1;
      }
      if (this.options.layout === "circular")
        i = 0;
      while (i < tickTexts.length) {
        tickTexts[i].visible = false;
        i += 1;
      }
      return ticks.length;
    }
    addCurvedText(textObj, cx) {
      const [width, height] = this.dimensions;
      const { startAngle, endAngle } = this.options;
      const factor = Math.min(width, height) / Math.min(this.options.width, this.options.height);
      const innerRadius = this.options.innerRadius * factor;
      const outerRadius = this.options.outerRadius * factor;
      const r = (outerRadius + innerRadius) / 2;
      const centerPos = cartesianToPolar(cx, width, r, width / 2, height / 2, startAngle, endAngle);
      textObj.x = centerPos.x;
      textObj.y = centerPos.y;
      textObj.resolution = 4;
      const txtStyle = new HGC.libraries.PIXI.TextStyle(this.pixiTextConfig);
      const metric = HGC.libraries.PIXI.TextMetrics.measureText(textObj.text, txtStyle);
      const tw = metric.width / (2 * r * Math.PI) * width * 360 / (endAngle - startAngle);
      let [minX, maxX] = [cx - tw / 2, cx + tw / 2];
      if (minX < 0) {
        const gap = -minX;
        minX = 0;
        maxX += gap;
      } else if (maxX > width) {
        const gap = maxX - width;
        maxX = width;
        minX -= gap;
      }
      const ropePoints = [];
      const baseR = innerRadius + metric.height / 2 + 3;
      for (let i = maxX; i >= minX; i -= tw / 10) {
        const p = cartesianToPolar(i, width, baseR, width / 2, height / 2, startAngle, endAngle);
        ropePoints.push(new HGC.libraries.PIXI.Point(p.x, p.y));
      }
      textObj.updateText();
      const rope = new HGC.libraries.PIXI.SimpleRope(textObj.texture, ropePoints);
      return rope;
    }
    draw() {
      this.allTexts = [];
      if (!this.texts)
        return;
      const x1 = absToChr(this._xScale.domain()[0], this.chromInfo);
      const x2 = absToChr(this._xScale.domain()[1], this.chromInfo);
      if (!x1 || !x2) {
        console.warn("Empty chromInfo:", this.dataConfig, this.chromInfo);
        return;
      }
      if (this.options.tickPositions === "ends" && this.options.layout !== "circular") {
        if (!this.gBoundTicks)
          return;
        this.gBoundTicks.visible = true;
        this.drawBoundsTicks(x1, x2);
        return;
      }
      if (!this.pTicks) {
        return;
      }
      const circular = this.options.layout === "circular";
      for (let i = 0; i < this.texts.length; i++) {
        this.texts[i].visible = false;
        this.gTicks[this.chromInfo.cumPositions[i].chr].visible = false;
      }
      let yPadding = this.tickHeight + this.tickTextSeparation;
      if (this.options.reverseOrientation) {
        yPadding = this.dimensions[1] - yPadding;
      }
      Object.keys(this.chromInfo.chrPositions).forEach((chrom) => {
        if (this.tickTexts[chrom]) {
          this.tickTexts[chrom].forEach((tick) => {
            tick.visible = false;
          });
        }
      });
      this.pTicksCircular.removeChildren();
      for (let i = x1[3]; i <= x2[3]; i++) {
        const xCumPos = this.chromInfo.cumPositions[i];
        const midX = xCumPos.pos + this.chromInfo.chromLengths[xCumPos.chr] / 2;
        const viewportMidX = this._xScale(midX);
        const chrText = this.texts[i];
        chrText.anchor.x = 0.5;
        chrText.anchor.y = circular ? 0.5 : this.options.reverseOrientation ? 0 : 1;
        let rope;
        if (circular) {
          rope = this.addCurvedText(chrText, viewportMidX);
          this.pTicksCircular.addChild(rope);
        } else {
          chrText.x = viewportMidX;
          chrText.y = this.dimensions[1] - yPadding;
        }
        chrText.updateTransform();
        if (this.flipText)
          chrText.scale.x = -1;
        const numTicksDrawn = this.drawTicks(xCumPos);
        if (!circular) {
          chrText.visible = numTicksDrawn <= 0;
        } else {
          if (numTicksDrawn > 0) {
            this.pTicksCircular.removeChild(rope);
          }
        }
        this.allTexts.push({
          importance: chrText.hashValue,
          text: chrText,
          rope
        });
      }
      this.hideOverlaps(this.allTexts);
    }
    hideOverlaps(allTexts) {
      const tree = new (rbush_min_default())();
      allTexts.sort((a, b) => b.importance - a.importance).forEach(({ text, rope }) => {
        text.updateTransform();
        const b = text.getBounds();
        const m = 5;
        const boxWithMargin = {
          minX: b.x - m,
          minY: b.y - m,
          maxX: b.x + b.width + m * 2,
          maxY: b.y + b.height + m * 2
        };
        if (!tree.collides(boxWithMargin)) {
          tree.insert(boxWithMargin);
        } else {
          text.visible = false;
          if (this.options.layout === "circular" && rope) {
            this.pTicksCircular.removeChild(rope);
          }
        }
      });
    }
    setPosition(newPosition) {
      super.setPosition(newPosition);
      [this.pMain.position.x, this.pMain.position.y] = this.position;
    }
    zoomed(newXScale, newYScale) {
      const domainValues = [...newXScale.domain(), ...newYScale.domain()];
      if (domainValues.filter((d) => isNaN(d)).length !== 0) {
        return;
      }
      this.xScale(newXScale);
      this.yScale(newYScale);
      this.draw();
    }
    exportSVG() {
      let track = null;
      let base = null;
      if (super.exportSVG) {
        [base, track] = super.exportSVG();
      } else {
        base = document.createElement("g");
        track = base;
      }
      base.setAttribute("class", "chromosome-labels");
      const output = document.createElement("g");
      track.appendChild(output);
      output.setAttribute("transform", `translate(${this.position[0]},${this.position[1]})`);
      this.allTexts.filter((text) => text.text.visible).forEach((text) => {
        const g = pixiTextToSvg(text.text);
        output.appendChild(g);
      });
      Object.values(this.tickTexts).forEach((texts) => {
        texts.filter((x) => x.visible).forEach((text) => {
          let g = pixiTextToSvg(text);
          output.appendChild(g);
          g = svgLine(text.x, this.options.reverseOrientation ? 0 : this.dimensions[1], text.x, this.options.reverseOrientation ? this.tickHeight : this.dimensions[1] - this.tickHeight, 1, this.tickColor);
          const line = document.createElement("line");
          line.setAttribute("x1", text.tickLine[0]);
          line.setAttribute("y1", text.tickLine[1]);
          line.setAttribute("x2", text.tickLine[2]);
          line.setAttribute("y2", text.tickLine[3]);
          line.setAttribute("style", "stroke: grey");
          output.appendChild(g);
          output.appendChild(line);
        });
      });
      return [base, track];
    }
  }
  return new AxisTrackClass(args);
}
const icon$1 = '<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 5640 5420" preserveAspectRatio="xMidYMid meet"> <g id="layer101" fill="#000000" stroke="none"> <path d="M0 2710 l0 -2710 2820 0 2820 0 0 2710 0 2710 -2820 0 -2820 0 0 -2710z"/> </g> <g id="layer102" fill="#750075" stroke="none"> <path d="M200 4480 l0 -740 630 0 630 0 0 740 0 740 -630 0 -630 0 0 -740z"/> <path d="M1660 4420 l0 -800 570 0 570 0 0 800 0 800 -570 0 -570 0 0 -800z"/> <path d="M3000 3450 l0 -1770 570 0 570 0 0 1770 0 1770 -570 0 -570 0 0 -1770z"/> <path d="M4340 2710 l0 -2510 560 0 560 0 0 2510 0 2510 -560 0 -560 0 0 -2510z"/> <path d="M200 1870 l0 -1670 630 0 630 0 0 1670 0 1670 -630 0 -630 0 0 -1670z"/> <path d="M1660 1810 l0 -1610 570 0 570 0 0 1610 0 1610 -570 0 -570 0 0 -1610z"/> <path d="M3000 840 l0 -640 570 0 570 0 0 640 0 640 -570 0 -570 0 0 -640z"/> </g> <g id="layer103" fill="#ffff04" stroke="none"> <path d="M200 4480 l0 -740 630 0 630 0 0 740 0 740 -630 0 -630 0 0 -740z"/> <path d="M1660 4420 l0 -800 570 0 570 0 0 800 0 800 -570 0 -570 0 0 -800z"/> <path d="M3000 3450 l0 -1770 570 0 570 0 0 1770 0 1770 -570 0 -570 0 0 -1770z"/> </g> </svg>';
AxisTrack.config = {
  type: "axis-track",
  datatype: ["multivec", "epilogos"],
  local: false,
  orientation: "1d-horizontal",
  thumbnail: new DOMParser().parseFromString(icon$1, "text/xml").documentElement,
  availableOptions: [
    "innerRadius",
    "outerRadius",
    "startAngle",
    "endAngle",
    "width",
    "height",
    "layout",
    "labelPosition",
    "labelColor",
    "labelTextOpacity",
    "labelBackgroundOpacity",
    "trackBorderWidth",
    "trackBorderColor",
    "trackType",
    "tickPositions",
    "scaledHeight",
    "backgroundColor"
  ],
  defaultOptions: {
    innerRadius: 340,
    outerRadius: 310,
    startAngle: 0,
    endAngle: 360,
    width: 700,
    height: 700,
    layout: "linear",
    labelPosition: "none",
    labelColor: "black",
    labelTextOpacity: 0.4,
    trackBorderWidth: 0,
    trackBorderColor: "black",
    tickPositions: ["even", "ends"][0],
    backgroundColor: "transparent"
  }
};
function BrushTrack(HGC, ...args) {
  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }
  class BrushTrackClass extends HGC.tracks.SVGTrack {
    constructor(params) {
      super(...params);
      var _a, _b;
      const [context2, options] = params;
      const { registerViewportChanged, removeViewportChanged, setDomainsCallback } = context2;
      this.uid = v1();
      this.options = options;
      this.hasFromView = !context2.projectionXDomain;
      this.removeViewportChanged = removeViewportChanged;
      this.setDomainsCallback = setDomainsCallback;
      this.viewportXDomain = this.hasFromView ? null : context2.projectionXDomain;
      this.viewportYDomain = this.hasFromView ? null : [0, 0];
      this.prevExtent = [0, 0];
      this.RR = 0.02;
      const extent = [0, Math.PI * 1.7];
      this.circularBrushData = this.getBrushData(extent);
      this.brush = arc().innerRadius((_a = this.options.innerRadius) != null ? _a : 100).outerRadius((_b = this.options.outerRadius) != null ? _b : 200);
      this.gBrush = this.gMain.append("g").attr("id", `brush-${this.uid}`).selectAll(".brush").data(this.circularBrushData).enter().append("path").attr("class", "brush").attr("d", this.brush).attr("fill", this.options.projectionFillColor).attr("stroke", this.options.projectionStrokeColor).attr("fill-opacity", (d) => d.type === "brush" ? this.options.projectionFillOpacity : 0).attr("stroke-opacity", (d) => d.type === "brush" ? this.options.projectionStrokeOpacity : 0).attr("stroke-width", this.options.strokeWidth).style("pointer-events", "all").style("cursor", (d) => d.cursor).call(this.dragged());
      registerViewportChanged(this.uid, this.viewportChanged.bind(this));
      this.draw();
    }
    getBrushData(extent) {
      return [
        {
          type: "brush",
          startAngle: extent[0],
          endAngle: extent[1],
          cursor: "grab"
        },
        {
          type: "start",
          startAngle: extent[0],
          endAngle: extent[0] + this.RR,
          cursor: "move"
        },
        {
          type: "end",
          startAngle: extent[1] - this.RR,
          endAngle: extent[1],
          cursor: "move"
        }
      ];
    }
    cropExtent(extent) {
      let [s, e] = extent;
      let round = 0;
      while (s > Math.PI * 2 || e > Math.PI * 2 || s < 0 || e < 0) {
        if (round++ > 10) {
          break;
        }
        if (s > Math.PI * 2 || e > Math.PI * 2) {
          s -= Math.PI * 2;
          e -= Math.PI * 2;
        } else if (s < 0 || e < 0) {
          s += Math.PI * 2;
          e += Math.PI * 2;
        }
      }
      return [s, e].sort((a, b) => a - b);
    }
    updateBrush(extent) {
      let [s, e] = extent;
      if (s <= RADIAN_GAP && e <= RADIAN_GAP || s >= Math.PI * 2 - RADIAN_GAP && e >= Math.PI * 2 - RADIAN_GAP) {
        this.gBrush.attr("visibility", "hidden");
        return;
      }
      if (s < RADIAN_GAP) {
        s = RADIAN_GAP;
      }
      if (s > Math.PI * 2 - RADIAN_GAP) {
        s = Math.PI * 2 - RADIAN_GAP;
      }
      if (e < RADIAN_GAP) {
        e = RADIAN_GAP;
      }
      if (e > Math.PI * 2 - RADIAN_GAP) {
        e = Math.PI * 2 - RADIAN_GAP;
      }
      this.circularBrushData = this.getBrushData(extent);
      this.gBrush.data(this.circularBrushData).attr("d", this.brush).attr("visibility", "visible");
    }
    dragged() {
      const start = () => {
        this.startEvent = HGC.libraries.d3Selection.event.sourceEvent;
        this.prevExtent = [this.circularBrushData[0].startAngle, this.circularBrushData[0].endAngle];
      };
      const drag = (d) => {
        const [x, y] = this.position;
        const [w, h] = this.dimensions;
        const endEvent = HGC.libraries.d3Selection.event.sourceEvent;
        const startX = this.startEvent.layerX - x;
        const startY = this.startEvent.layerY - y;
        const endX = endEvent.layerX - x;
        const endY = endEvent.layerY - y;
        const radDiff = Math.atan2(startX - w / 2, startY - h / 2) - Math.atan2(endX - w / 2, endY - h / 2);
        let [s, e] = this.prevExtent;
        if (d.type === "brush") {
          s = s + radDiff;
          e = e + radDiff;
          if (s < RADIAN_GAP || Math.PI * 2 - RADIAN_GAP < e) {
            const sto = RADIAN_GAP - s;
            const eto = e - (Math.PI * 2 - RADIAN_GAP);
            if (sto > eto) {
              e += sto;
              s += sto;
            } else {
              s -= eto;
              e -= eto;
            }
          }
        } else if (d.type === "start") {
          s = s + radDiff;
        } else if (d.type === "end") {
          e = e + radDiff;
        }
        [s, e] = this.cropExtent([s, e]);
        if (!this._xScale || !this._yScale) {
          return;
        }
        const scale = (this.options.endAngle - this.options.startAngle) / 360;
        const offsetedS = s - this.options.startAngle / 360 * Math.PI * 2;
        const offsetedE = e - this.options.startAngle / 360 * Math.PI * 2;
        const xDomain = [
          this._xScale.invert(w - w * offsetedE / (Math.PI * 2 * scale)),
          this._xScale.invert(w - w * offsetedS / (Math.PI * 2 * scale))
        ];
        const yDomain = this.viewportYDomain;
        if (!this.hasFromView) {
          this.viewportXDomain = xDomain;
        }
        this.setDomainsCallback(xDomain, yDomain);
        this.updateBrush([s, e]);
      };
      return HGC.libraries.d3Drag.drag().on("start", start).on("drag", drag);
    }
    draw() {
      if (!this._xScale || !this.yScale) {
        return;
      }
      if (!this.viewportXDomain || !this.viewportYDomain) {
        return;
      }
      const x0 = this._xScale(this.viewportXDomain[0]);
      const x1 = this._xScale(this.viewportXDomain[1]);
      const [w] = this.dimensions;
      let e = valueToRadian(x0, w, this.options.startAngle, this.options.endAngle) + Math.PI / 2;
      let s = valueToRadian(x1, w, this.options.startAngle, this.options.endAngle) + Math.PI / 2;
      [s, e] = this.cropExtent([s, e]);
      this.updateBrush([s, e]);
    }
    viewportChanged(viewportXScale, viewportYScale) {
      const viewportXDomain = viewportXScale.domain();
      const viewportYDomain = viewportYScale.domain();
      this.viewportXDomain = viewportXDomain;
      this.viewportYDomain = viewportYDomain;
      this.draw();
    }
    remove() {
      this.removeViewportChanged(this.uid);
      super.remove();
    }
    rerender() {
    }
    zoomed(newXScale, newYScale) {
      this.xScale(newXScale);
      this.yScale(newYScale);
      this.draw();
    }
    setPosition(newPosition) {
      super.setPosition(newPosition);
      this.draw();
    }
    setDimensions(newDimensions) {
      super.setDimensions(newDimensions);
      this.gBrush.attr("transform", `translate(${newDimensions[0] / 2},${newDimensions[1] / 2})`);
      this.draw();
    }
  }
  return new BrushTrackClass(args);
}
const gosling_es_icon = '<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" viewBox="0 0 5640 5420" preserveAspectRatio="xMidYMid meet"> <g id="layer101" fill="#000000" stroke="none"> <path d="M0 2710 l0 -2710 2820 0 2820 0 0 2710 0 2710 -2820 0 -2820 0 0 -2710z"/> </g> <g id="layer102" fill="#750075" stroke="none"> <path d="M200 4480 l0 -740 630 0 630 0 0 740 0 740 -630 0 -630 0 0 -740z"/> <path d="M1660 4420 l0 -800 570 0 570 0 0 800 0 800 -570 0 -570 0 0 -800z"/> <path d="M3000 3450 l0 -1770 570 0 570 0 0 1770 0 1770 -570 0 -570 0 0 -1770z"/> <path d="M4340 2710 l0 -2510 560 0 560 0 0 2510 0 2510 -560 0 -560 0 0 -2510z"/> <path d="M200 1870 l0 -1670 630 0 630 0 0 1670 0 1670 -630 0 -630 0 0 -1670z"/> <path d="M1660 1810 l0 -1610 570 0 570 0 0 1610 0 1610 -570 0 -570 0 0 -1610z"/> <path d="M3000 840 l0 -640 570 0 570 0 0 640 0 640 -570 0 -570 0 0 -640z"/> </g> <g id="layer103" fill="#ffff04" stroke="none"> <path d="M200 4480 l0 -740 630 0 630 0 0 740 0 740 -630 0 -630 0 0 -740z"/> <path d="M1660 4420 l0 -800 570 0 570 0 0 800 0 800 -570 0 -570 0 0 -800z"/> <path d="M3000 3450 l0 -1770 570 0 570 0 0 1770 0 1770 -570 0 -570 0 0 -1770z"/> </g> </svg>';
BrushTrack.config = {
  type: "brush-track",
  datatype: ["projection"],
  local: false,
  projection: true,
  orientation: "2d",
  thumbnail: new DOMParser().parseFromString(gosling_es_icon, "text/xml").documentElement,
  availableOptions: [
    "innerRadius",
    "outerRadius",
    "startAngle",
    "endAngle",
    "axisPositionHorizontal",
    "projectionFillColor",
    "projectionStrokeColor",
    "projectionFillOpacity",
    "projectionStrokeOpacity",
    "strokeWidth"
  ],
  defaultOptions: {
    innerRadius: 100,
    outerRadius: 200,
    startAngle: 0,
    endAngle: 360,
    axisPositionHorizontal: "left",
    projectionFillColor: "#777",
    projectionStrokeColor: "#777",
    projectionFillOpacity: 0.3,
    projectionStrokeOpacity: 0.7,
    strokeWidth: 1
  }
};
function filterData(filter2, data2) {
  const { field, not: not3 } = filter2;
  let output = Array.from(data2);
  if (IsOneOfFilter(filter2)) {
    const { oneOf: oneOf2 } = filter2;
    output = output.filter((d) => {
      return not3 ? oneOf2.indexOf(d[field]) === -1 : oneOf2.indexOf(d[field]) !== -1;
    });
  } else if (IsRangeFilter(filter2)) {
    const { inRange } = filter2;
    output = output.filter((d) => {
      return not3 ? !(inRange[0] <= d[field] && d[field] <= inRange[1]) : inRange[0] <= d[field] && d[field] <= inRange[1];
    });
  } else if (IsIncludeFilter(filter2)) {
    const { include } = filter2;
    output = output.filter((d) => {
      return not3 ? `${d[field]}`.includes(include) : !`${d[field]}`.includes(include);
    });
  }
  return output;
}
function concatString(concat2, data2) {
  const { fields, separator, newField } = concat2;
  let output = Array.from(data2);
  output = output.map((d) => {
    const strs = fields.map((f2) => d[f2]);
    d[newField] = strs.join(separator);
    return d;
  });
  return output;
}
function replaceString(_, data2) {
  const { field, replace, newField } = _;
  let output = Array.from(data2);
  output = output.map((d) => {
    d[newField] = d[field];
    replace.forEach((r) => {
      const { from: from2, to } = r;
      d[newField] = d[newField].toString().replaceAll(from2, to);
    });
    return d;
  });
  return output;
}
function calculateData(log, data2) {
  const { field, base, newField } = log;
  let output = Array.from(data2);
  output = output.map((d) => {
    if (+d[field]) {
      if (base === "e") {
        d[newField != null ? newField : field] = Math.log(+d[field]);
      } else {
        d[newField != null ? newField : field] = Math.log(+d[field]) / Math.log(base != null ? base : 10);
      }
    }
    return d;
  });
  return output;
}
function calculateGenomicLength(_, data2) {
  const { startField, endField, newField } = _;
  const output = Array.from(data2);
  output.forEach((d) => {
    const s = d[startField];
    const e = d[endField];
    if (!s || !e) {
      return;
    }
    d[newField] = Math.abs(+e - +s);
  });
  return output;
}
function aggregateCoverage(_, data2, scale) {
  const { startField, endField, newField, groupField } = _;
  const coverage = {};
  const binSize = 1;
  data2.forEach((d) => {
    const curStart = scale(d[startField]);
    const curEnd = scale(d[endField]);
    const group2 = groupField ? d[groupField] : "__NO_GROUP__";
    const adjustedStart = Math.floor(curStart);
    for (let i = adjustedStart; i < curEnd; i += binSize) {
      if (!coverage[group2]) {
        coverage[group2] = {};
      }
      if (!coverage[group2][i]) {
        coverage[group2][i] = 0;
      }
      coverage[group2][i]++;
    }
  });
  const output = Object.entries(coverage).flatMap((group2) => {
    const [groupName, coverageRecords] = group2;
    return Object.entries(coverageRecords).map((entry) => {
      const [key, value] = entry;
      return {
        [startField]: scale.invert(+key),
        [endField]: scale.invert(+key + binSize),
        [newField != null ? newField : "coverage"]: value,
        [groupField != null ? groupField : "group"]: groupName
      };
    });
  });
  return output;
}
function displace(t, data2, scale) {
  const { boundingBox, method, newField } = t;
  const { startField, endField, groupField } = boundingBox;
  let padding = 0;
  if (boundingBox.padding && scale && !boundingBox.isPaddingBP) {
    padding = Math.abs(scale.invert(boundingBox.padding) - scale.invert(0));
  } else if (boundingBox.padding && boundingBox.isPaddingBP) {
    padding = boundingBox.padding;
  }
  const base = Array.from(data2);
  if (base && base.length > 0) {
    if (!Object.keys(base[0]).find((d) => d === startField) || !Object.keys(base[0]).find((d) => d === endField)) {
      return base;
    }
  }
  if (method === "pile") {
    {
      const { maxRows } = t;
      const occupiedSpaceInRows = {};
      const sorted = base.sort((a, b) => a[startField] - b[startField]);
      sorted.forEach((d) => {
        const start = d[startField] - padding;
        const end = d[endField] + padding;
        const group2 = groupField ? d[groupField] : "__NO_GROUP__";
        if (!occupiedSpaceInRows[group2]) {
          occupiedSpaceInRows[group2] = [];
        }
        let rowIndex = occupiedSpaceInRows[group2].findIndex((d2) => {
          if (end < d2.start) {
            d2.start = start;
            return true;
          } else if (d2.end < start) {
            d2.end = end;
            return true;
          }
          return false;
        });
        if (rowIndex === -1) {
          occupiedSpaceInRows[group2].push({ start, end });
          rowIndex = occupiedSpaceInRows[group2].length - 1;
        }
        d[newField] = `${maxRows && maxRows <= rowIndex ? maxRows - 1 : rowIndex}`;
      });
    }
  } else if (method === "spread") {
    const boundingBoxes = [];
    base.sort((a, b) => a[startField] - b[startField]).forEach((d) => {
      let start = d[startField] - padding;
      let end = d[endField] + padding;
      let overlapped = boundingBoxes.filter((box) => box.start === start && end === box.end || box.start < start && start < box.end || box.start < end && end < box.end || start < box.start && box.end < end);
      if (overlapped.length > 0) {
        let trial = 0;
        do {
          overlapped = boundingBoxes.filter((box) => box.start === start && end === box.end || box.start < start && start < box.end || box.start < end && end < box.end || start < box.start && box.end < end);
          if (overlapped.length > 0) {
            if (trial % 2 === 0) {
              start += padding * trial;
              end += padding * trial;
            } else {
              start -= padding * trial;
              end -= padding * trial;
            }
          }
          trial++;
        } while (overlapped.length > 0 && trial < 1e3);
      }
      d[`${newField}Start`] = `${start + padding}`;
      d[`${newField}Etart`] = `${end - padding}`;
      boundingBoxes.push({ start, end });
    });
  }
  return base;
}
function splitExon(split, data2, assembly = "hg38") {
  const { separator, fields, flag } = split;
  let output = Array.from(data2);
  output = output.map((d) => {
    const newRows = [];
    fields.forEach((f2) => {
      const { field, type: type2, newField, chrField } = f2;
      const splitted = d[field].toString().split(separator);
      splitted.forEach((s, i) => {
        let newValue = s;
        if (type2 === "genomic") {
          newValue = GET_CHROM_SIZES(assembly).interval[d[chrField]][0] + +s;
        }
        if (!newRows[i]) {
          newRows[i] = lodash_es_assign(JSON.parse(JSON.stringify(d)), {
            [newField]: newValue,
            [flag.field]: flag.value
          });
        } else {
          newRows[i][newField] = newValue;
        }
      });
    });
    return [d, ...newRows];
  }).reduce((a, b) => a.concat(b), []);
  return output;
}
function parseSubJSON(_, data2) {
  const { field, genomicField, baseGenomicField, genomicLengthField } = _;
  let output = Array.from(data2);
  output = output.map((d) => {
    let newRows = JSON.parse(d[field]);
    newRows = newRows.map((row) => {
      var _a, _b;
      if (row[genomicField] && d[baseGenomicField]) {
        row[`${genomicField}_start`] = +row[genomicField] + +d[baseGenomicField];
        row[`${genomicField}_end`] = +row[genomicField] + +d[baseGenomicField] + +row[genomicLengthField];
      }
      return lodash_es_assign(JSON.parse(JSON.stringify(d)), {
        ...row,
        [`${genomicField}_start`]: row[`${genomicField}_start`],
        [`${genomicField}_end`]: row[`${genomicField}_end`],
        type: (_b = (_a = row.type) != null ? _a : row.variant) != null ? _b : null,
        isParsedRow: "yes"
      });
    });
    return [d, ...newRows];
  }).reduce((a, b) => a.concat(b), []);
  return output;
}
function aggregateData(spec, data2) {
  if (getChannelKeysByAggregateFnc(spec).length === 0) {
    return data2;
  }
  const nChannelKeys = getChannelKeysByType(spec, "nominal");
  if (nChannelKeys.length !== 1) {
    console.warn("Currently, we only support aggregating datasets with single nominal field.");
    return data2;
  }
  const nFieldSpec = spec[nChannelKeys[0]];
  if (!IsChannelDeep(nFieldSpec)) {
    return data2;
  }
  const nField = nFieldSpec.field;
  if (!nField) {
    return data2;
  }
  const qChannelKeys = [...getChannelKeysByType(spec, "quantitative"), ...getChannelKeysByType(spec, "genomic")];
  const aggregated = [];
  const uniqueCategories = Array.from(new Set(data2.map((d) => d[nField])));
  let failed = false;
  uniqueCategories.forEach((c) => {
    const datum = {};
    datum[nField] = c;
    qChannelKeys.forEach((q) => {
      const qFieldSpec = spec[q];
      if (!IsChannelDeep(qFieldSpec)) {
        failed = true;
        return;
      }
      const { field: qField } = qFieldSpec;
      if (!qField || !("aggregate" in qFieldSpec)) {
        failed = true;
        return;
      }
      datum[qField] = qFieldSpec.aggregate === "max" ? Math.max(...data2.filter((d) => d[nField] === c).map((d) => +d[qField])) : Math.min(...data2.filter((d) => d[nField] === c).map((d) => +d[qField]));
    });
    aggregated.push(datum);
  });
  return !failed ? aggregated : data2;
}
function CSVDataFetcher(HGC, ...args) {
  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }
  class CSVDataFetcherClass {
    constructor(params) {
      const [dataConfig] = params;
      this.dataConfig = dataConfig;
      this.tilesetInfoLoading = false;
      this.assembly = this.dataConfig.assembly;
      this.filter = this.dataConfig.filter;
      if (!dataConfig.url) {
        console.error("Please provide the `url` of the data");
        return;
      }
      const chromosomeSizes = GET_CHROM_SIZES(this.assembly).size;
      const chromosomeCumPositions = [];
      const chromosomePositions = {};
      let prevEndPosition = 0;
      Object.keys(GET_CHROM_SIZES(this.assembly).size).forEach((chrStr, i) => {
        const positionInfo = {
          id: i,
          chr: chrStr,
          pos: prevEndPosition
        };
        chromosomeCumPositions.push(positionInfo);
        chromosomePositions[chrStr] = positionInfo;
        prevEndPosition += GET_CHROM_SIZES(this.assembly).size[chrStr];
      });
      this.chromSizes = {
        chrToAbs: (chrom, chromPos) => this.chromSizes.chrPositions[chrom].pos + chromPos,
        cumPositions: chromosomeCumPositions,
        chrPositions: chromosomePositions,
        totalLength: prevEndPosition,
        chromLengths: chromosomeSizes
      };
      if (dataConfig.data) {
        this.values = dataConfig.data;
      } else {
        this.dataPromise = this.fetchCSV();
      }
    }
    fetchCSV() {
      var _a;
      const {
        url,
        chromosomeField,
        genomicFields,
        headerNames,
        chromosomePrefix,
        longToWideId,
        genomicFieldsToConvert
      } = this.dataConfig;
      const separator = (_a = this.dataConfig.separator) != null ? _a : ",";
      return fetch(url).then((response) => {
        return response.ok ? response.text() : Promise.reject(response.status);
      }).then((text) => {
        const textWithHeader = headerNames ? `${headerNames.join(separator)}
${text}` : text;
        return dsv(separator).parse(textWithHeader, (row) => {
          let successfullyGotChrInfo = true;
          if (genomicFieldsToConvert) {
            genomicFieldsToConvert.forEach((d) => {
              const cField = d.chromosomeField;
              d.genomicFields.forEach((g) => {
                try {
                  if (this.assembly !== "unknown") {
                    const chr = chromosomePrefix ? row[cField].replace(chromosomePrefix, "chr") : row[cField].includes("chr") ? row[cField] : `chr${row[cField]}`;
                    row[g] = GET_CHROM_SIZES(this.assembly).interval[chr][0] + +row[g];
                  } else {
                  }
                } catch (e) {
                  successfullyGotChrInfo = false;
                }
              });
            });
          } else {
            genomicFields.forEach((g) => {
              if (!row[chromosomeField]) {
                return;
              }
              try {
                const chr = chromosomePrefix ? row[chromosomeField].replace(chromosomePrefix, "chr") : row[chromosomeField].includes("chr") ? row[chromosomeField] : `chr${row[chromosomeField]}`;
                row[g] = GET_CHROM_SIZES(this.assembly).interval[chr][0] + +row[g];
              } catch (e) {
                successfullyGotChrInfo = false;
              }
            });
          }
          if (!successfullyGotChrInfo) {
            return void 0;
          }
          return row;
        });
      }).then((json) => {
        var _a2;
        if (longToWideId && ((_a2 = json[0]) == null ? void 0 : _a2[longToWideId])) {
          const keys = Object.keys(json[0]);
          const newJson = {};
          json.forEach((d) => {
            if (!newJson[d[longToWideId]]) {
              newJson[d[longToWideId]] = JSON.parse(JSON.stringify(d));
            } else {
              keys.forEach((k) => {
                newJson[d[longToWideId]][`${k}_2`] = d[k];
              });
            }
          });
          this.values = Object.keys(newJson).map((k) => newJson[k]);
        } else {
          this.values = json;
        }
      }).catch((error) => {
        console.error("[Gosling Data Fetcher] Error fetching data", error);
      });
    }
    generateTilesetInfo(callback) {
      this.tilesetInfoLoading = false;
      const TILE_SIZE = 1024;
      const totalLength = this.chromSizes.totalLength;
      const retVal = {
        tile_size: TILE_SIZE,
        max_zoom: Math.ceil(Math.log(totalLength / TILE_SIZE) / Math.log(2)),
        max_width: totalLength,
        min_pos: [0, 0],
        max_pos: [totalLength, totalLength]
      };
      if (callback) {
        callback(retVal);
      }
      return retVal;
    }
    tilesetInfo(callback) {
      if (!this.dataPromise) {
        return;
      }
      this.tilesetInfoLoading = true;
      return this.dataPromise.then(() => this.generateTilesetInfo(callback)).catch((err) => {
        this.tilesetInfoLoading = false;
        console.error("[Gosling Data Fetcher] Error parsing data:", err);
      });
    }
    fetchTilesDebounced(receivedTiles, tileIds) {
      const tiles = {};
      const validTileIds = [];
      const tilePromises = [];
      for (const tileId of tileIds) {
        const parts = tileId.split(".");
        const z = parseInt(parts[0], 10);
        const x = parseInt(parts[1], 10);
        const y = parseInt(parts[2], 10);
        if (Number.isNaN(x) || Number.isNaN(z)) {
          console.warn("[Gosling Data Fetcher] Invalid tile zoom or position:", z, x, y);
          continue;
        }
        validTileIds.push(tileId);
        tilePromises.push(this.tile(z, x, y));
      }
      Promise.all(tilePromises).then((values) => {
        values.forEach((value, i) => {
          const validTileId = validTileIds[i];
          tiles[validTileId] = value;
          tiles[validTileId].tilePositionId = validTileId;
        });
        receivedTiles(tiles);
      });
      return tiles;
    }
    tile(z, x, y) {
      var _a;
      return (_a = this.tilesetInfo()) == null ? void 0 : _a.then((tsInfo) => {
        var _a2, _b;
        const tileWidth = +tsInfo.max_width / 2 ** +z;
        const minX = tsInfo.min_pos[0] + x * tileWidth;
        const maxX = tsInfo.min_pos[0] + (x + 1) * tileWidth;
        let tabularData = this.values.filter((d) => {
          if (this.dataConfig.genomicFields) {
            return this.dataConfig.genomicFields.find((g) => minX < d[g] && d[g] <= maxX);
          } else {
            const allGenomicFields = [];
            this.dataConfig.genomicFieldsToConvert.forEach((d2) => allGenomicFields.push(...d2.genomicFields));
            return allGenomicFields.find((g) => minX < d[g] && d[g] <= maxX);
          }
        });
        (_a2 = this.filter) == null ? void 0 : _a2.forEach((f2) => {
          tabularData = filterData(f2, tabularData);
        });
        const sizeLimit = (_b = this.dataConfig.sampleLength) != null ? _b : 1e3;
        return {
          tabularData: tabularData.length > sizeLimit ? lodash_es_sampleSize(tabularData, sizeLimit) : tabularData,
          server: null,
          tilePos: [x, y],
          zoomLevel: z
        };
      });
    }
  }
  return new CSVDataFetcherClass(args);
}
CSVDataFetcher.config = {
  type: "csv"
};
function RawDataFetcher(HGC, ...args) {
  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }
  class RawDataFetcherClass {
    constructor(params) {
      const [dataConfig] = params;
      this.dataConfig = dataConfig;
      this.tilesetInfoLoading = false;
      this.assembly = this.dataConfig.assembly;
      if (!dataConfig.values) {
        console.error("Please provide `values` of the raw data");
        return;
      }
      const chromosomeSizes = GET_CHROM_SIZES(this.assembly).size;
      const chromosomeCumPositions = [];
      const chromosomePositions = {};
      let prevEndPosition = 0;
      Object.keys(GET_CHROM_SIZES(this.assembly).size).forEach((chrStr, i) => {
        const positionInfo = {
          id: i,
          chr: chrStr,
          pos: prevEndPosition
        };
        chromosomeCumPositions.push(positionInfo);
        chromosomePositions[chrStr] = positionInfo;
        prevEndPosition += GET_CHROM_SIZES(this.assembly).size[chrStr];
      });
      this.chromSizes = {
        chrToAbs: (chrom, chromPos) => this.chromSizes.chrPositions[chrom].pos + chromPos,
        cumPositions: chromosomeCumPositions,
        chrPositions: chromosomePositions,
        totalLength: prevEndPosition,
        chromLengths: chromosomeSizes
      };
      this.values = dataConfig.values.map((row) => {
        let successfullyGotChrInfo = true;
        this.dataConfig.genomicFields.forEach((g) => {
          if (!row[this.dataConfig.chromosomeField]) {
            return;
          }
          try {
            const chr = row[this.dataConfig.chromosomeField].includes("chr") ? row[this.dataConfig.chromosomeField] : `chr${row[this.dataConfig.chromosomeField]}`;
            row[g] = GET_CHROM_SIZES(this.assembly).interval[chr][0] + +row[g];
          } catch (e) {
            successfullyGotChrInfo = false;
          }
        });
        if (!successfullyGotChrInfo) {
          return void 0;
        }
        return row;
      });
    }
    tilesetInfo(callback) {
      this.tilesetInfoLoading = false;
      const TILE_SIZE = 1024;
      const totalLength = this.chromSizes.totalLength;
      const retVal = {
        tile_size: TILE_SIZE,
        max_zoom: Math.ceil(Math.log(totalLength / TILE_SIZE) / Math.log(2)),
        max_width: totalLength,
        min_pos: [0],
        max_pos: [totalLength]
      };
      if (callback) {
        callback(retVal);
      }
      return retVal;
    }
    fetchTilesDebounced(receivedTiles, tileIds) {
      const tiles = {};
      const validTileIds = [];
      const tilePromises = [];
      for (const tileId of tileIds) {
        const parts = tileId.split(".");
        const z = parseInt(parts[0], 10);
        const x = parseInt(parts[1], 10);
        if (Number.isNaN(x) || Number.isNaN(z)) {
          console.warn("[Gosling Data Fetcher] Invalid tile zoom or position:", z, x);
          continue;
        }
        validTileIds.push(tileId);
        tilePromises.push(this.tile(z, x));
      }
      Promise.all(tilePromises).then((values) => {
        values.forEach((value, i) => {
          const validTileId = validTileIds[i];
          tiles[validTileId] = value;
          tiles[validTileId].tilePositionId = validTileId;
        });
        receivedTiles(tiles);
      });
      return tiles;
    }
    tile(z, x) {
      var _a;
      const tsInfo = this.tilesetInfo();
      const tileWidth = +tsInfo.max_width / 2 ** +z;
      const minX = tsInfo.min_pos[0] + x * tileWidth;
      const maxX = tsInfo.min_pos[0] + (x + 1) * tileWidth;
      let tabularData = this.values;
      const sizeLimit = (_a = this.dataConfig.sampleLength) != null ? _a : 1e3;
      if (sizeLimit < tabularData.length) {
        tabularData = tabularData.filter((d) => {
          return this.dataConfig.genomicFields.find((g) => minX < d[g] && d[g] <= maxX);
        });
      }
      if (sizeLimit < tabularData.length) {
        tabularData = lodash_es_sampleSize(tabularData, sizeLimit);
      }
      return {
        tabularData,
        server: null,
        tilePos: [x],
        zoomLevel: z
      };
    }
  }
  return new RawDataFetcherClass(args);
}
RawDataFetcher.config = {
  type: "json"
};
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : {};
function getAugmentedNamespace(n) {
  if (n.__esModule)
    return n;
  var a = Object.defineProperty({}, "__esModule", { value: true });
  Object.keys(n).forEach(function(k) {
    var d = Object.getOwnPropertyDescriptor(n, k);
    Object.defineProperty(a, k, d.get ? d : {
      enumerable: true,
      get: function() {
        return n[k];
      }
    });
  });
  return a;
}
var dist$1 = {};
var bigwig = {};
var interopRequireDefault = { exports: {} };
(function(module2) {
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : {
      "default": obj
    };
  }
  module2.exports = _interopRequireDefault2;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(interopRequireDefault);
var runtime = { exports: {} };
(function(module2) {
  var runtime2 = function(exports2) {
    var Op = Object.prototype;
    var hasOwn = Op.hasOwnProperty;
    var undefined$1;
    var $Symbol = typeof Symbol === "function" ? Symbol : {};
    var iteratorSymbol = $Symbol.iterator || "@@iterator";
    var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
    var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
    function define(obj, key, value) {
      Object.defineProperty(obj, key, {
        value,
        enumerable: true,
        configurable: true,
        writable: true
      });
      return obj[key];
    }
    try {
      define({}, "");
    } catch (err) {
      define = function(obj, key, value) {
        return obj[key] = value;
      };
    }
    function wrap(innerFn, outerFn, self2, tryLocsList) {
      var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
      var generator = Object.create(protoGenerator.prototype);
      var context2 = new Context3(tryLocsList || []);
      generator._invoke = makeInvokeMethod(innerFn, self2, context2);
      return generator;
    }
    exports2.wrap = wrap;
    function tryCatch(fn, obj, arg) {
      try {
        return { type: "normal", arg: fn.call(obj, arg) };
      } catch (err) {
        return { type: "throw", arg: err };
      }
    }
    var GenStateSuspendedStart = "suspendedStart";
    var GenStateSuspendedYield = "suspendedYield";
    var GenStateExecuting = "executing";
    var GenStateCompleted = "completed";
    var ContinueSentinel = {};
    function Generator() {
    }
    function GeneratorFunction() {
    }
    function GeneratorFunctionPrototype() {
    }
    var IteratorPrototype = {};
    define(IteratorPrototype, iteratorSymbol, function() {
      return this;
    });
    var getProto = Object.getPrototypeOf;
    var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
    if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
      IteratorPrototype = NativeIteratorPrototype;
    }
    var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
    GeneratorFunction.prototype = GeneratorFunctionPrototype;
    define(Gp, "constructor", GeneratorFunctionPrototype);
    define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
    GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction");
    function defineIteratorMethods(prototype) {
      ["next", "throw", "return"].forEach(function(method) {
        define(prototype, method, function(arg) {
          return this._invoke(method, arg);
        });
      });
    }
    exports2.isGeneratorFunction = function(genFun) {
      var ctor = typeof genFun === "function" && genFun.constructor;
      return ctor ? ctor === GeneratorFunction || (ctor.displayName || ctor.name) === "GeneratorFunction" : false;
    };
    exports2.mark = function(genFun) {
      if (Object.setPrototypeOf) {
        Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
      } else {
        genFun.__proto__ = GeneratorFunctionPrototype;
        define(genFun, toStringTagSymbol, "GeneratorFunction");
      }
      genFun.prototype = Object.create(Gp);
      return genFun;
    };
    exports2.awrap = function(arg) {
      return { __await: arg };
    };
    function AsyncIterator(generator, PromiseImpl) {
      function invoke(method, arg, resolve2, reject) {
        var record = tryCatch(generator[method], generator, arg);
        if (record.type === "throw") {
          reject(record.arg);
        } else {
          var result = record.arg;
          var value = result.value;
          if (value && typeof value === "object" && hasOwn.call(value, "__await")) {
            return PromiseImpl.resolve(value.__await).then(function(value2) {
              invoke("next", value2, resolve2, reject);
            }, function(err) {
              invoke("throw", err, resolve2, reject);
            });
          }
          return PromiseImpl.resolve(value).then(function(unwrapped) {
            result.value = unwrapped;
            resolve2(result);
          }, function(error) {
            return invoke("throw", error, resolve2, reject);
          });
        }
      }
      var previousPromise;
      function enqueue(method, arg) {
        function callInvokeWithMethodAndArg() {
          return new PromiseImpl(function(resolve2, reject) {
            invoke(method, arg, resolve2, reject);
          });
        }
        return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
      }
      this._invoke = enqueue;
    }
    defineIteratorMethods(AsyncIterator.prototype);
    define(AsyncIterator.prototype, asyncIteratorSymbol, function() {
      return this;
    });
    exports2.AsyncIterator = AsyncIterator;
    exports2.async = function(innerFn, outerFn, self2, tryLocsList, PromiseImpl) {
      if (PromiseImpl === void 0)
        PromiseImpl = Promise;
      var iter = new AsyncIterator(wrap(innerFn, outerFn, self2, tryLocsList), PromiseImpl);
      return exports2.isGeneratorFunction(outerFn) ? iter : iter.next().then(function(result) {
        return result.done ? result.value : iter.next();
      });
    };
    function makeInvokeMethod(innerFn, self2, context2) {
      var state = GenStateSuspendedStart;
      return function invoke(method, arg) {
        if (state === GenStateExecuting) {
          throw new Error("Generator is already running");
        }
        if (state === GenStateCompleted) {
          if (method === "throw") {
            throw arg;
          }
          return doneResult();
        }
        context2.method = method;
        context2.arg = arg;
        while (true) {
          var delegate = context2.delegate;
          if (delegate) {
            var delegateResult = maybeInvokeDelegate(delegate, context2);
            if (delegateResult) {
              if (delegateResult === ContinueSentinel)
                continue;
              return delegateResult;
            }
          }
          if (context2.method === "next") {
            context2.sent = context2._sent = context2.arg;
          } else if (context2.method === "throw") {
            if (state === GenStateSuspendedStart) {
              state = GenStateCompleted;
              throw context2.arg;
            }
            context2.dispatchException(context2.arg);
          } else if (context2.method === "return") {
            context2.abrupt("return", context2.arg);
          }
          state = GenStateExecuting;
          var record = tryCatch(innerFn, self2, context2);
          if (record.type === "normal") {
            state = context2.done ? GenStateCompleted : GenStateSuspendedYield;
            if (record.arg === ContinueSentinel) {
              continue;
            }
            return {
              value: record.arg,
              done: context2.done
            };
          } else if (record.type === "throw") {
            state = GenStateCompleted;
            context2.method = "throw";
            context2.arg = record.arg;
          }
        }
      };
    }
    function maybeInvokeDelegate(delegate, context2) {
      var method = delegate.iterator[context2.method];
      if (method === undefined$1) {
        context2.delegate = null;
        if (context2.method === "throw") {
          if (delegate.iterator["return"]) {
            context2.method = "return";
            context2.arg = undefined$1;
            maybeInvokeDelegate(delegate, context2);
            if (context2.method === "throw") {
              return ContinueSentinel;
            }
          }
          context2.method = "throw";
          context2.arg = new TypeError("The iterator does not provide a 'throw' method");
        }
        return ContinueSentinel;
      }
      var record = tryCatch(method, delegate.iterator, context2.arg);
      if (record.type === "throw") {
        context2.method = "throw";
        context2.arg = record.arg;
        context2.delegate = null;
        return ContinueSentinel;
      }
      var info = record.arg;
      if (!info) {
        context2.method = "throw";
        context2.arg = new TypeError("iterator result is not an object");
        context2.delegate = null;
        return ContinueSentinel;
      }
      if (info.done) {
        context2[delegate.resultName] = info.value;
        context2.next = delegate.nextLoc;
        if (context2.method !== "return") {
          context2.method = "next";
          context2.arg = undefined$1;
        }
      } else {
        return info;
      }
      context2.delegate = null;
      return ContinueSentinel;
    }
    defineIteratorMethods(Gp);
    define(Gp, toStringTagSymbol, "Generator");
    define(Gp, iteratorSymbol, function() {
      return this;
    });
    define(Gp, "toString", function() {
      return "[object Generator]";
    });
    function pushTryEntry(locs) {
      var entry = { tryLoc: locs[0] };
      if (1 in locs) {
        entry.catchLoc = locs[1];
      }
      if (2 in locs) {
        entry.finallyLoc = locs[2];
        entry.afterLoc = locs[3];
      }
      this.tryEntries.push(entry);
    }
    function resetTryEntry(entry) {
      var record = entry.completion || {};
      record.type = "normal";
      delete record.arg;
      entry.completion = record;
    }
    function Context3(tryLocsList) {
      this.tryEntries = [{ tryLoc: "root" }];
      tryLocsList.forEach(pushTryEntry, this);
      this.reset(true);
    }
    exports2.keys = function(object) {
      var keys = [];
      for (var key in object) {
        keys.push(key);
      }
      keys.reverse();
      return function next() {
        while (keys.length) {
          var key2 = keys.pop();
          if (key2 in object) {
            next.value = key2;
            next.done = false;
            return next;
          }
        }
        next.done = true;
        return next;
      };
    };
    function values(iterable) {
      if (iterable) {
        var iteratorMethod = iterable[iteratorSymbol];
        if (iteratorMethod) {
          return iteratorMethod.call(iterable);
        }
        if (typeof iterable.next === "function") {
          return iterable;
        }
        if (!isNaN(iterable.length)) {
          var i = -1, next = function next2() {
            while (++i < iterable.length) {
              if (hasOwn.call(iterable, i)) {
                next2.value = iterable[i];
                next2.done = false;
                return next2;
              }
            }
            next2.value = undefined$1;
            next2.done = true;
            return next2;
          };
          return next.next = next;
        }
      }
      return { next: doneResult };
    }
    exports2.values = values;
    function doneResult() {
      return { value: undefined$1, done: true };
    }
    Context3.prototype = {
      constructor: Context3,
      reset: function(skipTempReset) {
        this.prev = 0;
        this.next = 0;
        this.sent = this._sent = undefined$1;
        this.done = false;
        this.delegate = null;
        this.method = "next";
        this.arg = undefined$1;
        this.tryEntries.forEach(resetTryEntry);
        if (!skipTempReset) {
          for (var name2 in this) {
            if (name2.charAt(0) === "t" && hasOwn.call(this, name2) && !isNaN(+name2.slice(1))) {
              this[name2] = undefined$1;
            }
          }
        }
      },
      stop: function() {
        this.done = true;
        var rootEntry = this.tryEntries[0];
        var rootRecord = rootEntry.completion;
        if (rootRecord.type === "throw") {
          throw rootRecord.arg;
        }
        return this.rval;
      },
      dispatchException: function(exception) {
        if (this.done) {
          throw exception;
        }
        var context2 = this;
        function handle(loc, caught) {
          record.type = "throw";
          record.arg = exception;
          context2.next = loc;
          if (caught) {
            context2.method = "next";
            context2.arg = undefined$1;
          }
          return !!caught;
        }
        for (var i = this.tryEntries.length - 1; i >= 0; --i) {
          var entry = this.tryEntries[i];
          var record = entry.completion;
          if (entry.tryLoc === "root") {
            return handle("end");
          }
          if (entry.tryLoc <= this.prev) {
            var hasCatch = hasOwn.call(entry, "catchLoc");
            var hasFinally = hasOwn.call(entry, "finallyLoc");
            if (hasCatch && hasFinally) {
              if (this.prev < entry.catchLoc) {
                return handle(entry.catchLoc, true);
              } else if (this.prev < entry.finallyLoc) {
                return handle(entry.finallyLoc);
              }
            } else if (hasCatch) {
              if (this.prev < entry.catchLoc) {
                return handle(entry.catchLoc, true);
              }
            } else if (hasFinally) {
              if (this.prev < entry.finallyLoc) {
                return handle(entry.finallyLoc);
              }
            } else {
              throw new Error("try statement without catch or finally");
            }
          }
        }
      },
      abrupt: function(type2, arg) {
        for (var i = this.tryEntries.length - 1; i >= 0; --i) {
          var entry = this.tryEntries[i];
          if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
            var finallyEntry = entry;
            break;
          }
        }
        if (finallyEntry && (type2 === "break" || type2 === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) {
          finallyEntry = null;
        }
        var record = finallyEntry ? finallyEntry.completion : {};
        record.type = type2;
        record.arg = arg;
        if (finallyEntry) {
          this.method = "next";
          this.next = finallyEntry.finallyLoc;
          return ContinueSentinel;
        }
        return this.complete(record);
      },
      complete: function(record, afterLoc) {
        if (record.type === "throw") {
          throw record.arg;
        }
        if (record.type === "break" || record.type === "continue") {
          this.next = record.arg;
        } else if (record.type === "return") {
          this.rval = this.arg = record.arg;
          this.method = "return";
          this.next = "end";
        } else if (record.type === "normal" && afterLoc) {
          this.next = afterLoc;
        }
        return ContinueSentinel;
      },
      finish: function(finallyLoc) {
        for (var i = this.tryEntries.length - 1; i >= 0; --i) {
          var entry = this.tryEntries[i];
          if (entry.finallyLoc === finallyLoc) {
            this.complete(entry.completion, entry.afterLoc);
            resetTryEntry(entry);
            return ContinueSentinel;
          }
        }
      },
      "catch": function(tryLoc) {
        for (var i = this.tryEntries.length - 1; i >= 0; --i) {
          var entry = this.tryEntries[i];
          if (entry.tryLoc === tryLoc) {
            var record = entry.completion;
            if (record.type === "throw") {
              var thrown = record.arg;
              resetTryEntry(entry);
            }
            return thrown;
          }
        }
        throw new Error("illegal catch attempt");
      },
      delegateYield: function(iterable, resultName, nextLoc) {
        this.delegate = {
          iterator: values(iterable),
          resultName,
          nextLoc
        };
        if (this.method === "next") {
          this.arg = undefined$1;
        }
        return ContinueSentinel;
      }
    };
    return exports2;
  }(module2.exports);
  try {
    regeneratorRuntime = runtime2;
  } catch (accidentalStrictMode) {
    if (typeof globalThis === "object") {
      globalThis.regeneratorRuntime = runtime2;
    } else {
      Function("r", "regeneratorRuntime = r")(runtime2);
    }
  }
})(runtime);
var regenerator = runtime.exports;
var asyncToGenerator = { exports: {} };
(function(module2) {
  function asyncGeneratorStep(gen, resolve2, reject, _next, _throw, key, arg) {
    try {
      var info = gen[key](arg);
      var value = info.value;
    } catch (error) {
      reject(error);
      return;
    }
    if (info.done) {
      resolve2(value);
    } else {
      Promise.resolve(value).then(_next, _throw);
    }
  }
  function _asyncToGenerator(fn) {
    return function() {
      var self2 = this, args = arguments;
      return new Promise(function(resolve2, reject) {
        var gen = fn.apply(self2, args);
        function _next(value) {
          asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "next", value);
        }
        function _throw(err) {
          asyncGeneratorStep(gen, resolve2, reject, _next, _throw, "throw", err);
        }
        _next(void 0);
      });
    };
  }
  module2.exports = _asyncToGenerator;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(asyncToGenerator);
var classCallCheck = { exports: {} };
(function(module2) {
  function _classCallCheck3(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }
  module2.exports = _classCallCheck3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(classCallCheck);
var createClass = { exports: {} };
(function(module2) {
  function _defineProperties2(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass3(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties2(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties2(Constructor, staticProps);
    return Constructor;
  }
  module2.exports = _createClass3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(createClass);
var inherits = { exports: {} };
var setPrototypeOf = { exports: {} };
(function(module2) {
  function _setPrototypeOf2(o, p) {
    module2.exports = _setPrototypeOf2 = Object.setPrototypeOf || function _setPrototypeOf3(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    return _setPrototypeOf2(o, p);
  }
  module2.exports = _setPrototypeOf2;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(setPrototypeOf);
(function(module2) {
  var setPrototypeOf$1 = setPrototypeOf.exports;
  function _inherits3(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
      throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
      constructor: {
        value: subClass,
        writable: true,
        configurable: true
      }
    });
    if (superClass)
      setPrototypeOf$1(subClass, superClass);
  }
  module2.exports = _inherits3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(inherits);
var possibleConstructorReturn = { exports: {} };
var _typeof$2 = { exports: {} };
(function(module2) {
  function _typeof3(obj) {
    "@babel/helpers - typeof";
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      module2.exports = _typeof3 = function _typeof4(obj2) {
        return typeof obj2;
      };
      module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    } else {
      module2.exports = _typeof3 = function _typeof4(obj2) {
        return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
      };
      module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    }
    return _typeof3(obj);
  }
  module2.exports = _typeof3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(_typeof$2);
var assertThisInitialized = { exports: {} };
(function(module2) {
  function _assertThisInitialized3(self2) {
    if (self2 === void 0) {
      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self2;
  }
  module2.exports = _assertThisInitialized3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(assertThisInitialized);
(function(module2) {
  var _typeof3 = _typeof$2.exports["default"];
  var assertThisInitialized$1 = assertThisInitialized.exports;
  function _possibleConstructorReturn3(self2, call) {
    if (call && (_typeof3(call) === "object" || typeof call === "function")) {
      return call;
    } else if (call !== void 0) {
      throw new TypeError("Derived constructors may only return object or undefined");
    }
    return assertThisInitialized$1(self2);
  }
  module2.exports = _possibleConstructorReturn3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(possibleConstructorReturn);
var getPrototypeOf = { exports: {} };
(function(module2) {
  function _getPrototypeOf3(o) {
    module2.exports = _getPrototypeOf3 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf4(o2) {
      return o2.__proto__ || Object.getPrototypeOf(o2);
    };
    module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    return _getPrototypeOf3(o);
  }
  module2.exports = _getPrototypeOf3;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(getPrototypeOf);
var blockView = {};
var gosling_es_defineProperty = { exports: {} };
(function(module2) {
  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  module2.exports = _defineProperty;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(gosling_es_defineProperty);
var binary_parser = {};
var vmBrowser = {};
function runInThisContext(code) {
  const fn = new Function("code", "return eval(code);");
  return fn.call(globalThis, code);
}
vmBrowser.runInThisContext = runInThisContext;
var context = {};
function _typeof$1(obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof$1 = function _typeof3(obj2) {
      return typeof obj2;
    };
  } else {
    _typeof$1 = function _typeof3(obj2) {
      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
    };
  }
  return _typeof$1(obj);
}
var Context$2 = function Context() {
  this.code = "";
  this.scopes = [["vars"]];
  this.isAsync = false;
  this.bitFields = [];
  this.tmpVariableCount = 0;
  this.references = {};
};
Context$2.prototype.generateVariable = function(name2) {
  var arr = [];
  Array.prototype.push.apply(arr, this.scopes[this.scopes.length - 1]);
  while (/^\$parent\./.test(name2)) {
    arr.pop();
    name2 = name2.replace(/^\$parent\./, "");
  }
  if (name2) {
    arr.push(name2);
  }
  return arr.join(".");
};
Context$2.prototype.generateOption = function(val) {
  switch (_typeof$1(val)) {
    case "number":
      return val.toString();
    case "string":
      return this.generateVariable(val);
    case "function":
      return "(".concat(val, ").call(").concat(this.generateVariable(), ", vars)");
    default:
      return void 0;
  }
};
Context$2.prototype.generateError = function() {
  var args = Array.prototype.slice.call(arguments);
  var err = Context$2.interpolate.apply(this, args);
  if (this.isAsync) {
    this.pushCode("return process.nextTick(function() { callback(new Error(".concat(err, "), vars); });"));
  } else {
    this.pushCode("throw new Error(".concat(err, ");"));
  }
};
Context$2.prototype.generateTmpVariable = function() {
  return "$tmp".concat(this.tmpVariableCount++);
};
Context$2.prototype.pushCode = function() {
  var args = Array.prototype.slice.call(arguments);
  this.code += "".concat(Context$2.interpolate.apply(this, args), "\n");
};
Context$2.prototype.pushPath = function(name2) {
  if (name2) {
    this.scopes[this.scopes.length - 1].push(name2);
  }
};
Context$2.prototype.popPath = function(name2) {
  if (name2) {
    this.scopes[this.scopes.length - 1].pop();
  }
};
Context$2.prototype.pushScope = function(name2) {
  this.scopes.push([name2]);
};
Context$2.prototype.popScope = function() {
  this.scopes.pop();
};
Context$2.prototype.addReference = function(alias) {
  if (this.references[alias])
    return;
  this.references[alias] = { resolved: false, requested: false };
};
Context$2.prototype.markResolved = function(alias) {
  this.references[alias].resolved = true;
};
Context$2.prototype.markRequested = function(aliasList) {
  aliasList.forEach(function(alias) {
    this.references[alias].requested = true;
  }.bind(this));
};
Context$2.prototype.getUnresolvedReferences = function() {
  var references = this.references;
  return Object.keys(this.references).filter(function(alias) {
    return !references[alias].resolved && !references[alias].requested;
  });
};
Context$2.interpolate = function(s) {
  var re2 = /{\d+}/g;
  var matches = s.match(re2);
  var params = Array.prototype.slice.call(arguments, 1);
  if (matches) {
    matches.forEach(function(match) {
      var index = parseInt(match.substr(1, match.length - 2), 10);
      s = s.replace(match, params[index].toString());
    });
  }
  return s;
};
context.Context = Context$2;
var gosling_es_long = Long$1;
var wasm = null;
try {
  wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
    0,
    97,
    115,
    109,
    1,
    0,
    0,
    0,
    1,
    13,
    2,
    96,
    0,
    1,
    127,
    96,
    4,
    127,
    127,
    127,
    127,
    1,
    127,
    3,
    7,
    6,
    0,
    1,
    1,
    1,
    1,
    1,
    6,
    6,
    1,
    127,
    1,
    65,
    0,
    11,
    7,
    50,
    6,
    3,
    109,
    117,
    108,
    0,
    1,
    5,
    100,
    105,
    118,
    95,
    115,
    0,
    2,
    5,
    100,
    105,
    118,
    95,
    117,
    0,
    3,
    5,
    114,
    101,
    109,
    95,
    115,
    0,
    4,
    5,
    114,
    101,
    109,
    95,
    117,
    0,
    5,
    8,
    103,
    101,
    116,
    95,
    104,
    105,
    103,
    104,
    0,
    0,
    10,
    191,
    1,
    6,
    4,
    0,
    35,
    0,
    11,
    36,
    1,
    1,
    126,
    32,
    0,
    173,
    32,
    1,
    173,
    66,
    32,
    134,
    132,
    32,
    2,
    173,
    32,
    3,
    173,
    66,
    32,
    134,
    132,
    126,
    34,
    4,
    66,
    32,
    135,
    167,
    36,
    0,
    32,
    4,
    167,
    11,
    36,
    1,
    1,
    126,
    32,
    0,
    173,
    32,
    1,
    173,
    66,
    32,
    134,
    132,
    32,
    2,
    173,
    32,
    3,
    173,
    66,
    32,
    134,
    132,
    127,
    34,
    4,
    66,
    32,
    135,
    167,
    36,
    0,
    32,
    4,
    167,
    11,
    36,
    1,
    1,
    126,
    32,
    0,
    173,
    32,
    1,
    173,
    66,
    32,
    134,
    132,
    32,
    2,
    173,
    32,
    3,
    173,
    66,
    32,
    134,
    132,
    128,
    34,
    4,
    66,
    32,
    135,
    167,
    36,
    0,
    32,
    4,
    167,
    11,
    36,
    1,
    1,
    126,
    32,
    0,
    173,
    32,
    1,
    173,
    66,
    32,
    134,
    132,
    32,
    2,
    173,
    32,
    3,
    173,
    66,
    32,
    134,
    132,
    129,
    34,
    4,
    66,
    32,
    135,
    167,
    36,
    0,
    32,
    4,
    167,
    11,
    36,
    1,
    1,
    126,
    32,
    0,
    173,
    32,
    1,
    173,
    66,
    32,
    134,
    132,
    32,
    2,
    173,
    32,
    3,
    173,
    66,
    32,
    134,
    132,
    130,
    34,
    4,
    66,
    32,
    135,
    167,
    36,
    0,
    32,
    4,
    167,
    11
  ])), {}).exports;
} catch (e) {
}
function Long$1(low, high, unsigned) {
  this.low = low | 0;
  this.high = high | 0;
  this.unsigned = !!unsigned;
}
Long$1.prototype.__isLong__;
Object.defineProperty(Long$1.prototype, "__isLong__", { value: true });
function isLong(obj) {
  return (obj && obj["__isLong__"]) === true;
}
Long$1.isLong = isLong;
var INT_CACHE = {};
var UINT_CACHE = {};
function fromInt(value, unsigned) {
  var obj, cachedObj, cache2;
  if (unsigned) {
    value >>>= 0;
    if (cache2 = 0 <= value && value < 256) {
      cachedObj = UINT_CACHE[value];
      if (cachedObj)
        return cachedObj;
    }
    obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
    if (cache2)
      UINT_CACHE[value] = obj;
    return obj;
  } else {
    value |= 0;
    if (cache2 = -128 <= value && value < 128) {
      cachedObj = INT_CACHE[value];
      if (cachedObj)
        return cachedObj;
    }
    obj = fromBits(value, value < 0 ? -1 : 0, false);
    if (cache2)
      INT_CACHE[value] = obj;
    return obj;
  }
}
Long$1.fromInt = fromInt;
function fromNumber(value, unsigned) {
  if (isNaN(value))
    return unsigned ? UZERO : gosling_es_ZERO;
  if (unsigned) {
    if (value < 0)
      return UZERO;
    if (value >= TWO_PWR_64_DBL)
      return MAX_UNSIGNED_VALUE;
  } else {
    if (value <= -TWO_PWR_63_DBL)
      return MIN_VALUE;
    if (value + 1 >= TWO_PWR_63_DBL)
      return MAX_VALUE;
  }
  if (value < 0)
    return fromNumber(-value, unsigned).neg();
  return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
}
Long$1.fromNumber = fromNumber;
function fromBits(lowBits, highBits, unsigned) {
  return new Long$1(lowBits, highBits, unsigned);
}
Long$1.fromBits = fromBits;
var pow_dbl = Math.pow;
function fromString(str, unsigned, radix) {
  if (str.length === 0)
    throw Error("empty string");
  if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
    return gosling_es_ZERO;
  if (typeof unsigned === "number") {
    radix = unsigned, unsigned = false;
  } else {
    unsigned = !!unsigned;
  }
  radix = radix || 10;
  if (radix < 2 || 36 < radix)
    throw RangeError("radix");
  var p;
  if ((p = str.indexOf("-")) > 0)
    throw Error("interior hyphen");
  else if (p === 0) {
    return fromString(str.substring(1), unsigned, radix).neg();
  }
  var radixToPower = fromNumber(pow_dbl(radix, 8));
  var result = gosling_es_ZERO;
  for (var i = 0; i < str.length; i += 8) {
    var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
    if (size < 8) {
      var power = fromNumber(pow_dbl(radix, size));
      result = result.mul(power).add(fromNumber(value));
    } else {
      result = result.mul(radixToPower);
      result = result.add(fromNumber(value));
    }
  }
  result.unsigned = unsigned;
  return result;
}
Long$1.fromString = fromString;
function fromValue(val, unsigned) {
  if (typeof val === "number")
    return fromNumber(val, unsigned);
  if (typeof val === "string")
    return fromString(val, unsigned);
  return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
}
Long$1.fromValue = fromValue;
var TWO_PWR_16_DBL = 1 << 16;
var TWO_PWR_24_DBL = 1 << 24;
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
var gosling_es_ZERO = fromInt(0);
Long$1.ZERO = gosling_es_ZERO;
var UZERO = fromInt(0, true);
Long$1.UZERO = UZERO;
var ONE = fromInt(1);
Long$1.ONE = ONE;
var UONE = fromInt(1, true);
Long$1.UONE = UONE;
var NEG_ONE = fromInt(-1);
Long$1.NEG_ONE = NEG_ONE;
var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false);
Long$1.MAX_VALUE = MAX_VALUE;
var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true);
Long$1.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
var MIN_VALUE = fromBits(0, 2147483648 | 0, false);
Long$1.MIN_VALUE = MIN_VALUE;
var LongPrototype = Long$1.prototype;
LongPrototype.toInt = function toInt() {
  return this.unsigned ? this.low >>> 0 : this.low;
};
LongPrototype.toNumber = function toNumber() {
  if (this.unsigned)
    return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};
LongPrototype.toString = function toString(radix) {
  radix = radix || 10;
  if (radix < 2 || 36 < radix)
    throw RangeError("radix");
  if (this.isZero())
    return "0";
  if (this.isNegative()) {
    if (this.eq(MIN_VALUE)) {
      var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
      return div.toString(radix) + rem1.toInt().toString(radix);
    } else
      return "-" + this.neg().toString(radix);
  }
  var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this;
  var result = "";
  while (true) {
    var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix);
    rem = remDiv;
    if (rem.isZero())
      return digits + result;
    else {
      while (digits.length < 6)
        digits = "0" + digits;
      result = "" + digits + result;
    }
  }
};
LongPrototype.getHighBits = function getHighBits() {
  return this.high;
};
LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
  return this.high >>> 0;
};
LongPrototype.getLowBits = function getLowBits() {
  return this.low;
};
LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
  return this.low >>> 0;
};
LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
  if (this.isNegative())
    return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  var val = this.high != 0 ? this.high : this.low;
  for (var bit = 31; bit > 0; bit--)
    if ((val & 1 << bit) != 0)
      break;
  return this.high != 0 ? bit + 33 : bit + 1;
};
LongPrototype.isZero = function isZero() {
  return this.high === 0 && this.low === 0;
};
LongPrototype.eqz = LongPrototype.isZero;
LongPrototype.isNegative = function isNegative() {
  return !this.unsigned && this.high < 0;
};
LongPrototype.isPositive = function isPositive() {
  return this.unsigned || this.high >= 0;
};
LongPrototype.isOdd = function isOdd() {
  return (this.low & 1) === 1;
};
LongPrototype.isEven = function isEven() {
  return (this.low & 1) === 0;
};
LongPrototype.equals = function equals(other) {
  if (!isLong(other))
    other = fromValue(other);
  if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
    return false;
  return this.high === other.high && this.low === other.low;
};
LongPrototype.eq = LongPrototype.equals;
LongPrototype.notEquals = function notEquals(other) {
  return !this.eq(other);
};
LongPrototype.neq = LongPrototype.notEquals;
LongPrototype.ne = LongPrototype.notEquals;
LongPrototype.lessThan = function lessThan(other) {
  return this.comp(other) < 0;
};
LongPrototype.lt = LongPrototype.lessThan;
LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
  return this.comp(other) <= 0;
};
LongPrototype.lte = LongPrototype.lessThanOrEqual;
LongPrototype.le = LongPrototype.lessThanOrEqual;
LongPrototype.greaterThan = function greaterThan(other) {
  return this.comp(other) > 0;
};
LongPrototype.gt = LongPrototype.greaterThan;
LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
  return this.comp(other) >= 0;
};
LongPrototype.gte = LongPrototype.greaterThanOrEqual;
LongPrototype.ge = LongPrototype.greaterThanOrEqual;
LongPrototype.compare = function compare(other) {
  if (!isLong(other))
    other = fromValue(other);
  if (this.eq(other))
    return 0;
  var thisNeg = this.isNegative(), otherNeg = other.isNegative();
  if (thisNeg && !otherNeg)
    return -1;
  if (!thisNeg && otherNeg)
    return 1;
  if (!this.unsigned)
    return this.sub(other).isNegative() ? -1 : 1;
  return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
};
LongPrototype.comp = LongPrototype.compare;
LongPrototype.negate = function negate() {
  if (!this.unsigned && this.eq(MIN_VALUE))
    return MIN_VALUE;
  return this.not().add(ONE);
};
LongPrototype.neg = LongPrototype.negate;
LongPrototype.add = function add(addend) {
  if (!isLong(addend))
    addend = fromValue(addend);
  var a48 = this.high >>> 16;
  var a32 = this.high & 65535;
  var a16 = this.low >>> 16;
  var a00 = this.low & 65535;
  var b48 = addend.high >>> 16;
  var b32 = addend.high & 65535;
  var b16 = addend.low >>> 16;
  var b00 = addend.low & 65535;
  var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  c00 += a00 + b00;
  c16 += c00 >>> 16;
  c00 &= 65535;
  c16 += a16 + b16;
  c32 += c16 >>> 16;
  c16 &= 65535;
  c32 += a32 + b32;
  c48 += c32 >>> 16;
  c32 &= 65535;
  c48 += a48 + b48;
  c48 &= 65535;
  return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
};
LongPrototype.subtract = function subtract(subtrahend) {
  if (!isLong(subtrahend))
    subtrahend = fromValue(subtrahend);
  return this.add(subtrahend.neg());
};
LongPrototype.sub = LongPrototype.subtract;
LongPrototype.multiply = function multiply(multiplier) {
  if (this.isZero())
    return gosling_es_ZERO;
  if (!isLong(multiplier))
    multiplier = fromValue(multiplier);
  if (wasm) {
    var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
    return fromBits(low, wasm.get_high(), this.unsigned);
  }
  if (multiplier.isZero())
    return gosling_es_ZERO;
  if (this.eq(MIN_VALUE))
    return multiplier.isOdd() ? MIN_VALUE : gosling_es_ZERO;
  if (multiplier.eq(MIN_VALUE))
    return this.isOdd() ? MIN_VALUE : gosling_es_ZERO;
  if (this.isNegative()) {
    if (multiplier.isNegative())
      return this.neg().mul(multiplier.neg());
    else
      return this.neg().mul(multiplier).neg();
  } else if (multiplier.isNegative())
    return this.mul(multiplier.neg()).neg();
  if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
    return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  var a48 = this.high >>> 16;
  var a32 = this.high & 65535;
  var a16 = this.low >>> 16;
  var a00 = this.low & 65535;
  var b48 = multiplier.high >>> 16;
  var b32 = multiplier.high & 65535;
  var b16 = multiplier.low >>> 16;
  var b00 = multiplier.low & 65535;
  var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  c00 += a00 * b00;
  c16 += c00 >>> 16;
  c00 &= 65535;
  c16 += a16 * b00;
  c32 += c16 >>> 16;
  c16 &= 65535;
  c16 += a00 * b16;
  c32 += c16 >>> 16;
  c16 &= 65535;
  c32 += a32 * b00;
  c48 += c32 >>> 16;
  c32 &= 65535;
  c32 += a16 * b16;
  c48 += c32 >>> 16;
  c32 &= 65535;
  c32 += a00 * b32;
  c48 += c32 >>> 16;
  c32 &= 65535;
  c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  c48 &= 65535;
  return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
};
LongPrototype.mul = LongPrototype.multiply;
LongPrototype.divide = function divide(divisor) {
  if (!isLong(divisor))
    divisor = fromValue(divisor);
  if (divisor.isZero())
    throw Error("division by zero");
  if (wasm) {
    if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
      return this;
    }
    var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
    return fromBits(low, wasm.get_high(), this.unsigned);
  }
  if (this.isZero())
    return this.unsigned ? UZERO : gosling_es_ZERO;
  var approx, rem, res;
  if (!this.unsigned) {
    if (this.eq(MIN_VALUE)) {
      if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
        return MIN_VALUE;
      else if (divisor.eq(MIN_VALUE))
        return ONE;
      else {
        var halfThis = this.shr(1);
        approx = halfThis.div(divisor).shl(1);
        if (approx.eq(gosling_es_ZERO)) {
          return divisor.isNegative() ? ONE : NEG_ONE;
        } else {
          rem = this.sub(divisor.mul(approx));
          res = approx.add(rem.div(divisor));
          return res;
        }
      }
    } else if (divisor.eq(MIN_VALUE))
      return this.unsigned ? UZERO : gosling_es_ZERO;
    if (this.isNegative()) {
      if (divisor.isNegative())
        return this.neg().div(divisor.neg());
      return this.neg().div(divisor).neg();
    } else if (divisor.isNegative())
      return this.div(divisor.neg()).neg();
    res = gosling_es_ZERO;
  } else {
    if (!divisor.unsigned)
      divisor = divisor.toUnsigned();
    if (divisor.gt(this))
      return UZERO;
    if (divisor.gt(this.shru(1)))
      return UONE;
    res = UZERO;
  }
  rem = this;
  while (rem.gte(divisor)) {
    approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
    var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor);
    while (approxRem.isNegative() || approxRem.gt(rem)) {
      approx -= delta;
      approxRes = fromNumber(approx, this.unsigned);
      approxRem = approxRes.mul(divisor);
    }
    if (approxRes.isZero())
      approxRes = ONE;
    res = res.add(approxRes);
    rem = rem.sub(approxRem);
  }
  return res;
};
LongPrototype.div = LongPrototype.divide;
LongPrototype.modulo = function modulo(divisor) {
  if (!isLong(divisor))
    divisor = fromValue(divisor);
  if (wasm) {
    var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
    return fromBits(low, wasm.get_high(), this.unsigned);
  }
  return this.sub(this.div(divisor).mul(divisor));
};
LongPrototype.mod = LongPrototype.modulo;
LongPrototype.rem = LongPrototype.modulo;
LongPrototype.not = function not() {
  return fromBits(~this.low, ~this.high, this.unsigned);
};
LongPrototype.and = function and(other) {
  if (!isLong(other))
    other = fromValue(other);
  return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
};
LongPrototype.or = function or(other) {
  if (!isLong(other))
    other = fromValue(other);
  return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
};
LongPrototype.xor = function xor(other) {
  if (!isLong(other))
    other = fromValue(other);
  return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
};
LongPrototype.shiftLeft = function shiftLeft(numBits) {
  if (isLong(numBits))
    numBits = numBits.toInt();
  if ((numBits &= 63) === 0)
    return this;
  else if (numBits < 32)
    return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
  else
    return fromBits(0, this.low << numBits - 32, this.unsigned);
};
LongPrototype.shl = LongPrototype.shiftLeft;
LongPrototype.shiftRight = function shiftRight(numBits) {
  if (isLong(numBits))
    numBits = numBits.toInt();
  if ((numBits &= 63) === 0)
    return this;
  else if (numBits < 32)
    return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
  else
    return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
};
LongPrototype.shr = LongPrototype.shiftRight;
LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
  if (isLong(numBits))
    numBits = numBits.toInt();
  numBits &= 63;
  if (numBits === 0)
    return this;
  else {
    var high = this.high;
    if (numBits < 32) {
      var low = this.low;
      return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
    } else if (numBits === 32)
      return fromBits(high, 0, this.unsigned);
    else
      return fromBits(high >>> numBits - 32, 0, this.unsigned);
  }
};
LongPrototype.shru = LongPrototype.shiftRightUnsigned;
LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
LongPrototype.toSigned = function toSigned() {
  if (!this.unsigned)
    return this;
  return fromBits(this.low, this.high, false);
};
LongPrototype.toUnsigned = function toUnsigned() {
  if (this.unsigned)
    return this;
  return fromBits(this.low, this.high, true);
};
LongPrototype.toBytes = function toBytes(le) {
  return le ? this.toBytesLE() : this.toBytesBE();
};
LongPrototype.toBytesLE = function toBytesLE() {
  var hi = this.high, lo = this.low;
  return [
    lo & 255,
    lo >>> 8 & 255,
    lo >>> 16 & 255,
    lo >>> 24,
    hi & 255,
    hi >>> 8 & 255,
    hi >>> 16 & 255,
    hi >>> 24
  ];
};
LongPrototype.toBytesBE = function toBytesBE() {
  var hi = this.high, lo = this.low;
  return [
    hi >>> 24,
    hi >>> 16 & 255,
    hi >>> 8 & 255,
    hi & 255,
    lo >>> 24,
    lo >>> 16 & 255,
    lo >>> 8 & 255,
    lo & 255
  ];
};
Long$1.fromBytes = function fromBytes(bytes, unsigned, le) {
  return le ? Long$1.fromBytesLE(bytes, unsigned) : Long$1.fromBytesBE(bytes, unsigned);
};
Long$1.fromBytesLE = function fromBytesLE(bytes, unsigned) {
  return new Long$1(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned);
};
Long$1.fromBytesBE = function fromBytesBE(bytes, unsigned) {
  return new Long$1(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned);
};
function _typeof(obj) {
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function _typeof3(obj2) {
      return typeof obj2;
    };
  } else {
    _typeof = function _typeof3(obj2) {
      return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
    };
  }
  return _typeof(obj);
}
var _require = buffer, Buffer$1 = _require.Buffer;
var vm = vmBrowser;
var Context$1 = context.Context;
var Long = gosling_es_long;
if (typeof window !== "undefined")
  window.Buffer = Buffer$1;
if (typeof self !== "undefined")
  self.Buffer = Buffer$1;
var PRIMITIVE_TYPES = {
  UInt8: 1,
  UInt16LE: 2,
  UInt16BE: 2,
  UInt32LE: 4,
  UInt32BE: 4,
  Int8: 1,
  Int16LE: 2,
  Int16BE: 2,
  Int32LE: 4,
  Int32BE: 4,
  FloatLE: 4,
  FloatBE: 4,
  DoubleLE: 8,
  DoubleBE: 8,
  UInt64: 8,
  Int64: 8
};
var SPECIAL_TYPES = {
  String: null,
  Buffer: null,
  Array: null,
  Skip: null,
  Choice: null,
  Nest: null,
  Bit: null,
  Itf8: null,
  Ltf8: null
};
var aliasRegistry = {};
var FUNCTION_PREFIX = "___parser_";
var BIT_RANGE = [];
(function() {
  var i;
  for (i = 1; i <= 32; i++) {
    BIT_RANGE.push(i);
  }
})();
var NAME_MAP = {};
Object.keys(PRIMITIVE_TYPES).concat(Object.keys(SPECIAL_TYPES)).forEach(function(type2) {
  NAME_MAP[type2.toLowerCase()] = type2;
});
var Parser = function Parser2() {
  this.varName = "";
  this.type = "";
  this.options = {};
  this.next = null;
  this.head = null;
  this.compiled = null;
  this.endian = "le";
  this.constructorFn = null;
  this.alias = null;
};
Parser.start = function() {
  return new Parser();
};
Object.keys(PRIMITIVE_TYPES).forEach(function(type2) {
  Parser.prototype[type2.toLowerCase()] = function(varName, options) {
    return this.setNextParser(type2.toLowerCase(), varName, options);
  };
  var typeWithoutEndian = type2.replace(/BE|LE/, "").toLowerCase();
  if (!(typeWithoutEndian in Parser.prototype)) {
    Parser.prototype[typeWithoutEndian] = function(varName, options) {
      return this[typeWithoutEndian + this.endian](varName, options);
    };
  }
});
BIT_RANGE.forEach(function(i) {
  Parser.prototype["bit".concat(i.toString())] = function(varName, options) {
    if (!options) {
      options = {};
    }
    options.length = i;
    return this.setNextParser("bit", varName, options);
  };
});
Parser.prototype.namely = function(alias) {
  aliasRegistry[alias] = this;
  this.alias = alias;
  return this;
};
Parser.prototype.skip = function(length, options) {
  if (options && options.assert) {
    throw new Error("assert option on skip is not allowed.");
  }
  return this.setNextParser("skip", "", { length });
};
Parser.prototype.string = function(varName, options) {
  if (!options.zeroTerminated && !options.length && !options.greedy) {
    throw new Error("Neither length, zeroTerminated, nor greedy is defined for string.");
  }
  if ((options.zeroTerminated || options.length) && options.greedy) {
    throw new Error("greedy is mutually exclusive with length and zeroTerminated for string.");
  }
  if (options.stripNull && !(options.length || options.greedy)) {
    throw new Error("Length or greedy must be defined if stripNull is defined.");
  }
  options.encoding = options.encoding || "utf8";
  return this.setNextParser("string", varName, options);
};
Parser.prototype.buffer = function(varName, options) {
  if (!options.length && !options.readUntil) {
    throw new Error("Length nor readUntil is defined in buffer parser");
  }
  return this.setNextParser("buffer", varName, options);
};
Parser.prototype.array = function(varName, options) {
  if (!options.readUntil && !options.length && !options.lengthInBytes) {
    throw new Error("Length option of array is not defined.");
  }
  if (!options.type) {
    throw new Error("Type option of array is not defined.");
  }
  if (typeof options.type === "string" && !aliasRegistry[options.type] && Object.keys(PRIMITIVE_TYPES).indexOf(NAME_MAP[options.type]) < 0) {
    throw new Error('Specified primitive type "'.concat(options.type, '" is not supported.'));
  }
  return this.setNextParser("array", varName, options);
};
Parser.prototype.choice = function(varName, options) {
  if (arguments.length === 1 && _typeof(varName) === "object") {
    options = varName;
    varName = null;
  }
  if (!options.tag) {
    throw new Error("Tag option of array is not defined.");
  }
  if (!options.choices) {
    throw new Error("Choices option of array is not defined.");
  }
  Object.keys(options.choices).forEach(function(key) {
    if (!options.choices[key]) {
      throw new Error("Choice Case ".concat(key, " of ").concat(varName, " is not valid."));
    }
    if (typeof options.choices[key] === "string" && !aliasRegistry[options.choices[key]] && Object.keys(PRIMITIVE_TYPES).indexOf(NAME_MAP[options.choices[key]]) < 0) {
      throw new Error('Specified primitive type "'.concat(options.choices[key], '" is not supported.'));
    }
  }, this);
  return this.setNextParser("choice", varName, options);
};
Parser.prototype.nest = function(varName, options) {
  if (arguments.length === 1 && _typeof(varName) === "object") {
    options = varName;
    varName = null;
  }
  if (!options.type) {
    throw new Error("Type option of nest is not defined.");
  }
  if (!(options.type instanceof Parser) && !aliasRegistry[options.type]) {
    throw new Error("Type option of nest must be a Parser object.");
  }
  if (!(options.type instanceof Parser) && !varName) {
    throw new Error("options.type must be a object if variable name is omitted.");
  }
  return this.setNextParser("nest", varName, options);
};
Parser.prototype.endianess = function(endianess) {
  switch (endianess.toLowerCase()) {
    case "little":
      this.endian = "le";
      break;
    case "big":
      this.endian = "be";
      break;
    default:
      throw new Error("Invalid endianess: ".concat(endianess));
  }
  return this;
};
Parser.prototype.create = function(constructorFn) {
  if (!(constructorFn instanceof Function)) {
    throw new Error("Constructor must be a Function object.");
  }
  this.constructorFn = constructorFn;
  return this;
};
Parser.prototype.getCode = function() {
  var ctx = new Context$1();
  ctx.pushCode("if (!Buffer.isBuffer(buffer)) {");
  ctx.generateError('"argument buffer is not a Buffer object"');
  ctx.pushCode("}");
  if (!this.alias) {
    this.addRawCode(ctx);
  } else {
    this.addAliasedCode(ctx);
  }
  if (this.alias) {
    ctx.pushCode("return {0}(0)", FUNCTION_PREFIX + this.alias);
  } else {
    ctx.pushCode("return { offset: offset, result: vars };");
  }
  return ctx.code;
};
Parser.prototype.addRawCode = function(ctx) {
  ctx.pushCode("var offset = 0;");
  if (this.constructorFn) {
    ctx.pushCode("var vars = new constructorFn();");
  } else {
    ctx.pushCode("var vars = {};");
  }
  this.generate(ctx);
  this.resolveReferences(ctx);
  ctx.pushCode("return { offset: offset, result: vars };");
};
Parser.prototype.addAliasedCode = function(ctx) {
  ctx.pushCode("function {0}(offset) {", FUNCTION_PREFIX + this.alias);
  if (this.constructorFn) {
    ctx.pushCode("var vars = new constructorFn();");
  } else {
    ctx.pushCode("var vars = {};");
  }
  this.generate(ctx);
  ctx.markResolved(this.alias);
  this.resolveReferences(ctx);
  ctx.pushCode("return { offset: offset, result: vars };");
  ctx.pushCode("}");
  return ctx;
};
Parser.prototype.resolveReferences = function(ctx) {
  var references = ctx.getUnresolvedReferences();
  ctx.markRequested(references);
  references.forEach(function(alias) {
    var parser = aliasRegistry[alias];
    parser.addAliasedCode(ctx);
  });
};
Parser.prototype.compile = function() {
  var src = "(function(buffer, constructorFn, Long) { ".concat(this.getCode(), " })");
  this.compiled = vm.runInThisContext(src);
};
Parser.prototype.sizeOf = function() {
  var size = NaN;
  if (Object.keys(PRIMITIVE_TYPES).indexOf(this.type) >= 0) {
    size = PRIMITIVE_TYPES[this.type];
  } else if (this.type === "String" && typeof this.options.length === "number") {
    size = this.options.length;
  } else if (this.type === "Buffer" && typeof this.options.length === "number") {
    size = this.options.length;
  } else if (this.type === "Array" && typeof this.options.length === "number") {
    var elementSize = NaN;
    if (typeof this.options.type === "string") {
      elementSize = PRIMITIVE_TYPES[NAME_MAP[this.options.type]];
    } else if (this.options.type instanceof Parser) {
      elementSize = this.options.type.sizeOf();
    }
    size = this.options.length * elementSize;
  } else if (this.type === "Skip") {
    size = this.options.length;
  } else if (this.type === "Nest") {
    size = this.options.type.sizeOf();
  } else if (!this.type) {
    size = 0;
  }
  if (this.next) {
    size += this.next.sizeOf();
  }
  return size;
};
Parser.prototype.parse = function(buffer2) {
  if (!this.compiled) {
    this.compile();
  }
  return this.compiled(buffer2, this.constructorFn, Long);
};
Parser.prototype.setNextParser = function(type2, varName, options) {
  var parser = new Parser();
  parser.type = NAME_MAP[type2];
  parser.varName = varName;
  parser.options = options || parser.options;
  parser.endian = this.endian;
  if (this.head) {
    this.head.next = parser;
  } else {
    this.next = parser;
  }
  this.head = parser;
  return this;
};
Parser.prototype.generate = function(ctx) {
  if (this.type) {
    this["generate".concat(this.type)](ctx);
    this.generateAssert(ctx);
  }
  var varName = ctx.generateVariable(this.varName);
  if (this.options.formatter) {
    this.generateFormatter(ctx, varName, this.options.formatter);
  }
  return this.generateNext(ctx);
};
Parser.prototype.generateAssert = function(ctx) {
  if (!this.options.assert) {
    return;
  }
  var varName = ctx.generateVariable(this.varName);
  switch (_typeof(this.options.assert)) {
    case "function":
      ctx.pushCode("if (!({0}).call(vars, {1})) {", this.options.assert, varName);
      break;
    case "number":
      ctx.pushCode("if ({0} !== {1}) {", this.options.assert, varName);
      break;
    case "string":
      ctx.pushCode('if ("{0}" !== {1}) {', this.options.assert, varName);
      break;
    default:
      throw new Error("Assert option supports only strings, numbers and assert functions.");
  }
  ctx.generateError('"Assert error: {0} is " + {0}', varName);
  ctx.pushCode("}");
};
Parser.prototype.generateNext = function(ctx) {
  if (this.next) {
    ctx = this.next.generate(ctx);
  }
  return ctx;
};
Object.keys(PRIMITIVE_TYPES).forEach(function(type2) {
  Parser.prototype["generate".concat(type2)] = function(ctx) {
    if (type2 === "UInt64") {
      ctx.pushCode("{0} = Long.fromBytes(buffer.slice(offset,offset+8), true, this.endian === 'le').toNumber();", ctx.generateVariable(this.varName), type2);
    } else if (type2 === "Int64") {
      ctx.pushCode("{0} = Long.fromBytes(buffer.slice(offset,offset+8), false, this.endian === 'le').toNumber();", ctx.generateVariable(this.varName), type2);
    } else {
      ctx.pushCode("{0} = buffer.read{1}(offset);", ctx.generateVariable(this.varName), type2);
    }
    ctx.pushCode("offset += {0};", PRIMITIVE_TYPES[type2]);
  };
});
Parser.prototype.generateBit = function(ctx) {
  var parser = JSON.parse(JSON.stringify(this));
  parser.varName = ctx.generateVariable(parser.varName);
  ctx.bitFields.push(parser);
  if (!this.next || this.next && ["Bit", "Nest"].indexOf(this.next.type) < 0) {
    var sum2 = 0;
    ctx.bitFields.forEach(function(p) {
      sum2 += p.options.length;
    });
    var val = ctx.generateTmpVariable();
    if (sum2 <= 8) {
      ctx.pushCode("var {0} = buffer.readUInt8(offset);", val);
      sum2 = 8;
    } else if (sum2 <= 16) {
      ctx.pushCode("var {0} = buffer.readUInt16BE(offset);", val);
      sum2 = 16;
    } else if (sum2 <= 24) {
      var val1 = ctx.generateTmpVariable();
      var val2 = ctx.generateTmpVariable();
      ctx.pushCode("var {0} = buffer.readUInt16BE(offset);", val1);
      ctx.pushCode("var {0} = buffer.readUInt8(offset + 2);", val2);
      ctx.pushCode("var {2} = ({0} << 8) | {1};", val1, val2, val);
      sum2 = 24;
    } else if (sum2 <= 32) {
      ctx.pushCode("var {0} = buffer.readUInt32BE(offset);", val);
      sum2 = 32;
    } else {
      throw new Error("Currently, bit field sequence longer than 4-bytes is not supported.");
    }
    ctx.pushCode("offset += {0};", sum2 / 8);
    var bitOffset = 0;
    var isBigEndian = this.endian === "be";
    ctx.bitFields.forEach(function(p) {
      ctx.pushCode("{0} = {1} >> {2} & {3};", p.varName, val, isBigEndian ? sum2 - bitOffset - p.options.length : bitOffset, (1 << p.options.length) - 1);
      bitOffset += p.options.length;
    });
    ctx.bitFields = [];
  }
};
Parser.prototype.generateSkip = function(ctx) {
  var length = ctx.generateOption(this.options.length);
  ctx.pushCode("offset += {0};", length);
};
Parser.prototype.generateString = function(ctx) {
  var name2 = ctx.generateVariable(this.varName);
  var start = ctx.generateTmpVariable();
  if (this.options.length && this.options.zeroTerminated) {
    ctx.pushCode("var {0} = offset;", start);
    ctx.pushCode("while(buffer.readUInt8(offset++) !== 0 && offset - {0}  < {1});", start, this.options.length);
    ctx.pushCode("{0} = buffer.toString('{1}', {2}, offset - {2} < {3} ? offset - 1 : offset);", name2, this.options.encoding, start, this.options.length);
  } else if (this.options.length) {
    ctx.pushCode("{0} = buffer.toString('{1}', offset, offset + {2});", name2, this.options.encoding, ctx.generateOption(this.options.length));
    ctx.pushCode("offset += {0};", ctx.generateOption(this.options.length));
  } else if (this.options.zeroTerminated) {
    ctx.pushCode("var {0} = offset;", start);
    ctx.pushCode("while(buffer.readUInt8(offset++) !== 0);");
    ctx.pushCode("{0} = buffer.toString('{1}', {2}, offset - 1);", name2, this.options.encoding, start);
  } else if (this.options.greedy) {
    ctx.pushCode("var {0} = offset;", start);
    ctx.pushCode("while(buffer.length > offset++);");
    ctx.pushCode("{0} = buffer.toString('{1}', {2}, offset);", name2, this.options.encoding, start);
  }
  if (this.options.stripNull) {
    ctx.pushCode("{0} = {0}.replace(/\\x00+$/g, '')", name2);
  }
};
Parser.prototype.generateBuffer = function(ctx) {
  if (this.options.readUntil === "eof") {
    ctx.pushCode("{0} = buffer.slice(offset);", ctx.generateVariable(this.varName));
  } else {
    ctx.pushCode("{0} = buffer.slice(offset, offset + {1});", ctx.generateVariable(this.varName), ctx.generateOption(this.options.length));
    ctx.pushCode("offset += {0};", ctx.generateOption(this.options.length));
  }
  if (this.options.clone) {
    ctx.pushCode("{0} = Buffer.from({0});", ctx.generateVariable(this.varName));
  }
};
Parser.prototype.generateArray = function(ctx) {
  var length = ctx.generateOption(this.options.length);
  var lengthInBytes = ctx.generateOption(this.options.lengthInBytes);
  var type2 = this.options.type;
  var counter = ctx.generateTmpVariable();
  var lhs = ctx.generateVariable(this.varName);
  var item = ctx.generateTmpVariable();
  var key = this.options.key;
  var isHash = typeof key === "string";
  if (isHash) {
    ctx.pushCode("{0} = {};", lhs);
  } else {
    ctx.pushCode("{0} = [];", lhs);
  }
  if (typeof this.options.readUntil === "function") {
    ctx.pushCode("do {");
  } else if (this.options.readUntil === "eof") {
    ctx.pushCode("for (var {0} = 0; offset < buffer.length; {0}++) {", counter);
  } else if (lengthInBytes !== void 0) {
    ctx.pushCode("for (var {0} = offset; offset - {0} < {1}; ) {", counter, lengthInBytes);
  } else {
    ctx.pushCode("for (var {0} = 0; {0} < {1}; {0}++) {", counter, length);
  }
  if (typeof type2 === "string") {
    if (!aliasRegistry[type2]) {
      ctx.pushCode("var {0} = buffer.read{1}(offset);", item, NAME_MAP[type2]);
      ctx.pushCode("offset += {0};", PRIMITIVE_TYPES[NAME_MAP[type2]]);
    } else {
      var tempVar = ctx.generateTmpVariable();
      ctx.pushCode("var {0} = {1}(offset);", tempVar, FUNCTION_PREFIX + type2);
      ctx.pushCode("var {0} = {1}.result; offset = {1}.offset;", item, tempVar);
      if (type2 !== this.alias)
        ctx.addReference(type2);
    }
  } else if (type2 instanceof Parser) {
    ctx.pushCode("var {0} = {};", item);
    ctx.pushScope(item);
    type2.generate(ctx);
    ctx.popScope();
  }
  if (isHash) {
    ctx.pushCode("{0}[{2}.{1}] = {2};", lhs, key, item);
  } else {
    ctx.pushCode("{0}.push({1});", lhs, item);
  }
  ctx.pushCode("}");
  if (typeof this.options.readUntil === "function") {
    ctx.pushCode(" while (!({0}).call(this, {1}, buffer.slice(offset)));", this.options.readUntil, item);
  }
};
Parser.prototype.generateChoiceCase = function(ctx, varName, type2) {
  if (typeof type2 === "string") {
    if (!aliasRegistry[type2]) {
      ctx.pushCode("{0} = buffer.read{1}(offset);", ctx.generateVariable(this.varName), NAME_MAP[type2]);
      ctx.pushCode("offset += {0};", PRIMITIVE_TYPES[NAME_MAP[type2]]);
    } else {
      var tempVar = ctx.generateTmpVariable();
      ctx.pushCode("var {0} = {1}(offset);", tempVar, FUNCTION_PREFIX + type2);
      ctx.pushCode("{0} = {1}.result; offset = {1}.offset;", ctx.generateVariable(this.varName), tempVar);
      if (type2 !== this.alias)
        ctx.addReference(type2);
    }
  } else if (type2 instanceof Parser) {
    ctx.pushPath(varName);
    type2.generate(ctx);
    ctx.popPath(varName);
  }
};
Parser.prototype.generateChoice = function(ctx) {
  var tag = ctx.generateOption(this.options.tag);
  if (this.varName) {
    ctx.pushCode("{0} = {};", ctx.generateVariable(this.varName));
  }
  ctx.pushCode("switch({0}) {", tag);
  Object.keys(this.options.choices).forEach(function(t) {
    var type2 = this.options.choices[t];
    if (Number.isNaN(parseInt(t, 10))) {
      ctx.pushCode("case '{0}':", t);
    } else {
      ctx.pushCode("case {0}:", t);
    }
    this.generateChoiceCase(ctx, this.varName, type2);
    ctx.pushCode("break;");
  }, this);
  ctx.pushCode("default:");
  if (this.options.defaultChoice) {
    this.generateChoiceCase(ctx, this.varName, this.options.defaultChoice);
  } else {
    ctx.generateError('"Met undefined tag value " + {0} + " at choice"', tag);
  }
  ctx.pushCode("}");
};
Parser.prototype.generateNest = function(ctx) {
  var nestVar = ctx.generateVariable(this.varName);
  if (this.options.type instanceof Parser) {
    if (this.varName) {
      ctx.pushCode("{0} = {};", nestVar);
    }
    ctx.pushPath(this.varName);
    this.options.type.generate(ctx);
    ctx.popPath(this.varName);
  } else if (aliasRegistry[this.options.type]) {
    var tempVar = ctx.generateTmpVariable();
    ctx.pushCode("var {0} = {1}(offset);", tempVar, FUNCTION_PREFIX + this.options.type);
    ctx.pushCode("{0} = {1}.result; offset = {1}.offset;", nestVar, tempVar);
    if (this.options.type !== this.alias)
      ctx.addReference(this.options.type);
  }
};
Parser.prototype.generateFormatter = function(ctx, varName, formatter) {
  if (typeof formatter === "function") {
    ctx.pushCode("{0} = ({1}).call(this, {0});", varName, formatter);
  }
};
Parser.prototype.isInteger = function() {
  return !!this.type.match(/U?Int[8|16|32][BE|LE]?|Bit\d+/);
};
Parser.prototype.itf8 = function(varName, options) {
  return this.setNextParser("itf8", varName, options);
};
Parser.prototype.itf8 = function(varName, options) {
  return this.setNextParser("itf8", varName, options);
};
Parser.prototype.generateItf8 = function(ctx) {
  var name2 = ctx.generateVariable(this.varName);
  var countFlags = ctx.generateTmpVariable();
  ctx.pushCode("\n    var ".concat(countFlags, " = buffer[offset];\n    if (").concat(countFlags, " < 0x80) {\n      ").concat(name2, " = ").concat(countFlags, ";\n      offset += 1;\n    } else if (").concat(countFlags, " < 0xc0) {\n      ").concat(name2, " = ((").concat(countFlags, "<<8) | buffer[offset+1]) & 0x3fff;\n      offset += 2;\n    } else if (").concat(countFlags, " < 0xe0) {\n      ").concat(name2, " = ((").concat(countFlags, "<<16) | (buffer[offset+1]<< 8) |  buffer[offset+2]) & 0x1fffff;\n      offset += 3;\n    } else if (").concat(countFlags, " < 0xf0) {\n      ").concat(name2, " = ((").concat(countFlags, "<<24) | (buffer[offset+1]<<16) | (buffer[offset+2]<<8) | buffer[offset+3]) & 0x0fffffff;\n      offset += 4\n    } else {\n      ").concat(name2, " = ((").concat(countFlags, " & 0x0f)<<28) | (buffer[offset+1]<<20) | (buffer[offset+2]<<12) | (buffer[offset+3]<<4) | (buffer[offset+4] & 0x0f);\n      // x=((0xff & 0x0f)<<28) | (0xff<<20) | (0xff<<12) | (0xff<<4) | (0x0f & 0x0f);\n      // TODO *val_p = uv < 0x80000000UL ? uv : -((int32_t) (0xffffffffUL - uv)) - 1;\n      offset += 5\n    }\n  "));
};
Parser.prototype.ltf8 = function(varName, options) {
  return this.setNextParser("ltf8", varName, options);
};
Parser.prototype.generateLtf8 = function(ctx) {
  var name2 = ctx.generateVariable(this.varName);
  var countFlags = ctx.generateTmpVariable();
  ctx.pushCode("\n  var ".concat(countFlags, " = buffer[offset];\n  if (").concat(countFlags, " < 0x80) {\n    ").concat(name2, " = ").concat(countFlags, ";\n    offset += 1;\n  } else if (").concat(countFlags, " < 0xc0) {\n    ").concat(name2, " = ((buffer[offset]<<8) | buffer[offset+1]) & 0x3fff;\n    offset += 2;\n  } else if (").concat(countFlags, " < 0xe0) {\n    ").concat(name2, " = ((buffer[offset]<<16) | (buffer[offset+1]<<8) | buffer[offset+2]) & 0x1fffff;\n    ").concat(name2, " = (((").concat(countFlags, " & 63) << 16) | buffer.readUInt16LE(offset + 1));\n    offset += 3;\n  } else if (").concat(countFlags, " < 0xf0) {\n    ").concat(name2, " = ((buffer[offset]<<24) | (buffer[offset+1]<<16) | (buffer[offset+2]<<8) | buffer[offset+3]) & 0x0fffffff;\n    offset += 4;\n  } else if (").concat(countFlags, " < 0xf8) {\n    ").concat(name2, " = (((buffer[offset] & 15) * Math.pow(2,32))) +\n      (buffer[offset+1]<<24) | (buffer[offset+2]<<16 | buffer[offset+3]<<8 | buffer[offset+4])\n    // TODO *val_p = uv < 0x80000000UL ? uv : -((int32_t) (0xffffffffUL - uv)) - 1;\n    offset += 5;\n  } else if (").concat(countFlags, " < 0xfc) {\n    ").concat(name2, " = ((((buffer[offset] & 7) << 8) | buffer[offset+1] )) * Math.pow(2,32) +\n      (buffer[offset+2]<<24) | (buffer[offset+3]<<16 | buffer[offset+4]<<8 | buffer[offset+5])\n    offset += 6;\n  } else if (").concat(countFlags, " < 0xfe) {\n    ").concat(name2, " = ((((buffer[offset] & 3) << 16) | buffer[offset+1]<<8 | buffer[offset+2])) * Math.pow(2,32) +\n      (buffer[offset+3]<<24) | (buffer[offset+4]<<16 | buffer[offset+5]<<8 | buffer[offset+6])\n    offset += 7;\n  } else if (").concat(countFlags, " < 0xff) {\n    ").concat(name2, " = Long.fromBytesBE(buffer.slice(offset+1,offset+8));\n    if (").concat(name2, ".greaterThan(Number.MAX_SAFE_INTEGER) || ").concat(name2, ".lessThan(Number.MIN_SAFE_INTEGER))\n      throw new Error('integer overflow')\n    ").concat(name2, " = ").concat(name2, ".toNumber()\n    offset += 8;\n  } else {\n    ").concat(name2, " = Long.fromBytesBE(buffer.slice(offset+1,offset+9));\n    if (").concat(name2, ".greaterThan(Number.MAX_SAFE_INTEGER) || ").concat(name2, ".lessThan(Number.MIN_SAFE_INTEGER))\n      throw new Error('integer overflow')\n    ").concat(name2, " = ").concat(name2, ".toNumber()\n    offset += 9;\n  }\n  "));
};
binary_parser.Parser = Parser;
var gosling_es_dist = {};
var AbortablePromiseCache$1 = {};
var abortcontrollerPonyfill = {};
var cjsPonyfill = {};
Object.defineProperty(cjsPonyfill, "__esModule", { value: true });
function gosling_es_classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor)
      descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}
function gosling_es_createClass(Constructor, protoProps, staticProps) {
  if (protoProps)
    _defineProperties(Constructor.prototype, protoProps);
  if (staticProps)
    _defineProperties(Constructor, staticProps);
  return Constructor;
}
function gosling_es_inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass)
    _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf3(o2) {
    return o2.__proto__ || Object.getPrototypeOf(o2);
  };
  return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) {
    o2.__proto__ = p2;
    return o2;
  };
  return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct$3() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
    return true;
  } catch (e) {
    return false;
  }
}
function _assertThisInitialized(self2) {
  if (self2 === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }
  return self2;
}
function gosling_es_possibleConstructorReturn(self2, call) {
  if (call && (typeof call === "object" || typeof call === "function")) {
    return call;
  }
  return _assertThisInitialized(self2);
}
function _createSuper$3(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct$3();
  return function _createSuperInternal() {
    var Super = _getPrototypeOf(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = _getPrototypeOf(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return gosling_es_possibleConstructorReturn(this, result);
  };
}
function _superPropBase(object, property) {
  while (!Object.prototype.hasOwnProperty.call(object, property)) {
    object = _getPrototypeOf(object);
    if (object === null)
      break;
  }
  return object;
}
function gosling_es_get(target, property, receiver) {
  if (typeof Reflect !== "undefined" && Reflect.get) {
    gosling_es_get = Reflect.get;
  } else {
    gosling_es_get = function _get2(target2, property2, receiver2) {
      var base = _superPropBase(target2, property2);
      if (!base)
        return;
      var desc = Object.getOwnPropertyDescriptor(base, property2);
      if (desc.get) {
        return desc.get.call(receiver2);
      }
      return desc.value;
    };
  }
  return gosling_es_get(target, property, receiver || target);
}
var Emitter = /* @__PURE__ */ function() {
  function Emitter2() {
    gosling_es_classCallCheck(this, Emitter2);
    Object.defineProperty(this, "listeners", {
      value: {},
      writable: true,
      configurable: true
    });
  }
  gosling_es_createClass(Emitter2, [{
    key: "addEventListener",
    value: function addEventListener(type2, callback, options) {
      if (!(type2 in this.listeners)) {
        this.listeners[type2] = [];
      }
      this.listeners[type2].push({
        callback,
        options
      });
    }
  }, {
    key: "removeEventListener",
    value: function removeEventListener(type2, callback) {
      if (!(type2 in this.listeners)) {
        return;
      }
      var stack = this.listeners[type2];
      for (var i = 0, l = stack.length; i < l; i++) {
        if (stack[i].callback === callback) {
          stack.splice(i, 1);
          return;
        }
      }
    }
  }, {
    key: "dispatchEvent",
    value: function dispatchEvent(event) {
      if (!(event.type in this.listeners)) {
        return;
      }
      var stack = this.listeners[event.type];
      var stackToCall = stack.slice();
      for (var i = 0, l = stackToCall.length; i < l; i++) {
        var listener = stackToCall[i];
        try {
          listener.callback.call(this, event);
        } catch (e) {
          Promise.resolve().then(function() {
            throw e;
          });
        }
        if (listener.options && listener.options.once) {
          this.removeEventListener(event.type, listener.callback);
        }
      }
      return !event.defaultPrevented;
    }
  }]);
  return Emitter2;
}();
var AbortSignal$1 = /* @__PURE__ */ function(_Emitter) {
  gosling_es_inherits(AbortSignal2, _Emitter);
  var _super = _createSuper$3(AbortSignal2);
  function AbortSignal2() {
    var _this;
    gosling_es_classCallCheck(this, AbortSignal2);
    _this = _super.call(this);
    if (!_this.listeners) {
      Emitter.call(_assertThisInitialized(_this));
    }
    Object.defineProperty(_assertThisInitialized(_this), "aborted", {
      value: false,
      writable: true,
      configurable: true
    });
    Object.defineProperty(_assertThisInitialized(_this), "onabort", {
      value: null,
      writable: true,
      configurable: true
    });
    return _this;
  }
  gosling_es_createClass(AbortSignal2, [{
    key: "toString",
    value: function toString2() {
      return "[object AbortSignal]";
    }
  }, {
    key: "dispatchEvent",
    value: function dispatchEvent(event) {
      if (event.type === "abort") {
        this.aborted = true;
        if (typeof this.onabort === "function") {
          this.onabort.call(this, event);
        }
      }
      gosling_es_get(_getPrototypeOf(AbortSignal2.prototype), "dispatchEvent", this).call(this, event);
    }
  }]);
  return AbortSignal2;
}(Emitter);
var AbortController$1 = /* @__PURE__ */ function() {
  function AbortController2() {
    gosling_es_classCallCheck(this, AbortController2);
    Object.defineProperty(this, "signal", {
      value: new AbortSignal$1(),
      writable: true,
      configurable: true
    });
  }
  gosling_es_createClass(AbortController2, [{
    key: "abort",
    value: function abort() {
      var event;
      try {
        event = new Event("abort");
      } catch (e) {
        if (typeof document !== "undefined") {
          if (!document.createEvent) {
            event = document.createEventObject();
            event.type = "abort";
          } else {
            event = document.createEvent("Event");
            event.initEvent("abort", false, false);
          }
        } else {
          event = {
            type: "abort",
            bubbles: false,
            cancelable: false
          };
        }
      }
      this.signal.dispatchEvent(event);
    }
  }, {
    key: "toString",
    value: function toString2() {
      return "[object AbortController]";
    }
  }]);
  return AbortController2;
}();
if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
  AbortController$1.prototype[Symbol.toStringTag] = "AbortController";
  AbortSignal$1.prototype[Symbol.toStringTag] = "AbortSignal";
}
function polyfillNeeded(self2) {
  if (self2.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
    console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill");
    return true;
  }
  return typeof self2.Request === "function" && !self2.Request.prototype.hasOwnProperty("signal") || !self2.AbortController;
}
function abortableFetchDecorator(patchTargets) {
  if (typeof patchTargets === "function") {
    patchTargets = {
      fetch: patchTargets
    };
  }
  var _patchTargets = patchTargets, fetch2 = _patchTargets.fetch, _patchTargets$Request = _patchTargets.Request, NativeRequest = _patchTargets$Request === void 0 ? fetch2.Request : _patchTargets$Request, NativeAbortController = _patchTargets.AbortController, _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL, __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === void 0 ? false : _patchTargets$__FORCE;
  if (!polyfillNeeded({
    fetch: fetch2,
    Request: NativeRequest,
    AbortController: NativeAbortController,
    __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL
  })) {
    return {
      fetch: fetch2,
      Request
    };
  }
  var Request = NativeRequest;
  if (Request && !Request.prototype.hasOwnProperty("signal") || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
    Request = function Request2(input, init2) {
      var signal;
      if (init2 && init2.signal) {
        signal = init2.signal;
        delete init2.signal;
      }
      var request = new NativeRequest(input, init2);
      if (signal) {
        Object.defineProperty(request, "signal", {
          writable: false,
          enumerable: false,
          configurable: true,
          value: signal
        });
      }
      return request;
    };
    Request.prototype = NativeRequest.prototype;
  }
  var realFetch = fetch2;
  var abortableFetch = function abortableFetch2(input, init2) {
    var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init2 ? init2.signal : void 0;
    if (signal) {
      var abortError;
      try {
        abortError = new DOMException("Aborted", "AbortError");
      } catch (err) {
        abortError = new Error("Aborted");
        abortError.name = "AbortError";
      }
      if (signal.aborted) {
        return Promise.reject(abortError);
      }
      var cancellation = new Promise(function(_, reject) {
        signal.addEventListener("abort", function() {
          return reject(abortError);
        }, {
          once: true
        });
      });
      if (init2 && init2.signal) {
        delete init2.signal;
      }
      return Promise.race([cancellation, realFetch(input, init2)]);
    }
    return realFetch(input, init2);
  };
  return {
    fetch: abortableFetch,
    Request
  };
}
cjsPonyfill.AbortController = AbortController$1;
cjsPonyfill.AbortSignal = AbortSignal$1;
cjsPonyfill.abortableFetch = abortableFetchDecorator;
Object.defineProperty(abortcontrollerPonyfill, "__esModule", { value: true });
abortcontrollerPonyfill.AbortSignal = abortcontrollerPonyfill.AbortController = void 0;
var _cjsPonyfill = cjsPonyfill;
var getGlobal = function getGlobal2() {
  if (typeof self !== "undefined") {
    return self;
  }
  if (typeof window !== "undefined") {
    return window;
  }
  if (typeof commonjsGlobal !== "undefined") {
    return commonjsGlobal;
  }
  throw new Error("unable to locate global object");
};
var AbortController = typeof getGlobal().AbortController === "undefined" ? _cjsPonyfill.AbortController : getGlobal().AbortController;
abortcontrollerPonyfill.AbortController = AbortController;
var AbortSignal = typeof getGlobal().AbortController === "undefined" ? _cjsPonyfill.AbortSignal : getGlobal().AbortSignal;
abortcontrollerPonyfill.AbortSignal = AbortSignal;
var AggregateAbortController$1 = {};
var _interopRequireDefault$9 = interopRequireDefault.exports;
Object.defineProperty(AggregateAbortController$1, "__esModule", { value: true });
AggregateAbortController$1.default = void 0;
var _createClass2$7 = _interopRequireDefault$9(createClass.exports);
var _defineProperty2$7 = _interopRequireDefault$9(gosling_es_defineProperty.exports);
var _classCallCheck2$8 = _interopRequireDefault$9(classCallCheck.exports);
var _abortcontrollerPonyfill$1 = abortcontrollerPonyfill;
var NullSignal = function NullSignal2() {
  (0, _classCallCheck2$8.default)(this, NullSignal2);
};
var AggregateAbortController = /* @__PURE__ */ function() {
  function AggregateAbortController2() {
    (0, _classCallCheck2$8.default)(this, AggregateAbortController2);
    (0, _defineProperty2$7.default)(this, "signals", new Set());
    (0, _defineProperty2$7.default)(this, "abortController", new _abortcontrollerPonyfill$1.AbortController());
  }
  (0, _createClass2$7.default)(AggregateAbortController2, [{
    key: "addSignal",
    value: function addSignal() {
      var _this = this;
      var signal = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : new NullSignal();
      if (this.signal.aborted) {
        throw new Error("cannot add a signal, already aborted!");
      }
      this.signals.add(signal);
      if (signal.aborted) {
        this.handleAborted(signal);
      } else if (typeof signal.addEventListener === "function") {
        signal.addEventListener("abort", function() {
          _this.handleAborted(signal);
        });
      }
    }
  }, { key: "handleAborted", value: function handleAborted(signal) {
    this.signals.delete(signal);
    if (this.signals.size === 0) {
      this.abortController.abort();
    }
  } }, { key: "abort", value: function abort() {
    this.abortController.abort();
  } }, { key: "signal", get: function get() {
    return this.abortController.signal;
  } }]);
  return AggregateAbortController2;
}();
AggregateAbortController$1.default = AggregateAbortController;
var AggregateStatusReporter$1 = {};
var _interopRequireDefault$8 = interopRequireDefault.exports;
Object.defineProperty(AggregateStatusReporter$1, "__esModule", { value: true });
AggregateStatusReporter$1.default = void 0;
var _classCallCheck2$7 = _interopRequireDefault$8(classCallCheck.exports);
var _createClass2$6 = _interopRequireDefault$8(createClass.exports);
var _defineProperty2$6 = _interopRequireDefault$8(gosling_es_defineProperty.exports);
var AggregateStatusReporter = /* @__PURE__ */ function() {
  function AggregateStatusReporter2() {
    (0, _classCallCheck2$7.default)(this, AggregateStatusReporter2);
    (0, _defineProperty2$6.default)(this, "callbacks", new Set());
    (0, _defineProperty2$6.default)(this, "currentMessage", void 0);
  }
  (0, _createClass2$6.default)(AggregateStatusReporter2, [{ key: "addCallback", value: function addCallback() {
    var callback = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : function() {
    };
    this.callbacks.add(callback);
    callback(this.currentMessage);
  } }, { key: "callback", value: function callback(message) {
    this.currentMessage = message;
    this.callbacks.forEach(function(elt) {
      elt(message);
    });
  } }]);
  return AggregateStatusReporter2;
}();
AggregateStatusReporter$1.default = AggregateStatusReporter;
var _interopRequireDefault$7 = interopRequireDefault.exports;
Object.defineProperty(AbortablePromiseCache$1, "__esModule", { value: true });
AbortablePromiseCache$1.default = void 0;
var _typeof2 = _interopRequireDefault$7(_typeof$2.exports);
var _classCallCheck2$6 = _interopRequireDefault$7(classCallCheck.exports);
var _createClass2$5 = _interopRequireDefault$7(createClass.exports);
var _defineProperty2$5 = _interopRequireDefault$7(gosling_es_defineProperty.exports);
var _abortcontrollerPonyfill = abortcontrollerPonyfill;
var _AggregateAbortController = _interopRequireDefault$7(AggregateAbortController$1);
var _AggregateStatusReporter = _interopRequireDefault$7(AggregateStatusReporter$1);
var AbortablePromiseCache = /* @__PURE__ */ function() {
  function AbortablePromiseCache2(_ref) {
    var fill = _ref.fill, cache2 = _ref.cache;
    (0, _classCallCheck2$6.default)(this, AbortablePromiseCache2);
    (0, _defineProperty2$5.default)(this, "cache", void 0);
    (0, _defineProperty2$5.default)(this, "fillCallback", void 0);
    if (typeof fill !== "function")
      throw new TypeError("must pass a fill function");
    if ((0, _typeof2.default)(cache2) !== "object")
      throw new TypeError("must pass a cache object");
    if (typeof cache2.get !== "function" || typeof cache2.set !== "function" || typeof cache2.delete !== "function")
      throw new TypeError("cache must implement get(key), set(key, val), and and delete(key)");
    this.cache = cache2;
    this.fillCallback = fill;
  }
  (0, _createClass2$5.default)(AbortablePromiseCache2, [{ key: "evict", value: function evict(key, entry) {
    if (this.cache.get(key) === entry)
      this.cache.delete(key);
  } }, { key: "fill", value: function fill(key, data2, signal, statusCallback) {
    var _this = this;
    var aborter = new _AggregateAbortController.default();
    var statusReporter = new _AggregateStatusReporter.default();
    statusReporter.addCallback(statusCallback);
    var newEntry = {
      aborter,
      promise: this.fillCallback(data2, aborter.signal, function(message) {
        statusReporter.callback(message);
      }),
      settled: false,
      statusReporter,
      get aborted() {
        return this.aborter.signal.aborted;
      }
    };
    newEntry.aborter.addSignal(signal);
    newEntry.aborter.signal.addEventListener("abort", function() {
      if (!newEntry.settled) {
        _this.evict(key, newEntry);
      }
    });
    newEntry.promise.then(function() {
      newEntry.settled = true;
    }, function(exception) {
      newEntry.settled = true;
      _this.evict(key, newEntry);
    }).catch(function(e) {
      console.error(e);
      throw e;
    });
    this.cache.set(key, newEntry);
  } }, {
    key: "has",
    value: function has(key) {
      return this.cache.has(key);
    }
  }, {
    key: "get",
    value: function get(key, data2, signal, statusCallback) {
      if (!signal && data2 instanceof _abortcontrollerPonyfill.AbortSignal)
        throw new TypeError("second get argument appears to be an AbortSignal, perhaps you meant to pass `null` for the fill data?");
      var cacheEntry = this.cache.get(key);
      if (cacheEntry) {
        if (cacheEntry.aborted && !cacheEntry.settled) {
          this.evict(key, cacheEntry);
          return this.get(key, data2, signal, statusCallback);
        }
        if (cacheEntry.settled) {
          return cacheEntry.promise;
        }
        cacheEntry.aborter.addSignal(signal);
        cacheEntry.statusReporter.addCallback(statusCallback);
        return AbortablePromiseCache2.checkSinglePromise(cacheEntry.promise, signal);
      }
      this.fill(key, data2, signal, statusCallback);
      return AbortablePromiseCache2.checkSinglePromise(this.cache.get(key).promise, signal);
    }
  }, {
    key: "delete",
    value: function _delete(key) {
      var cachedEntry = this.cache.get(key);
      if (cachedEntry) {
        if (!cachedEntry.settled)
          cachedEntry.aborter.abort();
        this.cache.delete(key);
      }
    }
  }, { key: "clear", value: function clear() {
    var keyIter = this.cache.keys();
    var deleteCount = 0;
    for (var result = keyIter.next(); !result.done; result = keyIter.next()) {
      this.delete(result.value);
      deleteCount += 1;
    }
    return deleteCount;
  } }], [{ key: "isAbortException", value: function isAbortException(exception) {
    return exception.name === "AbortError" || exception.code === "ERR_ABORTED" || exception.message === "AbortError: aborted" || exception.message === "Error: aborted";
  } }, { key: "checkSinglePromise", value: function checkSinglePromise(promise, signal) {
    function checkForSingleAbort() {
      if (signal && signal.aborted)
        throw Object.assign(new Error("aborted"), { code: "ERR_ABORTED" });
    }
    return promise.then(function(result) {
      checkForSingleAbort();
      return result;
    }, function(error) {
      checkForSingleAbort();
      throw error;
    });
  } }]);
  return AbortablePromiseCache2;
}();
AbortablePromiseCache$1.default = AbortablePromiseCache;
var _interopRequireDefault$6 = interopRequireDefault.exports;
Object.defineProperty(gosling_es_dist, "__esModule", { value: true });
gosling_es_dist.default = void 0;
var _AbortablePromiseCache = _interopRequireDefault$6(AbortablePromiseCache$1);
var _default = _AbortablePromiseCache.default;
gosling_es_dist.default = _default;
function gosling_es_inflateSync(src) {
  return buffer.Buffer.from(unzlibSync(src));
}
var gosling_es_zlib = { inflateSync: gosling_es_inflateSync };
var zlib$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  [Symbol.toStringTag]: "Module",
  inflateSync: gosling_es_inflateSync,
  "default": gosling_es_zlib
});
var require$$8 = /* @__PURE__ */ getAugmentedNamespace(zlib$1);
class QuickLRU {
  constructor(options = {}) {
    if (!(options.maxSize && options.maxSize > 0)) {
      throw new TypeError("`maxSize` must be a number greater than 0");
    }
    this.maxSize = options.maxSize;
    this.cache = new Map();
    this.oldCache = new Map();
    this._size = 0;
  }
  _set(key, value) {
    this.cache.set(key, value);
    this._size++;
    if (this._size >= this.maxSize) {
      this._size = 0;
      this.oldCache = this.cache;
      this.cache = new Map();
    }
  }
  get(key) {
    if (this.cache.has(key)) {
      return this.cache.get(key);
    }
    if (this.oldCache.has(key)) {
      const value = this.oldCache.get(key);
      this.oldCache.delete(key);
      this._set(key, value);
      return value;
    }
  }
  set(key, value) {
    if (this.cache.has(key)) {
      this.cache.set(key, value);
    } else {
      this._set(key, value);
    }
    return this;
  }
  has(key) {
    return this.cache.has(key) || this.oldCache.has(key);
  }
  peek(key) {
    if (this.cache.has(key)) {
      return this.cache.get(key);
    }
    if (this.oldCache.has(key)) {
      return this.oldCache.get(key);
    }
  }
  delete(key) {
    const deleted = this.cache.delete(key);
    if (deleted) {
      this._size--;
    }
    return this.oldCache.delete(key) || deleted;
  }
  clear() {
    this.cache.clear();
    this.oldCache.clear();
    this._size = 0;
  }
  *keys() {
    for (const [key] of this) {
      yield key;
    }
  }
  *values() {
    for (const [, value] of this) {
      yield value;
    }
  }
  *[Symbol.iterator]() {
    for (const item of this.cache) {
      yield item;
    }
    for (const item of this.oldCache) {
      const [key] = item;
      if (!this.cache.has(key)) {
        yield item;
      }
    }
  }
  get size() {
    let oldCacheSize = 0;
    for (const key of this.oldCache.keys()) {
      if (!this.cache.has(key)) {
        oldCacheSize++;
      }
    }
    return this._size + oldCacheSize;
  }
}
var quickLru = QuickLRU;
var range$1 = {};
var _interopRequireDefault$5 = interopRequireDefault.exports;
Object.defineProperty(range$1, "__esModule", {
  value: true
});
range$1.default = void 0;
var _classCallCheck2$5 = _interopRequireDefault$5(classCallCheck.exports);
var _createClass2$4 = _interopRequireDefault$5(createClass.exports);
var _defineProperty2$4 = _interopRequireDefault$5(gosling_es_defineProperty.exports);
var Range = /* @__PURE__ */ function() {
  function Range2(arg1, arg2) {
    (0, _classCallCheck2$5.default)(this, Range2);
    (0, _defineProperty2$4.default)(this, "ranges", void 0);
    this.ranges = arguments.length === 2 ? [{
      min: arg1,
      max: arg2
    }] : 0 in arg1 ? Object.assign({}, arg1) : [arg1];
  }
  (0, _createClass2$4.default)(Range2, [{
    key: "min",
    value: function min2() {
      return this.ranges[0].min;
    }
  }, {
    key: "max",
    value: function max2() {
      return this.ranges[this.ranges.length - 1].max;
    }
  }, {
    key: "contains",
    value: function contains2(pos) {
      for (var s = 0; s < this.ranges.length; s += 1) {
        var r = this.ranges[s];
        if (r.min <= pos && r.max >= pos) {
          return true;
        }
      }
      return false;
    }
  }, {
    key: "isContiguous",
    value: function isContiguous() {
      return this.ranges.length > 1;
    }
  }, {
    key: "getRanges",
    value: function getRanges() {
      return this.ranges.map(function(r) {
        return new Range2(r.min, r.max);
      });
    }
  }, {
    key: "toString",
    value: function toString2() {
      return this.ranges.map(function(r) {
        return "[".concat(r.min, "-").concat(r.max, "]");
      }).join(",");
    }
  }, {
    key: "union",
    value: function union(s1) {
      var ranges = this.getRanges().concat(s1.getRanges()).sort(this.rangeOrder);
      var oranges = [];
      var current = ranges[0];
      for (var i = 1; i < ranges.length; i += 1) {
        var nxt = ranges[i];
        if (nxt.min() > current.max() + 1) {
          oranges.push(current);
          current = nxt;
        } else if (nxt.max() > current.max()) {
          current = new Range2(current.min(), nxt.max());
        }
      }
      oranges.push(current);
      if (oranges.length === 1) {
        return oranges[0];
      }
      return new Range2(oranges);
    }
  }, {
    key: "intersection",
    value: function intersection(arg) {
      var s0 = this;
      var s1 = arg;
      var r0 = this.ranges();
      var r1 = s1.ranges();
      var l0 = r0.length;
      var l1 = r1.length;
      var i0 = 0;
      var i1 = 0;
      var or2 = [];
      while (i0 < l0 && i1 < l1) {
        s0 = r0[i0];
        s1 = r1[i1];
        var lapMin = Math.max(s0.min(), s1.min());
        var lapMax = Math.min(s0.max(), s1.max());
        if (lapMax >= lapMin) {
          or2.push(new Range2(lapMin, lapMax));
        }
        if (s0.max() > s1.max()) {
          i1 += 1;
        } else {
          i0 += 1;
        }
      }
      if (or2.length === 0) {
        throw new Error("found range of length 0");
      }
      if (or2.length === 1) {
        return or2[0];
      }
      return new Range2(or2);
    }
  }, {
    key: "coverage",
    value: function coverage() {
      var tot = 0;
      var rl = this.ranges();
      for (var ri = 0; ri < rl.length; ri += 1) {
        var r = rl[ri];
        tot += r.max() - r.min() + 1;
      }
      return tot;
    }
  }, {
    key: "rangeOrder",
    value: function rangeOrder(tmpa, tmpb) {
      var a = tmpa;
      var b = tmpb;
      if (arguments.length < 2) {
        b = a;
        a = this;
      }
      if (a.min() < b.min()) {
        return -1;
      }
      if (a.min() > b.min()) {
        return 1;
      }
      if (a.max() < b.max()) {
        return -1;
      }
      if (b.max() > a.max()) {
        return 1;
      }
      return 0;
    }
  }]);
  return Range2;
}();
range$1.default = Range;
var util$6 = {};
var wrapNativeSuper = { exports: {} };
var isNativeFunction = { exports: {} };
(function(module2) {
  function _isNativeFunction(fn) {
    return Function.toString.call(fn).indexOf("[native code]") !== -1;
  }
  module2.exports = _isNativeFunction;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(isNativeFunction);
var construct = { exports: {} };
var isNativeReflectConstruct = { exports: {} };
(function(module2) {
  function _isNativeReflectConstruct2() {
    if (typeof Reflect === "undefined" || !Reflect.construct)
      return false;
    if (Reflect.construct.sham)
      return false;
    if (typeof Proxy === "function")
      return true;
    try {
      Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
      }));
      return true;
    } catch (e) {
      return false;
    }
  }
  module2.exports = _isNativeReflectConstruct2;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(isNativeReflectConstruct);
(function(module2) {
  var setPrototypeOf$1 = setPrototypeOf.exports;
  var isNativeReflectConstruct$1 = isNativeReflectConstruct.exports;
  function _construct(Parent, args, Class) {
    if (isNativeReflectConstruct$1()) {
      module2.exports = _construct = Reflect.construct;
      module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    } else {
      module2.exports = _construct = function _construct2(Parent2, args2, Class2) {
        var a = [null];
        a.push.apply(a, args2);
        var Constructor = Function.bind.apply(Parent2, a);
        var instance = new Constructor();
        if (Class2)
          setPrototypeOf$1(instance, Class2.prototype);
        return instance;
      };
      module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    }
    return _construct.apply(null, arguments);
  }
  module2.exports = _construct;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(construct);
(function(module2) {
  var getPrototypeOf$1 = getPrototypeOf.exports;
  var setPrototypeOf$1 = setPrototypeOf.exports;
  var isNativeFunction$1 = isNativeFunction.exports;
  var construct$1 = construct.exports;
  function _wrapNativeSuper(Class) {
    var _cache = typeof Map === "function" ? new Map() : void 0;
    module2.exports = _wrapNativeSuper = function _wrapNativeSuper3(Class2) {
      if (Class2 === null || !isNativeFunction$1(Class2))
        return Class2;
      if (typeof Class2 !== "function") {
        throw new TypeError("Super expression must either be null or a function");
      }
      if (typeof _cache !== "undefined") {
        if (_cache.has(Class2))
          return _cache.get(Class2);
        _cache.set(Class2, Wrapper);
      }
      function Wrapper() {
        return construct$1(Class2, arguments, getPrototypeOf$1(this).constructor);
      }
      Wrapper.prototype = Object.create(Class2.prototype, {
        constructor: {
          value: Wrapper,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
      return setPrototypeOf$1(Wrapper, Class2);
    };
    module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
    return _wrapNativeSuper(Class);
  }
  module2.exports = _wrapNativeSuper;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(wrapNativeSuper);
var _interopRequireDefault$4 = interopRequireDefault.exports;
Object.defineProperty(util$6, "__esModule", {
  value: true
});
util$6.groupBlocks = groupBlocks;
util$6.checkAbortSignal = checkAbortSignal;
util$6.abortBreakPoint = abortBreakPoint;
util$6.AbortError = void 0;
var _regenerator$4 = _interopRequireDefault$4(regenerator);
var _asyncToGenerator2$4 = _interopRequireDefault$4(asyncToGenerator.exports);
var _classCallCheck2$4 = _interopRequireDefault$4(classCallCheck.exports);
var _assertThisInitialized2$1 = _interopRequireDefault$4(assertThisInitialized.exports);
var _inherits2$2 = _interopRequireDefault$4(inherits.exports);
var _possibleConstructorReturn2$2 = _interopRequireDefault$4(possibleConstructorReturn.exports);
var _getPrototypeOf2$2 = _interopRequireDefault$4(getPrototypeOf.exports);
var _wrapNativeSuper2 = _interopRequireDefault$4(wrapNativeSuper.exports);
var _defineProperty2$3 = _interopRequireDefault$4(gosling_es_defineProperty.exports);
function _createSuper$2(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct$2();
  return function _createSuperInternal() {
    var Super = (0, _getPrototypeOf2$2.default)(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = (0, _getPrototypeOf2$2.default)(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return (0, _possibleConstructorReturn2$2.default)(this, result);
  };
}
function _isNativeReflectConstruct$2() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Date.prototype.toString.call(Reflect.construct(Date, [], function() {
    }));
    return true;
  } catch (e) {
    return false;
  }
}
var AbortError = /* @__PURE__ */ function(_Error) {
  (0, _inherits2$2.default)(AbortError2, _Error);
  var _super = _createSuper$2(AbortError2);
  function AbortError2(message) {
    var _this;
    (0, _classCallCheck2$4.default)(this, AbortError2);
    _this = _super.call(this, message);
    (0, _defineProperty2$3.default)((0, _assertThisInitialized2$1.default)(_this), "code", void 0);
    _this.code = "ERR_ABORTED";
    return _this;
  }
  return AbortError2;
}(/* @__PURE__ */ (0, _wrapNativeSuper2.default)(Error));
util$6.AbortError = AbortError;
function groupBlocks(blocks) {
  blocks.sort(function(b0, b1) {
    return (b0.offset | 0) - (b1.offset | 0);
  });
  var blockGroups = [];
  var lastBlock;
  var lastBlockEnd;
  for (var i = 0; i < blocks.length; i += 1) {
    if (lastBlock && blocks[i].offset - lastBlockEnd <= 2e3) {
      lastBlock.length += blocks[i].length - lastBlockEnd + blocks[i].offset;
      lastBlock.blocks.push(blocks[i]);
    } else {
      blockGroups.push(lastBlock = {
        blocks: [blocks[i]],
        length: blocks[i].length,
        offset: blocks[i].offset
      });
    }
    lastBlockEnd = lastBlock.offset + lastBlock.length;
  }
  return blockGroups;
}
function checkAbortSignal(signal) {
  if (!signal)
    return;
  if (signal.aborted) {
    if (typeof DOMException !== "undefined") {
      throw new DOMException("aborted", "AbortError");
    } else {
      var e = new AbortError("aborted");
      e.code = "ERR_ABORTED";
      throw e;
    }
  }
}
function abortBreakPoint(_x) {
  return _abortBreakPoint.apply(this, arguments);
}
function _abortBreakPoint() {
  _abortBreakPoint = (0, _asyncToGenerator2$4.default)(/* @__PURE__ */ _regenerator$4.default.mark(function _callee(signal) {
    return _regenerator$4.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return Promise.resolve();
          case 2:
            checkAbortSignal(signal);
          case 3:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _abortBreakPoint.apply(this, arguments);
}
var _interopRequireDefault$3 = interopRequireDefault.exports;
Object.defineProperty(blockView, "__esModule", {
  value: true
});
blockView.BlockView = void 0;
var _regenerator$3 = _interopRequireDefault$3(regenerator);
var _asyncToGenerator2$3 = _interopRequireDefault$3(asyncToGenerator.exports);
var _classCallCheck2$3 = _interopRequireDefault$3(classCallCheck.exports);
var _createClass2$3 = _interopRequireDefault$3(createClass.exports);
var _defineProperty2$2 = _interopRequireDefault$3(gosling_es_defineProperty.exports);
var _binaryParser$2 = binary_parser;
var _abortablePromiseCache$2 = _interopRequireDefault$3(gosling_es_dist);
var _zlib = _interopRequireDefault$3(require$$8);
var _quickLru$2 = _interopRequireDefault$3(quickLru);
var _range = _interopRequireDefault$3(range$1);
var _util = util$6;
function ownKeys$2(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly)
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread$2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$2(Object(source), true).forEach(function(key) {
        (0, _defineProperty2$2.default)(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$2(Object(source)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
var BIG_WIG_TYPE_GRAPH = 1;
var BIG_WIG_TYPE_VSTEP = 2;
var BIG_WIG_TYPE_FSTEP = 3;
function getParsers$1(isBigEndian) {
  var _choices;
  var le = isBigEndian ? "big" : "little";
  var summaryParser = new _binaryParser$2.Parser().endianess(le).uint32("chromId").uint32("start").uint32("end").uint32("validCnt").float("minScore").float("maxScore").float("sumData").float("sumSqData");
  var leafParser = new _binaryParser$2.Parser().endianess(le).uint8("isLeaf").skip(1).uint16("cnt").choice({
    tag: "isLeaf",
    choices: {
      1: new _binaryParser$2.Parser().array("blocksToFetch", {
        length: "cnt",
        type: new _binaryParser$2.Parser().uint32("startChrom").uint32("startBase").uint32("endChrom").uint32("endBase").uint64("blockOffset").uint64("blockSize")
      }),
      0: new _binaryParser$2.Parser().array("recurOffsets", {
        length: "cnt",
        type: new _binaryParser$2.Parser().uint32("startChrom").uint32("startBase").uint32("endChrom").uint32("endBase").uint64("blockOffset")
      })
    }
  });
  var bigBedParser = new _binaryParser$2.Parser().endianess(le).uint32("chromId").int32("start").int32("end").string("rest", {
    zeroTerminated: true
  });
  var bigWigParser = new _binaryParser$2.Parser().endianess(le).skip(4).int32("blockStart").skip(4).uint32("itemStep").uint32("itemSpan").uint8("blockType").skip(1).uint16("itemCount").choice({
    tag: "blockType",
    choices: (_choices = {}, (0, _defineProperty2$2.default)(_choices, BIG_WIG_TYPE_FSTEP, new _binaryParser$2.Parser().array("items", {
      length: "itemCount",
      type: new _binaryParser$2.Parser().float("score")
    })), (0, _defineProperty2$2.default)(_choices, BIG_WIG_TYPE_VSTEP, new _binaryParser$2.Parser().array("items", {
      length: "itemCount",
      type: new _binaryParser$2.Parser().int32("start").float("score")
    })), (0, _defineProperty2$2.default)(_choices, BIG_WIG_TYPE_GRAPH, new _binaryParser$2.Parser().array("items", {
      length: "itemCount",
      type: new _binaryParser$2.Parser().int32("start").int32("end").float("score")
    })), _choices)
  });
  return {
    bigWigParser,
    bigBedParser,
    summaryParser,
    leafParser
  };
}
var BlockView = /* @__PURE__ */ function() {
  function BlockView2(bbi2, refsByName, cirTreeOffset, cirTreeLength, isBigEndian, isCompressed, blockType) {
    var _this = this;
    (0, _classCallCheck2$3.default)(this, BlockView2);
    (0, _defineProperty2$2.default)(this, "cirTreeOffset", void 0);
    (0, _defineProperty2$2.default)(this, "cirTreeLength", void 0);
    (0, _defineProperty2$2.default)(this, "bbi", void 0);
    (0, _defineProperty2$2.default)(this, "isCompressed", void 0);
    (0, _defineProperty2$2.default)(this, "isBigEndian", void 0);
    (0, _defineProperty2$2.default)(this, "refsByName", void 0);
    (0, _defineProperty2$2.default)(this, "blockType", void 0);
    (0, _defineProperty2$2.default)(this, "cirTreePromise", void 0);
    (0, _defineProperty2$2.default)(this, "featureCache", new _abortablePromiseCache$2.default({
      cache: new _quickLru$2.default({
        maxSize: 1e3
      }),
      fill: function() {
        var _fill = (0, _asyncToGenerator2$3.default)(/* @__PURE__ */ _regenerator$3.default.mark(function _callee(requestData, signal) {
          var length, offset, _yield$_this$bbi$read, buffer2;
          return _regenerator$3.default.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  length = requestData.length, offset = requestData.offset;
                  _context.next = 3;
                  return _this.bbi.read(Buffer.alloc(length), 0, length, offset, {
                    signal
                  });
                case 3:
                  _yield$_this$bbi$read = _context.sent;
                  buffer2 = _yield$_this$bbi$read.buffer;
                  return _context.abrupt("return", buffer2);
                case 6:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
        function fill(_x, _x2) {
          return _fill.apply(this, arguments);
        }
        return fill;
      }()
    }));
    (0, _defineProperty2$2.default)(this, "leafParser", void 0);
    (0, _defineProperty2$2.default)(this, "bigWigParser", void 0);
    (0, _defineProperty2$2.default)(this, "bigBedParser", void 0);
    (0, _defineProperty2$2.default)(this, "summaryParser", void 0);
    if (!(cirTreeOffset >= 0))
      throw new Error("invalid cirTreeOffset!");
    if (!(cirTreeLength > 0))
      throw new Error("invalid cirTreeLength!");
    this.cirTreeOffset = cirTreeOffset;
    this.cirTreeLength = cirTreeLength;
    this.isCompressed = isCompressed;
    this.refsByName = refsByName;
    this.isBigEndian = isBigEndian;
    this.bbi = bbi2;
    this.blockType = blockType;
    Object.assign(this, getParsers$1(isBigEndian));
  }
  (0, _createClass2$3.default)(BlockView2, [{
    key: "readWigData",
    value: function() {
      var _readWigData = (0, _asyncToGenerator2$3.default)(/* @__PURE__ */ _regenerator$3.default.mark(function _callee3(chrName, start, end, observer, opts) {
        var _this2 = this;
        var refsByName, bbi2, cirTreeOffset, isBigEndian, signal, chrId, request, _yield$this$cirTreePr, buffer2, cirBlockSize, blocksToFetch, outstanding, cirFobRecur2, filterFeats, cirFobStartFetch, cirFobRecur;
        return _regenerator$3.default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.prev = 0;
                refsByName = this.refsByName, bbi2 = this.bbi, cirTreeOffset = this.cirTreeOffset, isBigEndian = this.isBigEndian;
                signal = opts.signal;
                chrId = refsByName[chrName];
                if (chrId === void 0) {
                  observer.complete();
                }
                request = {
                  chrId,
                  start,
                  end
                };
                if (!this.cirTreePromise) {
                  this.cirTreePromise = bbi2.read(Buffer.alloc(48), 0, 48, cirTreeOffset, {
                    signal
                  });
                }
                _context3.next = 9;
                return this.cirTreePromise;
              case 9:
                _yield$this$cirTreePr = _context3.sent;
                buffer2 = _yield$this$cirTreePr.buffer;
                cirBlockSize = isBigEndian ? buffer2.readUInt32BE(4) : buffer2.readUInt32LE(4);
                blocksToFetch = [];
                outstanding = 0;
                filterFeats = function filterFeats2(b) {
                  return (b.startChrom < chrId || b.startChrom === chrId && b.startBase <= end) && (b.endChrom > chrId || b.endChrom === chrId && b.endBase >= start);
                };
                cirFobStartFetch = /* @__PURE__ */ function() {
                  var _ref = (0, _asyncToGenerator2$3.default)(/* @__PURE__ */ _regenerator$3.default.mark(function _callee2(off, fr, level) {
                    var length, offset, resultBuffer, i;
                    return _regenerator$3.default.wrap(function _callee2$(_context2) {
                      while (1) {
                        switch (_context2.prev = _context2.next) {
                          case 0:
                            _context2.prev = 0;
                            length = fr.max() - fr.min();
                            offset = fr.min();
                            _context2.next = 5;
                            return _this2.featureCache.get("".concat(length, "_").concat(offset), {
                              length,
                              offset
                            }, signal);
                          case 5:
                            resultBuffer = _context2.sent;
                            for (i = 0; i < off.length; i += 1) {
                              if (fr.contains(off[i])) {
                                cirFobRecur2(resultBuffer, off[i] - offset, level, observer, opts);
                                outstanding -= 1;
                                if (outstanding === 0) {
                                  _this2.readFeatures(observer, blocksToFetch, _objectSpread$2(_objectSpread$2({}, opts), {}, {
                                    request
                                  }));
                                }
                              }
                            }
                            _context2.next = 12;
                            break;
                          case 9:
                            _context2.prev = 9;
                            _context2.t0 = _context2["catch"](0);
                            observer.error(_context2.t0);
                          case 12:
                          case "end":
                            return _context2.stop();
                        }
                      }
                    }, _callee2, null, [[0, 9]]);
                  }));
                  return function cirFobStartFetch2(_x8, _x9, _x10) {
                    return _ref.apply(this, arguments);
                  };
                }();
                cirFobRecur = function cirFobRecur3(offset, level) {
                  try {
                    outstanding += offset.length;
                    var maxCirBlockSpan = 4 + cirBlockSize * 32;
                    var spans = new _range.default(offset[0], offset[0] + maxCirBlockSpan);
                    for (var i = 1; i < offset.length; i += 1) {
                      var blockSpan = new _range.default(offset[i], offset[i] + maxCirBlockSpan);
                      spans = spans.union(blockSpan);
                    }
                    spans.getRanges().map(function(fr) {
                      return cirFobStartFetch(offset, fr, level);
                    });
                  } catch (e) {
                    observer.error(e);
                  }
                };
                cirFobRecur2 = function cirFobRecur22(cirBlockData, offset, level) {
                  try {
                    var data2 = cirBlockData.slice(offset);
                    var p = _this2.leafParser.parse(data2).result;
                    if (p.blocksToFetch) {
                      blocksToFetch = blocksToFetch.concat(p.blocksToFetch.filter(filterFeats).map(function(l) {
                        return {
                          offset: l.blockOffset,
                          length: l.blockSize
                        };
                      }));
                    }
                    if (p.recurOffsets) {
                      var recurOffsets = p.recurOffsets.filter(filterFeats).map(function(l) {
                        return l.blockOffset;
                      });
                      if (recurOffsets.length > 0) {
                        cirFobRecur(recurOffsets, level + 1);
                      }
                    }
                  } catch (e) {
                    observer.error(e);
                  }
                };
                return _context3.abrupt("return", cirFobRecur([cirTreeOffset + 48], 1));
              case 21:
                _context3.prev = 21;
                _context3.t0 = _context3["catch"](0);
                observer.error(_context3.t0);
              case 24:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this, [[0, 21]]);
      }));
      function readWigData(_x3, _x4, _x5, _x6, _x7) {
        return _readWigData.apply(this, arguments);
      }
      return readWigData;
    }()
  }, {
    key: "parseSummaryBlock",
    value: function parseSummaryBlock(data2, startOffset, request) {
      var features = [];
      var currOffset = startOffset;
      while (currOffset < data2.byteLength) {
        var res = this.summaryParser.parse(data2.slice(currOffset));
        features.push(res.result);
        currOffset += res.offset;
      }
      var items2 = features;
      if (request)
        items2 = items2.filter(function(elt) {
          return elt.chromId === request.chrId;
        });
      items2 = items2.map(function(elt) {
        return {
          start: elt.start,
          end: elt.end,
          maxScore: elt.maxScore,
          minScore: elt.minScore,
          score: elt.sumData / (elt.validCnt || 1),
          summary: true
        };
      });
      return request ? items2.filter(function(f2) {
        return BlockView2.coordFilter(f2, request);
      }) : items2;
    }
  }, {
    key: "parseBigBedBlock",
    value: function parseBigBedBlock(data2, startOffset, offset, request) {
      var items2 = [];
      var currOffset = startOffset;
      while (currOffset < data2.byteLength) {
        var res = this.bigBedParser.parse(data2.slice(currOffset));
        res.result.uniqueId = "bb-".concat(offset + currOffset);
        items2.push(res.result);
        currOffset += res.offset;
      }
      return request ? items2.filter(function(f2) {
        return BlockView2.coordFilter(f2, request);
      }) : items2;
    }
  }, {
    key: "parseBigWigBlock",
    value: function parseBigWigBlock(bytes, startOffset, request) {
      var data2 = bytes.slice(startOffset);
      var results = this.bigWigParser.parse(data2).result;
      var items2 = results.items, itemSpan = results.itemSpan, itemStep = results.itemStep, blockStart = results.blockStart, blockType = results.blockType;
      if (blockType === BIG_WIG_TYPE_FSTEP) {
        for (var i = 0; i < items2.length; i++) {
          items2[i].start = blockStart + i * itemStep;
          items2[i].end = blockStart + i * itemStep + itemSpan;
        }
      } else if (blockType === BIG_WIG_TYPE_VSTEP) {
        for (var _i = 0; _i < items2.length; _i++) {
          items2[_i].end = items2[_i].start + itemSpan;
        }
      }
      return request ? items2.filter(function(f2) {
        return BlockView2.coordFilter(f2, request);
      }) : items2;
    }
  }, {
    key: "readFeatures",
    value: function() {
      var _readFeatures = (0, _asyncToGenerator2$3.default)(/* @__PURE__ */ _regenerator$3.default.mark(function _callee5(observer, blocks) {
        var _this3 = this;
        var opts, blockType, isCompressed, signal, request, blockGroupsToFetch, _args5 = arguments;
        return _regenerator$3.default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                opts = _args5.length > 2 && _args5[2] !== void 0 ? _args5[2] : {};
                _context5.prev = 1;
                blockType = this.blockType, isCompressed = this.isCompressed;
                signal = opts.signal, request = opts.request;
                blockGroupsToFetch = (0, _util.groupBlocks)(blocks);
                (0, _util.checkAbortSignal)(signal);
                _context5.next = 8;
                return Promise.all(blockGroupsToFetch.map(/* @__PURE__ */ function() {
                  var _ref2 = (0, _asyncToGenerator2$3.default)(/* @__PURE__ */ _regenerator$3.default.mark(function _callee4(blockGroup) {
                    var length, offset, data2;
                    return _regenerator$3.default.wrap(function _callee4$(_context4) {
                      while (1) {
                        switch (_context4.prev = _context4.next) {
                          case 0:
                            (0, _util.checkAbortSignal)(signal);
                            length = blockGroup.length, offset = blockGroup.offset;
                            _context4.next = 4;
                            return _this3.featureCache.get("".concat(length, "_").concat(offset), blockGroup, signal);
                          case 4:
                            data2 = _context4.sent;
                            blockGroup.blocks.forEach(function(block) {
                              (0, _util.checkAbortSignal)(signal);
                              var blockOffset = block.offset - blockGroup.offset;
                              var resultData = data2;
                              if (isCompressed) {
                                resultData = _zlib.default.inflateSync(data2.slice(blockOffset));
                                blockOffset = 0;
                              }
                              (0, _util.checkAbortSignal)(signal);
                              switch (blockType) {
                                case "summary":
                                  observer.next(_this3.parseSummaryBlock(resultData, blockOffset, request));
                                  break;
                                case "bigwig":
                                  observer.next(_this3.parseBigWigBlock(resultData, blockOffset, request));
                                  break;
                                case "bigbed":
                                  observer.next(_this3.parseBigBedBlock(resultData, blockOffset, block.offset * (1 << 8), request));
                                  break;
                                default:
                                  console.warn("Don't know what to do with ".concat(blockType));
                              }
                            });
                          case 6:
                          case "end":
                            return _context4.stop();
                        }
                      }
                    }, _callee4);
                  }));
                  return function(_x13) {
                    return _ref2.apply(this, arguments);
                  };
                }()));
              case 8:
                observer.complete();
                _context5.next = 14;
                break;
              case 11:
                _context5.prev = 11;
                _context5.t0 = _context5["catch"](1);
                observer.error(_context5.t0);
              case 14:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this, [[1, 11]]);
      }));
      function readFeatures(_x11, _x12) {
        return _readFeatures.apply(this, arguments);
      }
      return readFeatures;
    }()
  }], [{
    key: "coordFilter",
    value: function coordFilter(f2, range2) {
      return f2.start < range2.end && f2.end >= range2.start;
    }
  }]);
  return BlockView2;
}();
blockView.BlockView = BlockView;
var bbi = {};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2)
      if (b2.hasOwnProperty(p))
        d2[p] = b2[p];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function gosling_es_isFunction(x) {
  return typeof x === "function";
}
var _enable_super_gross_mode_that_will_cause_bad_things = false;
var config = {
  Promise: void 0,
  set useDeprecatedSynchronousErrorHandling(value) {
    if (value) {
      var error = /* @__PURE__ */ new Error();
      /* @__PURE__ */ console.warn("DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n" + error.stack);
    }
    _enable_super_gross_mode_that_will_cause_bad_things = value;
  },
  get useDeprecatedSynchronousErrorHandling() {
    return _enable_super_gross_mode_that_will_cause_bad_things;
  }
};
function hostReportError(err) {
  setTimeout(function() {
    throw err;
  }, 0);
}
var empty$1 = {
  closed: true,
  next: function(value) {
  },
  error: function(err) {
    if (config.useDeprecatedSynchronousErrorHandling) {
      throw err;
    } else {
      hostReportError(err);
    }
  },
  complete: function() {
  }
};
var gosling_es_isArray = /* @__PURE__ */ function() {
  return Array.isArray || function(x) {
    return x && typeof x.length === "number";
  };
}();
function gosling_es_isObject(x) {
  return x !== null && typeof x === "object";
}
var UnsubscriptionErrorImpl = /* @__PURE__ */ function() {
  function UnsubscriptionErrorImpl2(errors) {
    Error.call(this);
    this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
      return i + 1 + ") " + err.toString();
    }).join("\n  ") : "";
    this.name = "UnsubscriptionError";
    this.errors = errors;
    return this;
  }
  UnsubscriptionErrorImpl2.prototype = /* @__PURE__ */ Object.create(Error.prototype);
  return UnsubscriptionErrorImpl2;
}();
var UnsubscriptionError = UnsubscriptionErrorImpl;
var Subscription = /* @__PURE__ */ function() {
  function Subscription2(unsubscribe) {
    this.closed = false;
    this._parentOrParents = null;
    this._subscriptions = null;
    if (unsubscribe) {
      this._ctorUnsubscribe = true;
      this._unsubscribe = unsubscribe;
    }
  }
  Subscription2.prototype.unsubscribe = function() {
    var errors;
    if (this.closed) {
      return;
    }
    var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
    this.closed = true;
    this._parentOrParents = null;
    this._subscriptions = null;
    if (_parentOrParents instanceof Subscription2) {
      _parentOrParents.remove(this);
    } else if (_parentOrParents !== null) {
      for (var index = 0; index < _parentOrParents.length; ++index) {
        var parent_1 = _parentOrParents[index];
        parent_1.remove(this);
      }
    }
    if (gosling_es_isFunction(_unsubscribe)) {
      if (_ctorUnsubscribe) {
        this._unsubscribe = void 0;
      }
      try {
        _unsubscribe.call(this);
      } catch (e) {
        errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
      }
    }
    if (gosling_es_isArray(_subscriptions)) {
      var index = -1;
      var len = _subscriptions.length;
      while (++index < len) {
        var sub = _subscriptions[index];
        if (gosling_es_isObject(sub)) {
          try {
            sub.unsubscribe();
          } catch (e) {
            errors = errors || [];
            if (e instanceof UnsubscriptionError) {
              errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
            } else {
              errors.push(e);
            }
          }
        }
      }
    }
    if (errors) {
      throw new UnsubscriptionError(errors);
    }
  };
  Subscription2.prototype.add = function(teardown) {
    var subscription = teardown;
    if (!teardown) {
      return Subscription2.EMPTY;
    }
    switch (typeof teardown) {
      case "function":
        subscription = new Subscription2(teardown);
      case "object":
        if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== "function") {
          return subscription;
        } else if (this.closed) {
          subscription.unsubscribe();
          return subscription;
        } else if (!(subscription instanceof Subscription2)) {
          var tmp = subscription;
          subscription = new Subscription2();
          subscription._subscriptions = [tmp];
        }
        break;
      default: {
        throw new Error("unrecognized teardown " + teardown + " added to Subscription.");
      }
    }
    var _parentOrParents = subscription._parentOrParents;
    if (_parentOrParents === null) {
      subscription._parentOrParents = this;
    } else if (_parentOrParents instanceof Subscription2) {
      if (_parentOrParents === this) {
        return subscription;
      }
      subscription._parentOrParents = [_parentOrParents, this];
    } else if (_parentOrParents.indexOf(this) === -1) {
      _parentOrParents.push(this);
    } else {
      return subscription;
    }
    var subscriptions = this._subscriptions;
    if (subscriptions === null) {
      this._subscriptions = [subscription];
    } else {
      subscriptions.push(subscription);
    }
    return subscription;
  };
  Subscription2.prototype.remove = function(subscription) {
    var subscriptions = this._subscriptions;
    if (subscriptions) {
      var subscriptionIndex = subscriptions.indexOf(subscription);
      if (subscriptionIndex !== -1) {
        subscriptions.splice(subscriptionIndex, 1);
      }
    }
  };
  Subscription2.EMPTY = function(empty2) {
    empty2.closed = true;
    return empty2;
  }(new Subscription2());
  return Subscription2;
}();
function flattenUnsubscriptionErrors(errors) {
  return errors.reduce(function(errs, err) {
    return errs.concat(err instanceof UnsubscriptionError ? err.errors : err);
  }, []);
}
var rxSubscriber = /* @__PURE__ */ function() {
  return typeof Symbol === "function" ? /* @__PURE__ */ Symbol("rxSubscriber") : "@@rxSubscriber_" + /* @__PURE__ */ Math.random();
}();
var Subscriber = /* @__PURE__ */ function(_super) {
  __extends(Subscriber2, _super);
  function Subscriber2(destinationOrNext, error, complete) {
    var _this = _super.call(this) || this;
    _this.syncErrorValue = null;
    _this.syncErrorThrown = false;
    _this.syncErrorThrowable = false;
    _this.isStopped = false;
    switch (arguments.length) {
      case 0:
        _this.destination = empty$1;
        break;
      case 1:
        if (!destinationOrNext) {
          _this.destination = empty$1;
          break;
        }
        if (typeof destinationOrNext === "object") {
          if (destinationOrNext instanceof Subscriber2) {
            _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
            _this.destination = destinationOrNext;
            destinationOrNext.add(_this);
          } else {
            _this.syncErrorThrowable = true;
            _this.destination = new SafeSubscriber(_this, destinationOrNext);
          }
          break;
        }
      default:
        _this.syncErrorThrowable = true;
        _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
        break;
    }
    return _this;
  }
  Subscriber2.prototype[rxSubscriber] = function() {
    return this;
  };
  Subscriber2.create = function(next, error, complete) {
    var subscriber = new Subscriber2(next, error, complete);
    subscriber.syncErrorThrowable = false;
    return subscriber;
  };
  Subscriber2.prototype.next = function(value) {
    if (!this.isStopped) {
      this._next(value);
    }
  };
  Subscriber2.prototype.error = function(err) {
    if (!this.isStopped) {
      this.isStopped = true;
      this._error(err);
    }
  };
  Subscriber2.prototype.complete = function() {
    if (!this.isStopped) {
      this.isStopped = true;
      this._complete();
    }
  };
  Subscriber2.prototype.unsubscribe = function() {
    if (this.closed) {
      return;
    }
    this.isStopped = true;
    _super.prototype.unsubscribe.call(this);
  };
  Subscriber2.prototype._next = function(value) {
    this.destination.next(value);
  };
  Subscriber2.prototype._error = function(err) {
    this.destination.error(err);
    this.unsubscribe();
  };
  Subscriber2.prototype._complete = function() {
    this.destination.complete();
    this.unsubscribe();
  };
  Subscriber2.prototype._unsubscribeAndRecycle = function() {
    var _parentOrParents = this._parentOrParents;
    this._parentOrParents = null;
    this.unsubscribe();
    this.closed = false;
    this.isStopped = false;
    this._parentOrParents = _parentOrParents;
    return this;
  };
  return Subscriber2;
}(Subscription);
var SafeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SafeSubscriber2, _super);
  function SafeSubscriber2(_parentSubscriber, observerOrNext, error, complete) {
    var _this = _super.call(this) || this;
    _this._parentSubscriber = _parentSubscriber;
    var next;
    var context2 = _this;
    if (gosling_es_isFunction(observerOrNext)) {
      next = observerOrNext;
    } else if (observerOrNext) {
      next = observerOrNext.next;
      error = observerOrNext.error;
      complete = observerOrNext.complete;
      if (observerOrNext !== empty$1) {
        context2 = Object.create(observerOrNext);
        if (gosling_es_isFunction(context2.unsubscribe)) {
          _this.add(context2.unsubscribe.bind(context2));
        }
        context2.unsubscribe = _this.unsubscribe.bind(_this);
      }
    }
    _this._context = context2;
    _this._next = next;
    _this._error = error;
    _this._complete = complete;
    return _this;
  }
  SafeSubscriber2.prototype.next = function(value) {
    if (!this.isStopped && this._next) {
      var _parentSubscriber = this._parentSubscriber;
      if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
        this.__tryOrUnsub(this._next, value);
      } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
        this.unsubscribe();
      }
    }
  };
  SafeSubscriber2.prototype.error = function(err) {
    if (!this.isStopped) {
      var _parentSubscriber = this._parentSubscriber;
      var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;
      if (this._error) {
        if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
          this.__tryOrUnsub(this._error, err);
          this.unsubscribe();
        } else {
          this.__tryOrSetError(_parentSubscriber, this._error, err);
          this.unsubscribe();
        }
      } else if (!_parentSubscriber.syncErrorThrowable) {
        this.unsubscribe();
        if (useDeprecatedSynchronousErrorHandling) {
          throw err;
        }
        hostReportError(err);
      } else {
        if (useDeprecatedSynchronousErrorHandling) {
          _parentSubscriber.syncErrorValue = err;
          _parentSubscriber.syncErrorThrown = true;
        } else {
          hostReportError(err);
        }
        this.unsubscribe();
      }
    }
  };
  SafeSubscriber2.prototype.complete = function() {
    var _this = this;
    if (!this.isStopped) {
      var _parentSubscriber = this._parentSubscriber;
      if (this._complete) {
        var wrappedComplete = function() {
          return _this._complete.call(_this._context);
        };
        if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
          this.__tryOrUnsub(wrappedComplete);
          this.unsubscribe();
        } else {
          this.__tryOrSetError(_parentSubscriber, wrappedComplete);
          this.unsubscribe();
        }
      } else {
        this.unsubscribe();
      }
    }
  };
  SafeSubscriber2.prototype.__tryOrUnsub = function(fn, value) {
    try {
      fn.call(this._context, value);
    } catch (err) {
      this.unsubscribe();
      if (config.useDeprecatedSynchronousErrorHandling) {
        throw err;
      } else {
        hostReportError(err);
      }
    }
  };
  SafeSubscriber2.prototype.__tryOrSetError = function(parent, fn, value) {
    if (!config.useDeprecatedSynchronousErrorHandling) {
      throw new Error("bad call");
    }
    try {
      fn.call(this._context, value);
    } catch (err) {
      if (config.useDeprecatedSynchronousErrorHandling) {
        parent.syncErrorValue = err;
        parent.syncErrorThrown = true;
        return true;
      } else {
        hostReportError(err);
        return true;
      }
    }
    return false;
  };
  SafeSubscriber2.prototype._unsubscribe = function() {
    var _parentSubscriber = this._parentSubscriber;
    this._context = null;
    this._parentSubscriber = null;
    _parentSubscriber.unsubscribe();
  };
  return SafeSubscriber2;
}(Subscriber);
function canReportError(observer) {
  while (observer) {
    var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
    if (closed_1 || isStopped) {
      return false;
    } else if (destination && destination instanceof Subscriber) {
      observer = destination;
    } else {
      observer = null;
    }
  }
  return true;
}
function toSubscriber(nextOrObserver, error, complete) {
  if (nextOrObserver) {
    if (nextOrObserver instanceof Subscriber) {
      return nextOrObserver;
    }
    if (nextOrObserver[rxSubscriber]) {
      return nextOrObserver[rxSubscriber]();
    }
  }
  if (!nextOrObserver && !error && !complete) {
    return new Subscriber(empty$1);
  }
  return new Subscriber(nextOrObserver, error, complete);
}
var observable = /* @__PURE__ */ function() {
  return typeof Symbol === "function" && Symbol.observable || "@@observable";
}();
function gosling_es_identity(x) {
  return x;
}
function pipe() {
  var fns = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    fns[_i] = arguments[_i];
  }
  return pipeFromArray(fns);
}
function pipeFromArray(fns) {
  if (fns.length === 0) {
    return gosling_es_identity;
  }
  if (fns.length === 1) {
    return fns[0];
  }
  return function piped(input) {
    return fns.reduce(function(prev, fn) {
      return fn(prev);
    }, input);
  };
}
var Observable = /* @__PURE__ */ function() {
  function Observable2(subscribe) {
    this._isScalar = false;
    if (subscribe) {
      this._subscribe = subscribe;
    }
  }
  Observable2.prototype.lift = function(operator) {
    var observable2 = new Observable2();
    observable2.source = this;
    observable2.operator = operator;
    return observable2;
  };
  Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
    var operator = this.operator;
    var sink = toSubscriber(observerOrNext, error, complete);
    if (operator) {
      sink.add(operator.call(sink, this.source));
    } else {
      sink.add(this.source || config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable ? this._subscribe(sink) : this._trySubscribe(sink));
    }
    if (config.useDeprecatedSynchronousErrorHandling) {
      if (sink.syncErrorThrowable) {
        sink.syncErrorThrowable = false;
        if (sink.syncErrorThrown) {
          throw sink.syncErrorValue;
        }
      }
    }
    return sink;
  };
  Observable2.prototype._trySubscribe = function(sink) {
    try {
      return this._subscribe(sink);
    } catch (err) {
      if (config.useDeprecatedSynchronousErrorHandling) {
        sink.syncErrorThrown = true;
        sink.syncErrorValue = err;
      }
      if (canReportError(sink)) {
        sink.error(err);
      } else {
        console.warn(err);
      }
    }
  };
  Observable2.prototype.forEach = function(next, promiseCtor) {
    var _this = this;
    promiseCtor = getPromiseCtor(promiseCtor);
    return new promiseCtor(function(resolve2, reject) {
      var subscription;
      subscription = _this.subscribe(function(value) {
        try {
          next(value);
        } catch (err) {
          reject(err);
          if (subscription) {
            subscription.unsubscribe();
          }
        }
      }, reject, resolve2);
    });
  };
  Observable2.prototype._subscribe = function(subscriber) {
    var source = this.source;
    return source && source.subscribe(subscriber);
  };
  Observable2.prototype[observable] = function() {
    return this;
  };
  Observable2.prototype.pipe = function() {
    var operations = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      operations[_i] = arguments[_i];
    }
    if (operations.length === 0) {
      return this;
    }
    return pipeFromArray(operations)(this);
  };
  Observable2.prototype.toPromise = function(promiseCtor) {
    var _this = this;
    promiseCtor = getPromiseCtor(promiseCtor);
    return new promiseCtor(function(resolve2, reject) {
      var value;
      _this.subscribe(function(x) {
        return value = x;
      }, function(err) {
        return reject(err);
      }, function() {
        return resolve2(value);
      });
    });
  };
  Observable2.create = function(subscribe) {
    return new Observable2(subscribe);
  };
  return Observable2;
}();
function getPromiseCtor(promiseCtor) {
  if (!promiseCtor) {
    promiseCtor = config.Promise || Promise;
  }
  if (!promiseCtor) {
    throw new Error("no Promise impl found");
  }
  return promiseCtor;
}
var ObjectUnsubscribedErrorImpl = /* @__PURE__ */ function() {
  function ObjectUnsubscribedErrorImpl2() {
    Error.call(this);
    this.message = "object unsubscribed";
    this.name = "ObjectUnsubscribedError";
    return this;
  }
  ObjectUnsubscribedErrorImpl2.prototype = /* @__PURE__ */ Object.create(Error.prototype);
  return ObjectUnsubscribedErrorImpl2;
}();
var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
var SubjectSubscription = /* @__PURE__ */ function(_super) {
  __extends(SubjectSubscription2, _super);
  function SubjectSubscription2(subject, subscriber) {
    var _this = _super.call(this) || this;
    _this.subject = subject;
    _this.subscriber = subscriber;
    _this.closed = false;
    return _this;
  }
  SubjectSubscription2.prototype.unsubscribe = function() {
    if (this.closed) {
      return;
    }
    this.closed = true;
    var subject = this.subject;
    var observers = subject.observers;
    this.subject = null;
    if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
      return;
    }
    var subscriberIndex = observers.indexOf(this.subscriber);
    if (subscriberIndex !== -1) {
      observers.splice(subscriberIndex, 1);
    }
  };
  return SubjectSubscription2;
}(Subscription);
var SubjectSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SubjectSubscriber2, _super);
  function SubjectSubscriber2(destination) {
    var _this = _super.call(this, destination) || this;
    _this.destination = destination;
    return _this;
  }
  return SubjectSubscriber2;
}(Subscriber);
var Subject = /* @__PURE__ */ function(_super) {
  __extends(Subject2, _super);
  function Subject2() {
    var _this = _super.call(this) || this;
    _this.observers = [];
    _this.closed = false;
    _this.isStopped = false;
    _this.hasError = false;
    _this.thrownError = null;
    return _this;
  }
  Subject2.prototype[rxSubscriber] = function() {
    return new SubjectSubscriber(this);
  };
  Subject2.prototype.lift = function(operator) {
    var subject = new AnonymousSubject(this, this);
    subject.operator = operator;
    return subject;
  };
  Subject2.prototype.next = function(value) {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    }
    if (!this.isStopped) {
      var observers = this.observers;
      var len = observers.length;
      var copy2 = observers.slice();
      for (var i = 0; i < len; i++) {
        copy2[i].next(value);
      }
    }
  };
  Subject2.prototype.error = function(err) {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    }
    this.hasError = true;
    this.thrownError = err;
    this.isStopped = true;
    var observers = this.observers;
    var len = observers.length;
    var copy2 = observers.slice();
    for (var i = 0; i < len; i++) {
      copy2[i].error(err);
    }
    this.observers.length = 0;
  };
  Subject2.prototype.complete = function() {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    }
    this.isStopped = true;
    var observers = this.observers;
    var len = observers.length;
    var copy2 = observers.slice();
    for (var i = 0; i < len; i++) {
      copy2[i].complete();
    }
    this.observers.length = 0;
  };
  Subject2.prototype.unsubscribe = function() {
    this.isStopped = true;
    this.closed = true;
    this.observers = null;
  };
  Subject2.prototype._trySubscribe = function(subscriber) {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    } else {
      return _super.prototype._trySubscribe.call(this, subscriber);
    }
  };
  Subject2.prototype._subscribe = function(subscriber) {
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    } else if (this.hasError) {
      subscriber.error(this.thrownError);
      return Subscription.EMPTY;
    } else if (this.isStopped) {
      subscriber.complete();
      return Subscription.EMPTY;
    } else {
      this.observers.push(subscriber);
      return new SubjectSubscription(this, subscriber);
    }
  };
  Subject2.prototype.asObservable = function() {
    var observable2 = new Observable();
    observable2.source = this;
    return observable2;
  };
  Subject2.create = function(destination, source) {
    return new AnonymousSubject(destination, source);
  };
  return Subject2;
}(Observable);
var AnonymousSubject = /* @__PURE__ */ function(_super) {
  __extends(AnonymousSubject2, _super);
  function AnonymousSubject2(destination, source) {
    var _this = _super.call(this) || this;
    _this.destination = destination;
    _this.source = source;
    return _this;
  }
  AnonymousSubject2.prototype.next = function(value) {
    var destination = this.destination;
    if (destination && destination.next) {
      destination.next(value);
    }
  };
  AnonymousSubject2.prototype.error = function(err) {
    var destination = this.destination;
    if (destination && destination.error) {
      this.destination.error(err);
    }
  };
  AnonymousSubject2.prototype.complete = function() {
    var destination = this.destination;
    if (destination && destination.complete) {
      this.destination.complete();
    }
  };
  AnonymousSubject2.prototype._subscribe = function(subscriber) {
    var source = this.source;
    if (source) {
      return this.source.subscribe(subscriber);
    } else {
      return Subscription.EMPTY;
    }
  };
  return AnonymousSubject2;
}(Subject);
function refCount() {
  return function refCountOperatorFunction(source) {
    return source.lift(new RefCountOperator(source));
  };
}
var RefCountOperator = /* @__PURE__ */ function() {
  function RefCountOperator2(connectable) {
    this.connectable = connectable;
  }
  RefCountOperator2.prototype.call = function(subscriber, source) {
    var connectable = this.connectable;
    connectable._refCount++;
    var refCounter = new RefCountSubscriber(subscriber, connectable);
    var subscription = source.subscribe(refCounter);
    if (!refCounter.closed) {
      refCounter.connection = connectable.connect();
    }
    return subscription;
  };
  return RefCountOperator2;
}();
var RefCountSubscriber = /* @__PURE__ */ function(_super) {
  __extends(RefCountSubscriber2, _super);
  function RefCountSubscriber2(destination, connectable) {
    var _this = _super.call(this, destination) || this;
    _this.connectable = connectable;
    return _this;
  }
  RefCountSubscriber2.prototype._unsubscribe = function() {
    var connectable = this.connectable;
    if (!connectable) {
      this.connection = null;
      return;
    }
    this.connectable = null;
    var refCount2 = connectable._refCount;
    if (refCount2 <= 0) {
      this.connection = null;
      return;
    }
    connectable._refCount = refCount2 - 1;
    if (refCount2 > 1) {
      this.connection = null;
      return;
    }
    var connection = this.connection;
    var sharedConnection = connectable._connection;
    this.connection = null;
    if (sharedConnection && (!connection || sharedConnection === connection)) {
      sharedConnection.unsubscribe();
    }
  };
  return RefCountSubscriber2;
}(Subscriber);
var ConnectableObservable = /* @__PURE__ */ function(_super) {
  __extends(ConnectableObservable2, _super);
  function ConnectableObservable2(source, subjectFactory) {
    var _this = _super.call(this) || this;
    _this.source = source;
    _this.subjectFactory = subjectFactory;
    _this._refCount = 0;
    _this._isComplete = false;
    return _this;
  }
  ConnectableObservable2.prototype._subscribe = function(subscriber) {
    return this.getSubject().subscribe(subscriber);
  };
  ConnectableObservable2.prototype.getSubject = function() {
    var subject = this._subject;
    if (!subject || subject.isStopped) {
      this._subject = this.subjectFactory();
    }
    return this._subject;
  };
  ConnectableObservable2.prototype.connect = function() {
    var connection = this._connection;
    if (!connection) {
      this._isComplete = false;
      connection = this._connection = new Subscription();
      connection.add(this.source.subscribe(new ConnectableSubscriber(this.getSubject(), this)));
      if (connection.closed) {
        this._connection = null;
        connection = Subscription.EMPTY;
      }
    }
    return connection;
  };
  ConnectableObservable2.prototype.refCount = function() {
    return refCount()(this);
  };
  return ConnectableObservable2;
}(Observable);
var connectableObservableDescriptor = /* @__PURE__ */ function() {
  var connectableProto = ConnectableObservable.prototype;
  return {
    operator: { value: null },
    _refCount: { value: 0, writable: true },
    _subject: { value: null, writable: true },
    _connection: { value: null, writable: true },
    _subscribe: { value: connectableProto._subscribe },
    _isComplete: { value: connectableProto._isComplete, writable: true },
    getSubject: { value: connectableProto.getSubject },
    connect: { value: connectableProto.connect },
    refCount: { value: connectableProto.refCount }
  };
}();
var ConnectableSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ConnectableSubscriber2, _super);
  function ConnectableSubscriber2(destination, connectable) {
    var _this = _super.call(this, destination) || this;
    _this.connectable = connectable;
    return _this;
  }
  ConnectableSubscriber2.prototype._error = function(err) {
    this._unsubscribe();
    _super.prototype._error.call(this, err);
  };
  ConnectableSubscriber2.prototype._complete = function() {
    this.connectable._isComplete = true;
    this._unsubscribe();
    _super.prototype._complete.call(this);
  };
  ConnectableSubscriber2.prototype._unsubscribe = function() {
    var connectable = this.connectable;
    if (connectable) {
      this.connectable = null;
      var connection = connectable._connection;
      connectable._refCount = 0;
      connectable._subject = null;
      connectable._connection = null;
      if (connection) {
        connection.unsubscribe();
      }
    }
  };
  return ConnectableSubscriber2;
}(SubjectSubscriber);
function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) {
  return function(source) {
    return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
  };
}
var GroupByOperator = /* @__PURE__ */ function() {
  function GroupByOperator2(keySelector, elementSelector, durationSelector, subjectSelector) {
    this.keySelector = keySelector;
    this.elementSelector = elementSelector;
    this.durationSelector = durationSelector;
    this.subjectSelector = subjectSelector;
  }
  GroupByOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
  };
  return GroupByOperator2;
}();
var GroupBySubscriber = /* @__PURE__ */ function(_super) {
  __extends(GroupBySubscriber2, _super);
  function GroupBySubscriber2(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
    var _this = _super.call(this, destination) || this;
    _this.keySelector = keySelector;
    _this.elementSelector = elementSelector;
    _this.durationSelector = durationSelector;
    _this.subjectSelector = subjectSelector;
    _this.groups = null;
    _this.attemptedToUnsubscribe = false;
    _this.count = 0;
    return _this;
  }
  GroupBySubscriber2.prototype._next = function(value) {
    var key;
    try {
      key = this.keySelector(value);
    } catch (err) {
      this.error(err);
      return;
    }
    this._group(value, key);
  };
  GroupBySubscriber2.prototype._group = function(value, key) {
    var groups = this.groups;
    if (!groups) {
      groups = this.groups = new Map();
    }
    var group2 = groups.get(key);
    var element;
    if (this.elementSelector) {
      try {
        element = this.elementSelector(value);
      } catch (err) {
        this.error(err);
      }
    } else {
      element = value;
    }
    if (!group2) {
      group2 = this.subjectSelector ? this.subjectSelector() : new Subject();
      groups.set(key, group2);
      var groupedObservable = new GroupedObservable(key, group2, this);
      this.destination.next(groupedObservable);
      if (this.durationSelector) {
        var duration = void 0;
        try {
          duration = this.durationSelector(new GroupedObservable(key, group2));
        } catch (err) {
          this.error(err);
          return;
        }
        this.add(duration.subscribe(new GroupDurationSubscriber(key, group2, this)));
      }
    }
    if (!group2.closed) {
      group2.next(element);
    }
  };
  GroupBySubscriber2.prototype._error = function(err) {
    var groups = this.groups;
    if (groups) {
      groups.forEach(function(group2, key) {
        group2.error(err);
      });
      groups.clear();
    }
    this.destination.error(err);
  };
  GroupBySubscriber2.prototype._complete = function() {
    var groups = this.groups;
    if (groups) {
      groups.forEach(function(group2, key) {
        group2.complete();
      });
      groups.clear();
    }
    this.destination.complete();
  };
  GroupBySubscriber2.prototype.removeGroup = function(key) {
    this.groups.delete(key);
  };
  GroupBySubscriber2.prototype.unsubscribe = function() {
    if (!this.closed) {
      this.attemptedToUnsubscribe = true;
      if (this.count === 0) {
        _super.prototype.unsubscribe.call(this);
      }
    }
  };
  return GroupBySubscriber2;
}(Subscriber);
var GroupDurationSubscriber = /* @__PURE__ */ function(_super) {
  __extends(GroupDurationSubscriber2, _super);
  function GroupDurationSubscriber2(key, group2, parent) {
    var _this = _super.call(this, group2) || this;
    _this.key = key;
    _this.group = group2;
    _this.parent = parent;
    return _this;
  }
  GroupDurationSubscriber2.prototype._next = function(value) {
    this.complete();
  };
  GroupDurationSubscriber2.prototype._unsubscribe = function() {
    var _a = this, parent = _a.parent, key = _a.key;
    this.key = this.parent = null;
    if (parent) {
      parent.removeGroup(key);
    }
  };
  return GroupDurationSubscriber2;
}(Subscriber);
var GroupedObservable = /* @__PURE__ */ function(_super) {
  __extends(GroupedObservable2, _super);
  function GroupedObservable2(key, groupSubject, refCountSubscription) {
    var _this = _super.call(this) || this;
    _this.key = key;
    _this.groupSubject = groupSubject;
    _this.refCountSubscription = refCountSubscription;
    return _this;
  }
  GroupedObservable2.prototype._subscribe = function(subscriber) {
    var subscription = new Subscription();
    var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject;
    if (refCountSubscription && !refCountSubscription.closed) {
      subscription.add(new InnerRefCountSubscription(refCountSubscription));
    }
    subscription.add(groupSubject.subscribe(subscriber));
    return subscription;
  };
  return GroupedObservable2;
}(Observable);
var InnerRefCountSubscription = /* @__PURE__ */ function(_super) {
  __extends(InnerRefCountSubscription2, _super);
  function InnerRefCountSubscription2(parent) {
    var _this = _super.call(this) || this;
    _this.parent = parent;
    parent.count++;
    return _this;
  }
  InnerRefCountSubscription2.prototype.unsubscribe = function() {
    var parent = this.parent;
    if (!parent.closed && !this.closed) {
      _super.prototype.unsubscribe.call(this);
      parent.count -= 1;
      if (parent.count === 0 && parent.attemptedToUnsubscribe) {
        parent.unsubscribe();
      }
    }
  };
  return InnerRefCountSubscription2;
}(Subscription);
var BehaviorSubject = /* @__PURE__ */ function(_super) {
  __extends(BehaviorSubject2, _super);
  function BehaviorSubject2(_value) {
    var _this = _super.call(this) || this;
    _this._value = _value;
    return _this;
  }
  Object.defineProperty(BehaviorSubject2.prototype, "value", {
    get: function() {
      return this.getValue();
    },
    enumerable: true,
    configurable: true
  });
  BehaviorSubject2.prototype._subscribe = function(subscriber) {
    var subscription = _super.prototype._subscribe.call(this, subscriber);
    if (subscription && !subscription.closed) {
      subscriber.next(this._value);
    }
    return subscription;
  };
  BehaviorSubject2.prototype.getValue = function() {
    if (this.hasError) {
      throw this.thrownError;
    } else if (this.closed) {
      throw new ObjectUnsubscribedError();
    } else {
      return this._value;
    }
  };
  BehaviorSubject2.prototype.next = function(value) {
    _super.prototype.next.call(this, this._value = value);
  };
  return BehaviorSubject2;
}(Subject);
var Action = /* @__PURE__ */ function(_super) {
  __extends(Action2, _super);
  function Action2(scheduler, work) {
    return _super.call(this) || this;
  }
  Action2.prototype.schedule = function(state, delay2) {
    return this;
  };
  return Action2;
}(Subscription);
var AsyncAction = /* @__PURE__ */ function(_super) {
  __extends(AsyncAction2, _super);
  function AsyncAction2(scheduler, work) {
    var _this = _super.call(this, scheduler, work) || this;
    _this.scheduler = scheduler;
    _this.work = work;
    _this.pending = false;
    return _this;
  }
  AsyncAction2.prototype.schedule = function(state, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (this.closed) {
      return this;
    }
    this.state = state;
    var id = this.id;
    var scheduler = this.scheduler;
    if (id != null) {
      this.id = this.recycleAsyncId(scheduler, id, delay2);
    }
    this.pending = true;
    this.delay = delay2;
    this.id = this.id || this.requestAsyncId(scheduler, this.id, delay2);
    return this;
  };
  AsyncAction2.prototype.requestAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    return setInterval(scheduler.flush.bind(scheduler, this), delay2);
  };
  AsyncAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 !== null && this.delay === delay2 && this.pending === false) {
      return id;
    }
    clearInterval(id);
    return void 0;
  };
  AsyncAction2.prototype.execute = function(state, delay2) {
    if (this.closed) {
      return new Error("executing a cancelled action");
    }
    this.pending = false;
    var error = this._execute(state, delay2);
    if (error) {
      return error;
    } else if (this.pending === false && this.id != null) {
      this.id = this.recycleAsyncId(this.scheduler, this.id, null);
    }
  };
  AsyncAction2.prototype._execute = function(state, delay2) {
    var errored = false;
    var errorValue = void 0;
    try {
      this.work(state);
    } catch (e) {
      errored = true;
      errorValue = !!e && e || new Error(e);
    }
    if (errored) {
      this.unsubscribe();
      return errorValue;
    }
  };
  AsyncAction2.prototype._unsubscribe = function() {
    var id = this.id;
    var scheduler = this.scheduler;
    var actions = scheduler.actions;
    var index = actions.indexOf(this);
    this.work = null;
    this.state = null;
    this.pending = false;
    this.scheduler = null;
    if (index !== -1) {
      actions.splice(index, 1);
    }
    if (id != null) {
      this.id = this.recycleAsyncId(scheduler, id, null);
    }
    this.delay = null;
  };
  return AsyncAction2;
}(Action);
var QueueAction = /* @__PURE__ */ function(_super) {
  __extends(QueueAction2, _super);
  function QueueAction2(scheduler, work) {
    var _this = _super.call(this, scheduler, work) || this;
    _this.scheduler = scheduler;
    _this.work = work;
    return _this;
  }
  QueueAction2.prototype.schedule = function(state, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 > 0) {
      return _super.prototype.schedule.call(this, state, delay2);
    }
    this.delay = delay2;
    this.state = state;
    this.scheduler.flush(this);
    return this;
  };
  QueueAction2.prototype.execute = function(state, delay2) {
    return delay2 > 0 || this.closed ? _super.prototype.execute.call(this, state, delay2) : this._execute(state, delay2);
  };
  QueueAction2.prototype.requestAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 !== null && delay2 > 0 || delay2 === null && this.delay > 0) {
      return _super.prototype.requestAsyncId.call(this, scheduler, id, delay2);
    }
    return scheduler.flush(this);
  };
  return QueueAction2;
}(AsyncAction);
var Scheduler = /* @__PURE__ */ function() {
  function Scheduler2(SchedulerAction, now) {
    if (now === void 0) {
      now = Scheduler2.now;
    }
    this.SchedulerAction = SchedulerAction;
    this.now = now;
  }
  Scheduler2.prototype.schedule = function(work, delay2, state) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    return new this.SchedulerAction(this, work).schedule(state, delay2);
  };
  Scheduler2.now = function() {
    return Date.now();
  };
  return Scheduler2;
}();
var AsyncScheduler = /* @__PURE__ */ function(_super) {
  __extends(AsyncScheduler2, _super);
  function AsyncScheduler2(SchedulerAction, now) {
    if (now === void 0) {
      now = Scheduler.now;
    }
    var _this = _super.call(this, SchedulerAction, function() {
      if (AsyncScheduler2.delegate && AsyncScheduler2.delegate !== _this) {
        return AsyncScheduler2.delegate.now();
      } else {
        return now();
      }
    }) || this;
    _this.actions = [];
    _this.active = false;
    _this.scheduled = void 0;
    return _this;
  }
  AsyncScheduler2.prototype.schedule = function(work, delay2, state) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (AsyncScheduler2.delegate && AsyncScheduler2.delegate !== this) {
      return AsyncScheduler2.delegate.schedule(work, delay2, state);
    } else {
      return _super.prototype.schedule.call(this, work, delay2, state);
    }
  };
  AsyncScheduler2.prototype.flush = function(action) {
    var actions = this.actions;
    if (this.active) {
      actions.push(action);
      return;
    }
    var error;
    this.active = true;
    do {
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    } while (action = actions.shift());
    this.active = false;
    if (error) {
      while (action = actions.shift()) {
        action.unsubscribe();
      }
      throw error;
    }
  };
  return AsyncScheduler2;
}(Scheduler);
var QueueScheduler = /* @__PURE__ */ function(_super) {
  __extends(QueueScheduler2, _super);
  function QueueScheduler2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  return QueueScheduler2;
}(AsyncScheduler);
var queueScheduler = /* @__PURE__ */ new QueueScheduler(QueueAction);
var queue = queueScheduler;
var EMPTY = /* @__PURE__ */ new Observable(function(subscriber) {
  return subscriber.complete();
});
function empty(scheduler) {
  return scheduler ? emptyScheduled(scheduler) : EMPTY;
}
function emptyScheduled(scheduler) {
  return new Observable(function(subscriber) {
    return scheduler.schedule(function() {
      return subscriber.complete();
    });
  });
}
function isScheduler(value) {
  return value && typeof value.schedule === "function";
}
var subscribeToArray = function(array) {
  return function(subscriber) {
    for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {
      subscriber.next(array[i]);
    }
    subscriber.complete();
  };
};
function scheduleArray(input, scheduler) {
  return new Observable(function(subscriber) {
    var sub = new Subscription();
    var i = 0;
    sub.add(scheduler.schedule(function() {
      if (i === input.length) {
        subscriber.complete();
        return;
      }
      subscriber.next(input[i++]);
      if (!subscriber.closed) {
        sub.add(this.schedule());
      }
    }));
    return sub;
  });
}
function fromArray(input, scheduler) {
  if (!scheduler) {
    return new Observable(subscribeToArray(input));
  } else {
    return scheduleArray(input, scheduler);
  }
}
function of() {
  var args = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    args[_i] = arguments[_i];
  }
  var scheduler = args[args.length - 1];
  if (isScheduler(scheduler)) {
    args.pop();
    return scheduleArray(args, scheduler);
  } else {
    return fromArray(args);
  }
}
function throwError(error, scheduler) {
  if (!scheduler) {
    return new Observable(function(subscriber) {
      return subscriber.error(error);
    });
  } else {
    return new Observable(function(subscriber) {
      return scheduler.schedule(dispatch$7, 0, { error, subscriber });
    });
  }
}
function dispatch$7(_a) {
  var error = _a.error, subscriber = _a.subscriber;
  subscriber.error(error);
}
var NotificationKind;
/* @__PURE__ */ (function(NotificationKind2) {
  NotificationKind2["NEXT"] = "N";
  NotificationKind2["ERROR"] = "E";
  NotificationKind2["COMPLETE"] = "C";
})(NotificationKind || (NotificationKind = {}));
var Notification = /* @__PURE__ */ function() {
  function Notification2(kind, value, error) {
    this.kind = kind;
    this.value = value;
    this.error = error;
    this.hasValue = kind === "N";
  }
  Notification2.prototype.observe = function(observer) {
    switch (this.kind) {
      case "N":
        return observer.next && observer.next(this.value);
      case "E":
        return observer.error && observer.error(this.error);
      case "C":
        return observer.complete && observer.complete();
    }
  };
  Notification2.prototype.do = function(next, error, complete) {
    var kind = this.kind;
    switch (kind) {
      case "N":
        return next && next(this.value);
      case "E":
        return error && error(this.error);
      case "C":
        return complete && complete();
    }
  };
  Notification2.prototype.accept = function(nextOrObserver, error, complete) {
    if (nextOrObserver && typeof nextOrObserver.next === "function") {
      return this.observe(nextOrObserver);
    } else {
      return this.do(nextOrObserver, error, complete);
    }
  };
  Notification2.prototype.toObservable = function() {
    var kind = this.kind;
    switch (kind) {
      case "N":
        return of(this.value);
      case "E":
        return throwError(this.error);
      case "C":
        return empty();
    }
    throw new Error("unexpected notification kind value");
  };
  Notification2.createNext = function(value) {
    if (typeof value !== "undefined") {
      return new Notification2("N", value);
    }
    return Notification2.undefinedValueNotification;
  };
  Notification2.createError = function(err) {
    return new Notification2("E", void 0, err);
  };
  Notification2.createComplete = function() {
    return Notification2.completeNotification;
  };
  Notification2.completeNotification = new Notification2("C");
  Notification2.undefinedValueNotification = new Notification2("N", void 0);
  return Notification2;
}();
function observeOn(scheduler, delay2) {
  if (delay2 === void 0) {
    delay2 = 0;
  }
  return function observeOnOperatorFunction(source) {
    return source.lift(new ObserveOnOperator(scheduler, delay2));
  };
}
var ObserveOnOperator = /* @__PURE__ */ function() {
  function ObserveOnOperator2(scheduler, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    this.scheduler = scheduler;
    this.delay = delay2;
  }
  ObserveOnOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
  };
  return ObserveOnOperator2;
}();
var ObserveOnSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ObserveOnSubscriber2, _super);
  function ObserveOnSubscriber2(destination, scheduler, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    var _this = _super.call(this, destination) || this;
    _this.scheduler = scheduler;
    _this.delay = delay2;
    return _this;
  }
  ObserveOnSubscriber2.dispatch = function(arg) {
    var notification = arg.notification, destination = arg.destination;
    notification.observe(destination);
    this.unsubscribe();
  };
  ObserveOnSubscriber2.prototype.scheduleMessage = function(notification) {
    var destination = this.destination;
    destination.add(this.scheduler.schedule(ObserveOnSubscriber2.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
  };
  ObserveOnSubscriber2.prototype._next = function(value) {
    this.scheduleMessage(Notification.createNext(value));
  };
  ObserveOnSubscriber2.prototype._error = function(err) {
    this.scheduleMessage(Notification.createError(err));
    this.unsubscribe();
  };
  ObserveOnSubscriber2.prototype._complete = function() {
    this.scheduleMessage(Notification.createComplete());
    this.unsubscribe();
  };
  return ObserveOnSubscriber2;
}(Subscriber);
var ObserveOnMessage = /* @__PURE__ */ function() {
  function ObserveOnMessage2(notification, destination) {
    this.notification = notification;
    this.destination = destination;
  }
  return ObserveOnMessage2;
}();
var ReplaySubject = /* @__PURE__ */ function(_super) {
  __extends(ReplaySubject2, _super);
  function ReplaySubject2(bufferSize, windowTime2, scheduler) {
    if (bufferSize === void 0) {
      bufferSize = Number.POSITIVE_INFINITY;
    }
    if (windowTime2 === void 0) {
      windowTime2 = Number.POSITIVE_INFINITY;
    }
    var _this = _super.call(this) || this;
    _this.scheduler = scheduler;
    _this._events = [];
    _this._infiniteTimeWindow = false;
    _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
    _this._windowTime = windowTime2 < 1 ? 1 : windowTime2;
    if (windowTime2 === Number.POSITIVE_INFINITY) {
      _this._infiniteTimeWindow = true;
      _this.next = _this.nextInfiniteTimeWindow;
    } else {
      _this.next = _this.nextTimeWindow;
    }
    return _this;
  }
  ReplaySubject2.prototype.nextInfiniteTimeWindow = function(value) {
    if (!this.isStopped) {
      var _events = this._events;
      _events.push(value);
      if (_events.length > this._bufferSize) {
        _events.shift();
      }
    }
    _super.prototype.next.call(this, value);
  };
  ReplaySubject2.prototype.nextTimeWindow = function(value) {
    if (!this.isStopped) {
      this._events.push(new ReplayEvent(this._getNow(), value));
      this._trimBufferThenGetEvents();
    }
    _super.prototype.next.call(this, value);
  };
  ReplaySubject2.prototype._subscribe = function(subscriber) {
    var _infiniteTimeWindow = this._infiniteTimeWindow;
    var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
    var scheduler = this.scheduler;
    var len = _events.length;
    var subscription;
    if (this.closed) {
      throw new ObjectUnsubscribedError();
    } else if (this.isStopped || this.hasError) {
      subscription = Subscription.EMPTY;
    } else {
      this.observers.push(subscriber);
      subscription = new SubjectSubscription(this, subscriber);
    }
    if (scheduler) {
      subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));
    }
    if (_infiniteTimeWindow) {
      for (var i = 0; i < len && !subscriber.closed; i++) {
        subscriber.next(_events[i]);
      }
    } else {
      for (var i = 0; i < len && !subscriber.closed; i++) {
        subscriber.next(_events[i].value);
      }
    }
    if (this.hasError) {
      subscriber.error(this.thrownError);
    } else if (this.isStopped) {
      subscriber.complete();
    }
    return subscription;
  };
  ReplaySubject2.prototype._getNow = function() {
    return (this.scheduler || queue).now();
  };
  ReplaySubject2.prototype._trimBufferThenGetEvents = function() {
    var now = this._getNow();
    var _bufferSize = this._bufferSize;
    var _windowTime = this._windowTime;
    var _events = this._events;
    var eventsCount = _events.length;
    var spliceCount = 0;
    while (spliceCount < eventsCount) {
      if (now - _events[spliceCount].time < _windowTime) {
        break;
      }
      spliceCount++;
    }
    if (eventsCount > _bufferSize) {
      spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
    }
    if (spliceCount > 0) {
      _events.splice(0, spliceCount);
    }
    return _events;
  };
  return ReplaySubject2;
}(Subject);
var ReplayEvent = /* @__PURE__ */ function() {
  function ReplayEvent2(time2, value) {
    this.time = time2;
    this.value = value;
  }
  return ReplayEvent2;
}();
var AsyncSubject = /* @__PURE__ */ function(_super) {
  __extends(AsyncSubject2, _super);
  function AsyncSubject2() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this.value = null;
    _this.hasNext = false;
    _this.hasCompleted = false;
    return _this;
  }
  AsyncSubject2.prototype._subscribe = function(subscriber) {
    if (this.hasError) {
      subscriber.error(this.thrownError);
      return Subscription.EMPTY;
    } else if (this.hasCompleted && this.hasNext) {
      subscriber.next(this.value);
      subscriber.complete();
      return Subscription.EMPTY;
    }
    return _super.prototype._subscribe.call(this, subscriber);
  };
  AsyncSubject2.prototype.next = function(value) {
    if (!this.hasCompleted) {
      this.value = value;
      this.hasNext = true;
    }
  };
  AsyncSubject2.prototype.error = function(error) {
    if (!this.hasCompleted) {
      _super.prototype.error.call(this, error);
    }
  };
  AsyncSubject2.prototype.complete = function() {
    this.hasCompleted = true;
    if (this.hasNext) {
      _super.prototype.next.call(this, this.value);
    }
    _super.prototype.complete.call(this);
  };
  return AsyncSubject2;
}(Subject);
var nextHandle = 1;
var RESOLVED = /* @__PURE__ */ function() {
  return /* @__PURE__ */ Promise.resolve();
}();
var activeHandles = {};
function findAndClearHandle(handle) {
  if (handle in activeHandles) {
    delete activeHandles[handle];
    return true;
  }
  return false;
}
var Immediate = {
  setImmediate: function(cb) {
    var handle = nextHandle++;
    activeHandles[handle] = true;
    RESOLVED.then(function() {
      return findAndClearHandle(handle) && cb();
    });
    return handle;
  },
  clearImmediate: function(handle) {
    findAndClearHandle(handle);
  }
};
var AsapAction = /* @__PURE__ */ function(_super) {
  __extends(AsapAction2, _super);
  function AsapAction2(scheduler, work) {
    var _this = _super.call(this, scheduler, work) || this;
    _this.scheduler = scheduler;
    _this.work = work;
    return _this;
  }
  AsapAction2.prototype.requestAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 !== null && delay2 > 0) {
      return _super.prototype.requestAsyncId.call(this, scheduler, id, delay2);
    }
    scheduler.actions.push(this);
    return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
  };
  AsapAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 !== null && delay2 > 0 || delay2 === null && this.delay > 0) {
      return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay2);
    }
    if (scheduler.actions.length === 0) {
      Immediate.clearImmediate(id);
      scheduler.scheduled = void 0;
    }
    return void 0;
  };
  return AsapAction2;
}(AsyncAction);
var AsapScheduler = /* @__PURE__ */ function(_super) {
  __extends(AsapScheduler2, _super);
  function AsapScheduler2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  AsapScheduler2.prototype.flush = function(action) {
    this.active = true;
    this.scheduled = void 0;
    var actions = this.actions;
    var error;
    var index = -1;
    var count2 = actions.length;
    action = action || actions.shift();
    do {
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    } while (++index < count2 && (action = actions.shift()));
    this.active = false;
    if (error) {
      while (++index < count2 && (action = actions.shift())) {
        action.unsubscribe();
      }
      throw error;
    }
  };
  return AsapScheduler2;
}(AsyncScheduler);
var asapScheduler = /* @__PURE__ */ new AsapScheduler(AsapAction);
var asap = asapScheduler;
var asyncScheduler = /* @__PURE__ */ new AsyncScheduler(AsyncAction);
var async$1 = asyncScheduler;
var AnimationFrameAction = /* @__PURE__ */ function(_super) {
  __extends(AnimationFrameAction2, _super);
  function AnimationFrameAction2(scheduler, work) {
    var _this = _super.call(this, scheduler, work) || this;
    _this.scheduler = scheduler;
    _this.work = work;
    return _this;
  }
  AnimationFrameAction2.prototype.requestAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 !== null && delay2 > 0) {
      return _super.prototype.requestAsyncId.call(this, scheduler, id, delay2);
    }
    scheduler.actions.push(this);
    return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function() {
      return scheduler.flush(null);
    }));
  };
  AnimationFrameAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (delay2 !== null && delay2 > 0 || delay2 === null && this.delay > 0) {
      return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay2);
    }
    if (scheduler.actions.length === 0) {
      cancelAnimationFrame(id);
      scheduler.scheduled = void 0;
    }
    return void 0;
  };
  return AnimationFrameAction2;
}(AsyncAction);
var AnimationFrameScheduler = /* @__PURE__ */ function(_super) {
  __extends(AnimationFrameScheduler2, _super);
  function AnimationFrameScheduler2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  AnimationFrameScheduler2.prototype.flush = function(action) {
    this.active = true;
    this.scheduled = void 0;
    var actions = this.actions;
    var error;
    var index = -1;
    var count2 = actions.length;
    action = action || actions.shift();
    do {
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    } while (++index < count2 && (action = actions.shift()));
    this.active = false;
    if (error) {
      while (++index < count2 && (action = actions.shift())) {
        action.unsubscribe();
      }
      throw error;
    }
  };
  return AnimationFrameScheduler2;
}(AsyncScheduler);
var animationFrameScheduler = /* @__PURE__ */ new AnimationFrameScheduler(AnimationFrameAction);
var animationFrame = animationFrameScheduler;
var VirtualTimeScheduler = /* @__PURE__ */ function(_super) {
  __extends(VirtualTimeScheduler2, _super);
  function VirtualTimeScheduler2(SchedulerAction, maxFrames) {
    if (SchedulerAction === void 0) {
      SchedulerAction = VirtualAction;
    }
    if (maxFrames === void 0) {
      maxFrames = Number.POSITIVE_INFINITY;
    }
    var _this = _super.call(this, SchedulerAction, function() {
      return _this.frame;
    }) || this;
    _this.maxFrames = maxFrames;
    _this.frame = 0;
    _this.index = -1;
    return _this;
  }
  VirtualTimeScheduler2.prototype.flush = function() {
    var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
    var error, action;
    while ((action = actions[0]) && action.delay <= maxFrames) {
      actions.shift();
      this.frame = action.delay;
      if (error = action.execute(action.state, action.delay)) {
        break;
      }
    }
    if (error) {
      while (action = actions.shift()) {
        action.unsubscribe();
      }
      throw error;
    }
  };
  VirtualTimeScheduler2.frameTimeFactor = 10;
  return VirtualTimeScheduler2;
}(AsyncScheduler);
var VirtualAction = /* @__PURE__ */ function(_super) {
  __extends(VirtualAction2, _super);
  function VirtualAction2(scheduler, work, index) {
    if (index === void 0) {
      index = scheduler.index += 1;
    }
    var _this = _super.call(this, scheduler, work) || this;
    _this.scheduler = scheduler;
    _this.work = work;
    _this.index = index;
    _this.active = true;
    _this.index = scheduler.index = index;
    return _this;
  }
  VirtualAction2.prototype.schedule = function(state, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (!this.id) {
      return _super.prototype.schedule.call(this, state, delay2);
    }
    this.active = false;
    var action = new VirtualAction2(this.scheduler, this.work);
    this.add(action);
    return action.schedule(state, delay2);
  };
  VirtualAction2.prototype.requestAsyncId = function(scheduler, id, delay2) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    this.delay = scheduler.frame + delay2;
    var actions = scheduler.actions;
    actions.push(this);
    actions.sort(VirtualAction2.sortActions);
    return true;
  };
  VirtualAction2.prototype.recycleAsyncId = function(scheduler, id, delay2) {
    return void 0;
  };
  VirtualAction2.prototype._execute = function(state, delay2) {
    if (this.active === true) {
      return _super.prototype._execute.call(this, state, delay2);
    }
  };
  VirtualAction2.sortActions = function(a, b) {
    if (a.delay === b.delay) {
      if (a.index === b.index) {
        return 0;
      } else if (a.index > b.index) {
        return 1;
      } else {
        return -1;
      }
    } else if (a.delay > b.delay) {
      return 1;
    } else {
      return -1;
    }
  };
  return VirtualAction2;
}(AsyncAction);
function noop$1() {
}
function isObservable(obj) {
  return !!obj && (obj instanceof Observable || typeof obj.lift === "function" && typeof obj.subscribe === "function");
}
var ArgumentOutOfRangeErrorImpl = /* @__PURE__ */ function() {
  function ArgumentOutOfRangeErrorImpl2() {
    Error.call(this);
    this.message = "argument out of range";
    this.name = "ArgumentOutOfRangeError";
    return this;
  }
  ArgumentOutOfRangeErrorImpl2.prototype = /* @__PURE__ */ Object.create(Error.prototype);
  return ArgumentOutOfRangeErrorImpl2;
}();
var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
var EmptyErrorImpl = /* @__PURE__ */ function() {
  function EmptyErrorImpl2() {
    Error.call(this);
    this.message = "no elements in sequence";
    this.name = "EmptyError";
    return this;
  }
  EmptyErrorImpl2.prototype = /* @__PURE__ */ Object.create(Error.prototype);
  return EmptyErrorImpl2;
}();
var EmptyError = EmptyErrorImpl;
var TimeoutErrorImpl = /* @__PURE__ */ function() {
  function TimeoutErrorImpl2() {
    Error.call(this);
    this.message = "Timeout has occurred";
    this.name = "TimeoutError";
    return this;
  }
  TimeoutErrorImpl2.prototype = /* @__PURE__ */ Object.create(Error.prototype);
  return TimeoutErrorImpl2;
}();
var TimeoutError = TimeoutErrorImpl;
function gosling_es_map(project, thisArg) {
  return function mapOperation(source) {
    if (typeof project !== "function") {
      throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");
    }
    return source.lift(new MapOperator(project, thisArg));
  };
}
var MapOperator = /* @__PURE__ */ function() {
  function MapOperator2(project, thisArg) {
    this.project = project;
    this.thisArg = thisArg;
  }
  MapOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
  };
  return MapOperator2;
}();
var MapSubscriber = /* @__PURE__ */ function(_super) {
  __extends(MapSubscriber2, _super);
  function MapSubscriber2(destination, project, thisArg) {
    var _this = _super.call(this, destination) || this;
    _this.project = project;
    _this.count = 0;
    _this.thisArg = thisArg || _this;
    return _this;
  }
  MapSubscriber2.prototype._next = function(value) {
    var result;
    try {
      result = this.project.call(this.thisArg, value, this.count++);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.destination.next(result);
  };
  return MapSubscriber2;
}(Subscriber);
function bindCallback(callbackFunc, resultSelector, scheduler) {
  if (resultSelector) {
    if (isScheduler(resultSelector)) {
      scheduler = resultSelector;
    } else {
      return function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(gosling_es_map(function(args2) {
          return gosling_es_isArray(args2) ? resultSelector.apply(void 0, args2) : resultSelector(args2);
        }));
      };
    }
  }
  return function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var context2 = this;
    var subject;
    var params = {
      context: context2,
      subject,
      callbackFunc,
      scheduler
    };
    return new Observable(function(subscriber) {
      if (!scheduler) {
        if (!subject) {
          subject = new AsyncSubject();
          var handler = function() {
            var innerArgs = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              innerArgs[_i2] = arguments[_i2];
            }
            subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
            subject.complete();
          };
          try {
            callbackFunc.apply(context2, args.concat([handler]));
          } catch (err) {
            if (canReportError(subject)) {
              subject.error(err);
            } else {
              console.warn(err);
            }
          }
        }
        return subject.subscribe(subscriber);
      } else {
        var state = {
          args,
          subscriber,
          params
        };
        return scheduler.schedule(dispatch$6, 0, state);
      }
    });
  };
}
function dispatch$6(state) {
  var _this = this;
  var args = state.args, subscriber = state.subscriber, params = state.params;
  var callbackFunc = params.callbackFunc, context2 = params.context, scheduler = params.scheduler;
  var subject = params.subject;
  if (!subject) {
    subject = params.subject = new AsyncSubject();
    var handler = function() {
      var innerArgs = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        innerArgs[_i] = arguments[_i];
      }
      var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
      _this.add(scheduler.schedule(dispatchNext$3, 0, { value, subject }));
    };
    try {
      callbackFunc.apply(context2, args.concat([handler]));
    } catch (err) {
      subject.error(err);
    }
  }
  this.add(subject.subscribe(subscriber));
}
function dispatchNext$3(state) {
  var value = state.value, subject = state.subject;
  subject.next(value);
  subject.complete();
}
function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
  if (resultSelector) {
    if (isScheduler(resultSelector)) {
      scheduler = resultSelector;
    } else {
      return function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(gosling_es_map(function(args2) {
          return gosling_es_isArray(args2) ? resultSelector.apply(void 0, args2) : resultSelector(args2);
        }));
      };
    }
  }
  return function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var params = {
      subject: void 0,
      args,
      callbackFunc,
      scheduler,
      context: this
    };
    return new Observable(function(subscriber) {
      var context2 = params.context;
      var subject = params.subject;
      if (!scheduler) {
        if (!subject) {
          subject = params.subject = new AsyncSubject();
          var handler = function() {
            var innerArgs = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              innerArgs[_i2] = arguments[_i2];
            }
            var err = innerArgs.shift();
            if (err) {
              subject.error(err);
              return;
            }
            subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
            subject.complete();
          };
          try {
            callbackFunc.apply(context2, args.concat([handler]));
          } catch (err) {
            if (canReportError(subject)) {
              subject.error(err);
            } else {
              console.warn(err);
            }
          }
        }
        return subject.subscribe(subscriber);
      } else {
        return scheduler.schedule(dispatch$5, 0, { params, subscriber, context: context2 });
      }
    });
  };
}
function dispatch$5(state) {
  var _this = this;
  var params = state.params, subscriber = state.subscriber, context2 = state.context;
  var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler;
  var subject = params.subject;
  if (!subject) {
    subject = params.subject = new AsyncSubject();
    var handler = function() {
      var innerArgs = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        innerArgs[_i] = arguments[_i];
      }
      var err = innerArgs.shift();
      if (err) {
        _this.add(scheduler.schedule(dispatchError, 0, { err, subject }));
      } else {
        var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
        _this.add(scheduler.schedule(dispatchNext$2, 0, { value, subject }));
      }
    };
    try {
      callbackFunc.apply(context2, args.concat([handler]));
    } catch (err) {
      this.add(scheduler.schedule(dispatchError, 0, { err, subject }));
    }
  }
  this.add(subject.subscribe(subscriber));
}
function dispatchNext$2(arg) {
  var value = arg.value, subject = arg.subject;
  subject.next(value);
  subject.complete();
}
function dispatchError(arg) {
  var err = arg.err, subject = arg.subject;
  subject.error(err);
}
var OuterSubscriber = /* @__PURE__ */ function(_super) {
  __extends(OuterSubscriber2, _super);
  function OuterSubscriber2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  OuterSubscriber2.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
    this.destination.next(innerValue);
  };
  OuterSubscriber2.prototype.notifyError = function(error, innerSub) {
    this.destination.error(error);
  };
  OuterSubscriber2.prototype.notifyComplete = function(innerSub) {
    this.destination.complete();
  };
  return OuterSubscriber2;
}(Subscriber);
var InnerSubscriber = /* @__PURE__ */ function(_super) {
  __extends(InnerSubscriber2, _super);
  function InnerSubscriber2(parent, outerValue, outerIndex) {
    var _this = _super.call(this) || this;
    _this.parent = parent;
    _this.outerValue = outerValue;
    _this.outerIndex = outerIndex;
    _this.index = 0;
    return _this;
  }
  InnerSubscriber2.prototype._next = function(value) {
    this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
  };
  InnerSubscriber2.prototype._error = function(error) {
    this.parent.notifyError(error, this);
    this.unsubscribe();
  };
  InnerSubscriber2.prototype._complete = function() {
    this.parent.notifyComplete(this);
    this.unsubscribe();
  };
  return InnerSubscriber2;
}(Subscriber);
var subscribeToPromise = function(promise) {
  return function(subscriber) {
    promise.then(function(value) {
      if (!subscriber.closed) {
        subscriber.next(value);
        subscriber.complete();
      }
    }, function(err) {
      return subscriber.error(err);
    }).then(null, hostReportError);
    return subscriber;
  };
};
function getSymbolIterator() {
  if (typeof Symbol !== "function" || !Symbol.iterator) {
    return "@@iterator";
  }
  return Symbol.iterator;
}
var iterator = /* @__PURE__ */ getSymbolIterator();
var subscribeToIterable = function(iterable) {
  return function(subscriber) {
    var iterator$1 = iterable[iterator]();
    do {
      var item = void 0;
      try {
        item = iterator$1.next();
      } catch (err) {
        subscriber.error(err);
        return subscriber;
      }
      if (item.done) {
        subscriber.complete();
        break;
      }
      subscriber.next(item.value);
      if (subscriber.closed) {
        break;
      }
    } while (true);
    if (typeof iterator$1.return === "function") {
      subscriber.add(function() {
        if (iterator$1.return) {
          iterator$1.return();
        }
      });
    }
    return subscriber;
  };
};
var subscribeToObservable = function(obj) {
  return function(subscriber) {
    var obs = obj[observable]();
    if (typeof obs.subscribe !== "function") {
      throw new TypeError("Provided object does not correctly implement Symbol.observable");
    } else {
      return obs.subscribe(subscriber);
    }
  };
};
var gosling_es_isArrayLike = function(x) {
  return x && typeof x.length === "number" && typeof x !== "function";
};
function isPromise(value) {
  return !!value && typeof value.subscribe !== "function" && typeof value.then === "function";
}
var subscribeTo = function(result) {
  if (!!result && typeof result[observable] === "function") {
    return subscribeToObservable(result);
  } else if (gosling_es_isArrayLike(result)) {
    return subscribeToArray(result);
  } else if (isPromise(result)) {
    return subscribeToPromise(result);
  } else if (!!result && typeof result[iterator] === "function") {
    return subscribeToIterable(result);
  } else {
    var value = gosling_es_isObject(result) ? "an invalid object" : "'" + result + "'";
    var msg = "You provided " + value + " where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.";
    throw new TypeError(msg);
  }
};
function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) {
  if (innerSubscriber === void 0) {
    innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex);
  }
  if (innerSubscriber.closed) {
    return void 0;
  }
  if (result instanceof Observable) {
    return result.subscribe(innerSubscriber);
  }
  return subscribeTo(result)(innerSubscriber);
}
var NONE = {};
function combineLatest$1() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  var resultSelector = void 0;
  var scheduler = void 0;
  if (isScheduler(observables[observables.length - 1])) {
    scheduler = observables.pop();
  }
  if (typeof observables[observables.length - 1] === "function") {
    resultSelector = observables.pop();
  }
  if (observables.length === 1 && gosling_es_isArray(observables[0])) {
    observables = observables[0];
  }
  return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
}
var CombineLatestOperator = /* @__PURE__ */ function() {
  function CombineLatestOperator2(resultSelector) {
    this.resultSelector = resultSelector;
  }
  CombineLatestOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
  };
  return CombineLatestOperator2;
}();
var CombineLatestSubscriber = /* @__PURE__ */ function(_super) {
  __extends(CombineLatestSubscriber2, _super);
  function CombineLatestSubscriber2(destination, resultSelector) {
    var _this = _super.call(this, destination) || this;
    _this.resultSelector = resultSelector;
    _this.active = 0;
    _this.values = [];
    _this.observables = [];
    return _this;
  }
  CombineLatestSubscriber2.prototype._next = function(observable2) {
    this.values.push(NONE);
    this.observables.push(observable2);
  };
  CombineLatestSubscriber2.prototype._complete = function() {
    var observables = this.observables;
    var len = observables.length;
    if (len === 0) {
      this.destination.complete();
    } else {
      this.active = len;
      this.toRespond = len;
      for (var i = 0; i < len; i++) {
        var observable2 = observables[i];
        this.add(subscribeToResult(this, observable2, void 0, i));
      }
    }
  };
  CombineLatestSubscriber2.prototype.notifyComplete = function(unused) {
    if ((this.active -= 1) === 0) {
      this.destination.complete();
    }
  };
  CombineLatestSubscriber2.prototype.notifyNext = function(_outerValue, innerValue, outerIndex) {
    var values = this.values;
    var oldVal = values[outerIndex];
    var toRespond = !this.toRespond ? 0 : oldVal === NONE ? --this.toRespond : this.toRespond;
    values[outerIndex] = innerValue;
    if (toRespond === 0) {
      if (this.resultSelector) {
        this._tryResultSelector(values);
      } else {
        this.destination.next(values.slice());
      }
    }
  };
  CombineLatestSubscriber2.prototype._tryResultSelector = function(values) {
    var result;
    try {
      result = this.resultSelector.apply(this, values);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.destination.next(result);
  };
  return CombineLatestSubscriber2;
}(OuterSubscriber);
function scheduleObservable(input, scheduler) {
  return new Observable(function(subscriber) {
    var sub = new Subscription();
    sub.add(scheduler.schedule(function() {
      var observable$1 = input[observable]();
      sub.add(observable$1.subscribe({
        next: function(value) {
          sub.add(scheduler.schedule(function() {
            return subscriber.next(value);
          }));
        },
        error: function(err) {
          sub.add(scheduler.schedule(function() {
            return subscriber.error(err);
          }));
        },
        complete: function() {
          sub.add(scheduler.schedule(function() {
            return subscriber.complete();
          }));
        }
      }));
    }));
    return sub;
  });
}
function schedulePromise(input, scheduler) {
  return new Observable(function(subscriber) {
    var sub = new Subscription();
    sub.add(scheduler.schedule(function() {
      return input.then(function(value) {
        sub.add(scheduler.schedule(function() {
          subscriber.next(value);
          sub.add(scheduler.schedule(function() {
            return subscriber.complete();
          }));
        }));
      }, function(err) {
        sub.add(scheduler.schedule(function() {
          return subscriber.error(err);
        }));
      });
    }));
    return sub;
  });
}
function scheduleIterable(input, scheduler) {
  if (!input) {
    throw new Error("Iterable cannot be null");
  }
  return new Observable(function(subscriber) {
    var sub = new Subscription();
    var iterator$1;
    sub.add(function() {
      if (iterator$1 && typeof iterator$1.return === "function") {
        iterator$1.return();
      }
    });
    sub.add(scheduler.schedule(function() {
      iterator$1 = input[iterator]();
      sub.add(scheduler.schedule(function() {
        if (subscriber.closed) {
          return;
        }
        var value;
        var done;
        try {
          var result = iterator$1.next();
          value = result.value;
          done = result.done;
        } catch (err) {
          subscriber.error(err);
          return;
        }
        if (done) {
          subscriber.complete();
        } else {
          subscriber.next(value);
          this.schedule();
        }
      }));
    }));
    return sub;
  });
}
function isInteropObservable(input) {
  return input && typeof input[observable] === "function";
}
function isIterable(input) {
  return input && typeof input[iterator] === "function";
}
function scheduled(input, scheduler) {
  if (input != null) {
    if (isInteropObservable(input)) {
      return scheduleObservable(input, scheduler);
    } else if (isPromise(input)) {
      return schedulePromise(input, scheduler);
    } else if (gosling_es_isArrayLike(input)) {
      return scheduleArray(input, scheduler);
    } else if (isIterable(input) || typeof input === "string") {
      return scheduleIterable(input, scheduler);
    }
  }
  throw new TypeError((input !== null && typeof input || input) + " is not observable");
}
function from(input, scheduler) {
  if (!scheduler) {
    if (input instanceof Observable) {
      return input;
    }
    return new Observable(subscribeTo(input));
  } else {
    return scheduled(input, scheduler);
  }
}
var SimpleInnerSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SimpleInnerSubscriber2, _super);
  function SimpleInnerSubscriber2(parent) {
    var _this = _super.call(this) || this;
    _this.parent = parent;
    return _this;
  }
  SimpleInnerSubscriber2.prototype._next = function(value) {
    this.parent.notifyNext(value);
  };
  SimpleInnerSubscriber2.prototype._error = function(error) {
    this.parent.notifyError(error);
    this.unsubscribe();
  };
  SimpleInnerSubscriber2.prototype._complete = function() {
    this.parent.notifyComplete();
    this.unsubscribe();
  };
  return SimpleInnerSubscriber2;
}(Subscriber);
var SimpleOuterSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SimpleOuterSubscriber2, _super);
  function SimpleOuterSubscriber2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  SimpleOuterSubscriber2.prototype.notifyNext = function(innerValue) {
    this.destination.next(innerValue);
  };
  SimpleOuterSubscriber2.prototype.notifyError = function(err) {
    this.destination.error(err);
  };
  SimpleOuterSubscriber2.prototype.notifyComplete = function() {
    this.destination.complete();
  };
  return SimpleOuterSubscriber2;
}(Subscriber);
function innerSubscribe(result, innerSubscriber) {
  if (innerSubscriber.closed) {
    return void 0;
  }
  if (result instanceof Observable) {
    return result.subscribe(innerSubscriber);
  }
  var subscription;
  try {
    subscription = subscribeTo(result)(innerSubscriber);
  } catch (error) {
    innerSubscriber.error(error);
  }
  return subscription;
}
function mergeMap(project, resultSelector, concurrent) {
  if (concurrent === void 0) {
    concurrent = Number.POSITIVE_INFINITY;
  }
  if (typeof resultSelector === "function") {
    return function(source) {
      return source.pipe(mergeMap(function(a, i) {
        return from(project(a, i)).pipe(gosling_es_map(function(b, ii) {
          return resultSelector(a, b, i, ii);
        }));
      }, concurrent));
    };
  } else if (typeof resultSelector === "number") {
    concurrent = resultSelector;
  }
  return function(source) {
    return source.lift(new MergeMapOperator(project, concurrent));
  };
}
var MergeMapOperator = /* @__PURE__ */ function() {
  function MergeMapOperator2(project, concurrent) {
    if (concurrent === void 0) {
      concurrent = Number.POSITIVE_INFINITY;
    }
    this.project = project;
    this.concurrent = concurrent;
  }
  MergeMapOperator2.prototype.call = function(observer, source) {
    return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
  };
  return MergeMapOperator2;
}();
var MergeMapSubscriber = /* @__PURE__ */ function(_super) {
  __extends(MergeMapSubscriber2, _super);
  function MergeMapSubscriber2(destination, project, concurrent) {
    if (concurrent === void 0) {
      concurrent = Number.POSITIVE_INFINITY;
    }
    var _this = _super.call(this, destination) || this;
    _this.project = project;
    _this.concurrent = concurrent;
    _this.hasCompleted = false;
    _this.buffer = [];
    _this.active = 0;
    _this.index = 0;
    return _this;
  }
  MergeMapSubscriber2.prototype._next = function(value) {
    if (this.active < this.concurrent) {
      this._tryNext(value);
    } else {
      this.buffer.push(value);
    }
  };
  MergeMapSubscriber2.prototype._tryNext = function(value) {
    var result;
    var index = this.index++;
    try {
      result = this.project(value, index);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.active++;
    this._innerSub(result);
  };
  MergeMapSubscriber2.prototype._innerSub = function(ish) {
    var innerSubscriber = new SimpleInnerSubscriber(this);
    var destination = this.destination;
    destination.add(innerSubscriber);
    var innerSubscription = innerSubscribe(ish, innerSubscriber);
    if (innerSubscription !== innerSubscriber) {
      destination.add(innerSubscription);
    }
  };
  MergeMapSubscriber2.prototype._complete = function() {
    this.hasCompleted = true;
    if (this.active === 0 && this.buffer.length === 0) {
      this.destination.complete();
    }
    this.unsubscribe();
  };
  MergeMapSubscriber2.prototype.notifyNext = function(innerValue) {
    this.destination.next(innerValue);
  };
  MergeMapSubscriber2.prototype.notifyComplete = function() {
    var buffer2 = this.buffer;
    this.active--;
    if (buffer2.length > 0) {
      this._next(buffer2.shift());
    } else if (this.active === 0 && this.hasCompleted) {
      this.destination.complete();
    }
  };
  return MergeMapSubscriber2;
}(SimpleOuterSubscriber);
var flatMap = mergeMap;
function mergeAll(concurrent) {
  if (concurrent === void 0) {
    concurrent = Number.POSITIVE_INFINITY;
  }
  return mergeMap(gosling_es_identity, concurrent);
}
function concatAll() {
  return mergeAll(1);
}
function concat$1() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  return concatAll()(of.apply(void 0, observables));
}
function defer(observableFactory) {
  return new Observable(function(subscriber) {
    var input;
    try {
      input = observableFactory();
    } catch (err) {
      subscriber.error(err);
      return void 0;
    }
    var source = input ? from(input) : empty();
    return source.subscribe(subscriber);
  });
}
function forkJoin() {
  var sources = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    sources[_i] = arguments[_i];
  }
  if (sources.length === 1) {
    var first_1 = sources[0];
    if (gosling_es_isArray(first_1)) {
      return forkJoinInternal(first_1, null);
    }
    if (gosling_es_isObject(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) {
      var keys = Object.keys(first_1);
      return forkJoinInternal(keys.map(function(key) {
        return first_1[key];
      }), keys);
    }
  }
  if (typeof sources[sources.length - 1] === "function") {
    var resultSelector_1 = sources.pop();
    sources = sources.length === 1 && gosling_es_isArray(sources[0]) ? sources[0] : sources;
    return forkJoinInternal(sources, null).pipe(gosling_es_map(function(args) {
      return resultSelector_1.apply(void 0, args);
    }));
  }
  return forkJoinInternal(sources, null);
}
function forkJoinInternal(sources, keys) {
  return new Observable(function(subscriber) {
    var len = sources.length;
    if (len === 0) {
      subscriber.complete();
      return;
    }
    var values = new Array(len);
    var completed = 0;
    var emitted = 0;
    var _loop_1 = function(i2) {
      var source = from(sources[i2]);
      var hasValue = false;
      subscriber.add(source.subscribe({
        next: function(value) {
          if (!hasValue) {
            hasValue = true;
            emitted++;
          }
          values[i2] = value;
        },
        error: function(err) {
          return subscriber.error(err);
        },
        complete: function() {
          completed++;
          if (completed === len || !hasValue) {
            if (emitted === len) {
              subscriber.next(keys ? keys.reduce(function(result, key, i3) {
                return result[key] = values[i3], result;
              }, {}) : values);
            }
            subscriber.complete();
          }
        }
      }));
    };
    for (var i = 0; i < len; i++) {
      _loop_1(i);
    }
  });
}
function fromEvent(target, eventName, options, resultSelector) {
  if (gosling_es_isFunction(options)) {
    resultSelector = options;
    options = void 0;
  }
  if (resultSelector) {
    return fromEvent(target, eventName, options).pipe(gosling_es_map(function(args) {
      return gosling_es_isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args);
    }));
  }
  return new Observable(function(subscriber) {
    function handler(e) {
      if (arguments.length > 1) {
        subscriber.next(Array.prototype.slice.call(arguments));
      } else {
        subscriber.next(e);
      }
    }
    setupSubscription(target, eventName, handler, subscriber, options);
  });
}
function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
  var unsubscribe;
  if (isEventTarget(sourceObj)) {
    var source_1 = sourceObj;
    sourceObj.addEventListener(eventName, handler, options);
    unsubscribe = function() {
      return source_1.removeEventListener(eventName, handler, options);
    };
  } else if (isJQueryStyleEventEmitter(sourceObj)) {
    var source_2 = sourceObj;
    sourceObj.on(eventName, handler);
    unsubscribe = function() {
      return source_2.off(eventName, handler);
    };
  } else if (isNodeStyleEventEmitter(sourceObj)) {
    var source_3 = sourceObj;
    sourceObj.addListener(eventName, handler);
    unsubscribe = function() {
      return source_3.removeListener(eventName, handler);
    };
  } else if (sourceObj && sourceObj.length) {
    for (var i = 0, len = sourceObj.length; i < len; i++) {
      setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
    }
  } else {
    throw new TypeError("Invalid event target");
  }
  subscriber.add(unsubscribe);
}
function isNodeStyleEventEmitter(sourceObj) {
  return sourceObj && typeof sourceObj.addListener === "function" && typeof sourceObj.removeListener === "function";
}
function isJQueryStyleEventEmitter(sourceObj) {
  return sourceObj && typeof sourceObj.on === "function" && typeof sourceObj.off === "function";
}
function isEventTarget(sourceObj) {
  return sourceObj && typeof sourceObj.addEventListener === "function" && typeof sourceObj.removeEventListener === "function";
}
function fromEventPattern(addHandler, removeHandler, resultSelector) {
  if (resultSelector) {
    return fromEventPattern(addHandler, removeHandler).pipe(gosling_es_map(function(args) {
      return gosling_es_isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args);
    }));
  }
  return new Observable(function(subscriber) {
    var handler = function() {
      var e = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        e[_i] = arguments[_i];
      }
      return subscriber.next(e.length === 1 ? e[0] : e);
    };
    var retValue;
    try {
      retValue = addHandler(handler);
    } catch (err) {
      subscriber.error(err);
      return void 0;
    }
    if (!gosling_es_isFunction(removeHandler)) {
      return void 0;
    }
    return function() {
      return removeHandler(handler, retValue);
    };
  });
}
function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
  var resultSelector;
  var initialState;
  if (arguments.length == 1) {
    var options = initialStateOrOptions;
    initialState = options.initialState;
    condition = options.condition;
    iterate = options.iterate;
    resultSelector = options.resultSelector || gosling_es_identity;
    scheduler = options.scheduler;
  } else if (resultSelectorOrObservable === void 0 || isScheduler(resultSelectorOrObservable)) {
    initialState = initialStateOrOptions;
    resultSelector = gosling_es_identity;
    scheduler = resultSelectorOrObservable;
  } else {
    initialState = initialStateOrOptions;
    resultSelector = resultSelectorOrObservable;
  }
  return new Observable(function(subscriber) {
    var state = initialState;
    if (scheduler) {
      return scheduler.schedule(dispatch$4, 0, {
        subscriber,
        iterate,
        condition,
        resultSelector,
        state
      });
    }
    do {
      if (condition) {
        var conditionResult = void 0;
        try {
          conditionResult = condition(state);
        } catch (err) {
          subscriber.error(err);
          return void 0;
        }
        if (!conditionResult) {
          subscriber.complete();
          break;
        }
      }
      var value = void 0;
      try {
        value = resultSelector(state);
      } catch (err) {
        subscriber.error(err);
        return void 0;
      }
      subscriber.next(value);
      if (subscriber.closed) {
        break;
      }
      try {
        state = iterate(state);
      } catch (err) {
        subscriber.error(err);
        return void 0;
      }
    } while (true);
    return void 0;
  });
}
function dispatch$4(state) {
  var subscriber = state.subscriber, condition = state.condition;
  if (subscriber.closed) {
    return void 0;
  }
  if (state.needIterate) {
    try {
      state.state = state.iterate(state.state);
    } catch (err) {
      subscriber.error(err);
      return void 0;
    }
  } else {
    state.needIterate = true;
  }
  if (condition) {
    var conditionResult = void 0;
    try {
      conditionResult = condition(state.state);
    } catch (err) {
      subscriber.error(err);
      return void 0;
    }
    if (!conditionResult) {
      subscriber.complete();
      return void 0;
    }
    if (subscriber.closed) {
      return void 0;
    }
  }
  var value;
  try {
    value = state.resultSelector(state.state);
  } catch (err) {
    subscriber.error(err);
    return void 0;
  }
  if (subscriber.closed) {
    return void 0;
  }
  subscriber.next(value);
  if (subscriber.closed) {
    return void 0;
  }
  return this.schedule(state);
}
function iif(condition, trueResult, falseResult) {
  if (trueResult === void 0) {
    trueResult = EMPTY;
  }
  if (falseResult === void 0) {
    falseResult = EMPTY;
  }
  return defer(function() {
    return condition() ? trueResult : falseResult;
  });
}
function isNumeric(val) {
  return !gosling_es_isArray(val) && val - parseFloat(val) + 1 >= 0;
}
function interval(period, scheduler) {
  if (period === void 0) {
    period = 0;
  }
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  if (!isNumeric(period) || period < 0) {
    period = 0;
  }
  if (!scheduler || typeof scheduler.schedule !== "function") {
    scheduler = async$1;
  }
  return new Observable(function(subscriber) {
    subscriber.add(scheduler.schedule(dispatch$3, period, { subscriber, counter: 0, period }));
    return subscriber;
  });
}
function dispatch$3(state) {
  var subscriber = state.subscriber, counter = state.counter, period = state.period;
  subscriber.next(counter);
  this.schedule({ subscriber, counter: counter + 1, period }, period);
}
function merge$1() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  var concurrent = Number.POSITIVE_INFINITY;
  var scheduler = null;
  var last2 = observables[observables.length - 1];
  if (isScheduler(last2)) {
    scheduler = observables.pop();
    if (observables.length > 1 && typeof observables[observables.length - 1] === "number") {
      concurrent = observables.pop();
    }
  } else if (typeof last2 === "number") {
    concurrent = observables.pop();
  }
  if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {
    return observables[0];
  }
  return mergeAll(concurrent)(fromArray(observables, scheduler));
}
var NEVER = /* @__PURE__ */ new Observable(noop$1);
function never() {
  return NEVER;
}
function onErrorResumeNext$1() {
  var sources = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    sources[_i] = arguments[_i];
  }
  if (sources.length === 0) {
    return EMPTY;
  }
  var first2 = sources[0], remainder = sources.slice(1);
  if (sources.length === 1 && gosling_es_isArray(first2)) {
    return onErrorResumeNext$1.apply(void 0, first2);
  }
  return new Observable(function(subscriber) {
    var subNext = function() {
      return subscriber.add(onErrorResumeNext$1.apply(void 0, remainder).subscribe(subscriber));
    };
    return from(first2).subscribe({
      next: function(value) {
        subscriber.next(value);
      },
      error: subNext,
      complete: subNext
    });
  });
}
function pairs(obj, scheduler) {
  if (!scheduler) {
    return new Observable(function(subscriber) {
      var keys = Object.keys(obj);
      for (var i = 0; i < keys.length && !subscriber.closed; i++) {
        var key = keys[i];
        if (obj.hasOwnProperty(key)) {
          subscriber.next([key, obj[key]]);
        }
      }
      subscriber.complete();
    });
  } else {
    return new Observable(function(subscriber) {
      var keys = Object.keys(obj);
      var subscription = new Subscription();
      subscription.add(scheduler.schedule(dispatch$2, 0, { keys, index: 0, subscriber, subscription, obj }));
      return subscription;
    });
  }
}
function dispatch$2(state) {
  var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj;
  if (!subscriber.closed) {
    if (index < keys.length) {
      var key = keys[index];
      subscriber.next([key, obj[key]]);
      subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
    } else {
      subscriber.complete();
    }
  }
}
function not$1(pred, thisArg) {
  function notPred() {
    return !notPred.pred.apply(notPred.thisArg, arguments);
  }
  notPred.pred = pred;
  notPred.thisArg = thisArg;
  return notPred;
}
function filter(predicate, thisArg) {
  return function filterOperatorFunction(source) {
    return source.lift(new FilterOperator(predicate, thisArg));
  };
}
var FilterOperator = /* @__PURE__ */ function() {
  function FilterOperator2(predicate, thisArg) {
    this.predicate = predicate;
    this.thisArg = thisArg;
  }
  FilterOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
  };
  return FilterOperator2;
}();
var FilterSubscriber = /* @__PURE__ */ function(_super) {
  __extends(FilterSubscriber2, _super);
  function FilterSubscriber2(destination, predicate, thisArg) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.thisArg = thisArg;
    _this.count = 0;
    return _this;
  }
  FilterSubscriber2.prototype._next = function(value) {
    var result;
    try {
      result = this.predicate.call(this.thisArg, value, this.count++);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    if (result) {
      this.destination.next(value);
    }
  };
  return FilterSubscriber2;
}(Subscriber);
function partition$1(source, predicate, thisArg) {
  return [
    filter(predicate, thisArg)(new Observable(subscribeTo(source))),
    filter(not$1(predicate, thisArg))(new Observable(subscribeTo(source)))
  ];
}
function race$1() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  if (observables.length === 1) {
    if (gosling_es_isArray(observables[0])) {
      observables = observables[0];
    } else {
      return observables[0];
    }
  }
  return fromArray(observables, void 0).lift(new RaceOperator());
}
var RaceOperator = /* @__PURE__ */ function() {
  function RaceOperator2() {
  }
  RaceOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new RaceSubscriber(subscriber));
  };
  return RaceOperator2;
}();
var RaceSubscriber = /* @__PURE__ */ function(_super) {
  __extends(RaceSubscriber2, _super);
  function RaceSubscriber2(destination) {
    var _this = _super.call(this, destination) || this;
    _this.hasFirst = false;
    _this.observables = [];
    _this.subscriptions = [];
    return _this;
  }
  RaceSubscriber2.prototype._next = function(observable2) {
    this.observables.push(observable2);
  };
  RaceSubscriber2.prototype._complete = function() {
    var observables = this.observables;
    var len = observables.length;
    if (len === 0) {
      this.destination.complete();
    } else {
      for (var i = 0; i < len && !this.hasFirst; i++) {
        var observable2 = observables[i];
        var subscription = subscribeToResult(this, observable2, void 0, i);
        if (this.subscriptions) {
          this.subscriptions.push(subscription);
        }
        this.add(subscription);
      }
      this.observables = null;
    }
  };
  RaceSubscriber2.prototype.notifyNext = function(_outerValue, innerValue, outerIndex) {
    if (!this.hasFirst) {
      this.hasFirst = true;
      for (var i = 0; i < this.subscriptions.length; i++) {
        if (i !== outerIndex) {
          var subscription = this.subscriptions[i];
          subscription.unsubscribe();
          this.remove(subscription);
        }
      }
      this.subscriptions = null;
    }
    this.destination.next(innerValue);
  };
  return RaceSubscriber2;
}(OuterSubscriber);
function gosling_es_range(start, count2, scheduler) {
  if (start === void 0) {
    start = 0;
  }
  return new Observable(function(subscriber) {
    if (count2 === void 0) {
      count2 = start;
      start = 0;
    }
    var index = 0;
    var current = start;
    if (scheduler) {
      return scheduler.schedule(dispatch$1, 0, {
        index,
        count: count2,
        start,
        subscriber
      });
    } else {
      do {
        if (index++ >= count2) {
          subscriber.complete();
          break;
        }
        subscriber.next(current++);
        if (subscriber.closed) {
          break;
        }
      } while (true);
    }
    return void 0;
  });
}
function dispatch$1(state) {
  var start = state.start, index = state.index, count2 = state.count, subscriber = state.subscriber;
  if (index >= count2) {
    subscriber.complete();
    return;
  }
  subscriber.next(start);
  if (subscriber.closed) {
    return;
  }
  state.index = index + 1;
  state.start = start + 1;
  this.schedule(state);
}
function timer(dueTime, periodOrScheduler, scheduler) {
  if (dueTime === void 0) {
    dueTime = 0;
  }
  var period = -1;
  if (isNumeric(periodOrScheduler)) {
    period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
  } else if (isScheduler(periodOrScheduler)) {
    scheduler = periodOrScheduler;
  }
  if (!isScheduler(scheduler)) {
    scheduler = async$1;
  }
  return new Observable(function(subscriber) {
    var due = isNumeric(dueTime) ? dueTime : +dueTime - scheduler.now();
    return scheduler.schedule(dispatch, due, {
      index: 0,
      period,
      subscriber
    });
  });
}
function dispatch(state) {
  var index = state.index, period = state.period, subscriber = state.subscriber;
  subscriber.next(index);
  if (subscriber.closed) {
    return;
  } else if (period === -1) {
    return subscriber.complete();
  }
  state.index = index + 1;
  this.schedule(state, period);
}
function using(resourceFactory, observableFactory) {
  return new Observable(function(subscriber) {
    var resource;
    try {
      resource = resourceFactory();
    } catch (err) {
      subscriber.error(err);
      return void 0;
    }
    var result;
    try {
      result = observableFactory(resource);
    } catch (err) {
      subscriber.error(err);
      return void 0;
    }
    var source = result ? from(result) : EMPTY;
    var subscription = source.subscribe(subscriber);
    return function() {
      subscription.unsubscribe();
      if (resource) {
        resource.unsubscribe();
      }
    };
  });
}
function zip$1() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  var resultSelector = observables[observables.length - 1];
  if (typeof resultSelector === "function") {
    observables.pop();
  }
  return fromArray(observables, void 0).lift(new ZipOperator(resultSelector));
}
var ZipOperator = /* @__PURE__ */ function() {
  function ZipOperator2(resultSelector) {
    this.resultSelector = resultSelector;
  }
  ZipOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
  };
  return ZipOperator2;
}();
var ZipSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ZipSubscriber2, _super);
  function ZipSubscriber2(destination, resultSelector, values) {
    var _this = _super.call(this, destination) || this;
    _this.resultSelector = resultSelector;
    _this.iterators = [];
    _this.active = 0;
    _this.resultSelector = typeof resultSelector === "function" ? resultSelector : void 0;
    return _this;
  }
  ZipSubscriber2.prototype._next = function(value) {
    var iterators = this.iterators;
    if (gosling_es_isArray(value)) {
      iterators.push(new StaticArrayIterator(value));
    } else if (typeof value[iterator] === "function") {
      iterators.push(new StaticIterator(value[iterator]()));
    } else {
      iterators.push(new ZipBufferIterator(this.destination, this, value));
    }
  };
  ZipSubscriber2.prototype._complete = function() {
    var iterators = this.iterators;
    var len = iterators.length;
    this.unsubscribe();
    if (len === 0) {
      this.destination.complete();
      return;
    }
    this.active = len;
    for (var i = 0; i < len; i++) {
      var iterator2 = iterators[i];
      if (iterator2.stillUnsubscribed) {
        var destination = this.destination;
        destination.add(iterator2.subscribe());
      } else {
        this.active--;
      }
    }
  };
  ZipSubscriber2.prototype.notifyInactive = function() {
    this.active--;
    if (this.active === 0) {
      this.destination.complete();
    }
  };
  ZipSubscriber2.prototype.checkIterators = function() {
    var iterators = this.iterators;
    var len = iterators.length;
    var destination = this.destination;
    for (var i = 0; i < len; i++) {
      var iterator2 = iterators[i];
      if (typeof iterator2.hasValue === "function" && !iterator2.hasValue()) {
        return;
      }
    }
    var shouldComplete = false;
    var args = [];
    for (var i = 0; i < len; i++) {
      var iterator2 = iterators[i];
      var result = iterator2.next();
      if (iterator2.hasCompleted()) {
        shouldComplete = true;
      }
      if (result.done) {
        destination.complete();
        return;
      }
      args.push(result.value);
    }
    if (this.resultSelector) {
      this._tryresultSelector(args);
    } else {
      destination.next(args);
    }
    if (shouldComplete) {
      destination.complete();
    }
  };
  ZipSubscriber2.prototype._tryresultSelector = function(args) {
    var result;
    try {
      result = this.resultSelector.apply(this, args);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.destination.next(result);
  };
  return ZipSubscriber2;
}(Subscriber);
var StaticIterator = /* @__PURE__ */ function() {
  function StaticIterator2(iterator2) {
    this.iterator = iterator2;
    this.nextResult = iterator2.next();
  }
  StaticIterator2.prototype.hasValue = function() {
    return true;
  };
  StaticIterator2.prototype.next = function() {
    var result = this.nextResult;
    this.nextResult = this.iterator.next();
    return result;
  };
  StaticIterator2.prototype.hasCompleted = function() {
    var nextResult = this.nextResult;
    return Boolean(nextResult && nextResult.done);
  };
  return StaticIterator2;
}();
var StaticArrayIterator = /* @__PURE__ */ function() {
  function StaticArrayIterator2(array) {
    this.array = array;
    this.index = 0;
    this.length = 0;
    this.length = array.length;
  }
  StaticArrayIterator2.prototype[iterator] = function() {
    return this;
  };
  StaticArrayIterator2.prototype.next = function(value) {
    var i = this.index++;
    var array = this.array;
    return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
  };
  StaticArrayIterator2.prototype.hasValue = function() {
    return this.array.length > this.index;
  };
  StaticArrayIterator2.prototype.hasCompleted = function() {
    return this.array.length === this.index;
  };
  return StaticArrayIterator2;
}();
var ZipBufferIterator = /* @__PURE__ */ function(_super) {
  __extends(ZipBufferIterator2, _super);
  function ZipBufferIterator2(destination, parent, observable2) {
    var _this = _super.call(this, destination) || this;
    _this.parent = parent;
    _this.observable = observable2;
    _this.stillUnsubscribed = true;
    _this.buffer = [];
    _this.isComplete = false;
    return _this;
  }
  ZipBufferIterator2.prototype[iterator] = function() {
    return this;
  };
  ZipBufferIterator2.prototype.next = function() {
    var buffer2 = this.buffer;
    if (buffer2.length === 0 && this.isComplete) {
      return { value: null, done: true };
    } else {
      return { value: buffer2.shift(), done: false };
    }
  };
  ZipBufferIterator2.prototype.hasValue = function() {
    return this.buffer.length > 0;
  };
  ZipBufferIterator2.prototype.hasCompleted = function() {
    return this.buffer.length === 0 && this.isComplete;
  };
  ZipBufferIterator2.prototype.notifyComplete = function() {
    if (this.buffer.length > 0) {
      this.isComplete = true;
      this.parent.notifyInactive();
    } else {
      this.destination.complete();
    }
  };
  ZipBufferIterator2.prototype.notifyNext = function(innerValue) {
    this.buffer.push(innerValue);
    this.parent.checkIterators();
  };
  ZipBufferIterator2.prototype.subscribe = function() {
    return innerSubscribe(this.observable, new SimpleInnerSubscriber(this));
  };
  return ZipBufferIterator2;
}(SimpleOuterSubscriber);
var _esm5 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  [Symbol.toStringTag]: "Module",
  Observable,
  ConnectableObservable,
  GroupedObservable,
  observable,
  Subject,
  BehaviorSubject,
  ReplaySubject,
  AsyncSubject,
  asap,
  asapScheduler,
  async: async$1,
  asyncScheduler,
  queue,
  queueScheduler,
  animationFrame,
  animationFrameScheduler,
  VirtualTimeScheduler,
  VirtualAction,
  Scheduler,
  Subscription,
  Subscriber,
  Notification,
  get NotificationKind() {
    return NotificationKind;
  },
  pipe,
  noop: noop$1,
  identity: gosling_es_identity,
  isObservable,
  ArgumentOutOfRangeError,
  EmptyError,
  ObjectUnsubscribedError,
  UnsubscriptionError,
  TimeoutError,
  bindCallback,
  bindNodeCallback,
  combineLatest: combineLatest$1,
  concat: concat$1,
  defer,
  empty,
  forkJoin,
  from,
  fromEvent,
  fromEventPattern,
  generate,
  iif,
  interval,
  merge: merge$1,
  never,
  of,
  onErrorResumeNext: onErrorResumeNext$1,
  pairs,
  partition: partition$1,
  race: race$1,
  range: gosling_es_range,
  throwError,
  timer,
  using,
  zip: zip$1,
  scheduled,
  EMPTY,
  NEVER,
  config
});
var require$$12$1 = /* @__PURE__ */ getAugmentedNamespace(_esm5);
function audit(durationSelector) {
  return function auditOperatorFunction(source) {
    return source.lift(new AuditOperator(durationSelector));
  };
}
var AuditOperator = /* @__PURE__ */ function() {
  function AuditOperator2(durationSelector) {
    this.durationSelector = durationSelector;
  }
  AuditOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
  };
  return AuditOperator2;
}();
var AuditSubscriber = /* @__PURE__ */ function(_super) {
  __extends(AuditSubscriber2, _super);
  function AuditSubscriber2(destination, durationSelector) {
    var _this = _super.call(this, destination) || this;
    _this.durationSelector = durationSelector;
    _this.hasValue = false;
    return _this;
  }
  AuditSubscriber2.prototype._next = function(value) {
    this.value = value;
    this.hasValue = true;
    if (!this.throttled) {
      var duration = void 0;
      try {
        var durationSelector = this.durationSelector;
        duration = durationSelector(value);
      } catch (err) {
        return this.destination.error(err);
      }
      var innerSubscription = innerSubscribe(duration, new SimpleInnerSubscriber(this));
      if (!innerSubscription || innerSubscription.closed) {
        this.clearThrottle();
      } else {
        this.add(this.throttled = innerSubscription);
      }
    }
  };
  AuditSubscriber2.prototype.clearThrottle = function() {
    var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
    if (throttled) {
      this.remove(throttled);
      this.throttled = void 0;
      throttled.unsubscribe();
    }
    if (hasValue) {
      this.value = void 0;
      this.hasValue = false;
      this.destination.next(value);
    }
  };
  AuditSubscriber2.prototype.notifyNext = function() {
    this.clearThrottle();
  };
  AuditSubscriber2.prototype.notifyComplete = function() {
    this.clearThrottle();
  };
  return AuditSubscriber2;
}(SimpleOuterSubscriber);
function auditTime(duration, scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return audit(function() {
    return timer(duration, scheduler);
  });
}
function gosling_es_buffer(closingNotifier) {
  return function bufferOperatorFunction(source) {
    return source.lift(new BufferOperator(closingNotifier));
  };
}
var BufferOperator = /* @__PURE__ */ function() {
  function BufferOperator2(closingNotifier) {
    this.closingNotifier = closingNotifier;
  }
  BufferOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
  };
  return BufferOperator2;
}();
var BufferSubscriber = /* @__PURE__ */ function(_super) {
  __extends(BufferSubscriber2, _super);
  function BufferSubscriber2(destination, closingNotifier) {
    var _this = _super.call(this, destination) || this;
    _this.buffer = [];
    _this.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(_this)));
    return _this;
  }
  BufferSubscriber2.prototype._next = function(value) {
    this.buffer.push(value);
  };
  BufferSubscriber2.prototype.notifyNext = function() {
    var buffer2 = this.buffer;
    this.buffer = [];
    this.destination.next(buffer2);
  };
  return BufferSubscriber2;
}(SimpleOuterSubscriber);
function bufferCount(bufferSize, startBufferEvery) {
  if (startBufferEvery === void 0) {
    startBufferEvery = null;
  }
  return function bufferCountOperatorFunction(source) {
    return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
  };
}
var BufferCountOperator = /* @__PURE__ */ function() {
  function BufferCountOperator2(bufferSize, startBufferEvery) {
    this.bufferSize = bufferSize;
    this.startBufferEvery = startBufferEvery;
    if (!startBufferEvery || bufferSize === startBufferEvery) {
      this.subscriberClass = BufferCountSubscriber;
    } else {
      this.subscriberClass = BufferSkipCountSubscriber;
    }
  }
  BufferCountOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
  };
  return BufferCountOperator2;
}();
var BufferCountSubscriber = /* @__PURE__ */ function(_super) {
  __extends(BufferCountSubscriber2, _super);
  function BufferCountSubscriber2(destination, bufferSize) {
    var _this = _super.call(this, destination) || this;
    _this.bufferSize = bufferSize;
    _this.buffer = [];
    return _this;
  }
  BufferCountSubscriber2.prototype._next = function(value) {
    var buffer2 = this.buffer;
    buffer2.push(value);
    if (buffer2.length == this.bufferSize) {
      this.destination.next(buffer2);
      this.buffer = [];
    }
  };
  BufferCountSubscriber2.prototype._complete = function() {
    var buffer2 = this.buffer;
    if (buffer2.length > 0) {
      this.destination.next(buffer2);
    }
    _super.prototype._complete.call(this);
  };
  return BufferCountSubscriber2;
}(Subscriber);
var BufferSkipCountSubscriber = /* @__PURE__ */ function(_super) {
  __extends(BufferSkipCountSubscriber2, _super);
  function BufferSkipCountSubscriber2(destination, bufferSize, startBufferEvery) {
    var _this = _super.call(this, destination) || this;
    _this.bufferSize = bufferSize;
    _this.startBufferEvery = startBufferEvery;
    _this.buffers = [];
    _this.count = 0;
    return _this;
  }
  BufferSkipCountSubscriber2.prototype._next = function(value) {
    var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count2 = _a.count;
    this.count++;
    if (count2 % startBufferEvery === 0) {
      buffers.push([]);
    }
    for (var i = buffers.length; i--; ) {
      var buffer2 = buffers[i];
      buffer2.push(value);
      if (buffer2.length === bufferSize) {
        buffers.splice(i, 1);
        this.destination.next(buffer2);
      }
    }
  };
  BufferSkipCountSubscriber2.prototype._complete = function() {
    var _a = this, buffers = _a.buffers, destination = _a.destination;
    while (buffers.length > 0) {
      var buffer2 = buffers.shift();
      if (buffer2.length > 0) {
        destination.next(buffer2);
      }
    }
    _super.prototype._complete.call(this);
  };
  return BufferSkipCountSubscriber2;
}(Subscriber);
function bufferTime(bufferTimeSpan) {
  var length = arguments.length;
  var scheduler = async$1;
  if (isScheduler(arguments[arguments.length - 1])) {
    scheduler = arguments[arguments.length - 1];
    length--;
  }
  var bufferCreationInterval = null;
  if (length >= 2) {
    bufferCreationInterval = arguments[1];
  }
  var maxBufferSize = Number.POSITIVE_INFINITY;
  if (length >= 3) {
    maxBufferSize = arguments[2];
  }
  return function bufferTimeOperatorFunction(source) {
    return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
  };
}
var BufferTimeOperator = /* @__PURE__ */ function() {
  function BufferTimeOperator2(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
    this.bufferTimeSpan = bufferTimeSpan;
    this.bufferCreationInterval = bufferCreationInterval;
    this.maxBufferSize = maxBufferSize;
    this.scheduler = scheduler;
  }
  BufferTimeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
  };
  return BufferTimeOperator2;
}();
var Context2 = /* @__PURE__ */ function() {
  function Context3() {
    this.buffer = [];
  }
  return Context3;
}();
var BufferTimeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(BufferTimeSubscriber2, _super);
  function BufferTimeSubscriber2(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.bufferTimeSpan = bufferTimeSpan;
    _this.bufferCreationInterval = bufferCreationInterval;
    _this.maxBufferSize = maxBufferSize;
    _this.scheduler = scheduler;
    _this.contexts = [];
    var context2 = _this.openContext();
    _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
    if (_this.timespanOnly) {
      var timeSpanOnlyState = { subscriber: _this, context: context2, bufferTimeSpan };
      _this.add(context2.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
    } else {
      var closeState = { subscriber: _this, context: context2 };
      var creationState = { bufferTimeSpan, bufferCreationInterval, subscriber: _this, scheduler };
      _this.add(context2.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
      _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
    }
    return _this;
  }
  BufferTimeSubscriber2.prototype._next = function(value) {
    var contexts = this.contexts;
    var len = contexts.length;
    var filledBufferContext;
    for (var i = 0; i < len; i++) {
      var context_1 = contexts[i];
      var buffer2 = context_1.buffer;
      buffer2.push(value);
      if (buffer2.length == this.maxBufferSize) {
        filledBufferContext = context_1;
      }
    }
    if (filledBufferContext) {
      this.onBufferFull(filledBufferContext);
    }
  };
  BufferTimeSubscriber2.prototype._error = function(err) {
    this.contexts.length = 0;
    _super.prototype._error.call(this, err);
  };
  BufferTimeSubscriber2.prototype._complete = function() {
    var _a = this, contexts = _a.contexts, destination = _a.destination;
    while (contexts.length > 0) {
      var context_2 = contexts.shift();
      destination.next(context_2.buffer);
    }
    _super.prototype._complete.call(this);
  };
  BufferTimeSubscriber2.prototype._unsubscribe = function() {
    this.contexts = null;
  };
  BufferTimeSubscriber2.prototype.onBufferFull = function(context2) {
    this.closeContext(context2);
    var closeAction = context2.closeAction;
    closeAction.unsubscribe();
    this.remove(closeAction);
    if (!this.closed && this.timespanOnly) {
      context2 = this.openContext();
      var bufferTimeSpan = this.bufferTimeSpan;
      var timeSpanOnlyState = { subscriber: this, context: context2, bufferTimeSpan };
      this.add(context2.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
    }
  };
  BufferTimeSubscriber2.prototype.openContext = function() {
    var context2 = new Context2();
    this.contexts.push(context2);
    return context2;
  };
  BufferTimeSubscriber2.prototype.closeContext = function(context2) {
    this.destination.next(context2.buffer);
    var contexts = this.contexts;
    var spliceIndex = contexts ? contexts.indexOf(context2) : -1;
    if (spliceIndex >= 0) {
      contexts.splice(contexts.indexOf(context2), 1);
    }
  };
  return BufferTimeSubscriber2;
}(Subscriber);
function dispatchBufferTimeSpanOnly(state) {
  var subscriber = state.subscriber;
  var prevContext = state.context;
  if (prevContext) {
    subscriber.closeContext(prevContext);
  }
  if (!subscriber.closed) {
    state.context = subscriber.openContext();
    state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
  }
}
function dispatchBufferCreation(state) {
  var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
  var context2 = subscriber.openContext();
  var action = this;
  if (!subscriber.closed) {
    subscriber.add(context2.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber, context: context2 }));
    action.schedule(state, bufferCreationInterval);
  }
}
function dispatchBufferClose(arg) {
  var subscriber = arg.subscriber, context2 = arg.context;
  subscriber.closeContext(context2);
}
function bufferToggle(openings, closingSelector) {
  return function bufferToggleOperatorFunction(source) {
    return source.lift(new BufferToggleOperator(openings, closingSelector));
  };
}
var BufferToggleOperator = /* @__PURE__ */ function() {
  function BufferToggleOperator2(openings, closingSelector) {
    this.openings = openings;
    this.closingSelector = closingSelector;
  }
  BufferToggleOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
  };
  return BufferToggleOperator2;
}();
var BufferToggleSubscriber = /* @__PURE__ */ function(_super) {
  __extends(BufferToggleSubscriber2, _super);
  function BufferToggleSubscriber2(destination, openings, closingSelector) {
    var _this = _super.call(this, destination) || this;
    _this.closingSelector = closingSelector;
    _this.contexts = [];
    _this.add(subscribeToResult(_this, openings));
    return _this;
  }
  BufferToggleSubscriber2.prototype._next = function(value) {
    var contexts = this.contexts;
    var len = contexts.length;
    for (var i = 0; i < len; i++) {
      contexts[i].buffer.push(value);
    }
  };
  BufferToggleSubscriber2.prototype._error = function(err) {
    var contexts = this.contexts;
    while (contexts.length > 0) {
      var context_1 = contexts.shift();
      context_1.subscription.unsubscribe();
      context_1.buffer = null;
      context_1.subscription = null;
    }
    this.contexts = null;
    _super.prototype._error.call(this, err);
  };
  BufferToggleSubscriber2.prototype._complete = function() {
    var contexts = this.contexts;
    while (contexts.length > 0) {
      var context_2 = contexts.shift();
      this.destination.next(context_2.buffer);
      context_2.subscription.unsubscribe();
      context_2.buffer = null;
      context_2.subscription = null;
    }
    this.contexts = null;
    _super.prototype._complete.call(this);
  };
  BufferToggleSubscriber2.prototype.notifyNext = function(outerValue, innerValue) {
    outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
  };
  BufferToggleSubscriber2.prototype.notifyComplete = function(innerSub) {
    this.closeBuffer(innerSub.context);
  };
  BufferToggleSubscriber2.prototype.openBuffer = function(value) {
    try {
      var closingSelector = this.closingSelector;
      var closingNotifier = closingSelector.call(this, value);
      if (closingNotifier) {
        this.trySubscribe(closingNotifier);
      }
    } catch (err) {
      this._error(err);
    }
  };
  BufferToggleSubscriber2.prototype.closeBuffer = function(context2) {
    var contexts = this.contexts;
    if (contexts && context2) {
      var buffer2 = context2.buffer, subscription = context2.subscription;
      this.destination.next(buffer2);
      contexts.splice(contexts.indexOf(context2), 1);
      this.remove(subscription);
      subscription.unsubscribe();
    }
  };
  BufferToggleSubscriber2.prototype.trySubscribe = function(closingNotifier) {
    var contexts = this.contexts;
    var buffer2 = [];
    var subscription = new Subscription();
    var context2 = { buffer: buffer2, subscription };
    contexts.push(context2);
    var innerSubscription = subscribeToResult(this, closingNotifier, context2);
    if (!innerSubscription || innerSubscription.closed) {
      this.closeBuffer(context2);
    } else {
      innerSubscription.context = context2;
      this.add(innerSubscription);
      subscription.add(innerSubscription);
    }
  };
  return BufferToggleSubscriber2;
}(OuterSubscriber);
function bufferWhen(closingSelector) {
  return function(source) {
    return source.lift(new BufferWhenOperator(closingSelector));
  };
}
var BufferWhenOperator = /* @__PURE__ */ function() {
  function BufferWhenOperator2(closingSelector) {
    this.closingSelector = closingSelector;
  }
  BufferWhenOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
  };
  return BufferWhenOperator2;
}();
var BufferWhenSubscriber = /* @__PURE__ */ function(_super) {
  __extends(BufferWhenSubscriber2, _super);
  function BufferWhenSubscriber2(destination, closingSelector) {
    var _this = _super.call(this, destination) || this;
    _this.closingSelector = closingSelector;
    _this.subscribing = false;
    _this.openBuffer();
    return _this;
  }
  BufferWhenSubscriber2.prototype._next = function(value) {
    this.buffer.push(value);
  };
  BufferWhenSubscriber2.prototype._complete = function() {
    var buffer2 = this.buffer;
    if (buffer2) {
      this.destination.next(buffer2);
    }
    _super.prototype._complete.call(this);
  };
  BufferWhenSubscriber2.prototype._unsubscribe = function() {
    this.buffer = void 0;
    this.subscribing = false;
  };
  BufferWhenSubscriber2.prototype.notifyNext = function() {
    this.openBuffer();
  };
  BufferWhenSubscriber2.prototype.notifyComplete = function() {
    if (this.subscribing) {
      this.complete();
    } else {
      this.openBuffer();
    }
  };
  BufferWhenSubscriber2.prototype.openBuffer = function() {
    var closingSubscription = this.closingSubscription;
    if (closingSubscription) {
      this.remove(closingSubscription);
      closingSubscription.unsubscribe();
    }
    var buffer2 = this.buffer;
    if (this.buffer) {
      this.destination.next(buffer2);
    }
    this.buffer = [];
    var closingNotifier;
    try {
      var closingSelector = this.closingSelector;
      closingNotifier = closingSelector();
    } catch (err) {
      return this.error(err);
    }
    closingSubscription = new Subscription();
    this.closingSubscription = closingSubscription;
    this.add(closingSubscription);
    this.subscribing = true;
    closingSubscription.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(this)));
    this.subscribing = false;
  };
  return BufferWhenSubscriber2;
}(SimpleOuterSubscriber);
function catchError(selector) {
  return function catchErrorOperatorFunction(source) {
    var operator = new CatchOperator(selector);
    var caught = source.lift(operator);
    return operator.caught = caught;
  };
}
var CatchOperator = /* @__PURE__ */ function() {
  function CatchOperator2(selector) {
    this.selector = selector;
  }
  CatchOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
  };
  return CatchOperator2;
}();
var CatchSubscriber = /* @__PURE__ */ function(_super) {
  __extends(CatchSubscriber2, _super);
  function CatchSubscriber2(destination, selector, caught) {
    var _this = _super.call(this, destination) || this;
    _this.selector = selector;
    _this.caught = caught;
    return _this;
  }
  CatchSubscriber2.prototype.error = function(err) {
    if (!this.isStopped) {
      var result = void 0;
      try {
        result = this.selector(err, this.caught);
      } catch (err2) {
        _super.prototype.error.call(this, err2);
        return;
      }
      this._unsubscribeAndRecycle();
      var innerSubscriber = new SimpleInnerSubscriber(this);
      this.add(innerSubscriber);
      var innerSubscription = innerSubscribe(result, innerSubscriber);
      if (innerSubscription !== innerSubscriber) {
        this.add(innerSubscription);
      }
    }
  };
  return CatchSubscriber2;
}(SimpleOuterSubscriber);
function combineAll(project) {
  return function(source) {
    return source.lift(new CombineLatestOperator(project));
  };
}
function combineLatest() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  var project = null;
  if (typeof observables[observables.length - 1] === "function") {
    project = observables.pop();
  }
  if (observables.length === 1 && gosling_es_isArray(observables[0])) {
    observables = observables[0].slice();
  }
  return function(source) {
    return source.lift.call(from([source].concat(observables)), new CombineLatestOperator(project));
  };
}
function concat() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  return function(source) {
    return source.lift.call(concat$1.apply(void 0, [source].concat(observables)));
  };
}
function concatMap(project, resultSelector) {
  return mergeMap(project, resultSelector, 1);
}
function concatMapTo(innerObservable, resultSelector) {
  return concatMap(function() {
    return innerObservable;
  }, resultSelector);
}
function count(predicate) {
  return function(source) {
    return source.lift(new CountOperator(predicate, source));
  };
}
var CountOperator = /* @__PURE__ */ function() {
  function CountOperator2(predicate, source) {
    this.predicate = predicate;
    this.source = source;
  }
  CountOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source));
  };
  return CountOperator2;
}();
var CountSubscriber = /* @__PURE__ */ function(_super) {
  __extends(CountSubscriber2, _super);
  function CountSubscriber2(destination, predicate, source) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.source = source;
    _this.count = 0;
    _this.index = 0;
    return _this;
  }
  CountSubscriber2.prototype._next = function(value) {
    if (this.predicate) {
      this._tryPredicate(value);
    } else {
      this.count++;
    }
  };
  CountSubscriber2.prototype._tryPredicate = function(value) {
    var result;
    try {
      result = this.predicate(value, this.index++, this.source);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    if (result) {
      this.count++;
    }
  };
  CountSubscriber2.prototype._complete = function() {
    this.destination.next(this.count);
    this.destination.complete();
  };
  return CountSubscriber2;
}(Subscriber);
function debounce(durationSelector) {
  return function(source) {
    return source.lift(new DebounceOperator(durationSelector));
  };
}
var DebounceOperator = /* @__PURE__ */ function() {
  function DebounceOperator2(durationSelector) {
    this.durationSelector = durationSelector;
  }
  DebounceOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector));
  };
  return DebounceOperator2;
}();
var DebounceSubscriber = /* @__PURE__ */ function(_super) {
  __extends(DebounceSubscriber2, _super);
  function DebounceSubscriber2(destination, durationSelector) {
    var _this = _super.call(this, destination) || this;
    _this.durationSelector = durationSelector;
    _this.hasValue = false;
    return _this;
  }
  DebounceSubscriber2.prototype._next = function(value) {
    try {
      var result = this.durationSelector.call(this, value);
      if (result) {
        this._tryNext(value, result);
      }
    } catch (err) {
      this.destination.error(err);
    }
  };
  DebounceSubscriber2.prototype._complete = function() {
    this.emitValue();
    this.destination.complete();
  };
  DebounceSubscriber2.prototype._tryNext = function(value, duration) {
    var subscription = this.durationSubscription;
    this.value = value;
    this.hasValue = true;
    if (subscription) {
      subscription.unsubscribe();
      this.remove(subscription);
    }
    subscription = innerSubscribe(duration, new SimpleInnerSubscriber(this));
    if (subscription && !subscription.closed) {
      this.add(this.durationSubscription = subscription);
    }
  };
  DebounceSubscriber2.prototype.notifyNext = function() {
    this.emitValue();
  };
  DebounceSubscriber2.prototype.notifyComplete = function() {
    this.emitValue();
  };
  DebounceSubscriber2.prototype.emitValue = function() {
    if (this.hasValue) {
      var value = this.value;
      var subscription = this.durationSubscription;
      if (subscription) {
        this.durationSubscription = void 0;
        subscription.unsubscribe();
        this.remove(subscription);
      }
      this.value = void 0;
      this.hasValue = false;
      _super.prototype._next.call(this, value);
    }
  };
  return DebounceSubscriber2;
}(SimpleOuterSubscriber);
function debounceTime(dueTime, scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return function(source) {
    return source.lift(new DebounceTimeOperator(dueTime, scheduler));
  };
}
var DebounceTimeOperator = /* @__PURE__ */ function() {
  function DebounceTimeOperator2(dueTime, scheduler) {
    this.dueTime = dueTime;
    this.scheduler = scheduler;
  }
  DebounceTimeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
  };
  return DebounceTimeOperator2;
}();
var DebounceTimeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(DebounceTimeSubscriber2, _super);
  function DebounceTimeSubscriber2(destination, dueTime, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.dueTime = dueTime;
    _this.scheduler = scheduler;
    _this.debouncedSubscription = null;
    _this.lastValue = null;
    _this.hasValue = false;
    return _this;
  }
  DebounceTimeSubscriber2.prototype._next = function(value) {
    this.clearDebounce();
    this.lastValue = value;
    this.hasValue = true;
    this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext$1, this.dueTime, this));
  };
  DebounceTimeSubscriber2.prototype._complete = function() {
    this.debouncedNext();
    this.destination.complete();
  };
  DebounceTimeSubscriber2.prototype.debouncedNext = function() {
    this.clearDebounce();
    if (this.hasValue) {
      var lastValue = this.lastValue;
      this.lastValue = null;
      this.hasValue = false;
      this.destination.next(lastValue);
    }
  };
  DebounceTimeSubscriber2.prototype.clearDebounce = function() {
    var debouncedSubscription = this.debouncedSubscription;
    if (debouncedSubscription !== null) {
      this.remove(debouncedSubscription);
      debouncedSubscription.unsubscribe();
      this.debouncedSubscription = null;
    }
  };
  return DebounceTimeSubscriber2;
}(Subscriber);
function dispatchNext$1(subscriber) {
  subscriber.debouncedNext();
}
function defaultIfEmpty(defaultValue) {
  if (defaultValue === void 0) {
    defaultValue = null;
  }
  return function(source) {
    return source.lift(new DefaultIfEmptyOperator(defaultValue));
  };
}
var DefaultIfEmptyOperator = /* @__PURE__ */ function() {
  function DefaultIfEmptyOperator2(defaultValue) {
    this.defaultValue = defaultValue;
  }
  DefaultIfEmptyOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
  };
  return DefaultIfEmptyOperator2;
}();
var DefaultIfEmptySubscriber = /* @__PURE__ */ function(_super) {
  __extends(DefaultIfEmptySubscriber2, _super);
  function DefaultIfEmptySubscriber2(destination, defaultValue) {
    var _this = _super.call(this, destination) || this;
    _this.defaultValue = defaultValue;
    _this.isEmpty = true;
    return _this;
  }
  DefaultIfEmptySubscriber2.prototype._next = function(value) {
    this.isEmpty = false;
    this.destination.next(value);
  };
  DefaultIfEmptySubscriber2.prototype._complete = function() {
    if (this.isEmpty) {
      this.destination.next(this.defaultValue);
    }
    this.destination.complete();
  };
  return DefaultIfEmptySubscriber2;
}(Subscriber);
function isDate(value) {
  return value instanceof Date && !isNaN(+value);
}
function delay(delay2, scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  var absoluteDelay = isDate(delay2);
  var delayFor = absoluteDelay ? +delay2 - scheduler.now() : Math.abs(delay2);
  return function(source) {
    return source.lift(new DelayOperator(delayFor, scheduler));
  };
}
var DelayOperator = /* @__PURE__ */ function() {
  function DelayOperator2(delay2, scheduler) {
    this.delay = delay2;
    this.scheduler = scheduler;
  }
  DelayOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
  };
  return DelayOperator2;
}();
var DelaySubscriber = /* @__PURE__ */ function(_super) {
  __extends(DelaySubscriber2, _super);
  function DelaySubscriber2(destination, delay2, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.delay = delay2;
    _this.scheduler = scheduler;
    _this.queue = [];
    _this.active = false;
    _this.errored = false;
    return _this;
  }
  DelaySubscriber2.dispatch = function(state) {
    var source = state.source;
    var queue2 = source.queue;
    var scheduler = state.scheduler;
    var destination = state.destination;
    while (queue2.length > 0 && queue2[0].time - scheduler.now() <= 0) {
      queue2.shift().notification.observe(destination);
    }
    if (queue2.length > 0) {
      var delay_1 = Math.max(0, queue2[0].time - scheduler.now());
      this.schedule(state, delay_1);
    } else {
      this.unsubscribe();
      source.active = false;
    }
  };
  DelaySubscriber2.prototype._schedule = function(scheduler) {
    this.active = true;
    var destination = this.destination;
    destination.add(scheduler.schedule(DelaySubscriber2.dispatch, this.delay, {
      source: this,
      destination: this.destination,
      scheduler
    }));
  };
  DelaySubscriber2.prototype.scheduleNotification = function(notification) {
    if (this.errored === true) {
      return;
    }
    var scheduler = this.scheduler;
    var message = new DelayMessage(scheduler.now() + this.delay, notification);
    this.queue.push(message);
    if (this.active === false) {
      this._schedule(scheduler);
    }
  };
  DelaySubscriber2.prototype._next = function(value) {
    this.scheduleNotification(Notification.createNext(value));
  };
  DelaySubscriber2.prototype._error = function(err) {
    this.errored = true;
    this.queue = [];
    this.destination.error(err);
    this.unsubscribe();
  };
  DelaySubscriber2.prototype._complete = function() {
    this.scheduleNotification(Notification.createComplete());
    this.unsubscribe();
  };
  return DelaySubscriber2;
}(Subscriber);
var DelayMessage = /* @__PURE__ */ function() {
  function DelayMessage2(time2, notification) {
    this.time = time2;
    this.notification = notification;
  }
  return DelayMessage2;
}();
function delayWhen(delayDurationSelector, subscriptionDelay) {
  if (subscriptionDelay) {
    return function(source) {
      return new SubscriptionDelayObservable(source, subscriptionDelay).lift(new DelayWhenOperator(delayDurationSelector));
    };
  }
  return function(source) {
    return source.lift(new DelayWhenOperator(delayDurationSelector));
  };
}
var DelayWhenOperator = /* @__PURE__ */ function() {
  function DelayWhenOperator2(delayDurationSelector) {
    this.delayDurationSelector = delayDurationSelector;
  }
  DelayWhenOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector));
  };
  return DelayWhenOperator2;
}();
var DelayWhenSubscriber = /* @__PURE__ */ function(_super) {
  __extends(DelayWhenSubscriber2, _super);
  function DelayWhenSubscriber2(destination, delayDurationSelector) {
    var _this = _super.call(this, destination) || this;
    _this.delayDurationSelector = delayDurationSelector;
    _this.completed = false;
    _this.delayNotifierSubscriptions = [];
    _this.index = 0;
    return _this;
  }
  DelayWhenSubscriber2.prototype.notifyNext = function(outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) {
    this.destination.next(outerValue);
    this.removeSubscription(innerSub);
    this.tryComplete();
  };
  DelayWhenSubscriber2.prototype.notifyError = function(error, innerSub) {
    this._error(error);
  };
  DelayWhenSubscriber2.prototype.notifyComplete = function(innerSub) {
    var value = this.removeSubscription(innerSub);
    if (value) {
      this.destination.next(value);
    }
    this.tryComplete();
  };
  DelayWhenSubscriber2.prototype._next = function(value) {
    var index = this.index++;
    try {
      var delayNotifier = this.delayDurationSelector(value, index);
      if (delayNotifier) {
        this.tryDelay(delayNotifier, value);
      }
    } catch (err) {
      this.destination.error(err);
    }
  };
  DelayWhenSubscriber2.prototype._complete = function() {
    this.completed = true;
    this.tryComplete();
    this.unsubscribe();
  };
  DelayWhenSubscriber2.prototype.removeSubscription = function(subscription) {
    subscription.unsubscribe();
    var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
    if (subscriptionIdx !== -1) {
      this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
    }
    return subscription.outerValue;
  };
  DelayWhenSubscriber2.prototype.tryDelay = function(delayNotifier, value) {
    var notifierSubscription = subscribeToResult(this, delayNotifier, value);
    if (notifierSubscription && !notifierSubscription.closed) {
      var destination = this.destination;
      destination.add(notifierSubscription);
      this.delayNotifierSubscriptions.push(notifierSubscription);
    }
  };
  DelayWhenSubscriber2.prototype.tryComplete = function() {
    if (this.completed && this.delayNotifierSubscriptions.length === 0) {
      this.destination.complete();
    }
  };
  return DelayWhenSubscriber2;
}(OuterSubscriber);
var SubscriptionDelayObservable = /* @__PURE__ */ function(_super) {
  __extends(SubscriptionDelayObservable2, _super);
  function SubscriptionDelayObservable2(source, subscriptionDelay) {
    var _this = _super.call(this) || this;
    _this.source = source;
    _this.subscriptionDelay = subscriptionDelay;
    return _this;
  }
  SubscriptionDelayObservable2.prototype._subscribe = function(subscriber) {
    this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source));
  };
  return SubscriptionDelayObservable2;
}(Observable);
var SubscriptionDelaySubscriber = /* @__PURE__ */ function(_super) {
  __extends(SubscriptionDelaySubscriber2, _super);
  function SubscriptionDelaySubscriber2(parent, source) {
    var _this = _super.call(this) || this;
    _this.parent = parent;
    _this.source = source;
    _this.sourceSubscribed = false;
    return _this;
  }
  SubscriptionDelaySubscriber2.prototype._next = function(unused) {
    this.subscribeToSource();
  };
  SubscriptionDelaySubscriber2.prototype._error = function(err) {
    this.unsubscribe();
    this.parent.error(err);
  };
  SubscriptionDelaySubscriber2.prototype._complete = function() {
    this.unsubscribe();
    this.subscribeToSource();
  };
  SubscriptionDelaySubscriber2.prototype.subscribeToSource = function() {
    if (!this.sourceSubscribed) {
      this.sourceSubscribed = true;
      this.unsubscribe();
      this.source.subscribe(this.parent);
    }
  };
  return SubscriptionDelaySubscriber2;
}(Subscriber);
function dematerialize() {
  return function dematerializeOperatorFunction(source) {
    return source.lift(new DeMaterializeOperator());
  };
}
var DeMaterializeOperator = /* @__PURE__ */ function() {
  function DeMaterializeOperator2() {
  }
  DeMaterializeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DeMaterializeSubscriber(subscriber));
  };
  return DeMaterializeOperator2;
}();
var DeMaterializeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(DeMaterializeSubscriber2, _super);
  function DeMaterializeSubscriber2(destination) {
    return _super.call(this, destination) || this;
  }
  DeMaterializeSubscriber2.prototype._next = function(value) {
    value.observe(this.destination);
  };
  return DeMaterializeSubscriber2;
}(Subscriber);
function distinct(keySelector, flushes) {
  return function(source) {
    return source.lift(new DistinctOperator(keySelector, flushes));
  };
}
var DistinctOperator = /* @__PURE__ */ function() {
  function DistinctOperator2(keySelector, flushes) {
    this.keySelector = keySelector;
    this.flushes = flushes;
  }
  DistinctOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
  };
  return DistinctOperator2;
}();
var DistinctSubscriber = /* @__PURE__ */ function(_super) {
  __extends(DistinctSubscriber2, _super);
  function DistinctSubscriber2(destination, keySelector, flushes) {
    var _this = _super.call(this, destination) || this;
    _this.keySelector = keySelector;
    _this.values = new Set();
    if (flushes) {
      _this.add(innerSubscribe(flushes, new SimpleInnerSubscriber(_this)));
    }
    return _this;
  }
  DistinctSubscriber2.prototype.notifyNext = function() {
    this.values.clear();
  };
  DistinctSubscriber2.prototype.notifyError = function(error) {
    this._error(error);
  };
  DistinctSubscriber2.prototype._next = function(value) {
    if (this.keySelector) {
      this._useKeySelector(value);
    } else {
      this._finalizeNext(value, value);
    }
  };
  DistinctSubscriber2.prototype._useKeySelector = function(value) {
    var key;
    var destination = this.destination;
    try {
      key = this.keySelector(value);
    } catch (err) {
      destination.error(err);
      return;
    }
    this._finalizeNext(key, value);
  };
  DistinctSubscriber2.prototype._finalizeNext = function(key, value) {
    var values = this.values;
    if (!values.has(key)) {
      values.add(key);
      this.destination.next(value);
    }
  };
  return DistinctSubscriber2;
}(SimpleOuterSubscriber);
function distinctUntilChanged(compare2, keySelector) {
  return function(source) {
    return source.lift(new DistinctUntilChangedOperator(compare2, keySelector));
  };
}
var DistinctUntilChangedOperator = /* @__PURE__ */ function() {
  function DistinctUntilChangedOperator2(compare2, keySelector) {
    this.compare = compare2;
    this.keySelector = keySelector;
  }
  DistinctUntilChangedOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
  };
  return DistinctUntilChangedOperator2;
}();
var DistinctUntilChangedSubscriber = /* @__PURE__ */ function(_super) {
  __extends(DistinctUntilChangedSubscriber2, _super);
  function DistinctUntilChangedSubscriber2(destination, compare2, keySelector) {
    var _this = _super.call(this, destination) || this;
    _this.keySelector = keySelector;
    _this.hasKey = false;
    if (typeof compare2 === "function") {
      _this.compare = compare2;
    }
    return _this;
  }
  DistinctUntilChangedSubscriber2.prototype.compare = function(x, y) {
    return x === y;
  };
  DistinctUntilChangedSubscriber2.prototype._next = function(value) {
    var key;
    try {
      var keySelector = this.keySelector;
      key = keySelector ? keySelector(value) : value;
    } catch (err) {
      return this.destination.error(err);
    }
    var result = false;
    if (this.hasKey) {
      try {
        var compare2 = this.compare;
        result = compare2(this.key, key);
      } catch (err) {
        return this.destination.error(err);
      }
    } else {
      this.hasKey = true;
    }
    if (!result) {
      this.key = key;
      this.destination.next(value);
    }
  };
  return DistinctUntilChangedSubscriber2;
}(Subscriber);
function distinctUntilKeyChanged(key, compare2) {
  return distinctUntilChanged(function(x, y) {
    return compare2 ? compare2(x[key], y[key]) : x[key] === y[key];
  });
}
function throwIfEmpty(errorFactory) {
  if (errorFactory === void 0) {
    errorFactory = defaultErrorFactory;
  }
  return function(source) {
    return source.lift(new ThrowIfEmptyOperator(errorFactory));
  };
}
var ThrowIfEmptyOperator = /* @__PURE__ */ function() {
  function ThrowIfEmptyOperator2(errorFactory) {
    this.errorFactory = errorFactory;
  }
  ThrowIfEmptyOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));
  };
  return ThrowIfEmptyOperator2;
}();
var ThrowIfEmptySubscriber = /* @__PURE__ */ function(_super) {
  __extends(ThrowIfEmptySubscriber2, _super);
  function ThrowIfEmptySubscriber2(destination, errorFactory) {
    var _this = _super.call(this, destination) || this;
    _this.errorFactory = errorFactory;
    _this.hasValue = false;
    return _this;
  }
  ThrowIfEmptySubscriber2.prototype._next = function(value) {
    this.hasValue = true;
    this.destination.next(value);
  };
  ThrowIfEmptySubscriber2.prototype._complete = function() {
    if (!this.hasValue) {
      var err = void 0;
      try {
        err = this.errorFactory();
      } catch (e) {
        err = e;
      }
      this.destination.error(err);
    } else {
      return this.destination.complete();
    }
  };
  return ThrowIfEmptySubscriber2;
}(Subscriber);
function defaultErrorFactory() {
  return new EmptyError();
}
function take(count2) {
  return function(source) {
    if (count2 === 0) {
      return empty();
    } else {
      return source.lift(new TakeOperator(count2));
    }
  };
}
var TakeOperator = /* @__PURE__ */ function() {
  function TakeOperator2(total) {
    this.total = total;
    if (this.total < 0) {
      throw new ArgumentOutOfRangeError();
    }
  }
  TakeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new TakeSubscriber(subscriber, this.total));
  };
  return TakeOperator2;
}();
var TakeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(TakeSubscriber2, _super);
  function TakeSubscriber2(destination, total) {
    var _this = _super.call(this, destination) || this;
    _this.total = total;
    _this.count = 0;
    return _this;
  }
  TakeSubscriber2.prototype._next = function(value) {
    var total = this.total;
    var count2 = ++this.count;
    if (count2 <= total) {
      this.destination.next(value);
      if (count2 === total) {
        this.destination.complete();
        this.unsubscribe();
      }
    }
  };
  return TakeSubscriber2;
}(Subscriber);
function elementAt(index, defaultValue) {
  if (index < 0) {
    throw new ArgumentOutOfRangeError();
  }
  var hasDefaultValue = arguments.length >= 2;
  return function(source) {
    return source.pipe(filter(function(v, i) {
      return i === index;
    }), take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function() {
      return new ArgumentOutOfRangeError();
    }));
  };
}
function endWith() {
  var array = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    array[_i] = arguments[_i];
  }
  return function(source) {
    return concat$1(source, of.apply(void 0, array));
  };
}
function every(predicate, thisArg) {
  return function(source) {
    return source.lift(new EveryOperator(predicate, thisArg, source));
  };
}
var EveryOperator = /* @__PURE__ */ function() {
  function EveryOperator2(predicate, thisArg, source) {
    this.predicate = predicate;
    this.thisArg = thisArg;
    this.source = source;
  }
  EveryOperator2.prototype.call = function(observer, source) {
    return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source));
  };
  return EveryOperator2;
}();
var EverySubscriber = /* @__PURE__ */ function(_super) {
  __extends(EverySubscriber2, _super);
  function EverySubscriber2(destination, predicate, thisArg, source) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.thisArg = thisArg;
    _this.source = source;
    _this.index = 0;
    _this.thisArg = thisArg || _this;
    return _this;
  }
  EverySubscriber2.prototype.notifyComplete = function(everyValueMatch) {
    this.destination.next(everyValueMatch);
    this.destination.complete();
  };
  EverySubscriber2.prototype._next = function(value) {
    var result = false;
    try {
      result = this.predicate.call(this.thisArg, value, this.index++, this.source);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    if (!result) {
      this.notifyComplete(false);
    }
  };
  EverySubscriber2.prototype._complete = function() {
    this.notifyComplete(true);
  };
  return EverySubscriber2;
}(Subscriber);
function exhaust() {
  return function(source) {
    return source.lift(new SwitchFirstOperator());
  };
}
var SwitchFirstOperator = /* @__PURE__ */ function() {
  function SwitchFirstOperator2() {
  }
  SwitchFirstOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SwitchFirstSubscriber(subscriber));
  };
  return SwitchFirstOperator2;
}();
var SwitchFirstSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SwitchFirstSubscriber2, _super);
  function SwitchFirstSubscriber2(destination) {
    var _this = _super.call(this, destination) || this;
    _this.hasCompleted = false;
    _this.hasSubscription = false;
    return _this;
  }
  SwitchFirstSubscriber2.prototype._next = function(value) {
    if (!this.hasSubscription) {
      this.hasSubscription = true;
      this.add(innerSubscribe(value, new SimpleInnerSubscriber(this)));
    }
  };
  SwitchFirstSubscriber2.prototype._complete = function() {
    this.hasCompleted = true;
    if (!this.hasSubscription) {
      this.destination.complete();
    }
  };
  SwitchFirstSubscriber2.prototype.notifyComplete = function() {
    this.hasSubscription = false;
    if (this.hasCompleted) {
      this.destination.complete();
    }
  };
  return SwitchFirstSubscriber2;
}(SimpleOuterSubscriber);
function exhaustMap(project, resultSelector) {
  if (resultSelector) {
    return function(source) {
      return source.pipe(exhaustMap(function(a, i) {
        return from(project(a, i)).pipe(gosling_es_map(function(b, ii) {
          return resultSelector(a, b, i, ii);
        }));
      }));
    };
  }
  return function(source) {
    return source.lift(new ExhaustMapOperator(project));
  };
}
var ExhaustMapOperator = /* @__PURE__ */ function() {
  function ExhaustMapOperator2(project) {
    this.project = project;
  }
  ExhaustMapOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project));
  };
  return ExhaustMapOperator2;
}();
var ExhaustMapSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ExhaustMapSubscriber2, _super);
  function ExhaustMapSubscriber2(destination, project) {
    var _this = _super.call(this, destination) || this;
    _this.project = project;
    _this.hasSubscription = false;
    _this.hasCompleted = false;
    _this.index = 0;
    return _this;
  }
  ExhaustMapSubscriber2.prototype._next = function(value) {
    if (!this.hasSubscription) {
      this.tryNext(value);
    }
  };
  ExhaustMapSubscriber2.prototype.tryNext = function(value) {
    var result;
    var index = this.index++;
    try {
      result = this.project(value, index);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.hasSubscription = true;
    this._innerSub(result);
  };
  ExhaustMapSubscriber2.prototype._innerSub = function(result) {
    var innerSubscriber = new SimpleInnerSubscriber(this);
    var destination = this.destination;
    destination.add(innerSubscriber);
    var innerSubscription = innerSubscribe(result, innerSubscriber);
    if (innerSubscription !== innerSubscriber) {
      destination.add(innerSubscription);
    }
  };
  ExhaustMapSubscriber2.prototype._complete = function() {
    this.hasCompleted = true;
    if (!this.hasSubscription) {
      this.destination.complete();
    }
    this.unsubscribe();
  };
  ExhaustMapSubscriber2.prototype.notifyNext = function(innerValue) {
    this.destination.next(innerValue);
  };
  ExhaustMapSubscriber2.prototype.notifyError = function(err) {
    this.destination.error(err);
  };
  ExhaustMapSubscriber2.prototype.notifyComplete = function() {
    this.hasSubscription = false;
    if (this.hasCompleted) {
      this.destination.complete();
    }
  };
  return ExhaustMapSubscriber2;
}(SimpleOuterSubscriber);
function expand(project, concurrent, scheduler) {
  if (concurrent === void 0) {
    concurrent = Number.POSITIVE_INFINITY;
  }
  concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
  return function(source) {
    return source.lift(new ExpandOperator(project, concurrent, scheduler));
  };
}
var ExpandOperator = /* @__PURE__ */ function() {
  function ExpandOperator2(project, concurrent, scheduler) {
    this.project = project;
    this.concurrent = concurrent;
    this.scheduler = scheduler;
  }
  ExpandOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
  };
  return ExpandOperator2;
}();
var ExpandSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ExpandSubscriber2, _super);
  function ExpandSubscriber2(destination, project, concurrent, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.project = project;
    _this.concurrent = concurrent;
    _this.scheduler = scheduler;
    _this.index = 0;
    _this.active = 0;
    _this.hasCompleted = false;
    if (concurrent < Number.POSITIVE_INFINITY) {
      _this.buffer = [];
    }
    return _this;
  }
  ExpandSubscriber2.dispatch = function(arg) {
    var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
    subscriber.subscribeToProjection(result, value, index);
  };
  ExpandSubscriber2.prototype._next = function(value) {
    var destination = this.destination;
    if (destination.closed) {
      this._complete();
      return;
    }
    var index = this.index++;
    if (this.active < this.concurrent) {
      destination.next(value);
      try {
        var project = this.project;
        var result = project(value, index);
        if (!this.scheduler) {
          this.subscribeToProjection(result, value, index);
        } else {
          var state = { subscriber: this, result, value, index };
          var destination_1 = this.destination;
          destination_1.add(this.scheduler.schedule(ExpandSubscriber2.dispatch, 0, state));
        }
      } catch (e) {
        destination.error(e);
      }
    } else {
      this.buffer.push(value);
    }
  };
  ExpandSubscriber2.prototype.subscribeToProjection = function(result, value, index) {
    this.active++;
    var destination = this.destination;
    destination.add(innerSubscribe(result, new SimpleInnerSubscriber(this)));
  };
  ExpandSubscriber2.prototype._complete = function() {
    this.hasCompleted = true;
    if (this.hasCompleted && this.active === 0) {
      this.destination.complete();
    }
    this.unsubscribe();
  };
  ExpandSubscriber2.prototype.notifyNext = function(innerValue) {
    this._next(innerValue);
  };
  ExpandSubscriber2.prototype.notifyComplete = function() {
    var buffer2 = this.buffer;
    this.active--;
    if (buffer2 && buffer2.length > 0) {
      this._next(buffer2.shift());
    }
    if (this.hasCompleted && this.active === 0) {
      this.destination.complete();
    }
  };
  return ExpandSubscriber2;
}(SimpleOuterSubscriber);
function finalize(callback) {
  return function(source) {
    return source.lift(new FinallyOperator(callback));
  };
}
var FinallyOperator = /* @__PURE__ */ function() {
  function FinallyOperator2(callback) {
    this.callback = callback;
  }
  FinallyOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new FinallySubscriber(subscriber, this.callback));
  };
  return FinallyOperator2;
}();
var FinallySubscriber = /* @__PURE__ */ function(_super) {
  __extends(FinallySubscriber2, _super);
  function FinallySubscriber2(destination, callback) {
    var _this = _super.call(this, destination) || this;
    _this.add(new Subscription(callback));
    return _this;
  }
  return FinallySubscriber2;
}(Subscriber);
function find(predicate, thisArg) {
  if (typeof predicate !== "function") {
    throw new TypeError("predicate is not a function");
  }
  return function(source) {
    return source.lift(new FindValueOperator(predicate, source, false, thisArg));
  };
}
var FindValueOperator = /* @__PURE__ */ function() {
  function FindValueOperator2(predicate, source, yieldIndex, thisArg) {
    this.predicate = predicate;
    this.source = source;
    this.yieldIndex = yieldIndex;
    this.thisArg = thisArg;
  }
  FindValueOperator2.prototype.call = function(observer, source) {
    return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
  };
  return FindValueOperator2;
}();
var FindValueSubscriber = /* @__PURE__ */ function(_super) {
  __extends(FindValueSubscriber2, _super);
  function FindValueSubscriber2(destination, predicate, source, yieldIndex, thisArg) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.source = source;
    _this.yieldIndex = yieldIndex;
    _this.thisArg = thisArg;
    _this.index = 0;
    return _this;
  }
  FindValueSubscriber2.prototype.notifyComplete = function(value) {
    var destination = this.destination;
    destination.next(value);
    destination.complete();
    this.unsubscribe();
  };
  FindValueSubscriber2.prototype._next = function(value) {
    var _a = this, predicate = _a.predicate, thisArg = _a.thisArg;
    var index = this.index++;
    try {
      var result = predicate.call(thisArg || this, value, index, this.source);
      if (result) {
        this.notifyComplete(this.yieldIndex ? index : value);
      }
    } catch (err) {
      this.destination.error(err);
    }
  };
  FindValueSubscriber2.prototype._complete = function() {
    this.notifyComplete(this.yieldIndex ? -1 : void 0);
  };
  return FindValueSubscriber2;
}(Subscriber);
function findIndex(predicate, thisArg) {
  return function(source) {
    return source.lift(new FindValueOperator(predicate, source, true, thisArg));
  };
}
function first(predicate, defaultValue) {
  var hasDefaultValue = arguments.length >= 2;
  return function(source) {
    return source.pipe(predicate ? filter(function(v, i) {
      return predicate(v, i, source);
    }) : gosling_es_identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function() {
      return new EmptyError();
    }));
  };
}
function ignoreElements() {
  return function ignoreElementsOperatorFunction(source) {
    return source.lift(new IgnoreElementsOperator());
  };
}
var IgnoreElementsOperator = /* @__PURE__ */ function() {
  function IgnoreElementsOperator2() {
  }
  IgnoreElementsOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new IgnoreElementsSubscriber(subscriber));
  };
  return IgnoreElementsOperator2;
}();
var IgnoreElementsSubscriber = /* @__PURE__ */ function(_super) {
  __extends(IgnoreElementsSubscriber2, _super);
  function IgnoreElementsSubscriber2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  IgnoreElementsSubscriber2.prototype._next = function(unused) {
  };
  return IgnoreElementsSubscriber2;
}(Subscriber);
function isEmpty() {
  return function(source) {
    return source.lift(new IsEmptyOperator());
  };
}
var IsEmptyOperator = /* @__PURE__ */ function() {
  function IsEmptyOperator2() {
  }
  IsEmptyOperator2.prototype.call = function(observer, source) {
    return source.subscribe(new IsEmptySubscriber(observer));
  };
  return IsEmptyOperator2;
}();
var IsEmptySubscriber = /* @__PURE__ */ function(_super) {
  __extends(IsEmptySubscriber2, _super);
  function IsEmptySubscriber2(destination) {
    return _super.call(this, destination) || this;
  }
  IsEmptySubscriber2.prototype.notifyComplete = function(isEmpty2) {
    var destination = this.destination;
    destination.next(isEmpty2);
    destination.complete();
  };
  IsEmptySubscriber2.prototype._next = function(value) {
    this.notifyComplete(false);
  };
  IsEmptySubscriber2.prototype._complete = function() {
    this.notifyComplete(true);
  };
  return IsEmptySubscriber2;
}(Subscriber);
function takeLast(count2) {
  return function takeLastOperatorFunction(source) {
    if (count2 === 0) {
      return empty();
    } else {
      return source.lift(new TakeLastOperator(count2));
    }
  };
}
var TakeLastOperator = /* @__PURE__ */ function() {
  function TakeLastOperator2(total) {
    this.total = total;
    if (this.total < 0) {
      throw new ArgumentOutOfRangeError();
    }
  }
  TakeLastOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
  };
  return TakeLastOperator2;
}();
var TakeLastSubscriber = /* @__PURE__ */ function(_super) {
  __extends(TakeLastSubscriber2, _super);
  function TakeLastSubscriber2(destination, total) {
    var _this = _super.call(this, destination) || this;
    _this.total = total;
    _this.ring = new Array();
    _this.count = 0;
    return _this;
  }
  TakeLastSubscriber2.prototype._next = function(value) {
    var ring = this.ring;
    var total = this.total;
    var count2 = this.count++;
    if (ring.length < total) {
      ring.push(value);
    } else {
      var index = count2 % total;
      ring[index] = value;
    }
  };
  TakeLastSubscriber2.prototype._complete = function() {
    var destination = this.destination;
    var count2 = this.count;
    if (count2 > 0) {
      var total = this.count >= this.total ? this.total : this.count;
      var ring = this.ring;
      for (var i = 0; i < total; i++) {
        var idx = count2++ % total;
        destination.next(ring[idx]);
      }
    }
    destination.complete();
  };
  return TakeLastSubscriber2;
}(Subscriber);
function last(predicate, defaultValue) {
  var hasDefaultValue = arguments.length >= 2;
  return function(source) {
    return source.pipe(predicate ? filter(function(v, i) {
      return predicate(v, i, source);
    }) : gosling_es_identity, takeLast(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function() {
      return new EmptyError();
    }));
  };
}
function mapTo(value) {
  return function(source) {
    return source.lift(new MapToOperator(value));
  };
}
var MapToOperator = /* @__PURE__ */ function() {
  function MapToOperator2(value) {
    this.value = value;
  }
  MapToOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new MapToSubscriber(subscriber, this.value));
  };
  return MapToOperator2;
}();
var MapToSubscriber = /* @__PURE__ */ function(_super) {
  __extends(MapToSubscriber2, _super);
  function MapToSubscriber2(destination, value) {
    var _this = _super.call(this, destination) || this;
    _this.value = value;
    return _this;
  }
  MapToSubscriber2.prototype._next = function(x) {
    this.destination.next(this.value);
  };
  return MapToSubscriber2;
}(Subscriber);
function materialize() {
  return function materializeOperatorFunction(source) {
    return source.lift(new MaterializeOperator());
  };
}
var MaterializeOperator = /* @__PURE__ */ function() {
  function MaterializeOperator2() {
  }
  MaterializeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new MaterializeSubscriber(subscriber));
  };
  return MaterializeOperator2;
}();
var MaterializeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(MaterializeSubscriber2, _super);
  function MaterializeSubscriber2(destination) {
    return _super.call(this, destination) || this;
  }
  MaterializeSubscriber2.prototype._next = function(value) {
    this.destination.next(Notification.createNext(value));
  };
  MaterializeSubscriber2.prototype._error = function(err) {
    var destination = this.destination;
    destination.next(Notification.createError(err));
    destination.complete();
  };
  MaterializeSubscriber2.prototype._complete = function() {
    var destination = this.destination;
    destination.next(Notification.createComplete());
    destination.complete();
  };
  return MaterializeSubscriber2;
}(Subscriber);
function scan(accumulator, seed) {
  var hasSeed = false;
  if (arguments.length >= 2) {
    hasSeed = true;
  }
  return function scanOperatorFunction(source) {
    return source.lift(new ScanOperator(accumulator, seed, hasSeed));
  };
}
var ScanOperator = /* @__PURE__ */ function() {
  function ScanOperator2(accumulator, seed, hasSeed) {
    if (hasSeed === void 0) {
      hasSeed = false;
    }
    this.accumulator = accumulator;
    this.seed = seed;
    this.hasSeed = hasSeed;
  }
  ScanOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
  };
  return ScanOperator2;
}();
var ScanSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ScanSubscriber2, _super);
  function ScanSubscriber2(destination, accumulator, _seed, hasSeed) {
    var _this = _super.call(this, destination) || this;
    _this.accumulator = accumulator;
    _this._seed = _seed;
    _this.hasSeed = hasSeed;
    _this.index = 0;
    return _this;
  }
  Object.defineProperty(ScanSubscriber2.prototype, "seed", {
    get: function() {
      return this._seed;
    },
    set: function(value) {
      this.hasSeed = true;
      this._seed = value;
    },
    enumerable: true,
    configurable: true
  });
  ScanSubscriber2.prototype._next = function(value) {
    if (!this.hasSeed) {
      this.seed = value;
      this.destination.next(value);
    } else {
      return this._tryNext(value);
    }
  };
  ScanSubscriber2.prototype._tryNext = function(value) {
    var index = this.index++;
    var result;
    try {
      result = this.accumulator(this.seed, value, index);
    } catch (err) {
      this.destination.error(err);
    }
    this.seed = result;
    this.destination.next(result);
  };
  return ScanSubscriber2;
}(Subscriber);
function reduce(accumulator, seed) {
  if (arguments.length >= 2) {
    return function reduceOperatorFunctionWithSeed(source) {
      return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source);
    };
  }
  return function reduceOperatorFunction(source) {
    return pipe(scan(function(acc, value, index) {
      return accumulator(acc, value, index + 1);
    }), takeLast(1))(source);
  };
}
function gosling_es_max(comparer) {
  var max2 = typeof comparer === "function" ? function(x, y) {
    return comparer(x, y) > 0 ? x : y;
  } : function(x, y) {
    return x > y ? x : y;
  };
  return reduce(max2);
}
function merge() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  return function(source) {
    return source.lift.call(merge$1.apply(void 0, [source].concat(observables)));
  };
}
function mergeMapTo(innerObservable, resultSelector, concurrent) {
  if (concurrent === void 0) {
    concurrent = Number.POSITIVE_INFINITY;
  }
  if (typeof resultSelector === "function") {
    return mergeMap(function() {
      return innerObservable;
    }, resultSelector, concurrent);
  }
  if (typeof resultSelector === "number") {
    concurrent = resultSelector;
  }
  return mergeMap(function() {
    return innerObservable;
  }, concurrent);
}
function mergeScan(accumulator, seed, concurrent) {
  if (concurrent === void 0) {
    concurrent = Number.POSITIVE_INFINITY;
  }
  return function(source) {
    return source.lift(new MergeScanOperator(accumulator, seed, concurrent));
  };
}
var MergeScanOperator = /* @__PURE__ */ function() {
  function MergeScanOperator2(accumulator, seed, concurrent) {
    this.accumulator = accumulator;
    this.seed = seed;
    this.concurrent = concurrent;
  }
  MergeScanOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
  };
  return MergeScanOperator2;
}();
var MergeScanSubscriber = /* @__PURE__ */ function(_super) {
  __extends(MergeScanSubscriber2, _super);
  function MergeScanSubscriber2(destination, accumulator, acc, concurrent) {
    var _this = _super.call(this, destination) || this;
    _this.accumulator = accumulator;
    _this.acc = acc;
    _this.concurrent = concurrent;
    _this.hasValue = false;
    _this.hasCompleted = false;
    _this.buffer = [];
    _this.active = 0;
    _this.index = 0;
    return _this;
  }
  MergeScanSubscriber2.prototype._next = function(value) {
    if (this.active < this.concurrent) {
      var index = this.index++;
      var destination = this.destination;
      var ish = void 0;
      try {
        var accumulator = this.accumulator;
        ish = accumulator(this.acc, value, index);
      } catch (e) {
        return destination.error(e);
      }
      this.active++;
      this._innerSub(ish);
    } else {
      this.buffer.push(value);
    }
  };
  MergeScanSubscriber2.prototype._innerSub = function(ish) {
    var innerSubscriber = new SimpleInnerSubscriber(this);
    var destination = this.destination;
    destination.add(innerSubscriber);
    var innerSubscription = innerSubscribe(ish, innerSubscriber);
    if (innerSubscription !== innerSubscriber) {
      destination.add(innerSubscription);
    }
  };
  MergeScanSubscriber2.prototype._complete = function() {
    this.hasCompleted = true;
    if (this.active === 0 && this.buffer.length === 0) {
      if (this.hasValue === false) {
        this.destination.next(this.acc);
      }
      this.destination.complete();
    }
    this.unsubscribe();
  };
  MergeScanSubscriber2.prototype.notifyNext = function(innerValue) {
    var destination = this.destination;
    this.acc = innerValue;
    this.hasValue = true;
    destination.next(innerValue);
  };
  MergeScanSubscriber2.prototype.notifyComplete = function() {
    var buffer2 = this.buffer;
    this.active--;
    if (buffer2.length > 0) {
      this._next(buffer2.shift());
    } else if (this.active === 0 && this.hasCompleted) {
      if (this.hasValue === false) {
        this.destination.next(this.acc);
      }
      this.destination.complete();
    }
  };
  return MergeScanSubscriber2;
}(SimpleOuterSubscriber);
function gosling_es_min(comparer) {
  var min2 = typeof comparer === "function" ? function(x, y) {
    return comparer(x, y) < 0 ? x : y;
  } : function(x, y) {
    return x < y ? x : y;
  };
  return reduce(min2);
}
function multicast(subjectOrSubjectFactory, selector) {
  return function multicastOperatorFunction(source) {
    var subjectFactory;
    if (typeof subjectOrSubjectFactory === "function") {
      subjectFactory = subjectOrSubjectFactory;
    } else {
      subjectFactory = function subjectFactory2() {
        return subjectOrSubjectFactory;
      };
    }
    if (typeof selector === "function") {
      return source.lift(new MulticastOperator(subjectFactory, selector));
    }
    var connectable = Object.create(source, connectableObservableDescriptor);
    connectable.source = source;
    connectable.subjectFactory = subjectFactory;
    return connectable;
  };
}
var MulticastOperator = /* @__PURE__ */ function() {
  function MulticastOperator2(subjectFactory, selector) {
    this.subjectFactory = subjectFactory;
    this.selector = selector;
  }
  MulticastOperator2.prototype.call = function(subscriber, source) {
    var selector = this.selector;
    var subject = this.subjectFactory();
    var subscription = selector(subject).subscribe(subscriber);
    subscription.add(source.subscribe(subject));
    return subscription;
  };
  return MulticastOperator2;
}();
function onErrorResumeNext() {
  var nextSources = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    nextSources[_i] = arguments[_i];
  }
  if (nextSources.length === 1 && gosling_es_isArray(nextSources[0])) {
    nextSources = nextSources[0];
  }
  return function(source) {
    return source.lift(new OnErrorResumeNextOperator(nextSources));
  };
}
var OnErrorResumeNextOperator = /* @__PURE__ */ function() {
  function OnErrorResumeNextOperator2(nextSources) {
    this.nextSources = nextSources;
  }
  OnErrorResumeNextOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources));
  };
  return OnErrorResumeNextOperator2;
}();
var OnErrorResumeNextSubscriber = /* @__PURE__ */ function(_super) {
  __extends(OnErrorResumeNextSubscriber2, _super);
  function OnErrorResumeNextSubscriber2(destination, nextSources) {
    var _this = _super.call(this, destination) || this;
    _this.destination = destination;
    _this.nextSources = nextSources;
    return _this;
  }
  OnErrorResumeNextSubscriber2.prototype.notifyError = function() {
    this.subscribeToNextSource();
  };
  OnErrorResumeNextSubscriber2.prototype.notifyComplete = function() {
    this.subscribeToNextSource();
  };
  OnErrorResumeNextSubscriber2.prototype._error = function(err) {
    this.subscribeToNextSource();
    this.unsubscribe();
  };
  OnErrorResumeNextSubscriber2.prototype._complete = function() {
    this.subscribeToNextSource();
    this.unsubscribe();
  };
  OnErrorResumeNextSubscriber2.prototype.subscribeToNextSource = function() {
    var next = this.nextSources.shift();
    if (!!next) {
      var innerSubscriber = new SimpleInnerSubscriber(this);
      var destination = this.destination;
      destination.add(innerSubscriber);
      var innerSubscription = innerSubscribe(next, innerSubscriber);
      if (innerSubscription !== innerSubscriber) {
        destination.add(innerSubscription);
      }
    } else {
      this.destination.complete();
    }
  };
  return OnErrorResumeNextSubscriber2;
}(SimpleOuterSubscriber);
function pairwise() {
  return function(source) {
    return source.lift(new PairwiseOperator());
  };
}
var PairwiseOperator = /* @__PURE__ */ function() {
  function PairwiseOperator2() {
  }
  PairwiseOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new PairwiseSubscriber(subscriber));
  };
  return PairwiseOperator2;
}();
var PairwiseSubscriber = /* @__PURE__ */ function(_super) {
  __extends(PairwiseSubscriber2, _super);
  function PairwiseSubscriber2(destination) {
    var _this = _super.call(this, destination) || this;
    _this.hasPrev = false;
    return _this;
  }
  PairwiseSubscriber2.prototype._next = function(value) {
    var pair;
    if (this.hasPrev) {
      pair = [this.prev, value];
    } else {
      this.hasPrev = true;
    }
    this.prev = value;
    if (pair) {
      this.destination.next(pair);
    }
  };
  return PairwiseSubscriber2;
}(Subscriber);
function partition(predicate, thisArg) {
  return function(source) {
    return [
      filter(predicate, thisArg)(source),
      filter(not$1(predicate, thisArg))(source)
    ];
  };
}
function pluck() {
  var properties2 = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    properties2[_i] = arguments[_i];
  }
  var length = properties2.length;
  if (length === 0) {
    throw new Error("list of properties cannot be empty.");
  }
  return function(source) {
    return gosling_es_map(plucker(properties2, length))(source);
  };
}
function plucker(props, length) {
  var mapper = function(x) {
    var currentProp = x;
    for (var i = 0; i < length; i++) {
      var p = currentProp != null ? currentProp[props[i]] : void 0;
      if (p !== void 0) {
        currentProp = p;
      } else {
        return void 0;
      }
    }
    return currentProp;
  };
  return mapper;
}
function publish(selector) {
  return selector ? multicast(function() {
    return new Subject();
  }, selector) : multicast(new Subject());
}
function publishBehavior(value) {
  return function(source) {
    return multicast(new BehaviorSubject(value))(source);
  };
}
function publishLast() {
  return function(source) {
    return multicast(new AsyncSubject())(source);
  };
}
function publishReplay(bufferSize, windowTime2, selectorOrScheduler, scheduler) {
  if (selectorOrScheduler && typeof selectorOrScheduler !== "function") {
    scheduler = selectorOrScheduler;
  }
  var selector = typeof selectorOrScheduler === "function" ? selectorOrScheduler : void 0;
  var subject = new ReplaySubject(bufferSize, windowTime2, scheduler);
  return function(source) {
    return multicast(function() {
      return subject;
    }, selector)(source);
  };
}
function race() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  return function raceOperatorFunction(source) {
    if (observables.length === 1 && gosling_es_isArray(observables[0])) {
      observables = observables[0];
    }
    return source.lift.call(race$1.apply(void 0, [source].concat(observables)));
  };
}
function repeat(count2) {
  if (count2 === void 0) {
    count2 = -1;
  }
  return function(source) {
    if (count2 === 0) {
      return empty();
    } else if (count2 < 0) {
      return source.lift(new RepeatOperator(-1, source));
    } else {
      return source.lift(new RepeatOperator(count2 - 1, source));
    }
  };
}
var RepeatOperator = /* @__PURE__ */ function() {
  function RepeatOperator2(count2, source) {
    this.count = count2;
    this.source = source;
  }
  RepeatOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source));
  };
  return RepeatOperator2;
}();
var RepeatSubscriber = /* @__PURE__ */ function(_super) {
  __extends(RepeatSubscriber2, _super);
  function RepeatSubscriber2(destination, count2, source) {
    var _this = _super.call(this, destination) || this;
    _this.count = count2;
    _this.source = source;
    return _this;
  }
  RepeatSubscriber2.prototype.complete = function() {
    if (!this.isStopped) {
      var _a = this, source = _a.source, count2 = _a.count;
      if (count2 === 0) {
        return _super.prototype.complete.call(this);
      } else if (count2 > -1) {
        this.count = count2 - 1;
      }
      source.subscribe(this._unsubscribeAndRecycle());
    }
  };
  return RepeatSubscriber2;
}(Subscriber);
function repeatWhen(notifier) {
  return function(source) {
    return source.lift(new RepeatWhenOperator(notifier));
  };
}
var RepeatWhenOperator = /* @__PURE__ */ function() {
  function RepeatWhenOperator2(notifier) {
    this.notifier = notifier;
  }
  RepeatWhenOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source));
  };
  return RepeatWhenOperator2;
}();
var RepeatWhenSubscriber = /* @__PURE__ */ function(_super) {
  __extends(RepeatWhenSubscriber2, _super);
  function RepeatWhenSubscriber2(destination, notifier, source) {
    var _this = _super.call(this, destination) || this;
    _this.notifier = notifier;
    _this.source = source;
    _this.sourceIsBeingSubscribedTo = true;
    return _this;
  }
  RepeatWhenSubscriber2.prototype.notifyNext = function() {
    this.sourceIsBeingSubscribedTo = true;
    this.source.subscribe(this);
  };
  RepeatWhenSubscriber2.prototype.notifyComplete = function() {
    if (this.sourceIsBeingSubscribedTo === false) {
      return _super.prototype.complete.call(this);
    }
  };
  RepeatWhenSubscriber2.prototype.complete = function() {
    this.sourceIsBeingSubscribedTo = false;
    if (!this.isStopped) {
      if (!this.retries) {
        this.subscribeToRetries();
      }
      if (!this.retriesSubscription || this.retriesSubscription.closed) {
        return _super.prototype.complete.call(this);
      }
      this._unsubscribeAndRecycle();
      this.notifications.next(void 0);
    }
  };
  RepeatWhenSubscriber2.prototype._unsubscribe = function() {
    var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription;
    if (notifications) {
      notifications.unsubscribe();
      this.notifications = void 0;
    }
    if (retriesSubscription) {
      retriesSubscription.unsubscribe();
      this.retriesSubscription = void 0;
    }
    this.retries = void 0;
  };
  RepeatWhenSubscriber2.prototype._unsubscribeAndRecycle = function() {
    var _unsubscribe = this._unsubscribe;
    this._unsubscribe = null;
    _super.prototype._unsubscribeAndRecycle.call(this);
    this._unsubscribe = _unsubscribe;
    return this;
  };
  RepeatWhenSubscriber2.prototype.subscribeToRetries = function() {
    this.notifications = new Subject();
    var retries;
    try {
      var notifier = this.notifier;
      retries = notifier(this.notifications);
    } catch (e) {
      return _super.prototype.complete.call(this);
    }
    this.retries = retries;
    this.retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this));
  };
  return RepeatWhenSubscriber2;
}(SimpleOuterSubscriber);
function retry(count2) {
  if (count2 === void 0) {
    count2 = -1;
  }
  return function(source) {
    return source.lift(new RetryOperator(count2, source));
  };
}
var RetryOperator = /* @__PURE__ */ function() {
  function RetryOperator2(count2, source) {
    this.count = count2;
    this.source = source;
  }
  RetryOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
  };
  return RetryOperator2;
}();
var RetrySubscriber = /* @__PURE__ */ function(_super) {
  __extends(RetrySubscriber2, _super);
  function RetrySubscriber2(destination, count2, source) {
    var _this = _super.call(this, destination) || this;
    _this.count = count2;
    _this.source = source;
    return _this;
  }
  RetrySubscriber2.prototype.error = function(err) {
    if (!this.isStopped) {
      var _a = this, source = _a.source, count2 = _a.count;
      if (count2 === 0) {
        return _super.prototype.error.call(this, err);
      } else if (count2 > -1) {
        this.count = count2 - 1;
      }
      source.subscribe(this._unsubscribeAndRecycle());
    }
  };
  return RetrySubscriber2;
}(Subscriber);
function retryWhen(notifier) {
  return function(source) {
    return source.lift(new RetryWhenOperator(notifier, source));
  };
}
var RetryWhenOperator = /* @__PURE__ */ function() {
  function RetryWhenOperator2(notifier, source) {
    this.notifier = notifier;
    this.source = source;
  }
  RetryWhenOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source));
  };
  return RetryWhenOperator2;
}();
var RetryWhenSubscriber = /* @__PURE__ */ function(_super) {
  __extends(RetryWhenSubscriber2, _super);
  function RetryWhenSubscriber2(destination, notifier, source) {
    var _this = _super.call(this, destination) || this;
    _this.notifier = notifier;
    _this.source = source;
    return _this;
  }
  RetryWhenSubscriber2.prototype.error = function(err) {
    if (!this.isStopped) {
      var errors = this.errors;
      var retries = this.retries;
      var retriesSubscription = this.retriesSubscription;
      if (!retries) {
        errors = new Subject();
        try {
          var notifier = this.notifier;
          retries = notifier(errors);
        } catch (e) {
          return _super.prototype.error.call(this, e);
        }
        retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this));
      } else {
        this.errors = void 0;
        this.retriesSubscription = void 0;
      }
      this._unsubscribeAndRecycle();
      this.errors = errors;
      this.retries = retries;
      this.retriesSubscription = retriesSubscription;
      errors.next(err);
    }
  };
  RetryWhenSubscriber2.prototype._unsubscribe = function() {
    var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
    if (errors) {
      errors.unsubscribe();
      this.errors = void 0;
    }
    if (retriesSubscription) {
      retriesSubscription.unsubscribe();
      this.retriesSubscription = void 0;
    }
    this.retries = void 0;
  };
  RetryWhenSubscriber2.prototype.notifyNext = function() {
    var _unsubscribe = this._unsubscribe;
    this._unsubscribe = null;
    this._unsubscribeAndRecycle();
    this._unsubscribe = _unsubscribe;
    this.source.subscribe(this);
  };
  return RetryWhenSubscriber2;
}(SimpleOuterSubscriber);
function sample(notifier) {
  return function(source) {
    return source.lift(new SampleOperator(notifier));
  };
}
var SampleOperator = /* @__PURE__ */ function() {
  function SampleOperator2(notifier) {
    this.notifier = notifier;
  }
  SampleOperator2.prototype.call = function(subscriber, source) {
    var sampleSubscriber = new SampleSubscriber(subscriber);
    var subscription = source.subscribe(sampleSubscriber);
    subscription.add(innerSubscribe(this.notifier, new SimpleInnerSubscriber(sampleSubscriber)));
    return subscription;
  };
  return SampleOperator2;
}();
var SampleSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SampleSubscriber2, _super);
  function SampleSubscriber2() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this.hasValue = false;
    return _this;
  }
  SampleSubscriber2.prototype._next = function(value) {
    this.value = value;
    this.hasValue = true;
  };
  SampleSubscriber2.prototype.notifyNext = function() {
    this.emitValue();
  };
  SampleSubscriber2.prototype.notifyComplete = function() {
    this.emitValue();
  };
  SampleSubscriber2.prototype.emitValue = function() {
    if (this.hasValue) {
      this.hasValue = false;
      this.destination.next(this.value);
    }
  };
  return SampleSubscriber2;
}(SimpleOuterSubscriber);
function sampleTime(period, scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return function(source) {
    return source.lift(new SampleTimeOperator(period, scheduler));
  };
}
var SampleTimeOperator = /* @__PURE__ */ function() {
  function SampleTimeOperator2(period, scheduler) {
    this.period = period;
    this.scheduler = scheduler;
  }
  SampleTimeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler));
  };
  return SampleTimeOperator2;
}();
var SampleTimeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SampleTimeSubscriber2, _super);
  function SampleTimeSubscriber2(destination, period, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.period = period;
    _this.scheduler = scheduler;
    _this.hasValue = false;
    _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period }));
    return _this;
  }
  SampleTimeSubscriber2.prototype._next = function(value) {
    this.lastValue = value;
    this.hasValue = true;
  };
  SampleTimeSubscriber2.prototype.notifyNext = function() {
    if (this.hasValue) {
      this.hasValue = false;
      this.destination.next(this.lastValue);
    }
  };
  return SampleTimeSubscriber2;
}(Subscriber);
function dispatchNotification(state) {
  var subscriber = state.subscriber, period = state.period;
  subscriber.notifyNext();
  this.schedule(state, period);
}
function sequenceEqual(compareTo, comparator) {
  return function(source) {
    return source.lift(new SequenceEqualOperator(compareTo, comparator));
  };
}
var SequenceEqualOperator = /* @__PURE__ */ function() {
  function SequenceEqualOperator2(compareTo, comparator) {
    this.compareTo = compareTo;
    this.comparator = comparator;
  }
  SequenceEqualOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator));
  };
  return SequenceEqualOperator2;
}();
var SequenceEqualSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SequenceEqualSubscriber2, _super);
  function SequenceEqualSubscriber2(destination, compareTo, comparator) {
    var _this = _super.call(this, destination) || this;
    _this.compareTo = compareTo;
    _this.comparator = comparator;
    _this._a = [];
    _this._b = [];
    _this._oneComplete = false;
    _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this)));
    return _this;
  }
  SequenceEqualSubscriber2.prototype._next = function(value) {
    if (this._oneComplete && this._b.length === 0) {
      this.emit(false);
    } else {
      this._a.push(value);
      this.checkValues();
    }
  };
  SequenceEqualSubscriber2.prototype._complete = function() {
    if (this._oneComplete) {
      this.emit(this._a.length === 0 && this._b.length === 0);
    } else {
      this._oneComplete = true;
    }
    this.unsubscribe();
  };
  SequenceEqualSubscriber2.prototype.checkValues = function() {
    var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator;
    while (_a.length > 0 && _b.length > 0) {
      var a = _a.shift();
      var b = _b.shift();
      var areEqual = false;
      try {
        areEqual = comparator ? comparator(a, b) : a === b;
      } catch (e) {
        this.destination.error(e);
      }
      if (!areEqual) {
        this.emit(false);
      }
    }
  };
  SequenceEqualSubscriber2.prototype.emit = function(value) {
    var destination = this.destination;
    destination.next(value);
    destination.complete();
  };
  SequenceEqualSubscriber2.prototype.nextB = function(value) {
    if (this._oneComplete && this._a.length === 0) {
      this.emit(false);
    } else {
      this._b.push(value);
      this.checkValues();
    }
  };
  SequenceEqualSubscriber2.prototype.completeB = function() {
    if (this._oneComplete) {
      this.emit(this._a.length === 0 && this._b.length === 0);
    } else {
      this._oneComplete = true;
    }
  };
  return SequenceEqualSubscriber2;
}(Subscriber);
var SequenceEqualCompareToSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SequenceEqualCompareToSubscriber2, _super);
  function SequenceEqualCompareToSubscriber2(destination, parent) {
    var _this = _super.call(this, destination) || this;
    _this.parent = parent;
    return _this;
  }
  SequenceEqualCompareToSubscriber2.prototype._next = function(value) {
    this.parent.nextB(value);
  };
  SequenceEqualCompareToSubscriber2.prototype._error = function(err) {
    this.parent.error(err);
    this.unsubscribe();
  };
  SequenceEqualCompareToSubscriber2.prototype._complete = function() {
    this.parent.completeB();
    this.unsubscribe();
  };
  return SequenceEqualCompareToSubscriber2;
}(Subscriber);
function shareSubjectFactory() {
  return new Subject();
}
function share() {
  return function(source) {
    return refCount()(multicast(shareSubjectFactory)(source));
  };
}
function shareReplay(configOrBufferSize, windowTime2, scheduler) {
  var config2;
  if (configOrBufferSize && typeof configOrBufferSize === "object") {
    config2 = configOrBufferSize;
  } else {
    config2 = {
      bufferSize: configOrBufferSize,
      windowTime: windowTime2,
      refCount: false,
      scheduler
    };
  }
  return function(source) {
    return source.lift(shareReplayOperator(config2));
  };
}
function shareReplayOperator(_a) {
  var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime2 = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler;
  var subject;
  var refCount2 = 0;
  var subscription;
  var hasError = false;
  var isComplete = false;
  return function shareReplayOperation(source) {
    refCount2++;
    var innerSub;
    if (!subject || hasError) {
      hasError = false;
      subject = new ReplaySubject(bufferSize, windowTime2, scheduler);
      innerSub = subject.subscribe(this);
      subscription = source.subscribe({
        next: function(value) {
          subject.next(value);
        },
        error: function(err) {
          hasError = true;
          subject.error(err);
        },
        complete: function() {
          isComplete = true;
          subscription = void 0;
          subject.complete();
        }
      });
      if (isComplete) {
        subscription = void 0;
      }
    } else {
      innerSub = subject.subscribe(this);
    }
    this.add(function() {
      refCount2--;
      innerSub.unsubscribe();
      innerSub = void 0;
      if (subscription && !isComplete && useRefCount && refCount2 === 0) {
        subscription.unsubscribe();
        subscription = void 0;
        subject = void 0;
      }
    });
  };
}
function single(predicate) {
  return function(source) {
    return source.lift(new SingleOperator(predicate, source));
  };
}
var SingleOperator = /* @__PURE__ */ function() {
  function SingleOperator2(predicate, source) {
    this.predicate = predicate;
    this.source = source;
  }
  SingleOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source));
  };
  return SingleOperator2;
}();
var SingleSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SingleSubscriber2, _super);
  function SingleSubscriber2(destination, predicate, source) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.source = source;
    _this.seenValue = false;
    _this.index = 0;
    return _this;
  }
  SingleSubscriber2.prototype.applySingleValue = function(value) {
    if (this.seenValue) {
      this.destination.error("Sequence contains more than one element");
    } else {
      this.seenValue = true;
      this.singleValue = value;
    }
  };
  SingleSubscriber2.prototype._next = function(value) {
    var index = this.index++;
    if (this.predicate) {
      this.tryNext(value, index);
    } else {
      this.applySingleValue(value);
    }
  };
  SingleSubscriber2.prototype.tryNext = function(value, index) {
    try {
      if (this.predicate(value, index, this.source)) {
        this.applySingleValue(value);
      }
    } catch (err) {
      this.destination.error(err);
    }
  };
  SingleSubscriber2.prototype._complete = function() {
    var destination = this.destination;
    if (this.index > 0) {
      destination.next(this.seenValue ? this.singleValue : void 0);
      destination.complete();
    } else {
      destination.error(new EmptyError());
    }
  };
  return SingleSubscriber2;
}(Subscriber);
function skip(count2) {
  return function(source) {
    return source.lift(new SkipOperator(count2));
  };
}
var SkipOperator = /* @__PURE__ */ function() {
  function SkipOperator2(total) {
    this.total = total;
  }
  SkipOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SkipSubscriber(subscriber, this.total));
  };
  return SkipOperator2;
}();
var SkipSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SkipSubscriber2, _super);
  function SkipSubscriber2(destination, total) {
    var _this = _super.call(this, destination) || this;
    _this.total = total;
    _this.count = 0;
    return _this;
  }
  SkipSubscriber2.prototype._next = function(x) {
    if (++this.count > this.total) {
      this.destination.next(x);
    }
  };
  return SkipSubscriber2;
}(Subscriber);
function skipLast(count2) {
  return function(source) {
    return source.lift(new SkipLastOperator(count2));
  };
}
var SkipLastOperator = /* @__PURE__ */ function() {
  function SkipLastOperator2(_skipCount) {
    this._skipCount = _skipCount;
    if (this._skipCount < 0) {
      throw new ArgumentOutOfRangeError();
    }
  }
  SkipLastOperator2.prototype.call = function(subscriber, source) {
    if (this._skipCount === 0) {
      return source.subscribe(new Subscriber(subscriber));
    } else {
      return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount));
    }
  };
  return SkipLastOperator2;
}();
var SkipLastSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SkipLastSubscriber2, _super);
  function SkipLastSubscriber2(destination, _skipCount) {
    var _this = _super.call(this, destination) || this;
    _this._skipCount = _skipCount;
    _this._count = 0;
    _this._ring = new Array(_skipCount);
    return _this;
  }
  SkipLastSubscriber2.prototype._next = function(value) {
    var skipCount = this._skipCount;
    var count2 = this._count++;
    if (count2 < skipCount) {
      this._ring[count2] = value;
    } else {
      var currentIndex = count2 % skipCount;
      var ring = this._ring;
      var oldValue = ring[currentIndex];
      ring[currentIndex] = value;
      this.destination.next(oldValue);
    }
  };
  return SkipLastSubscriber2;
}(Subscriber);
function skipUntil(notifier) {
  return function(source) {
    return source.lift(new SkipUntilOperator(notifier));
  };
}
var SkipUntilOperator = /* @__PURE__ */ function() {
  function SkipUntilOperator2(notifier) {
    this.notifier = notifier;
  }
  SkipUntilOperator2.prototype.call = function(destination, source) {
    return source.subscribe(new SkipUntilSubscriber(destination, this.notifier));
  };
  return SkipUntilOperator2;
}();
var SkipUntilSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SkipUntilSubscriber2, _super);
  function SkipUntilSubscriber2(destination, notifier) {
    var _this = _super.call(this, destination) || this;
    _this.hasValue = false;
    var innerSubscriber = new SimpleInnerSubscriber(_this);
    _this.add(innerSubscriber);
    _this.innerSubscription = innerSubscriber;
    var innerSubscription = innerSubscribe(notifier, innerSubscriber);
    if (innerSubscription !== innerSubscriber) {
      _this.add(innerSubscription);
      _this.innerSubscription = innerSubscription;
    }
    return _this;
  }
  SkipUntilSubscriber2.prototype._next = function(value) {
    if (this.hasValue) {
      _super.prototype._next.call(this, value);
    }
  };
  SkipUntilSubscriber2.prototype.notifyNext = function() {
    this.hasValue = true;
    if (this.innerSubscription) {
      this.innerSubscription.unsubscribe();
    }
  };
  SkipUntilSubscriber2.prototype.notifyComplete = function() {
  };
  return SkipUntilSubscriber2;
}(SimpleOuterSubscriber);
function skipWhile(predicate) {
  return function(source) {
    return source.lift(new SkipWhileOperator(predicate));
  };
}
var SkipWhileOperator = /* @__PURE__ */ function() {
  function SkipWhileOperator2(predicate) {
    this.predicate = predicate;
  }
  SkipWhileOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
  };
  return SkipWhileOperator2;
}();
var SkipWhileSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SkipWhileSubscriber2, _super);
  function SkipWhileSubscriber2(destination, predicate) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.skipping = true;
    _this.index = 0;
    return _this;
  }
  SkipWhileSubscriber2.prototype._next = function(value) {
    var destination = this.destination;
    if (this.skipping) {
      this.tryCallPredicate(value);
    }
    if (!this.skipping) {
      destination.next(value);
    }
  };
  SkipWhileSubscriber2.prototype.tryCallPredicate = function(value) {
    try {
      var result = this.predicate(value, this.index++);
      this.skipping = Boolean(result);
    } catch (err) {
      this.destination.error(err);
    }
  };
  return SkipWhileSubscriber2;
}(Subscriber);
function startWith() {
  var array = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    array[_i] = arguments[_i];
  }
  var scheduler = array[array.length - 1];
  if (isScheduler(scheduler)) {
    array.pop();
    return function(source) {
      return concat$1(array, source, scheduler);
    };
  } else {
    return function(source) {
      return concat$1(array, source);
    };
  }
}
var SubscribeOnObservable = /* @__PURE__ */ function(_super) {
  __extends(SubscribeOnObservable2, _super);
  function SubscribeOnObservable2(source, delayTime, scheduler) {
    if (delayTime === void 0) {
      delayTime = 0;
    }
    if (scheduler === void 0) {
      scheduler = asap;
    }
    var _this = _super.call(this) || this;
    _this.source = source;
    _this.delayTime = delayTime;
    _this.scheduler = scheduler;
    if (!isNumeric(delayTime) || delayTime < 0) {
      _this.delayTime = 0;
    }
    if (!scheduler || typeof scheduler.schedule !== "function") {
      _this.scheduler = asap;
    }
    return _this;
  }
  SubscribeOnObservable2.create = function(source, delay2, scheduler) {
    if (delay2 === void 0) {
      delay2 = 0;
    }
    if (scheduler === void 0) {
      scheduler = asap;
    }
    return new SubscribeOnObservable2(source, delay2, scheduler);
  };
  SubscribeOnObservable2.dispatch = function(arg) {
    var source = arg.source, subscriber = arg.subscriber;
    return this.add(source.subscribe(subscriber));
  };
  SubscribeOnObservable2.prototype._subscribe = function(subscriber) {
    var delay2 = this.delayTime;
    var source = this.source;
    var scheduler = this.scheduler;
    return scheduler.schedule(SubscribeOnObservable2.dispatch, delay2, {
      source,
      subscriber
    });
  };
  return SubscribeOnObservable2;
}(Observable);
function subscribeOn(scheduler, delay2) {
  if (delay2 === void 0) {
    delay2 = 0;
  }
  return function subscribeOnOperatorFunction(source) {
    return source.lift(new SubscribeOnOperator(scheduler, delay2));
  };
}
var SubscribeOnOperator = /* @__PURE__ */ function() {
  function SubscribeOnOperator2(scheduler, delay2) {
    this.scheduler = scheduler;
    this.delay = delay2;
  }
  SubscribeOnOperator2.prototype.call = function(subscriber, source) {
    return new SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
  };
  return SubscribeOnOperator2;
}();
function switchMap(project, resultSelector) {
  if (typeof resultSelector === "function") {
    return function(source) {
      return source.pipe(switchMap(function(a, i) {
        return from(project(a, i)).pipe(gosling_es_map(function(b, ii) {
          return resultSelector(a, b, i, ii);
        }));
      }));
    };
  }
  return function(source) {
    return source.lift(new SwitchMapOperator(project));
  };
}
var SwitchMapOperator = /* @__PURE__ */ function() {
  function SwitchMapOperator2(project) {
    this.project = project;
  }
  SwitchMapOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new SwitchMapSubscriber(subscriber, this.project));
  };
  return SwitchMapOperator2;
}();
var SwitchMapSubscriber = /* @__PURE__ */ function(_super) {
  __extends(SwitchMapSubscriber2, _super);
  function SwitchMapSubscriber2(destination, project) {
    var _this = _super.call(this, destination) || this;
    _this.project = project;
    _this.index = 0;
    return _this;
  }
  SwitchMapSubscriber2.prototype._next = function(value) {
    var result;
    var index = this.index++;
    try {
      result = this.project(value, index);
    } catch (error) {
      this.destination.error(error);
      return;
    }
    this._innerSub(result);
  };
  SwitchMapSubscriber2.prototype._innerSub = function(result) {
    var innerSubscription = this.innerSubscription;
    if (innerSubscription) {
      innerSubscription.unsubscribe();
    }
    var innerSubscriber = new SimpleInnerSubscriber(this);
    var destination = this.destination;
    destination.add(innerSubscriber);
    this.innerSubscription = innerSubscribe(result, innerSubscriber);
    if (this.innerSubscription !== innerSubscriber) {
      destination.add(this.innerSubscription);
    }
  };
  SwitchMapSubscriber2.prototype._complete = function() {
    var innerSubscription = this.innerSubscription;
    if (!innerSubscription || innerSubscription.closed) {
      _super.prototype._complete.call(this);
    }
    this.unsubscribe();
  };
  SwitchMapSubscriber2.prototype._unsubscribe = function() {
    this.innerSubscription = void 0;
  };
  SwitchMapSubscriber2.prototype.notifyComplete = function() {
    this.innerSubscription = void 0;
    if (this.isStopped) {
      _super.prototype._complete.call(this);
    }
  };
  SwitchMapSubscriber2.prototype.notifyNext = function(innerValue) {
    this.destination.next(innerValue);
  };
  return SwitchMapSubscriber2;
}(SimpleOuterSubscriber);
function switchAll() {
  return switchMap(gosling_es_identity);
}
function switchMapTo(innerObservable, resultSelector) {
  return resultSelector ? switchMap(function() {
    return innerObservable;
  }, resultSelector) : switchMap(function() {
    return innerObservable;
  });
}
function takeUntil(notifier) {
  return function(source) {
    return source.lift(new TakeUntilOperator(notifier));
  };
}
var TakeUntilOperator = /* @__PURE__ */ function() {
  function TakeUntilOperator2(notifier) {
    this.notifier = notifier;
  }
  TakeUntilOperator2.prototype.call = function(subscriber, source) {
    var takeUntilSubscriber = new TakeUntilSubscriber(subscriber);
    var notifierSubscription = innerSubscribe(this.notifier, new SimpleInnerSubscriber(takeUntilSubscriber));
    if (notifierSubscription && !takeUntilSubscriber.seenValue) {
      takeUntilSubscriber.add(notifierSubscription);
      return source.subscribe(takeUntilSubscriber);
    }
    return takeUntilSubscriber;
  };
  return TakeUntilOperator2;
}();
var TakeUntilSubscriber = /* @__PURE__ */ function(_super) {
  __extends(TakeUntilSubscriber2, _super);
  function TakeUntilSubscriber2(destination) {
    var _this = _super.call(this, destination) || this;
    _this.seenValue = false;
    return _this;
  }
  TakeUntilSubscriber2.prototype.notifyNext = function() {
    this.seenValue = true;
    this.complete();
  };
  TakeUntilSubscriber2.prototype.notifyComplete = function() {
  };
  return TakeUntilSubscriber2;
}(SimpleOuterSubscriber);
function takeWhile(predicate, inclusive) {
  if (inclusive === void 0) {
    inclusive = false;
  }
  return function(source) {
    return source.lift(new TakeWhileOperator(predicate, inclusive));
  };
}
var TakeWhileOperator = /* @__PURE__ */ function() {
  function TakeWhileOperator2(predicate, inclusive) {
    this.predicate = predicate;
    this.inclusive = inclusive;
  }
  TakeWhileOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive));
  };
  return TakeWhileOperator2;
}();
var TakeWhileSubscriber = /* @__PURE__ */ function(_super) {
  __extends(TakeWhileSubscriber2, _super);
  function TakeWhileSubscriber2(destination, predicate, inclusive) {
    var _this = _super.call(this, destination) || this;
    _this.predicate = predicate;
    _this.inclusive = inclusive;
    _this.index = 0;
    return _this;
  }
  TakeWhileSubscriber2.prototype._next = function(value) {
    var destination = this.destination;
    var result;
    try {
      result = this.predicate(value, this.index++);
    } catch (err) {
      destination.error(err);
      return;
    }
    this.nextOrComplete(value, result);
  };
  TakeWhileSubscriber2.prototype.nextOrComplete = function(value, predicateResult) {
    var destination = this.destination;
    if (Boolean(predicateResult)) {
      destination.next(value);
    } else {
      if (this.inclusive) {
        destination.next(value);
      }
      destination.complete();
    }
  };
  return TakeWhileSubscriber2;
}(Subscriber);
function tap(nextOrObserver, error, complete) {
  return function tapOperatorFunction(source) {
    return source.lift(new DoOperator(nextOrObserver, error, complete));
  };
}
var DoOperator = /* @__PURE__ */ function() {
  function DoOperator2(nextOrObserver, error, complete) {
    this.nextOrObserver = nextOrObserver;
    this.error = error;
    this.complete = complete;
  }
  DoOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
  };
  return DoOperator2;
}();
var TapSubscriber = /* @__PURE__ */ function(_super) {
  __extends(TapSubscriber2, _super);
  function TapSubscriber2(destination, observerOrNext, error, complete) {
    var _this = _super.call(this, destination) || this;
    _this._tapNext = noop$1;
    _this._tapError = noop$1;
    _this._tapComplete = noop$1;
    _this._tapError = error || noop$1;
    _this._tapComplete = complete || noop$1;
    if (gosling_es_isFunction(observerOrNext)) {
      _this._context = _this;
      _this._tapNext = observerOrNext;
    } else if (observerOrNext) {
      _this._context = observerOrNext;
      _this._tapNext = observerOrNext.next || noop$1;
      _this._tapError = observerOrNext.error || noop$1;
      _this._tapComplete = observerOrNext.complete || noop$1;
    }
    return _this;
  }
  TapSubscriber2.prototype._next = function(value) {
    try {
      this._tapNext.call(this._context, value);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.destination.next(value);
  };
  TapSubscriber2.prototype._error = function(err) {
    try {
      this._tapError.call(this._context, err);
    } catch (err2) {
      this.destination.error(err2);
      return;
    }
    this.destination.error(err);
  };
  TapSubscriber2.prototype._complete = function() {
    try {
      this._tapComplete.call(this._context);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    return this.destination.complete();
  };
  return TapSubscriber2;
}(Subscriber);
var defaultThrottleConfig = {
  leading: true,
  trailing: false
};
function throttle(durationSelector, config2) {
  if (config2 === void 0) {
    config2 = defaultThrottleConfig;
  }
  return function(source) {
    return source.lift(new ThrottleOperator(durationSelector, !!config2.leading, !!config2.trailing));
  };
}
var ThrottleOperator = /* @__PURE__ */ function() {
  function ThrottleOperator2(durationSelector, leading, trailing) {
    this.durationSelector = durationSelector;
    this.leading = leading;
    this.trailing = trailing;
  }
  ThrottleOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
  };
  return ThrottleOperator2;
}();
var ThrottleSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ThrottleSubscriber2, _super);
  function ThrottleSubscriber2(destination, durationSelector, _leading, _trailing) {
    var _this = _super.call(this, destination) || this;
    _this.destination = destination;
    _this.durationSelector = durationSelector;
    _this._leading = _leading;
    _this._trailing = _trailing;
    _this._hasValue = false;
    return _this;
  }
  ThrottleSubscriber2.prototype._next = function(value) {
    this._hasValue = true;
    this._sendValue = value;
    if (!this._throttled) {
      if (this._leading) {
        this.send();
      } else {
        this.throttle(value);
      }
    }
  };
  ThrottleSubscriber2.prototype.send = function() {
    var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
    if (_hasValue) {
      this.destination.next(_sendValue);
      this.throttle(_sendValue);
    }
    this._hasValue = false;
    this._sendValue = void 0;
  };
  ThrottleSubscriber2.prototype.throttle = function(value) {
    var duration = this.tryDurationSelector(value);
    if (!!duration) {
      this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this)));
    }
  };
  ThrottleSubscriber2.prototype.tryDurationSelector = function(value) {
    try {
      return this.durationSelector(value);
    } catch (err) {
      this.destination.error(err);
      return null;
    }
  };
  ThrottleSubscriber2.prototype.throttlingDone = function() {
    var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
    if (_throttled) {
      _throttled.unsubscribe();
    }
    this._throttled = void 0;
    if (_trailing) {
      this.send();
    }
  };
  ThrottleSubscriber2.prototype.notifyNext = function() {
    this.throttlingDone();
  };
  ThrottleSubscriber2.prototype.notifyComplete = function() {
    this.throttlingDone();
  };
  return ThrottleSubscriber2;
}(SimpleOuterSubscriber);
function throttleTime(duration, scheduler, config2) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  if (config2 === void 0) {
    config2 = defaultThrottleConfig;
  }
  return function(source) {
    return source.lift(new ThrottleTimeOperator(duration, scheduler, config2.leading, config2.trailing));
  };
}
var ThrottleTimeOperator = /* @__PURE__ */ function() {
  function ThrottleTimeOperator2(duration, scheduler, leading, trailing) {
    this.duration = duration;
    this.scheduler = scheduler;
    this.leading = leading;
    this.trailing = trailing;
  }
  ThrottleTimeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
  };
  return ThrottleTimeOperator2;
}();
var ThrottleTimeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(ThrottleTimeSubscriber2, _super);
  function ThrottleTimeSubscriber2(destination, duration, scheduler, leading, trailing) {
    var _this = _super.call(this, destination) || this;
    _this.duration = duration;
    _this.scheduler = scheduler;
    _this.leading = leading;
    _this.trailing = trailing;
    _this._hasTrailingValue = false;
    _this._trailingValue = null;
    return _this;
  }
  ThrottleTimeSubscriber2.prototype._next = function(value) {
    if (this.throttled) {
      if (this.trailing) {
        this._trailingValue = value;
        this._hasTrailingValue = true;
      }
    } else {
      this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
      if (this.leading) {
        this.destination.next(value);
      } else if (this.trailing) {
        this._trailingValue = value;
        this._hasTrailingValue = true;
      }
    }
  };
  ThrottleTimeSubscriber2.prototype._complete = function() {
    if (this._hasTrailingValue) {
      this.destination.next(this._trailingValue);
      this.destination.complete();
    } else {
      this.destination.complete();
    }
  };
  ThrottleTimeSubscriber2.prototype.clearThrottle = function() {
    var throttled = this.throttled;
    if (throttled) {
      if (this.trailing && this._hasTrailingValue) {
        this.destination.next(this._trailingValue);
        this._trailingValue = null;
        this._hasTrailingValue = false;
      }
      throttled.unsubscribe();
      this.remove(throttled);
      this.throttled = null;
    }
  };
  return ThrottleTimeSubscriber2;
}(Subscriber);
function dispatchNext(arg) {
  var subscriber = arg.subscriber;
  subscriber.clearThrottle();
}
function timeInterval(scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return function(source) {
    return defer(function() {
      return source.pipe(scan(function(_a, value) {
        var current = _a.current;
        return { value, current: scheduler.now(), last: current };
      }, { current: scheduler.now(), value: void 0, last: void 0 }), gosling_es_map(function(_a) {
        var current = _a.current, last2 = _a.last, value = _a.value;
        return new TimeInterval(value, current - last2);
      }));
    });
  };
}
var TimeInterval = /* @__PURE__ */ function() {
  function TimeInterval2(value, interval2) {
    this.value = value;
    this.interval = interval2;
  }
  return TimeInterval2;
}();
function timeoutWith(due, withObservable, scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return function(source) {
    var absoluteTimeout = isDate(due);
    var waitFor = absoluteTimeout ? +due - scheduler.now() : Math.abs(due);
    return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
  };
}
var TimeoutWithOperator = /* @__PURE__ */ function() {
  function TimeoutWithOperator2(waitFor, absoluteTimeout, withObservable, scheduler) {
    this.waitFor = waitFor;
    this.absoluteTimeout = absoluteTimeout;
    this.withObservable = withObservable;
    this.scheduler = scheduler;
  }
  TimeoutWithOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
  };
  return TimeoutWithOperator2;
}();
var TimeoutWithSubscriber = /* @__PURE__ */ function(_super) {
  __extends(TimeoutWithSubscriber2, _super);
  function TimeoutWithSubscriber2(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.absoluteTimeout = absoluteTimeout;
    _this.waitFor = waitFor;
    _this.withObservable = withObservable;
    _this.scheduler = scheduler;
    _this.scheduleTimeout();
    return _this;
  }
  TimeoutWithSubscriber2.dispatchTimeout = function(subscriber) {
    var withObservable = subscriber.withObservable;
    subscriber._unsubscribeAndRecycle();
    subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber)));
  };
  TimeoutWithSubscriber2.prototype.scheduleTimeout = function() {
    var action = this.action;
    if (action) {
      this.action = action.schedule(this, this.waitFor);
    } else {
      this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber2.dispatchTimeout, this.waitFor, this));
    }
  };
  TimeoutWithSubscriber2.prototype._next = function(value) {
    if (!this.absoluteTimeout) {
      this.scheduleTimeout();
    }
    _super.prototype._next.call(this, value);
  };
  TimeoutWithSubscriber2.prototype._unsubscribe = function() {
    this.action = void 0;
    this.scheduler = null;
    this.withObservable = null;
  };
  return TimeoutWithSubscriber2;
}(SimpleOuterSubscriber);
function timeout(due, scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return timeoutWith(due, throwError(new TimeoutError()), scheduler);
}
function timestamp(scheduler) {
  if (scheduler === void 0) {
    scheduler = async$1;
  }
  return gosling_es_map(function(value) {
    return new Timestamp(value, scheduler.now());
  });
}
var Timestamp = /* @__PURE__ */ function() {
  function Timestamp2(value, timestamp2) {
    this.value = value;
    this.timestamp = timestamp2;
  }
  return Timestamp2;
}();
function toArrayReducer(arr, item, index) {
  if (index === 0) {
    return [item];
  }
  arr.push(item);
  return arr;
}
function toArray() {
  return reduce(toArrayReducer, []);
}
function window$1(windowBoundaries) {
  return function windowOperatorFunction(source) {
    return source.lift(new WindowOperator$1(windowBoundaries));
  };
}
var WindowOperator$1 = /* @__PURE__ */ function() {
  function WindowOperator2(windowBoundaries) {
    this.windowBoundaries = windowBoundaries;
  }
  WindowOperator2.prototype.call = function(subscriber, source) {
    var windowSubscriber = new WindowSubscriber$1(subscriber);
    var sourceSubscription = source.subscribe(windowSubscriber);
    if (!sourceSubscription.closed) {
      windowSubscriber.add(innerSubscribe(this.windowBoundaries, new SimpleInnerSubscriber(windowSubscriber)));
    }
    return sourceSubscription;
  };
  return WindowOperator2;
}();
var WindowSubscriber$1 = /* @__PURE__ */ function(_super) {
  __extends(WindowSubscriber2, _super);
  function WindowSubscriber2(destination) {
    var _this = _super.call(this, destination) || this;
    _this.window = new Subject();
    destination.next(_this.window);
    return _this;
  }
  WindowSubscriber2.prototype.notifyNext = function() {
    this.openWindow();
  };
  WindowSubscriber2.prototype.notifyError = function(error) {
    this._error(error);
  };
  WindowSubscriber2.prototype.notifyComplete = function() {
    this._complete();
  };
  WindowSubscriber2.prototype._next = function(value) {
    this.window.next(value);
  };
  WindowSubscriber2.prototype._error = function(err) {
    this.window.error(err);
    this.destination.error(err);
  };
  WindowSubscriber2.prototype._complete = function() {
    this.window.complete();
    this.destination.complete();
  };
  WindowSubscriber2.prototype._unsubscribe = function() {
    this.window = null;
  };
  WindowSubscriber2.prototype.openWindow = function() {
    var prevWindow = this.window;
    if (prevWindow) {
      prevWindow.complete();
    }
    var destination = this.destination;
    var newWindow = this.window = new Subject();
    destination.next(newWindow);
  };
  return WindowSubscriber2;
}(SimpleOuterSubscriber);
function windowCount(windowSize, startWindowEvery) {
  if (startWindowEvery === void 0) {
    startWindowEvery = 0;
  }
  return function windowCountOperatorFunction(source) {
    return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
  };
}
var WindowCountOperator = /* @__PURE__ */ function() {
  function WindowCountOperator2(windowSize, startWindowEvery) {
    this.windowSize = windowSize;
    this.startWindowEvery = startWindowEvery;
  }
  WindowCountOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
  };
  return WindowCountOperator2;
}();
var WindowCountSubscriber = /* @__PURE__ */ function(_super) {
  __extends(WindowCountSubscriber2, _super);
  function WindowCountSubscriber2(destination, windowSize, startWindowEvery) {
    var _this = _super.call(this, destination) || this;
    _this.destination = destination;
    _this.windowSize = windowSize;
    _this.startWindowEvery = startWindowEvery;
    _this.windows = [new Subject()];
    _this.count = 0;
    destination.next(_this.windows[0]);
    return _this;
  }
  WindowCountSubscriber2.prototype._next = function(value) {
    var startWindowEvery = this.startWindowEvery > 0 ? this.startWindowEvery : this.windowSize;
    var destination = this.destination;
    var windowSize = this.windowSize;
    var windows = this.windows;
    var len = windows.length;
    for (var i = 0; i < len && !this.closed; i++) {
      windows[i].next(value);
    }
    var c = this.count - windowSize + 1;
    if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
      windows.shift().complete();
    }
    if (++this.count % startWindowEvery === 0 && !this.closed) {
      var window_1 = new Subject();
      windows.push(window_1);
      destination.next(window_1);
    }
  };
  WindowCountSubscriber2.prototype._error = function(err) {
    var windows = this.windows;
    if (windows) {
      while (windows.length > 0 && !this.closed) {
        windows.shift().error(err);
      }
    }
    this.destination.error(err);
  };
  WindowCountSubscriber2.prototype._complete = function() {
    var windows = this.windows;
    if (windows) {
      while (windows.length > 0 && !this.closed) {
        windows.shift().complete();
      }
    }
    this.destination.complete();
  };
  WindowCountSubscriber2.prototype._unsubscribe = function() {
    this.count = 0;
    this.windows = null;
  };
  return WindowCountSubscriber2;
}(Subscriber);
function windowTime(windowTimeSpan) {
  var scheduler = async$1;
  var windowCreationInterval = null;
  var maxWindowSize = Number.POSITIVE_INFINITY;
  if (isScheduler(arguments[3])) {
    scheduler = arguments[3];
  }
  if (isScheduler(arguments[2])) {
    scheduler = arguments[2];
  } else if (isNumeric(arguments[2])) {
    maxWindowSize = Number(arguments[2]);
  }
  if (isScheduler(arguments[1])) {
    scheduler = arguments[1];
  } else if (isNumeric(arguments[1])) {
    windowCreationInterval = Number(arguments[1]);
  }
  return function windowTimeOperatorFunction(source) {
    return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
  };
}
var WindowTimeOperator = /* @__PURE__ */ function() {
  function WindowTimeOperator2(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
    this.windowTimeSpan = windowTimeSpan;
    this.windowCreationInterval = windowCreationInterval;
    this.maxWindowSize = maxWindowSize;
    this.scheduler = scheduler;
  }
  WindowTimeOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
  };
  return WindowTimeOperator2;
}();
var CountedSubject = /* @__PURE__ */ function(_super) {
  __extends(CountedSubject2, _super);
  function CountedSubject2() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this._numberOfNextedValues = 0;
    return _this;
  }
  CountedSubject2.prototype.next = function(value) {
    this._numberOfNextedValues++;
    _super.prototype.next.call(this, value);
  };
  Object.defineProperty(CountedSubject2.prototype, "numberOfNextedValues", {
    get: function() {
      return this._numberOfNextedValues;
    },
    enumerable: true,
    configurable: true
  });
  return CountedSubject2;
}(Subject);
var WindowTimeSubscriber = /* @__PURE__ */ function(_super) {
  __extends(WindowTimeSubscriber2, _super);
  function WindowTimeSubscriber2(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
    var _this = _super.call(this, destination) || this;
    _this.destination = destination;
    _this.windowTimeSpan = windowTimeSpan;
    _this.windowCreationInterval = windowCreationInterval;
    _this.maxWindowSize = maxWindowSize;
    _this.scheduler = scheduler;
    _this.windows = [];
    var window2 = _this.openWindow();
    if (windowCreationInterval !== null && windowCreationInterval >= 0) {
      var closeState = { subscriber: _this, window: window2, context: null };
      var creationState = { windowTimeSpan, windowCreationInterval, subscriber: _this, scheduler };
      _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
      _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
    } else {
      var timeSpanOnlyState = { subscriber: _this, window: window2, windowTimeSpan };
      _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
    }
    return _this;
  }
  WindowTimeSubscriber2.prototype._next = function(value) {
    var windows = this.windows;
    var len = windows.length;
    for (var i = 0; i < len; i++) {
      var window_1 = windows[i];
      if (!window_1.closed) {
        window_1.next(value);
        if (window_1.numberOfNextedValues >= this.maxWindowSize) {
          this.closeWindow(window_1);
        }
      }
    }
  };
  WindowTimeSubscriber2.prototype._error = function(err) {
    var windows = this.windows;
    while (windows.length > 0) {
      windows.shift().error(err);
    }
    this.destination.error(err);
  };
  WindowTimeSubscriber2.prototype._complete = function() {
    var windows = this.windows;
    while (windows.length > 0) {
      var window_2 = windows.shift();
      if (!window_2.closed) {
        window_2.complete();
      }
    }
    this.destination.complete();
  };
  WindowTimeSubscriber2.prototype.openWindow = function() {
    var window2 = new CountedSubject();
    this.windows.push(window2);
    var destination = this.destination;
    destination.next(window2);
    return window2;
  };
  WindowTimeSubscriber2.prototype.closeWindow = function(window2) {
    window2.complete();
    var windows = this.windows;
    windows.splice(windows.indexOf(window2), 1);
  };
  return WindowTimeSubscriber2;
}(Subscriber);
function dispatchWindowTimeSpanOnly(state) {
  var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window2 = state.window;
  if (window2) {
    subscriber.closeWindow(window2);
  }
  state.window = subscriber.openWindow();
  this.schedule(state, windowTimeSpan);
}
function dispatchWindowCreation(state) {
  var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval;
  var window2 = subscriber.openWindow();
  var action = this;
  var context2 = { action, subscription: null };
  var timeSpanState = { subscriber, window: window2, context: context2 };
  context2.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
  action.add(context2.subscription);
  action.schedule(state, windowCreationInterval);
}
function dispatchWindowClose(state) {
  var subscriber = state.subscriber, window2 = state.window, context2 = state.context;
  if (context2 && context2.action && context2.subscription) {
    context2.action.remove(context2.subscription);
  }
  subscriber.closeWindow(window2);
}
function windowToggle(openings, closingSelector) {
  return function(source) {
    return source.lift(new WindowToggleOperator(openings, closingSelector));
  };
}
var WindowToggleOperator = /* @__PURE__ */ function() {
  function WindowToggleOperator2(openings, closingSelector) {
    this.openings = openings;
    this.closingSelector = closingSelector;
  }
  WindowToggleOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
  };
  return WindowToggleOperator2;
}();
var WindowToggleSubscriber = /* @__PURE__ */ function(_super) {
  __extends(WindowToggleSubscriber2, _super);
  function WindowToggleSubscriber2(destination, openings, closingSelector) {
    var _this = _super.call(this, destination) || this;
    _this.openings = openings;
    _this.closingSelector = closingSelector;
    _this.contexts = [];
    _this.add(_this.openSubscription = subscribeToResult(_this, openings, openings));
    return _this;
  }
  WindowToggleSubscriber2.prototype._next = function(value) {
    var contexts = this.contexts;
    if (contexts) {
      var len = contexts.length;
      for (var i = 0; i < len; i++) {
        contexts[i].window.next(value);
      }
    }
  };
  WindowToggleSubscriber2.prototype._error = function(err) {
    var contexts = this.contexts;
    this.contexts = null;
    if (contexts) {
      var len = contexts.length;
      var index = -1;
      while (++index < len) {
        var context_1 = contexts[index];
        context_1.window.error(err);
        context_1.subscription.unsubscribe();
      }
    }
    _super.prototype._error.call(this, err);
  };
  WindowToggleSubscriber2.prototype._complete = function() {
    var contexts = this.contexts;
    this.contexts = null;
    if (contexts) {
      var len = contexts.length;
      var index = -1;
      while (++index < len) {
        var context_2 = contexts[index];
        context_2.window.complete();
        context_2.subscription.unsubscribe();
      }
    }
    _super.prototype._complete.call(this);
  };
  WindowToggleSubscriber2.prototype._unsubscribe = function() {
    var contexts = this.contexts;
    this.contexts = null;
    if (contexts) {
      var len = contexts.length;
      var index = -1;
      while (++index < len) {
        var context_3 = contexts[index];
        context_3.window.unsubscribe();
        context_3.subscription.unsubscribe();
      }
    }
  };
  WindowToggleSubscriber2.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex, innerSub) {
    if (outerValue === this.openings) {
      var closingNotifier = void 0;
      try {
        var closingSelector = this.closingSelector;
        closingNotifier = closingSelector(innerValue);
      } catch (e) {
        return this.error(e);
      }
      var window_1 = new Subject();
      var subscription = new Subscription();
      var context_4 = { window: window_1, subscription };
      this.contexts.push(context_4);
      var innerSubscription = subscribeToResult(this, closingNotifier, context_4);
      if (innerSubscription.closed) {
        this.closeWindow(this.contexts.length - 1);
      } else {
        innerSubscription.context = context_4;
        subscription.add(innerSubscription);
      }
      this.destination.next(window_1);
    } else {
      this.closeWindow(this.contexts.indexOf(outerValue));
    }
  };
  WindowToggleSubscriber2.prototype.notifyError = function(err) {
    this.error(err);
  };
  WindowToggleSubscriber2.prototype.notifyComplete = function(inner) {
    if (inner !== this.openSubscription) {
      this.closeWindow(this.contexts.indexOf(inner.context));
    }
  };
  WindowToggleSubscriber2.prototype.closeWindow = function(index) {
    if (index === -1) {
      return;
    }
    var contexts = this.contexts;
    var context2 = contexts[index];
    var window2 = context2.window, subscription = context2.subscription;
    contexts.splice(index, 1);
    window2.complete();
    subscription.unsubscribe();
  };
  return WindowToggleSubscriber2;
}(OuterSubscriber);
function windowWhen(closingSelector) {
  return function windowWhenOperatorFunction(source) {
    return source.lift(new WindowOperator(closingSelector));
  };
}
var WindowOperator = /* @__PURE__ */ function() {
  function WindowOperator2(closingSelector) {
    this.closingSelector = closingSelector;
  }
  WindowOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new WindowSubscriber(subscriber, this.closingSelector));
  };
  return WindowOperator2;
}();
var WindowSubscriber = /* @__PURE__ */ function(_super) {
  __extends(WindowSubscriber2, _super);
  function WindowSubscriber2(destination, closingSelector) {
    var _this = _super.call(this, destination) || this;
    _this.destination = destination;
    _this.closingSelector = closingSelector;
    _this.openWindow();
    return _this;
  }
  WindowSubscriber2.prototype.notifyNext = function(_outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) {
    this.openWindow(innerSub);
  };
  WindowSubscriber2.prototype.notifyError = function(error) {
    this._error(error);
  };
  WindowSubscriber2.prototype.notifyComplete = function(innerSub) {
    this.openWindow(innerSub);
  };
  WindowSubscriber2.prototype._next = function(value) {
    this.window.next(value);
  };
  WindowSubscriber2.prototype._error = function(err) {
    this.window.error(err);
    this.destination.error(err);
    this.unsubscribeClosingNotification();
  };
  WindowSubscriber2.prototype._complete = function() {
    this.window.complete();
    this.destination.complete();
    this.unsubscribeClosingNotification();
  };
  WindowSubscriber2.prototype.unsubscribeClosingNotification = function() {
    if (this.closingNotification) {
      this.closingNotification.unsubscribe();
    }
  };
  WindowSubscriber2.prototype.openWindow = function(innerSub) {
    if (innerSub === void 0) {
      innerSub = null;
    }
    if (innerSub) {
      this.remove(innerSub);
      innerSub.unsubscribe();
    }
    var prevWindow = this.window;
    if (prevWindow) {
      prevWindow.complete();
    }
    var window2 = this.window = new Subject();
    this.destination.next(window2);
    var closingNotifier;
    try {
      var closingSelector = this.closingSelector;
      closingNotifier = closingSelector();
    } catch (e) {
      this.destination.error(e);
      this.window.error(e);
      return;
    }
    this.add(this.closingNotification = subscribeToResult(this, closingNotifier));
  };
  return WindowSubscriber2;
}(OuterSubscriber);
function withLatestFrom() {
  var args = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    args[_i] = arguments[_i];
  }
  return function(source) {
    var project;
    if (typeof args[args.length - 1] === "function") {
      project = args.pop();
    }
    var observables = args;
    return source.lift(new WithLatestFromOperator(observables, project));
  };
}
var WithLatestFromOperator = /* @__PURE__ */ function() {
  function WithLatestFromOperator2(observables, project) {
    this.observables = observables;
    this.project = project;
  }
  WithLatestFromOperator2.prototype.call = function(subscriber, source) {
    return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
  };
  return WithLatestFromOperator2;
}();
var WithLatestFromSubscriber = /* @__PURE__ */ function(_super) {
  __extends(WithLatestFromSubscriber2, _super);
  function WithLatestFromSubscriber2(destination, observables, project) {
    var _this = _super.call(this, destination) || this;
    _this.observables = observables;
    _this.project = project;
    _this.toRespond = [];
    var len = observables.length;
    _this.values = new Array(len);
    for (var i = 0; i < len; i++) {
      _this.toRespond.push(i);
    }
    for (var i = 0; i < len; i++) {
      var observable2 = observables[i];
      _this.add(subscribeToResult(_this, observable2, void 0, i));
    }
    return _this;
  }
  WithLatestFromSubscriber2.prototype.notifyNext = function(_outerValue, innerValue, outerIndex) {
    this.values[outerIndex] = innerValue;
    var toRespond = this.toRespond;
    if (toRespond.length > 0) {
      var found = toRespond.indexOf(outerIndex);
      if (found !== -1) {
        toRespond.splice(found, 1);
      }
    }
  };
  WithLatestFromSubscriber2.prototype.notifyComplete = function() {
  };
  WithLatestFromSubscriber2.prototype._next = function(value) {
    if (this.toRespond.length === 0) {
      var args = [value].concat(this.values);
      if (this.project) {
        this._tryProject(args);
      } else {
        this.destination.next(args);
      }
    }
  };
  WithLatestFromSubscriber2.prototype._tryProject = function(args) {
    var result;
    try {
      result = this.project.apply(this, args);
    } catch (err) {
      this.destination.error(err);
      return;
    }
    this.destination.next(result);
  };
  return WithLatestFromSubscriber2;
}(OuterSubscriber);
function gosling_es_zip() {
  var observables = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    observables[_i] = arguments[_i];
  }
  return function zipOperatorFunction(source) {
    return source.lift.call(zip$1.apply(void 0, [source].concat(observables)));
  };
}
function zipAll(project) {
  return function(source) {
    return source.lift(new ZipOperator(project));
  };
}
var operators = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  [Symbol.toStringTag]: "Module",
  audit,
  auditTime,
  buffer: gosling_es_buffer,
  bufferCount,
  bufferTime,
  bufferToggle,
  bufferWhen,
  catchError,
  combineAll,
  combineLatest,
  concat,
  concatAll,
  concatMap,
  concatMapTo,
  count,
  debounce,
  debounceTime,
  defaultIfEmpty,
  delay,
  delayWhen,
  dematerialize,
  distinct,
  distinctUntilChanged,
  distinctUntilKeyChanged,
  elementAt,
  endWith,
  every,
  exhaust,
  exhaustMap,
  expand,
  filter,
  finalize,
  find,
  findIndex,
  first,
  groupBy,
  ignoreElements,
  isEmpty,
  last,
  map: gosling_es_map,
  mapTo,
  materialize,
  max: gosling_es_max,
  merge,
  mergeAll,
  mergeMap,
  flatMap,
  mergeMapTo,
  mergeScan,
  min: gosling_es_min,
  multicast,
  observeOn,
  onErrorResumeNext,
  pairwise,
  partition,
  pluck,
  publish,
  publishBehavior,
  publishLast,
  publishReplay,
  race,
  reduce,
  repeat,
  repeatWhen,
  retry,
  retryWhen,
  refCount,
  sample,
  sampleTime,
  scan,
  sequenceEqual,
  share,
  shareReplay,
  single,
  skip,
  skipLast,
  skipUntil,
  skipWhile,
  startWith,
  subscribeOn,
  switchAll,
  switchMap,
  switchMapTo,
  take,
  takeLast,
  takeUntil,
  takeWhile,
  tap,
  throttle,
  throttleTime,
  throwIfEmpty,
  timeInterval,
  timeout,
  timeoutWith,
  timestamp,
  toArray,
  window: window$1,
  windowCount,
  windowTime,
  windowToggle,
  windowWhen,
  withLatestFrom,
  zip: gosling_es_zip,
  zipAll
});
var require$$13$1 = /* @__PURE__ */ getAugmentedNamespace(operators);
var _interopRequireDefault$2 = interopRequireDefault.exports;
Object.defineProperty(bbi, "__esModule", {
  value: true
});
bbi.BBI = void 0;
var _regenerator$2 = _interopRequireDefault$2(regenerator);
var _asyncToGenerator2$2 = _interopRequireDefault$2(asyncToGenerator.exports);
var _classCallCheck2$2 = _interopRequireDefault$2(classCallCheck.exports);
var _createClass2$2 = _interopRequireDefault$2(createClass.exports);
var _defineProperty2$1 = _interopRequireDefault$2(gosling_es_defineProperty.exports);
var _binaryParser$1 = binary_parser;
var _genericFilehandle = (index_js_default());
var _rxjs$1 = require$$12$1;
var _operators$1 = require$$13$1;
var _abortablePromiseCache$1 = _interopRequireDefault$2(gosling_es_dist);
var _quickLru$1 = _interopRequireDefault$2(quickLru);
var _blockView$1 = blockView;
function ownKeys$1(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly)
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread$1(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys$1(Object(source), true).forEach(function(key) {
        (0, _defineProperty2$1.default)(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys$1(Object(source)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
var BIG_WIG_MAGIC = -2003829722;
var BIG_BED_MAGIC = -2021002517;
function getParsers(isBE) {
  var le = isBE ? "big" : "little";
  var headerParser = new _binaryParser$1.Parser().endianess(le).int32("magic").uint16("version").uint16("numZoomLevels").uint64("chromTreeOffset").uint64("unzoomedDataOffset").uint64("unzoomedIndexOffset").uint16("fieldCount").uint16("definedFieldCount").uint64("asOffset").uint64("totalSummaryOffset").uint32("uncompressBufSize").uint64("extHeaderOffset").array("zoomLevels", {
    length: "numZoomLevels",
    type: new _binaryParser$1.Parser().uint32("reductionLevel").uint32("reserved").uint64("dataOffset").uint64("indexOffset")
  });
  var totalSummaryParser = new _binaryParser$1.Parser().endianess(le).uint64("basesCovered").double("scoreMin").double("scoreMax").double("scoreSum").double("scoreSumSquares");
  var chromTreeParser = new _binaryParser$1.Parser().endianess(le).uint32("magic").uint32("blockSize").uint32("keySize").uint32("valSize").uint64("itemCount");
  var isLeafNode = new _binaryParser$1.Parser().endianess(le).uint8("isLeafNode").skip(1).uint16("cnt");
  return {
    chromTreeParser,
    totalSummaryParser,
    headerParser,
    isLeafNode
  };
}
var BBI = /* @__PURE__ */ function() {
  (0, _createClass2$2.default)(BBI2, [{
    key: "getHeader",
    value: function getHeader() {
      var opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var options = "aborted" in opts ? {
        signal: opts
      } : opts;
      return this.headerCache.get(JSON.stringify(options), options, options.signal);
    }
  }]);
  function BBI2() {
    var _this = this;
    var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    (0, _classCallCheck2$2.default)(this, BBI2);
    (0, _defineProperty2$1.default)(this, "bbi", void 0);
    (0, _defineProperty2$1.default)(this, "headerCache", new _abortablePromiseCache$1.default({
      cache: new _quickLru$1.default({
        maxSize: 1
      }),
      fill: function() {
        var _fill = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee(params, signal) {
          return _regenerator$2.default.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  return _context.abrupt("return", _this._getHeader(_objectSpread$1(_objectSpread$1({}, params), {}, {
                    signal
                  })));
                case 1:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
        function fill(_x, _x2) {
          return _fill.apply(this, arguments);
        }
        return fill;
      }()
    }));
    (0, _defineProperty2$1.default)(this, "renameRefSeqs", void 0);
    var filehandle = options.filehandle, renameRefSeqs = options.renameRefSeqs, path = options.path, url = options.url;
    this.renameRefSeqs = renameRefSeqs || function(s) {
      return s;
    };
    if (filehandle) {
      this.bbi = filehandle;
    } else if (url) {
      this.bbi = new _genericFilehandle.RemoteFile(url);
    } else if (path) {
      this.bbi = new _genericFilehandle.LocalFile(path);
    } else {
      throw new Error("no file given");
    }
  }
  (0, _createClass2$2.default)(BBI2, [{
    key: "_getHeader",
    value: function() {
      var _getHeader2 = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee2(opts) {
        var header, chroms;
        return _regenerator$2.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return this._getMainHeader(opts);
              case 2:
                header = _context2.sent;
                _context2.next = 5;
                return this._readChromTree(header, opts);
              case 5:
                chroms = _context2.sent;
                return _context2.abrupt("return", _objectSpread$1(_objectSpread$1({}, header), chroms));
              case 7:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));
      function _getHeader(_x3) {
        return _getHeader2.apply(this, arguments);
      }
      return _getHeader;
    }()
  }, {
    key: "_getMainHeader",
    value: function() {
      var _getMainHeader2 = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee3(opts) {
        var requestSize, _yield$this$bbi$read, buffer2, isBigEndian, ret, header, tail, _args3 = arguments;
        return _regenerator$2.default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                requestSize = _args3.length > 1 && _args3[1] !== void 0 ? _args3[1] : 2e3;
                _context3.next = 3;
                return this.bbi.read(Buffer.alloc(requestSize), 0, requestSize, 0, opts);
              case 3:
                _yield$this$bbi$read = _context3.sent;
                buffer2 = _yield$this$bbi$read.buffer;
                isBigEndian = this._isBigEndian(buffer2);
                ret = getParsers(isBigEndian);
                header = ret.headerParser.parse(buffer2).result;
                header.fileType = header.magic === BIG_BED_MAGIC ? "bigbed" : "bigwig";
                if (!(header.asOffset > requestSize || header.totalSummaryOffset > requestSize)) {
                  _context3.next = 11;
                  break;
                }
                return _context3.abrupt("return", this._getMainHeader(opts, requestSize * 2));
              case 11:
                if (header.asOffset) {
                  header.autoSql = buffer2.slice(header.asOffset, buffer2.indexOf(0, header.asOffset)).toString("utf8");
                }
                if (!(header.totalSummaryOffset > requestSize)) {
                  _context3.next = 14;
                  break;
                }
                return _context3.abrupt("return", this._getMainHeader(opts, requestSize * 2));
              case 14:
                if (header.totalSummaryOffset) {
                  tail = buffer2.slice(header.totalSummaryOffset);
                  header.totalSummary = ret.totalSummaryParser.parse(tail).result;
                }
                return _context3.abrupt("return", _objectSpread$1(_objectSpread$1({}, header), {}, {
                  isBigEndian
                }));
              case 16:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));
      function _getMainHeader(_x4) {
        return _getMainHeader2.apply(this, arguments);
      }
      return _getMainHeader;
    }()
  }, {
    key: "_isBigEndian",
    value: function _isBigEndian(buffer2) {
      var ret = buffer2.readInt32LE(0);
      if (ret === BIG_WIG_MAGIC || ret === BIG_BED_MAGIC) {
        return false;
      }
      ret = buffer2.readInt32BE(0);
      if (ret === BIG_WIG_MAGIC || ret === BIG_BED_MAGIC) {
        return true;
      }
      throw new Error("not a BigWig/BigBed file");
    }
  }, {
    key: "_readChromTree",
    value: function() {
      var _readChromTree2 = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee5(header, opts) {
        var _this2 = this;
        var isBE, le, refsByNumber, refsByName, chromTreeOffset, unzoomedDataOffset, _yield$this$bbi$read2, data2, p, keySize, leafNodeParser, nonleafNodeParser, rootNodeOffset, bptReadNode;
        return _regenerator$2.default.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                isBE = header.isBigEndian;
                le = isBE ? "big" : "little";
                refsByNumber = [];
                refsByName = {};
                chromTreeOffset = header.chromTreeOffset;
                unzoomedDataOffset = header.unzoomedDataOffset;
                while (unzoomedDataOffset % 4 !== 0) {
                  unzoomedDataOffset += 1;
                }
                _context5.next = 9;
                return this.bbi.read(Buffer.alloc(unzoomedDataOffset - chromTreeOffset), 0, unzoomedDataOffset - chromTreeOffset, chromTreeOffset, opts);
              case 9:
                _yield$this$bbi$read2 = _context5.sent;
                data2 = _yield$this$bbi$read2.buffer;
                p = getParsers(isBE);
                keySize = p.chromTreeParser.parse(data2).result.keySize;
                leafNodeParser = new _binaryParser$1.Parser().endianess(le).string("key", {
                  stripNull: true,
                  length: keySize
                }).uint32("refId").uint32("refSize");
                nonleafNodeParser = new _binaryParser$1.Parser().endianess(le).skip(keySize).uint64("childOffset");
                rootNodeOffset = 32;
                bptReadNode = /* @__PURE__ */ function() {
                  var _ref = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee4(currentOffset) {
                    var offset, ret, _ret$result, isLeafNode, cnt, n, leafRet, _leafRet$result, _key, refId, refSize, refRec, nextNodes, _n, nonleafRet, childOffset;
                    return _regenerator$2.default.wrap(function _callee4$(_context4) {
                      while (1) {
                        switch (_context4.prev = _context4.next) {
                          case 0:
                            offset = currentOffset;
                            if (!(offset >= data2.length)) {
                              _context4.next = 3;
                              break;
                            }
                            throw new Error("reading beyond end of buffer");
                          case 3:
                            ret = p.isLeafNode.parse(data2.slice(offset));
                            _ret$result = ret.result, isLeafNode = _ret$result.isLeafNode, cnt = _ret$result.cnt;
                            offset += ret.offset;
                            if (!isLeafNode) {
                              _context4.next = 10;
                              break;
                            }
                            for (n = 0; n < cnt; n += 1) {
                              leafRet = leafNodeParser.parse(data2.slice(offset));
                              offset += leafRet.offset;
                              _leafRet$result = leafRet.result, _key = _leafRet$result.key, refId = _leafRet$result.refId, refSize = _leafRet$result.refSize;
                              refRec = {
                                name: _key,
                                id: refId,
                                length: refSize
                              };
                              refsByName[_this2.renameRefSeqs(_key)] = refId;
                              refsByNumber[refId] = refRec;
                            }
                            _context4.next = 14;
                            break;
                          case 10:
                            nextNodes = [];
                            for (_n = 0; _n < cnt; _n += 1) {
                              nonleafRet = nonleafNodeParser.parse(data2.slice(offset));
                              childOffset = nonleafRet.result.childOffset;
                              offset += nonleafRet.offset;
                              childOffset -= chromTreeOffset;
                              nextNodes.push(bptReadNode(childOffset));
                            }
                            _context4.next = 14;
                            return Promise.all(nextNodes);
                          case 14:
                          case "end":
                            return _context4.stop();
                        }
                      }
                    }, _callee4);
                  }));
                  return function bptReadNode2(_x7) {
                    return _ref.apply(this, arguments);
                  };
                }();
                _context5.next = 19;
                return bptReadNode(rootNodeOffset);
              case 19:
                return _context5.abrupt("return", {
                  refsByName,
                  refsByNumber
                });
              case 20:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));
      function _readChromTree(_x5, _x6) {
        return _readChromTree2.apply(this, arguments);
      }
      return _readChromTree;
    }()
  }, {
    key: "getUnzoomedView",
    value: function() {
      var _getUnzoomedView = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee6(opts) {
        var _yield$this$getHeader, unzoomedIndexOffset, zoomLevels, refsByName, uncompressBufSize, isBigEndian, fileType, nzl, cirLen;
        return _regenerator$2.default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                _context6.next = 2;
                return this.getHeader(opts);
              case 2:
                _yield$this$getHeader = _context6.sent;
                unzoomedIndexOffset = _yield$this$getHeader.unzoomedIndexOffset;
                zoomLevels = _yield$this$getHeader.zoomLevels;
                refsByName = _yield$this$getHeader.refsByName;
                uncompressBufSize = _yield$this$getHeader.uncompressBufSize;
                isBigEndian = _yield$this$getHeader.isBigEndian;
                fileType = _yield$this$getHeader.fileType;
                nzl = zoomLevels[0];
                cirLen = nzl ? nzl.dataOffset - unzoomedIndexOffset : 4e3;
                return _context6.abrupt("return", new _blockView$1.BlockView(this.bbi, refsByName, unzoomedIndexOffset, cirLen, isBigEndian, uncompressBufSize > 0, fileType));
              case 12:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));
      function getUnzoomedView(_x8) {
        return _getUnzoomedView.apply(this, arguments);
      }
      return getUnzoomedView;
    }()
  }, {
    key: "getFeatureStream",
    value: function() {
      var _getFeatureStream = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee7(refName, start, end) {
        var opts, chrName, view, _args7 = arguments;
        return _regenerator$2.default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                opts = _args7.length > 3 && _args7[3] !== void 0 ? _args7[3] : {
                  scale: 1
                };
                _context7.next = 3;
                return this.getHeader(opts);
              case 3:
                chrName = this.renameRefSeqs(refName);
                if (!opts.basesPerSpan) {
                  _context7.next = 10;
                  break;
                }
                _context7.next = 7;
                return this.getView(1 / opts.basesPerSpan, opts);
              case 7:
                view = _context7.sent;
                _context7.next = 19;
                break;
              case 10:
                if (!opts.scale) {
                  _context7.next = 16;
                  break;
                }
                _context7.next = 13;
                return this.getView(opts.scale, opts);
              case 13:
                view = _context7.sent;
                _context7.next = 19;
                break;
              case 16:
                _context7.next = 18;
                return this.getView(1, opts);
              case 18:
                view = _context7.sent;
              case 19:
                if (view) {
                  _context7.next = 21;
                  break;
                }
                throw new Error("unable to get block view for data");
              case 21:
                return _context7.abrupt("return", new _rxjs$1.Observable(function(observer) {
                  view.readWigData(chrName, start, end, observer, opts);
                }));
              case 22:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));
      function getFeatureStream(_x9, _x10, _x11) {
        return _getFeatureStream.apply(this, arguments);
      }
      return getFeatureStream;
    }()
  }, {
    key: "getFeatures",
    value: function() {
      var _getFeatures = (0, _asyncToGenerator2$2.default)(/* @__PURE__ */ _regenerator$2.default.mark(function _callee8(refName, start, end) {
        var opts, ob, ret, _args8 = arguments;
        return _regenerator$2.default.wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                opts = _args8.length > 3 && _args8[3] !== void 0 ? _args8[3] : {
                  scale: 1
                };
                _context8.next = 3;
                return this.getFeatureStream(refName, start, end, opts);
              case 3:
                ob = _context8.sent;
                _context8.next = 6;
                return ob.pipe((0, _operators$1.reduce)(function(acc, curr) {
                  return acc.concat(curr);
                })).toPromise();
              case 6:
                ret = _context8.sent;
                return _context8.abrupt("return", ret || []);
              case 8:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));
      function getFeatures(_x12, _x13, _x14) {
        return _getFeatures.apply(this, arguments);
      }
      return getFeatures;
    }()
  }]);
  return BBI2;
}();
bbi.BBI = BBI;
var _interopRequireDefault$1 = interopRequireDefault.exports;
Object.defineProperty(bigwig, "__esModule", {
  value: true
});
bigwig.BigWig = void 0;
var _regenerator$1 = _interopRequireDefault$1(regenerator);
var _asyncToGenerator2$1 = _interopRequireDefault$1(asyncToGenerator.exports);
var _classCallCheck2$1 = _interopRequireDefault$1(classCallCheck.exports);
var _createClass2$1 = _interopRequireDefault$1(createClass.exports);
var _inherits2$1 = _interopRequireDefault$1(inherits.exports);
var _possibleConstructorReturn2$1 = _interopRequireDefault$1(possibleConstructorReturn.exports);
var _getPrototypeOf2$1 = _interopRequireDefault$1(getPrototypeOf.exports);
var _blockView = blockView;
var _bbi$1 = bbi;
function _createSuper$1(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct$1();
  return function _createSuperInternal() {
    var Super = (0, _getPrototypeOf2$1.default)(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = (0, _getPrototypeOf2$1.default)(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return (0, _possibleConstructorReturn2$1.default)(this, result);
  };
}
function _isNativeReflectConstruct$1() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Date.prototype.toString.call(Reflect.construct(Date, [], function() {
    }));
    return true;
  } catch (e) {
    return false;
  }
}
var BigWig = /* @__PURE__ */ function(_BBI) {
  (0, _inherits2$1.default)(BigWig2, _BBI);
  var _super = _createSuper$1(BigWig2);
  function BigWig2() {
    (0, _classCallCheck2$1.default)(this, BigWig2);
    return _super.apply(this, arguments);
  }
  (0, _createClass2$1.default)(BigWig2, [{
    key: "getView",
    value: function() {
      var _getView = (0, _asyncToGenerator2$1.default)(/* @__PURE__ */ _regenerator$1.default.mark(function _callee(scale, opts) {
        var _yield$this$getHeader, zoomLevels, refsByName, fileSize, isBigEndian, uncompressBufSize, basesPerPx, maxLevel, i, zh, indexLength;
        return _regenerator$1.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return this.getHeader(opts);
              case 2:
                _yield$this$getHeader = _context.sent;
                zoomLevels = _yield$this$getHeader.zoomLevels;
                refsByName = _yield$this$getHeader.refsByName;
                fileSize = _yield$this$getHeader.fileSize;
                isBigEndian = _yield$this$getHeader.isBigEndian;
                uncompressBufSize = _yield$this$getHeader.uncompressBufSize;
                basesPerPx = 1 / scale;
                maxLevel = zoomLevels.length;
                if (!fileSize) {
                  maxLevel -= 1;
                }
                i = maxLevel;
              case 12:
                if (!(i >= 0)) {
                  _context.next = 20;
                  break;
                }
                zh = zoomLevels[i];
                if (!(zh && zh.reductionLevel <= 2 * basesPerPx)) {
                  _context.next = 17;
                  break;
                }
                indexLength = i < zoomLevels.length - 1 ? zoomLevels[i + 1].dataOffset - zh.indexOffset : fileSize - 4 - zh.indexOffset;
                return _context.abrupt("return", new _blockView.BlockView(this.bbi, refsByName, zh.indexOffset, indexLength, isBigEndian, uncompressBufSize > 0, "summary"));
              case 17:
                i -= 1;
                _context.next = 12;
                break;
              case 20:
                return _context.abrupt("return", this.getUnzoomedView(opts));
              case 21:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));
      function getView(_x, _x2) {
        return _getView.apply(this, arguments);
      }
      return getView;
    }()
  }]);
  return BigWig2;
}(_bbi$1.BBI);
bigwig.BigWig = BigWig;
var bigbed = {};
var toConsumableArray = { exports: {} };
var arrayWithoutHoles = { exports: {} };
var arrayLikeToArray = { exports: {} };
(function(module2) {
  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length)
      len = arr.length;
    for (var i = 0, arr2 = new Array(len); i < len; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  }
  module2.exports = _arrayLikeToArray;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(arrayLikeToArray);
(function(module2) {
  var arrayLikeToArray$1 = arrayLikeToArray.exports;
  function _arrayWithoutHoles(arr) {
    if (Array.isArray(arr))
      return arrayLikeToArray$1(arr);
  }
  module2.exports = _arrayWithoutHoles;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(arrayWithoutHoles);
var iterableToArray = { exports: {} };
(function(module2) {
  function _iterableToArray(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
      return Array.from(iter);
  }
  module2.exports = _iterableToArray;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(iterableToArray);
var unsupportedIterableToArray = { exports: {} };
(function(module2) {
  var arrayLikeToArray$1 = arrayLikeToArray.exports;
  function _unsupportedIterableToArray(o, minLen) {
    if (!o)
      return;
    if (typeof o === "string")
      return arrayLikeToArray$1(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor)
      n = o.constructor.name;
    if (n === "Map" || n === "Set")
      return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
      return arrayLikeToArray$1(o, minLen);
  }
  module2.exports = _unsupportedIterableToArray;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(unsupportedIterableToArray);
var nonIterableSpread = { exports: {} };
(function(module2) {
  function _nonIterableSpread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  }
  module2.exports = _nonIterableSpread;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(nonIterableSpread);
(function(module2) {
  var arrayWithoutHoles$1 = arrayWithoutHoles.exports;
  var iterableToArray$1 = iterableToArray.exports;
  var unsupportedIterableToArray$1 = unsupportedIterableToArray.exports;
  var nonIterableSpread$1 = nonIterableSpread.exports;
  function _toConsumableArray(arr) {
    return arrayWithoutHoles$1(arr) || iterableToArray$1(arr) || unsupportedIterableToArray$1(arr) || nonIterableSpread$1();
  }
  module2.exports = _toConsumableArray;
  module2.exports["default"] = module2.exports, module2.exports.__esModule = true;
})(toConsumableArray);
var _interopRequireDefault = interopRequireDefault.exports;
Object.defineProperty(bigbed, "__esModule", {
  value: true
});
bigbed.filterUndef = filterUndef;
bigbed.BigBed = void 0;
var _toConsumableArray2 = _interopRequireDefault(toConsumableArray.exports);
var _regenerator = _interopRequireDefault(regenerator);
var _asyncToGenerator2 = _interopRequireDefault(asyncToGenerator.exports);
var _classCallCheck2 = _interopRequireDefault(classCallCheck.exports);
var _createClass2 = _interopRequireDefault(createClass.exports);
var _assertThisInitialized2 = _interopRequireDefault(assertThisInitialized.exports);
var _inherits2 = _interopRequireDefault(inherits.exports);
var _possibleConstructorReturn2 = _interopRequireDefault(possibleConstructorReturn.exports);
var _getPrototypeOf2 = _interopRequireDefault(getPrototypeOf.exports);
var _defineProperty2 = _interopRequireDefault(gosling_es_defineProperty.exports);
var _binaryParser = binary_parser;
var _rxjs = require$$12$1;
var _operators = require$$13$1;
var _abortablePromiseCache = _interopRequireDefault(gosling_es_dist);
var _quickLru = _interopRequireDefault(quickLru);
var _bbi = bbi;
function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    if (enumerableOnly)
      symbols = symbols.filter(function(sym) {
        return Object.getOwnPropertyDescriptor(object, sym).enumerable;
      });
    keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    if (i % 2) {
      ownKeys(Object(source), true).forEach(function(key) {
        (0, _defineProperty2.default)(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys(Object(source)).forEach(function(key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }
  return target;
}
function _createSuper(Derived) {
  var hasNativeReflectConstruct = _isNativeReflectConstruct();
  return function _createSuperInternal() {
    var Super = (0, _getPrototypeOf2.default)(Derived), result;
    if (hasNativeReflectConstruct) {
      var NewTarget = (0, _getPrototypeOf2.default)(this).constructor;
      result = Reflect.construct(Super, arguments, NewTarget);
    } else {
      result = Super.apply(this, arguments);
    }
    return (0, _possibleConstructorReturn2.default)(this, result);
  };
}
function _isNativeReflectConstruct() {
  if (typeof Reflect === "undefined" || !Reflect.construct)
    return false;
  if (Reflect.construct.sham)
    return false;
  if (typeof Proxy === "function")
    return true;
  try {
    Date.prototype.toString.call(Reflect.construct(Date, [], function() {
    }));
    return true;
  } catch (e) {
    return false;
  }
}
function filterUndef(ts) {
  return ts.filter(function(t) {
    return !!t;
  });
}
var BigBed = /* @__PURE__ */ function(_BBI) {
  (0, _inherits2.default)(BigBed2, _BBI);
  var _super = _createSuper(BigBed2);
  function BigBed2(opts) {
    var _this;
    (0, _classCallCheck2.default)(this, BigBed2);
    _this = _super.call(this, opts);
    (0, _defineProperty2.default)((0, _assertThisInitialized2.default)(_this), "readIndicesCache", new _abortablePromiseCache.default({
      cache: new _quickLru.default({
        maxSize: 1
      }),
      fill: function() {
        var _fill = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee(args, signal) {
          return _regenerator.default.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  return _context.abrupt("return", _this._readIndices(_objectSpread(_objectSpread({}, args), {}, {
                    signal
                  })));
                case 1:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
        function fill(_x, _x2) {
          return _fill.apply(this, arguments);
        }
        return fill;
      }()
    }));
    return _this;
  }
  (0, _createClass2.default)(BigBed2, [{
    key: "readIndices",
    value: function readIndices() {
      var opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var options = "aborted" in opts ? {
        signal: opts
      } : opts;
      return this.readIndicesCache.get(JSON.stringify(options), options, options.signal);
    }
  }, {
    key: "getView",
    value: function() {
      var _getView = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee2(scale, opts) {
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                return _context2.abrupt("return", this.getUnzoomedView(opts));
              case 1:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));
      function getView(_x3, _x4) {
        return _getView.apply(this, arguments);
      }
      return getView;
    }()
  }, {
    key: "_readIndices",
    value: function() {
      var _readIndices2 = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee3(opts) {
        var _yield$this$getHeader, extHeaderOffset, isBigEndian, _yield$this$bbi$read, data2, le, ret, count2, offset, blocklen, len, _yield$this$bbi$read2, buffer2, extParser, indices, i;
        return _regenerator.default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return this.getHeader(opts);
              case 2:
                _yield$this$getHeader = _context3.sent;
                extHeaderOffset = _yield$this$getHeader.extHeaderOffset;
                isBigEndian = _yield$this$getHeader.isBigEndian;
                _context3.next = 7;
                return this.bbi.read(Buffer.alloc(64), 0, 64, extHeaderOffset);
              case 7:
                _yield$this$bbi$read = _context3.sent;
                data2 = _yield$this$bbi$read.buffer;
                le = isBigEndian ? "big" : "little";
                ret = new _binaryParser.Parser().endianess(le).uint16("size").uint16("count").uint64("offset").parse(data2).result;
                count2 = ret.count, offset = ret.offset;
                if (!(count2 === 0)) {
                  _context3.next = 14;
                  break;
                }
                return _context3.abrupt("return", []);
              case 14:
                blocklen = 20;
                len = blocklen * count2;
                _context3.next = 18;
                return this.bbi.read(Buffer.alloc(len), 0, len, offset);
              case 18:
                _yield$this$bbi$read2 = _context3.sent;
                buffer2 = _yield$this$bbi$read2.buffer;
                extParser = new _binaryParser.Parser().endianess(le).int16("type").int16("fieldcount").uint64("offset").skip(4).int16("field");
                indices = [];
                for (i = 0; i < count2; i += 1) {
                  indices.push(extParser.parse(buffer2.slice(i * blocklen)).result);
                }
                return _context3.abrupt("return", indices);
              case 24:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));
      function _readIndices(_x5) {
        return _readIndices2.apply(this, arguments);
      }
      return _readIndices;
    }()
  }, {
    key: "searchExtraIndexBlocks",
    value: function() {
      var _searchExtraIndexBlocks = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee6(name2) {
        var _this2 = this;
        var opts, _yield$this$getHeader2, isBigEndian, indices, locs, _args6 = arguments;
        return _regenerator.default.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                opts = _args6.length > 1 && _args6[1] !== void 0 ? _args6[1] : {};
                _context6.next = 3;
                return this.getHeader(opts);
              case 3:
                _yield$this$getHeader2 = _context6.sent;
                isBigEndian = _yield$this$getHeader2.isBigEndian;
                _context6.next = 7;
                return this.readIndices(opts);
              case 7:
                indices = _context6.sent;
                if (indices.length) {
                  _context6.next = 10;
                  break;
                }
                return _context6.abrupt("return", []);
              case 10:
                locs = indices.map(/* @__PURE__ */ function() {
                  var _ref = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee5(index) {
                    var offset, field, _yield$_this2$bbi$rea, data2, p, _p$parse$result, blockSize, keySize, valSize, bpt, bptReadNode, rootNodeOffset;
                    return _regenerator.default.wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            offset = index.offset, field = index.field;
                            _context5.next = 3;
                            return _this2.bbi.read(Buffer.alloc(32), 0, 32, offset, opts);
                          case 3:
                            _yield$_this2$bbi$rea = _context5.sent;
                            data2 = _yield$_this2$bbi$rea.buffer;
                            p = new _binaryParser.Parser().endianess(isBigEndian ? "big" : "little").int32("magic").int32("blockSize").int32("keySize").int32("valSize").uint64("itemCount");
                            _p$parse$result = p.parse(data2).result, blockSize = _p$parse$result.blockSize, keySize = _p$parse$result.keySize, valSize = _p$parse$result.valSize;
                            bpt = new _binaryParser.Parser().endianess(isBigEndian ? "big" : "little").int8("nodeType").skip(1).int16("cnt").choice({
                              tag: "nodeType",
                              choices: {
                                0: new _binaryParser.Parser().array("leafkeys", {
                                  length: "cnt",
                                  type: new _binaryParser.Parser().string("key", {
                                    length: keySize,
                                    stripNull: true
                                  }).uint64("offset")
                                }),
                                1: new _binaryParser.Parser().array("keys", {
                                  length: "cnt",
                                  type: new _binaryParser.Parser().string("key", {
                                    length: keySize,
                                    stripNull: true
                                  }).uint64("offset").uint32("length").uint32("reserved")
                                })
                              }
                            });
                            bptReadNode = /* @__PURE__ */ function() {
                              var _ref2 = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee4(nodeOffset) {
                                var len, _yield$_this2$bbi$rea2, buffer2, node, lastOffset, i, key, _i;
                                return _regenerator.default.wrap(function _callee4$(_context4) {
                                  while (1) {
                                    switch (_context4.prev = _context4.next) {
                                      case 0:
                                        len = 4 + blockSize * (keySize + valSize);
                                        _context4.next = 3;
                                        return _this2.bbi.read(Buffer.alloc(len), 0, len, nodeOffset, opts);
                                      case 3:
                                        _yield$_this2$bbi$rea2 = _context4.sent;
                                        buffer2 = _yield$_this2$bbi$rea2.buffer;
                                        node = bpt.parse(buffer2).result;
                                        if (!node.leafkeys) {
                                          _context4.next = 17;
                                          break;
                                        }
                                        i = 0;
                                      case 8:
                                        if (!(i < node.leafkeys.length)) {
                                          _context4.next = 16;
                                          break;
                                        }
                                        key = node.leafkeys[i].key;
                                        if (!(name2.localeCompare(key) < 0 && lastOffset)) {
                                          _context4.next = 12;
                                          break;
                                        }
                                        return _context4.abrupt("return", bptReadNode(lastOffset));
                                      case 12:
                                        lastOffset = node.leafkeys[i].offset;
                                      case 13:
                                        i += 1;
                                        _context4.next = 8;
                                        break;
                                      case 16:
                                        return _context4.abrupt("return", bptReadNode(lastOffset));
                                      case 17:
                                        _i = 0;
                                      case 18:
                                        if (!(_i < node.keys.length)) {
                                          _context4.next = 24;
                                          break;
                                        }
                                        if (!(node.keys[_i].key === name2)) {
                                          _context4.next = 21;
                                          break;
                                        }
                                        return _context4.abrupt("return", _objectSpread(_objectSpread({}, node.keys[_i]), {}, {
                                          field
                                        }));
                                      case 21:
                                        _i += 1;
                                        _context4.next = 18;
                                        break;
                                      case 24:
                                        return _context4.abrupt("return", void 0);
                                      case 25:
                                      case "end":
                                        return _context4.stop();
                                    }
                                  }
                                }, _callee4);
                              }));
                              return function bptReadNode2(_x8) {
                                return _ref2.apply(this, arguments);
                              };
                            }();
                            rootNodeOffset = 32;
                            return _context5.abrupt("return", bptReadNode(offset + rootNodeOffset));
                          case 11:
                          case "end":
                            return _context5.stop();
                        }
                      }
                    }, _callee5);
                  }));
                  return function(_x7) {
                    return _ref.apply(this, arguments);
                  };
                }());
                _context6.t0 = filterUndef;
                _context6.next = 14;
                return Promise.all(locs);
              case 14:
                _context6.t1 = _context6.sent;
                return _context6.abrupt("return", (0, _context6.t0)(_context6.t1));
              case 16:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));
      function searchExtraIndexBlocks(_x6) {
        return _searchExtraIndexBlocks.apply(this, arguments);
      }
      return searchExtraIndexBlocks;
    }()
  }, {
    key: "searchExtraIndex",
    value: function() {
      var _searchExtraIndex = (0, _asyncToGenerator2.default)(/* @__PURE__ */ _regenerator.default.mark(function _callee7(name2) {
        var opts, blocks, view, res, ret, _args7 = arguments;
        return _regenerator.default.wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                opts = _args7.length > 1 && _args7[1] !== void 0 ? _args7[1] : {};
                _context7.next = 3;
                return this.searchExtraIndexBlocks(name2, opts);
              case 3:
                blocks = _context7.sent;
                if (blocks.length) {
                  _context7.next = 6;
                  break;
                }
                return _context7.abrupt("return", []);
              case 6:
                _context7.next = 8;
                return this.getUnzoomedView(opts);
              case 8:
                view = _context7.sent;
                res = blocks.map(function(block) {
                  return new _rxjs.Observable(function(observer) {
                    view.readFeatures(observer, [block], opts);
                  }).pipe((0, _operators.reduce)(function(acc, curr) {
                    return acc.concat(curr);
                  }), (0, _operators.map)(function(x) {
                    for (var i = 0; i < x.length; i += 1) {
                      x[i].field = block.field;
                    }
                    return x;
                  }));
                });
                _context7.next = 12;
                return _rxjs.merge.apply(void 0, (0, _toConsumableArray2.default)(res)).toPromise();
              case 12:
                ret = _context7.sent;
                return _context7.abrupt("return", ret.filter(function(f2) {
                  return f2.rest.split("	")[f2.field - 3] === name2;
                }));
              case 14:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this);
      }));
      function searchExtraIndex(_x9) {
        return _searchExtraIndex.apply(this, arguments);
      }
      return searchExtraIndex;
    }()
  }]);
  return BigBed2;
}(_bbi.BBI);
bigbed.BigBed = BigBed;
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", {
    value: true
  });
  Object.defineProperty(exports2, "BigWig", {
    enumerable: true,
    get: function get() {
      return _bigwig.BigWig;
    }
  });
  Object.defineProperty(exports2, "BigBed", {
    enumerable: true,
    get: function get() {
      return _bigbed.BigBed;
    }
  });
  Object.defineProperty(exports2, "Feature", {
    enumerable: true,
    get: function get() {
      return _bbi2.Feature;
    }
  });
  Object.defineProperty(exports2, "Header", {
    enumerable: true,
    get: function get() {
      return _bbi2.Header;
    }
  });
  Object.defineProperty(exports2, "RequestOptions", {
    enumerable: true,
    get: function get() {
      return _bbi2.RequestOptions;
    }
  });
  var _bigwig = bigwig;
  var _bigbed = bigbed;
  var _bbi2 = bbi;
})(dist$1);
function BBIDataFetcher(HGC, ...args) {
  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }
  const cls = class BBIDataFetcherClass {
    constructor(dataConfig) {
      dataConfig.chromSizesUrl = "https://aveit.s3.amazonaws.com/higlass/data/sequence/hg38.chrom.sizes";
      this.dataConfig = dataConfig;
      this.bwFileHeader = null;
      this.bwFile = null;
      this.TILE_SIZE = 1024;
      this.errorTxt = "";
      this.dataPromises = [];
      const chromosomeSizes = GET_CHROM_SIZES(this.assembly).size;
      const chromosomeCumPositions = [];
      const chromosomePositions = {};
      let prevEndPosition = 0;
      Object.keys(GET_CHROM_SIZES(this.assembly).size).forEach((chrStr, i) => {
        const positionInfo = {
          id: i,
          chr: chrStr,
          pos: prevEndPosition
        };
        chromosomeCumPositions.push(positionInfo);
        chromosomePositions[chrStr] = positionInfo;
        prevEndPosition += GET_CHROM_SIZES(this.assembly).size[chrStr];
      });
      this.chromSizes = {
        chrToAbs: (chrom, chromPos) => this.chromSizes.chrPositions[chrom].pos + chromPos,
        cumPositions: chromosomeCumPositions,
        chrPositions: chromosomePositions,
        totalLength: prevEndPosition,
        chromLengths: chromosomeSizes
      };
      this.dataPromises.push(this.loadBBI(dataConfig));
    }
    loadBBI(dataConfig) {
      if (dataConfig.url) {
        this.bwFile = new dist$1.BigWig({
          filehandle: new index_js_.RemoteFile(dataConfig.url)
        });
        return this.bwFile.getHeader().then((h) => {
          this.bwFileHeader = h;
        });
      } else {
        console.error('Please enter a "url" field to the data config');
        return null;
      }
    }
    tilesetInfo(callback) {
      this.tilesetInfoLoading = true;
      return Promise.all(this.dataPromises).then(() => {
        this.tilesetInfoLoading = false;
        let retVal = {};
        const totalLength = this.chromSizes.totalLength;
        retVal = {
          tile_size: this.TILE_SIZE,
          max_zoom: Math.ceil(Math.log(totalLength / this.TILE_SIZE) / Math.log(2)),
          max_width: 2 ** Math.ceil(Math.log(totalLength) / Math.log(2)),
          min_pos: [0],
          max_pos: [totalLength]
        };
        if (callback) {
          callback(retVal);
        }
        return retVal;
      }).catch((err) => {
        this.tilesetInfoLoading = false;
        console.error(err);
        if (callback) {
          callback({
            error: `Error parsing bigwig: ${err}`
          });
        }
      });
    }
    fetchTilesDebounced(receivedTiles, tileIds) {
      const tiles = {};
      const validTileIds = [];
      const tilePromises = [];
      for (const tileId of tileIds) {
        const parts = tileId.split(".");
        const z = parseInt(parts[0], 10);
        const x = parseInt(parts[1], 10);
        if (Number.isNaN(x) || Number.isNaN(z)) {
          console.warn("Invalid tile zoom or position:", z, x);
          continue;
        }
        validTileIds.push(tileId);
        tilePromises.push(this.tile(z, x));
      }
      Promise.all(tilePromises).then((values) => {
        for (let i = 0; i < values.length; i++) {
          const validTileId = validTileIds[i];
          tiles[validTileId] = values[i];
          tiles[validTileId].tilePositionId = validTileId;
        }
        receivedTiles(tiles);
      });
      return tiles;
    }
    tile(z, x) {
      return this.tilesetInfo().then((tsInfo) => {
        const tileWidth = +tsInfo.max_width / 2 ** +z;
        const recordPromises = [];
        const tile = {
          tilePos: [x],
          tileId: `bigwig.${z}.${x}`,
          zoomLevel: z
        };
        const minXOriginal = tsInfo.min_pos[0] + x * tileWidth;
        let minX = minXOriginal;
        const maxX = tsInfo.min_pos[0] + (x + 1) * tileWidth;
        const basesPerPixel = this.determineScale(minX, maxX);
        const basesPerBin = (maxX - minX) / this.TILE_SIZE;
        const binStarts = [];
        for (let i = 0; i < this.TILE_SIZE; i++) {
          binStarts.push(minX + i * basesPerBin);
        }
        const { chromLengths, cumPositions } = this.chromSizes;
        cumPositions.forEach((cumPos) => {
          const chromName = cumPos.chr;
          const chromStart = cumPos.pos;
          const chromEnd = cumPos.pos + chromLengths[chromName];
          let startPos, endPos;
          if (chromStart <= minX && minX < chromEnd) {
            if (maxX > chromEnd) {
              startPos = minX - chromStart;
              endPos = chromEnd - chromStart;
              recordPromises.push(this.bwFile.getFeatures(chromName, startPos, endPos, {
                scale: 1 / basesPerPixel
              }).then((values) => {
                values.forEach((v) => {
                  v["startAbs"] = HGC.utils.chrToAbs(chromName, v.start, this.chromSizes);
                  v["endAbs"] = HGC.utils.chrToAbs(chromName, v.end, this.chromSizes);
                });
                return values;
              }));
              minX = chromEnd;
            } else {
              startPos = Math.floor(minX - chromStart);
              endPos = Math.ceil(maxX - chromStart);
              recordPromises.push(this.bwFile.getFeatures(chromName, startPos, endPos, {
                scale: 1 / basesPerPixel
              }).then((values) => {
                values.forEach((v) => {
                  v["startAbs"] = HGC.utils.chrToAbs(chromName, v.start, this.chromSizes);
                  v["endAbs"] = HGC.utils.chrToAbs(chromName, v.end, this.chromSizes);
                });
                return values;
              }));
              return;
            }
          }
        });
        return Promise.all(recordPromises).then((v) => {
          const values = v.flat();
          var dense = [];
          for (var i = 0; i < this.TILE_SIZE; i++) {
            dense.push(null);
          }
          binStarts.forEach((curStart, index) => {
            if (curStart < minXOriginal || curStart > maxX) {
              return;
            }
            const filtered = values.filter((v2) => {
              return curStart >= v2.startAbs && curStart < v2.endAbs;
            }).map((v2) => v2.score);
            dense[index] = filtered.length > 0 ? filtered[0] : null;
          });
          tile.min_value = Math.min(...dense);
          tile.max_value = Math.max(...dense);
          const dde = new HGC.utils.DenseDataExtrema1D(dense);
          tile.dense = dense;
          tile.denseDataExtrema = dde;
          tile.minNonZero = dde.minNonZeroInTile;
          tile.maxNonZero = dde.maxNonZeroInTile;
          return tile;
        });
      });
    }
    determineScale(minX, maxX) {
      const reductionLevels = [1];
      const numRequestedElements = maxX - minX;
      this.bwFileHeader.zoomLevels.forEach((z) => {
        reductionLevels.push(z.reductionLevel);
      });
      let level;
      reductionLevels.forEach((rl) => {
        if (level)
          return;
        const numElementsFromFile = numRequestedElements / rl;
        if (numElementsFromFile <= this.TILE_SIZE * 20) {
          level = rl;
        }
      });
      return level || reductionLevels.slice(-1)[0];
    }
  };
  return new cls(...args);
}
BBIDataFetcher.config = {
  type: "bigwig"
};
var uri_all = { exports: {} };
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
(function(module2, exports2) {
  (function(global2, factory) {
    factory(exports2);
  })(commonjsGlobal, function(exports3) {
    function merge2() {
      for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
        sets[_key] = arguments[_key];
      }
      if (sets.length > 1) {
        sets[0] = sets[0].slice(0, -1);
        var xl = sets.length - 1;
        for (var x = 1; x < xl; ++x) {
          sets[x] = sets[x].slice(1, -1);
        }
        sets[xl] = sets[xl].slice(1);
        return sets.join("");
      } else {
        return sets[0];
      }
    }
    function subexp(str) {
      return "(?:" + str + ")";
    }
    function typeOf(o) {
      return o === void 0 ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
    }
    function toUpperCase(str) {
      return str.toUpperCase();
    }
    function toArray2(obj) {
      return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
    }
    function assign2(target, source) {
      var obj = target;
      if (source) {
        for (var key in source) {
          obj[key] = source[key];
        }
      }
      return obj;
    }
    function buildExps(isIRI) {
      var ALPHA$$ = "[A-Za-z]", DIGIT$$ = "[0-9]", HEXDIG$$2 = merge2(DIGIT$$, "[A-Fa-f]"), PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge2(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge2(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$);
      subexp(ALPHA$$ + merge2(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*");
      subexp(subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*");
      var DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$2 + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$2 + "|" + PCT_ENCODED$2) + "+");
      subexp("[vV]" + HEXDIG$$2 + "+\\." + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+");
      subexp(subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$)) + "*");
      var PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]"));
      subexp(subexp(PCT_ENCODED$2 + "|" + merge2(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+");
      subexp(subexp(PCHAR$ + "|" + merge2("[\\/\\?]", IPRIVATE$$)) + "*");
      return {
        NOT_SCHEME: new RegExp(merge2("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
        NOT_USERINFO: new RegExp(merge2("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_HOST: new RegExp(merge2("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_PATH: new RegExp(merge2("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_PATH_NOSCHEME: new RegExp(merge2("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_QUERY: new RegExp(merge2("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
        NOT_FRAGMENT: new RegExp(merge2("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
        ESCAPE: new RegExp(merge2("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        UNRESERVED: new RegExp(UNRESERVED$$2, "g"),
        OTHER_CHARS: new RegExp(merge2("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"),
        PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"),
        IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
        IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$")
      };
    }
    var URI_PROTOCOL = buildExps(false);
    var IRI_PROTOCOL = buildExps(true);
    var slicedToArray = function() {
      function sliceIterator(arr, i) {
        var _arr = [];
        var _n = true;
        var _d = false;
        var _e = void 0;
        try {
          for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
            _arr.push(_s.value);
            if (i && _arr.length === i)
              break;
          }
        } catch (err) {
          _d = true;
          _e = err;
        } finally {
          try {
            if (!_n && _i["return"])
              _i["return"]();
          } finally {
            if (_d)
              throw _e;
          }
        }
        return _arr;
      }
      return function(arr, i) {
        if (Array.isArray(arr)) {
          return arr;
        } else if (Symbol.iterator in Object(arr)) {
          return sliceIterator(arr, i);
        } else {
          throw new TypeError("Invalid attempt to destructure non-iterable instance");
        }
      };
    }();
    var toConsumableArray2 = function(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);
      }
    };
    var maxInt = 2147483647;
    var base = 36;
    var tMin = 1;
    var tMax = 26;
    var skew = 38;
    var damp = 700;
    var initialBias = 72;
    var initialN = 128;
    var delimiter = "-";
    var regexPunycode = /^xn--/;
    var regexNonASCII = /[^\0-\x7E]/;
    var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
    var errors = {
      "overflow": "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    };
    var baseMinusTMin = base - tMin;
    var floor = Math.floor;
    var stringFromCharCode = String.fromCharCode;
    function error$1(type2) {
      throw new RangeError(errors[type2]);
    }
    function map2(array, fn) {
      var result = [];
      var length = array.length;
      while (length--) {
        result[length] = fn(array[length]);
      }
      return result;
    }
    function mapDomain(string, fn) {
      var parts = string.split("@");
      var result = "";
      if (parts.length > 1) {
        result = parts[0] + "@";
        string = parts[1];
      }
      string = string.replace(regexSeparators, ".");
      var labels = string.split(".");
      var encoded = map2(labels, fn).join(".");
      return result + encoded;
    }
    function ucs2decode(string) {
      var output = [];
      var counter = 0;
      var length = string.length;
      while (counter < length) {
        var value = string.charCodeAt(counter++);
        if (value >= 55296 && value <= 56319 && counter < length) {
          var extra = string.charCodeAt(counter++);
          if ((extra & 64512) == 56320) {
            output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
          } else {
            output.push(value);
            counter--;
          }
        } else {
          output.push(value);
        }
      }
      return output;
    }
    var ucs2encode = function ucs2encode2(array) {
      return String.fromCodePoint.apply(String, toConsumableArray2(array));
    };
    var basicToDigit = function basicToDigit2(codePoint) {
      if (codePoint - 48 < 10) {
        return codePoint - 22;
      }
      if (codePoint - 65 < 26) {
        return codePoint - 65;
      }
      if (codePoint - 97 < 26) {
        return codePoint - 97;
      }
      return base;
    };
    var digitToBasic = function digitToBasic2(digit, flag) {
      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
    };
    var adapt = function adapt2(delta, numPoints, firstTime) {
      var k = 0;
      delta = firstTime ? floor(delta / damp) : delta >> 1;
      delta += floor(delta / numPoints);
      for (; delta > baseMinusTMin * tMax >> 1; k += base) {
        delta = floor(delta / baseMinusTMin);
      }
      return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
    };
    var decode = function decode2(input) {
      var output = [];
      var inputLength = input.length;
      var i = 0;
      var n = initialN;
      var bias = initialBias;
      var basic = input.lastIndexOf(delimiter);
      if (basic < 0) {
        basic = 0;
      }
      for (var j = 0; j < basic; ++j) {
        if (input.charCodeAt(j) >= 128) {
          error$1("not-basic");
        }
        output.push(input.charCodeAt(j));
      }
      for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
        var oldi = i;
        for (var w = 1, k = base; ; k += base) {
          if (index >= inputLength) {
            error$1("invalid-input");
          }
          var digit = basicToDigit(input.charCodeAt(index++));
          if (digit >= base || digit > floor((maxInt - i) / w)) {
            error$1("overflow");
          }
          i += digit * w;
          var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
          if (digit < t) {
            break;
          }
          var baseMinusT = base - t;
          if (w > floor(maxInt / baseMinusT)) {
            error$1("overflow");
          }
          w *= baseMinusT;
        }
        var out = output.length + 1;
        bias = adapt(i - oldi, out, oldi == 0);
        if (floor(i / out) > maxInt - n) {
          error$1("overflow");
        }
        n += floor(i / out);
        i %= out;
        output.splice(i++, 0, n);
      }
      return String.fromCodePoint.apply(String, output);
    };
    var encode = function encode2(input) {
      var output = [];
      input = ucs2decode(input);
      var inputLength = input.length;
      var n = initialN;
      var delta = 0;
      var bias = initialBias;
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = void 0;
      try {
        for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var _currentValue2 = _step.value;
          if (_currentValue2 < 128) {
            output.push(stringFromCharCode(_currentValue2));
          }
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
      var basicLength = output.length;
      var handledCPCount = basicLength;
      if (basicLength) {
        output.push(delimiter);
      }
      while (handledCPCount < inputLength) {
        var m = maxInt;
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = void 0;
        try {
          for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var currentValue = _step2.value;
            if (currentValue >= n && currentValue < m) {
              m = currentValue;
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2.return) {
              _iterator2.return();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }
        var handledCPCountPlusOne = handledCPCount + 1;
        if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
          error$1("overflow");
        }
        delta += (m - n) * handledCPCountPlusOne;
        n = m;
        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = void 0;
        try {
          for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
            var _currentValue = _step3.value;
            if (_currentValue < n && ++delta > maxInt) {
              error$1("overflow");
            }
            if (_currentValue == n) {
              var q = delta;
              for (var k = base; ; k += base) {
                var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
                if (q < t) {
                  break;
                }
                var qMinusT = q - t;
                var baseMinusT = base - t;
                output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
                q = floor(qMinusT / baseMinusT);
              }
              output.push(stringFromCharCode(digitToBasic(q, 0)));
              bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
              delta = 0;
              ++handledCPCount;
            }
          }
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3.return) {
              _iterator3.return();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }
        ++delta;
        ++n;
      }
      return output.join("");
    };
    var toUnicode = function toUnicode2(input) {
      return mapDomain(input, function(string) {
        return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
      });
    };
    var toASCII = function toASCII2(input) {
      return mapDomain(input, function(string) {
        return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
      });
    };
    var punycode = {
      "version": "2.1.0",
      "ucs2": {
        "decode": ucs2decode,
        "encode": ucs2encode
      },
      "decode": decode,
      "encode": encode,
      "toASCII": toASCII,
      "toUnicode": toUnicode
    };
    var SCHEMES = {};
    function pctEncChar(chr) {
      var c = chr.charCodeAt(0);
      var e = void 0;
      if (c < 16)
        e = "%0" + c.toString(16).toUpperCase();
      else if (c < 128)
        e = "%" + c.toString(16).toUpperCase();
      else if (c < 2048)
        e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
      else
        e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
      return e;
    }
    function pctDecChars(str) {
      var newStr = "";
      var i = 0;
      var il = str.length;
      while (i < il) {
        var c = parseInt(str.substr(i + 1, 2), 16);
        if (c < 128) {
          newStr += String.fromCharCode(c);
          i += 3;
        } else if (c >= 194 && c < 224) {
          if (il - i >= 6) {
            var c2 = parseInt(str.substr(i + 4, 2), 16);
            newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
          } else {
            newStr += str.substr(i, 6);
          }
          i += 6;
        } else if (c >= 224) {
          if (il - i >= 9) {
            var _c = parseInt(str.substr(i + 4, 2), 16);
            var c3 = parseInt(str.substr(i + 7, 2), 16);
            newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
          } else {
            newStr += str.substr(i, 9);
          }
          i += 9;
        } else {
          newStr += str.substr(i, 3);
          i += 3;
        }
      }
      return newStr;
    }
    function _normalizeComponentEncoding(components, protocol) {
      function decodeUnreserved2(str) {
        var decStr = pctDecChars(str);
        return !decStr.match(protocol.UNRESERVED) ? str : decStr;
      }
      if (components.scheme)
        components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, "");
      if (components.userinfo !== void 0)
        components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.host !== void 0)
        components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.path !== void 0)
        components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.query !== void 0)
        components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.fragment !== void 0)
        components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      return components;
    }
    function _stripLeadingZeros(str) {
      return str.replace(/^0*(.*)/, "$1") || "0";
    }
    function _normalizeIPv4(host, protocol) {
      var matches = host.match(protocol.IPV4ADDRESS) || [];
      var _matches = slicedToArray(matches, 2), address = _matches[1];
      if (address) {
        return address.split(".").map(_stripLeadingZeros).join(".");
      } else {
        return host;
      }
    }
    function _normalizeIPv6(host, protocol) {
      var matches = host.match(protocol.IPV6ADDRESS) || [];
      var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2];
      if (address) {
        var _address$toLowerCase$ = address.toLowerCase().split("::").reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last2 = _address$toLowerCase$2[0], first2 = _address$toLowerCase$2[1];
        var firstFields = first2 ? first2.split(":").map(_stripLeadingZeros) : [];
        var lastFields = last2.split(":").map(_stripLeadingZeros);
        var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
        var fieldCount = isLastFieldIPv4Address ? 7 : 8;
        var lastFieldsStart = lastFields.length - fieldCount;
        var fields = Array(fieldCount);
        for (var x = 0; x < fieldCount; ++x) {
          fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || "";
        }
        if (isLastFieldIPv4Address) {
          fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
        }
        var allZeroFields = fields.reduce(function(acc, field, index) {
          if (!field || field === "0") {
            var lastLongest = acc[acc.length - 1];
            if (lastLongest && lastLongest.index + lastLongest.length === index) {
              lastLongest.length++;
            } else {
              acc.push({ index, length: 1 });
            }
          }
          return acc;
        }, []);
        var longestZeroFields = allZeroFields.sort(function(a, b) {
          return b.length - a.length;
        })[0];
        var newHost = void 0;
        if (longestZeroFields && longestZeroFields.length > 1) {
          var newFirst = fields.slice(0, longestZeroFields.index);
          var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
          newHost = newFirst.join(":") + "::" + newLast.join(":");
        } else {
          newHost = fields.join(":");
        }
        if (zone) {
          newHost += "%" + zone;
        }
        return newHost;
      } else {
        return host;
      }
    }
    var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
    var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0;
    function parse2(uriString) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var components = {};
      var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
      if (options.reference === "suffix")
        uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
      var matches = uriString.match(URI_PARSE);
      if (matches) {
        if (NO_MATCH_IS_UNDEFINED) {
          components.scheme = matches[1];
          components.userinfo = matches[3];
          components.host = matches[4];
          components.port = parseInt(matches[5], 10);
          components.path = matches[6] || "";
          components.query = matches[7];
          components.fragment = matches[8];
          if (isNaN(components.port)) {
            components.port = matches[5];
          }
        } else {
          components.scheme = matches[1] || void 0;
          components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : void 0;
          components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0;
          components.port = parseInt(matches[5], 10);
          components.path = matches[6] || "";
          components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0;
          components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : void 0;
          if (isNaN(components.port)) {
            components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0;
          }
        }
        if (components.host) {
          components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
        }
        if (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) {
          components.reference = "same-document";
        } else if (components.scheme === void 0) {
          components.reference = "relative";
        } else if (components.fragment === void 0) {
          components.reference = "absolute";
        } else {
          components.reference = "uri";
        }
        if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
          components.error = components.error || "URI is not a " + options.reference + " reference.";
        }
        var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
            try {
              components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
            } catch (e) {
              components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
            }
          }
          _normalizeComponentEncoding(components, URI_PROTOCOL);
        } else {
          _normalizeComponentEncoding(components, protocol);
        }
        if (schemeHandler && schemeHandler.parse) {
          schemeHandler.parse(components, options);
        }
      } else {
        components.error = components.error || "URI can not be parsed.";
      }
      return components;
    }
    function _recomposeAuthority(components, options) {
      var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
      var uriTokens = [];
      if (components.userinfo !== void 0) {
        uriTokens.push(components.userinfo);
        uriTokens.push("@");
      }
      if (components.host !== void 0) {
        uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_, $1, $2) {
          return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
        }));
      }
      if (typeof components.port === "number" || typeof components.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(components.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    var RDS1 = /^\.\.?\//;
    var RDS2 = /^\/\.(\/|$)/;
    var RDS3 = /^\/\.\.(\/|$)/;
    var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
    function removeDotSegments(input) {
      var output = [];
      while (input.length) {
        if (input.match(RDS1)) {
          input = input.replace(RDS1, "");
        } else if (input.match(RDS2)) {
          input = input.replace(RDS2, "/");
        } else if (input.match(RDS3)) {
          input = input.replace(RDS3, "/");
          output.pop();
        } else if (input === "." || input === "..") {
          input = "";
        } else {
          var im = input.match(RDS5);
          if (im) {
            var s = im[0];
            input = input.slice(s.length);
            output.push(s);
          } else {
            throw new Error("Unexpected dot segment condition");
          }
        }
      }
      return output.join("");
    }
    function serialize(components) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
      var uriTokens = [];
      var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
      if (schemeHandler && schemeHandler.serialize)
        schemeHandler.serialize(components, options);
      if (components.host) {
        if (protocol.IPV6ADDRESS.test(components.host))
          ;
        else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
          try {
            components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
          } catch (e) {
            components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
          }
        }
      }
      _normalizeComponentEncoding(components, protocol);
      if (options.reference !== "suffix" && components.scheme) {
        uriTokens.push(components.scheme);
        uriTokens.push(":");
      }
      var authority = _recomposeAuthority(components, options);
      if (authority !== void 0) {
        if (options.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (components.path && components.path.charAt(0) !== "/") {
          uriTokens.push("/");
        }
      }
      if (components.path !== void 0) {
        var s = components.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s = removeDotSegments(s);
        }
        if (authority === void 0) {
          s = s.replace(/^\/\//, "/%2F");
        }
        uriTokens.push(s);
      }
      if (components.query !== void 0) {
        uriTokens.push("?");
        uriTokens.push(components.query);
      }
      if (components.fragment !== void 0) {
        uriTokens.push("#");
        uriTokens.push(components.fragment);
      }
      return uriTokens.join("");
    }
    function resolveComponents(base2, relative) {
      var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      var skipNormalization = arguments[3];
      var target = {};
      if (!skipNormalization) {
        base2 = parse2(serialize(base2, options), options);
        relative = parse2(serialize(relative, options), options);
      }
      options = options || {};
      if (!options.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
      } else {
        if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
          target.userinfo = relative.userinfo;
          target.host = relative.host;
          target.port = relative.port;
          target.path = removeDotSegments(relative.path || "");
          target.query = relative.query;
        } else {
          if (!relative.path) {
            target.path = base2.path;
            if (relative.query !== void 0) {
              target.query = relative.query;
            } else {
              target.query = base2.query;
            }
          } else {
            if (relative.path.charAt(0) === "/") {
              target.path = removeDotSegments(relative.path);
            } else {
              if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) {
                target.path = "/" + relative.path;
              } else if (!base2.path) {
                target.path = relative.path;
              } else {
                target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative.query;
          }
          target.userinfo = base2.userinfo;
          target.host = base2.host;
          target.port = base2.port;
        }
        target.scheme = base2.scheme;
      }
      target.fragment = relative.fragment;
      return target;
    }
    function resolve2(baseURI, relativeURI, options) {
      var schemelessOptions = assign2({ scheme: "null" }, options);
      return serialize(resolveComponents(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
    }
    function normalize(uri2, options) {
      if (typeof uri2 === "string") {
        uri2 = serialize(parse2(uri2, options), options);
      } else if (typeOf(uri2) === "object") {
        uri2 = parse2(serialize(uri2, options), options);
      }
      return uri2;
    }
    function equal3(uriA, uriB, options) {
      if (typeof uriA === "string") {
        uriA = serialize(parse2(uriA, options), options);
      } else if (typeOf(uriA) === "object") {
        uriA = serialize(uriA, options);
      }
      if (typeof uriB === "string") {
        uriB = serialize(parse2(uriB, options), options);
      } else if (typeOf(uriB) === "object") {
        uriB = serialize(uriB, options);
      }
      return uriA === uriB;
    }
    function escapeComponent(str, options) {
      return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
    }
    function unescapeComponent(str, options) {
      return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
    }
    var handler = {
      scheme: "http",
      domainHost: true,
      parse: function parse3(components, options) {
        if (!components.host) {
          components.error = components.error || "HTTP URIs must have a host.";
        }
        return components;
      },
      serialize: function serialize2(components, options) {
        var secure = String(components.scheme).toLowerCase() === "https";
        if (components.port === (secure ? 443 : 80) || components.port === "") {
          components.port = void 0;
        }
        if (!components.path) {
          components.path = "/";
        }
        return components;
      }
    };
    var handler$1 = {
      scheme: "https",
      domainHost: handler.domainHost,
      parse: handler.parse,
      serialize: handler.serialize
    };
    function isSecure(wsComponents) {
      return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
    }
    var handler$2 = {
      scheme: "ws",
      domainHost: true,
      parse: function parse3(components, options) {
        var wsComponents = components;
        wsComponents.secure = isSecure(wsComponents);
        wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : "");
        wsComponents.path = void 0;
        wsComponents.query = void 0;
        return wsComponents;
      },
      serialize: function serialize2(wsComponents, options) {
        if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
          wsComponents.port = void 0;
        }
        if (typeof wsComponents.secure === "boolean") {
          wsComponents.scheme = wsComponents.secure ? "wss" : "ws";
          wsComponents.secure = void 0;
        }
        if (wsComponents.resourceName) {
          var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
          wsComponents.path = path && path !== "/" ? path : void 0;
          wsComponents.query = query;
          wsComponents.resourceName = void 0;
        }
        wsComponents.fragment = void 0;
        return wsComponents;
      }
    };
    var handler$3 = {
      scheme: "wss",
      domainHost: handler$2.domainHost,
      parse: handler$2.parse,
      serialize: handler$2.serialize
    };
    var O = {};
    var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]";
    var HEXDIG$$ = "[0-9A-Fa-f]";
    var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$));
    var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
    var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
    var VCHAR$$ = merge2(QTEXT$$, '[\\"\\\\]');
    var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
    var UNRESERVED = new RegExp(UNRESERVED$$, "g");
    var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
    var NOT_LOCAL_PART = new RegExp(merge2("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
    var NOT_HFNAME = new RegExp(merge2("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
    var NOT_HFVALUE = NOT_HFNAME;
    function decodeUnreserved(str) {
      var decStr = pctDecChars(str);
      return !decStr.match(UNRESERVED) ? str : decStr;
    }
    var handler$4 = {
      scheme: "mailto",
      parse: function parse$$1(components, options) {
        var mailtoComponents = components;
        var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
        mailtoComponents.path = void 0;
        if (mailtoComponents.query) {
          var unknownHeaders = false;
          var headers = {};
          var hfields = mailtoComponents.query.split("&");
          for (var x = 0, xl = hfields.length; x < xl; ++x) {
            var hfield = hfields[x].split("=");
            switch (hfield[0]) {
              case "to":
                var toAddrs = hfield[1].split(",");
                for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
                  to.push(toAddrs[_x]);
                }
                break;
              case "subject":
                mailtoComponents.subject = unescapeComponent(hfield[1], options);
                break;
              case "body":
                mailtoComponents.body = unescapeComponent(hfield[1], options);
                break;
              default:
                unknownHeaders = true;
                headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
                break;
            }
          }
          if (unknownHeaders)
            mailtoComponents.headers = headers;
        }
        mailtoComponents.query = void 0;
        for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
          var addr = to[_x2].split("@");
          addr[0] = unescapeComponent(addr[0]);
          if (!options.unicodeSupport) {
            try {
              addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
            } catch (e) {
              mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
            }
          } else {
            addr[1] = unescapeComponent(addr[1], options).toLowerCase();
          }
          to[_x2] = addr.join("@");
        }
        return mailtoComponents;
      },
      serialize: function serialize$$1(mailtoComponents, options) {
        var components = mailtoComponents;
        var to = toArray2(mailtoComponents.to);
        if (to) {
          for (var x = 0, xl = to.length; x < xl; ++x) {
            var toAddr = String(to[x]);
            var atIdx = toAddr.lastIndexOf("@");
            var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
            var domain = toAddr.slice(atIdx + 1);
            try {
              domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
            } catch (e) {
              components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
            }
            to[x] = localPart + "@" + domain;
          }
          components.path = to.join(",");
        }
        var headers = mailtoComponents.headers = mailtoComponents.headers || {};
        if (mailtoComponents.subject)
          headers["subject"] = mailtoComponents.subject;
        if (mailtoComponents.body)
          headers["body"] = mailtoComponents.body;
        var fields = [];
        for (var name2 in headers) {
          if (headers[name2] !== O[name2]) {
            fields.push(name2.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name2].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
          }
        }
        if (fields.length) {
          components.query = fields.join("&");
        }
        return components;
      }
    };
    var URN_PARSE = /^([^\:]+)\:(.*)/;
    var handler$5 = {
      scheme: "urn",
      parse: function parse$$1(components, options) {
        var matches = components.path && components.path.match(URN_PARSE);
        var urnComponents = components;
        if (matches) {
          var scheme = options.scheme || urnComponents.scheme || "urn";
          var nid = matches[1].toLowerCase();
          var nss = matches[2];
          var urnScheme = scheme + ":" + (options.nid || nid);
          var schemeHandler = SCHEMES[urnScheme];
          urnComponents.nid = nid;
          urnComponents.nss = nss;
          urnComponents.path = void 0;
          if (schemeHandler) {
            urnComponents = schemeHandler.parse(urnComponents, options);
          }
        } else {
          urnComponents.error = urnComponents.error || "URN can not be parsed.";
        }
        return urnComponents;
      },
      serialize: function serialize$$1(urnComponents, options) {
        var scheme = options.scheme || urnComponents.scheme || "urn";
        var nid = urnComponents.nid;
        var urnScheme = scheme + ":" + (options.nid || nid);
        var schemeHandler = SCHEMES[urnScheme];
        if (schemeHandler) {
          urnComponents = schemeHandler.serialize(urnComponents, options);
        }
        var uriComponents = urnComponents;
        var nss = urnComponents.nss;
        uriComponents.path = (nid || options.nid) + ":" + nss;
        return uriComponents;
      }
    };
    var UUID2 = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
    var handler$6 = {
      scheme: "urn:uuid",
      parse: function parse3(urnComponents, options) {
        var uuidComponents = urnComponents;
        uuidComponents.uuid = uuidComponents.nss;
        uuidComponents.nss = void 0;
        if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID2))) {
          uuidComponents.error = uuidComponents.error || "UUID is not valid.";
        }
        return uuidComponents;
      },
      serialize: function serialize2(uuidComponents, options) {
        var urnComponents = uuidComponents;
        urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
        return urnComponents;
      }
    };
    SCHEMES[handler.scheme] = handler;
    SCHEMES[handler$1.scheme] = handler$1;
    SCHEMES[handler$2.scheme] = handler$2;
    SCHEMES[handler$3.scheme] = handler$3;
    SCHEMES[handler$4.scheme] = handler$4;
    SCHEMES[handler$5.scheme] = handler$5;
    SCHEMES[handler$6.scheme] = handler$6;
    exports3.SCHEMES = SCHEMES;
    exports3.pctEncChar = pctEncChar;
    exports3.pctDecChars = pctDecChars;
    exports3.parse = parse2;
    exports3.removeDotSegments = removeDotSegments;
    exports3.serialize = serialize;
    exports3.resolveComponents = resolveComponents;
    exports3.resolve = resolve2;
    exports3.normalize = normalize;
    exports3.equal = equal3;
    exports3.escapeComponent = escapeComponent;
    exports3.unescapeComponent = unescapeComponent;
    Object.defineProperty(exports3, "__esModule", { value: true });
  });
})(uri_all, uri_all.exports);
var fastDeepEqual = function equal(a, b) {
  if (a === b)
    return true;
  if (a && b && typeof a == "object" && typeof b == "object") {
    if (a.constructor !== b.constructor)
      return false;
    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length)
        return false;
      for (i = length; i-- !== 0; )
        if (!equal(a[i], b[i]))
          return false;
      return true;
    }
    if (a.constructor === RegExp)
      return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf)
      return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString)
      return a.toString() === b.toString();
    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length)
      return false;
    for (i = length; i-- !== 0; )
      if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
        return false;
    for (i = length; i-- !== 0; ) {
      var key = keys[i];
      if (!equal(a[key], b[key]))
        return false;
    }
    return true;
  }
  return a !== a && b !== b;
};
var ucs2length$1 = function ucs2length(str) {
  var length = 0, len = str.length, pos = 0, value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 55296 && value <= 56319 && pos < len) {
      value = str.charCodeAt(pos);
      if ((value & 64512) == 56320)
        pos++;
    }
  }
  return length;
};
var util$5 = {
  copy: gosling_es_copy,
  checkDataType,
  checkDataTypes,
  coerceToTypes,
  toHash: toHash$1,
  getProperty,
  escapeQuotes,
  equal: fastDeepEqual,
  ucs2length: ucs2length$1,
  varOccurences,
  varReplace,
  schemaHasRules,
  schemaHasRulesExcept,
  schemaUnknownRules,
  toQuotedString,
  getPathExpr,
  getPath,
  getData,
  unescapeFragment,
  unescapeJsonPointer,
  escapeFragment,
  escapeJsonPointer
};
function gosling_es_copy(o, to) {
  to = to || {};
  for (var key in o)
    to[key] = o[key];
  return to;
}
function checkDataType(dataType, data2, strictNumbers, negate2) {
  var EQUAL = negate2 ? " !== " : " === ", AND = negate2 ? " || " : " && ", OK = negate2 ? "!" : "", NOT = negate2 ? "" : "!";
  switch (dataType) {
    case "null":
      return data2 + EQUAL + "null";
    case "array":
      return OK + "Array.isArray(" + data2 + ")";
    case "object":
      return "(" + OK + data2 + AND + "typeof " + data2 + EQUAL + '"object"' + AND + NOT + "Array.isArray(" + data2 + "))";
    case "integer":
      return "(typeof " + data2 + EQUAL + '"number"' + AND + NOT + "(" + data2 + " % 1)" + AND + data2 + EQUAL + data2 + (strictNumbers ? AND + OK + "isFinite(" + data2 + ")" : "") + ")";
    case "number":
      return "(typeof " + data2 + EQUAL + '"' + dataType + '"' + (strictNumbers ? AND + OK + "isFinite(" + data2 + ")" : "") + ")";
    default:
      return "typeof " + data2 + EQUAL + '"' + dataType + '"';
  }
}
function checkDataTypes(dataTypes, data2, strictNumbers) {
  switch (dataTypes.length) {
    case 1:
      return checkDataType(dataTypes[0], data2, strictNumbers, true);
    default:
      var code = "";
      var types2 = toHash$1(dataTypes);
      if (types2.array && types2.object) {
        code = types2.null ? "(" : "(!" + data2 + " || ";
        code += "typeof " + data2 + ' !== "object")';
        delete types2.null;
        delete types2.array;
        delete types2.object;
      }
      if (types2.number)
        delete types2.integer;
      for (var t in types2)
        code += (code ? " && " : "") + checkDataType(t, data2, strictNumbers, true);
      return code;
  }
}
var COERCE_TO_TYPES = toHash$1(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
  if (Array.isArray(dataTypes)) {
    var types2 = [];
    for (var i = 0; i < dataTypes.length; i++) {
      var t = dataTypes[i];
      if (COERCE_TO_TYPES[t])
        types2[types2.length] = t;
      else if (optionCoerceTypes === "array" && t === "array")
        types2[types2.length] = t;
    }
    if (types2.length)
      return types2;
  } else if (COERCE_TO_TYPES[dataTypes]) {
    return [dataTypes];
  } else if (optionCoerceTypes === "array" && dataTypes === "array") {
    return ["array"];
  }
}
function toHash$1(arr) {
  var hash = {};
  for (var i = 0; i < arr.length; i++)
    hash[arr[i]] = true;
  return hash;
}
var IDENTIFIER$1 = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
  return typeof key == "number" ? "[" + key + "]" : IDENTIFIER$1.test(key) ? "." + key : "['" + escapeQuotes(key) + "']";
}
function escapeQuotes(str) {
  return str.replace(SINGLE_QUOTE, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\f/g, "\\f").replace(/\t/g, "\\t");
}
function varOccurences(str, dataVar) {
  dataVar += "[^0-9]";
  var matches = str.match(new RegExp(dataVar, "g"));
  return matches ? matches.length : 0;
}
function varReplace(str, dataVar, expr) {
  dataVar += "([^0-9])";
  expr = expr.replace(/\$/g, "$$$$");
  return str.replace(new RegExp(dataVar, "g"), expr + "$1");
}
function schemaHasRules(schema, rules3) {
  if (typeof schema == "boolean")
    return !schema;
  for (var key in schema)
    if (rules3[key])
      return true;
}
function schemaHasRulesExcept(schema, rules3, exceptKeyword) {
  if (typeof schema == "boolean")
    return !schema && exceptKeyword != "not";
  for (var key in schema)
    if (key != exceptKeyword && rules3[key])
      return true;
}
function schemaUnknownRules(schema, rules3) {
  if (typeof schema == "boolean")
    return;
  for (var key in schema)
    if (!rules3[key])
      return key;
}
function toQuotedString(str) {
  return "'" + escapeQuotes(str) + "'";
}
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  var path = jsonPointers ? "'/' + " + expr + (isNumber ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
  return joinPaths(currentPath, path);
}
function getPath(currentPath, prop, jsonPointers) {
  var path = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
  return joinPaths(currentPath, path);
}
var JSON_POINTER$1 = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER$1 = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
  var up, jsonPointer, data2, matches;
  if ($data === "")
    return "rootData";
  if ($data[0] == "/") {
    if (!JSON_POINTER$1.test($data))
      throw new Error("Invalid JSON-pointer: " + $data);
    jsonPointer = $data;
    data2 = "rootData";
  } else {
    matches = $data.match(RELATIVE_JSON_POINTER$1);
    if (!matches)
      throw new Error("Invalid JSON-pointer: " + $data);
    up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer == "#") {
      if (up >= lvl)
        throw new Error("Cannot access property/index " + up + " levels up, current level is " + lvl);
      return paths[lvl - up];
    }
    if (up > lvl)
      throw new Error("Cannot access data " + up + " levels up, current level is " + lvl);
    data2 = "data" + (lvl - up || "");
    if (!jsonPointer)
      return data2;
  }
  var expr = data2;
  var segments = jsonPointer.split("/");
  for (var i = 0; i < segments.length; i++) {
    var segment = segments[i];
    if (segment) {
      data2 += getProperty(unescapeJsonPointer(segment));
      expr += " && " + data2;
    }
  }
  return expr;
}
function joinPaths(a, b) {
  if (a == '""')
    return b;
  return (a + " + " + b).replace(/([^\\])' \+ '/g, "$1");
}
function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}
function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}
function escapeJsonPointer(str) {
  return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
function unescapeJsonPointer(str) {
  return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
var util$4 = util$5;
var schema_obj = SchemaObject$2;
function SchemaObject$2(obj) {
  util$4.copy(obj, this);
}
var jsonSchemaTraverse = { exports: {} };
var traverse$1 = jsonSchemaTraverse.exports = function(schema, opts, cb) {
  if (typeof opts == "function") {
    cb = opts;
    opts = {};
  }
  cb = opts.cb || cb;
  var pre = typeof cb == "function" ? cb : cb.pre || function() {
  };
  var post = cb.post || function() {
  };
  _traverse(opts, pre, post, schema, "", schema);
};
traverse$1.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true
};
traverse$1.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};
traverse$1.propsKeywords = {
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};
traverse$1.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == "object" && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse$1.arrayKeywords) {
          for (var i = 0; i < sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse$1.propsKeywords) {
        if (sch && typeof sch == "object") {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse$1.keywords || opts.allKeys && !(key in traverse$1.skipKeywords)) {
        _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}
function escapeJsonPtr(str) {
  return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
var URI$1 = uri_all.exports, equal$1 = fastDeepEqual, util$3 = util$5, SchemaObject$1 = schema_obj, traverse = jsonSchemaTraverse.exports;
var resolve_1 = resolve$3;
resolve$3.normalizeId = normalizeId;
resolve$3.fullPath = getFullPath;
resolve$3.url = resolveUrl;
resolve$3.ids = resolveIds;
resolve$3.inlineRef = inlineRef;
resolve$3.schema = resolveSchema;
function resolve$3(compile2, root, ref2) {
  var refVal = this._refs[ref2];
  if (typeof refVal == "string") {
    if (this._refs[refVal])
      refVal = this._refs[refVal];
    else
      return resolve$3.call(this, compile2, root, refVal);
  }
  refVal = refVal || this._schemas[ref2];
  if (refVal instanceof SchemaObject$1) {
    return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal);
  }
  var res = resolveSchema.call(this, root, ref2);
  var schema, v, baseId;
  if (res) {
    schema = res.schema;
    root = res.root;
    baseId = res.baseId;
  }
  if (schema instanceof SchemaObject$1) {
    v = schema.validate || compile2.call(this, schema.schema, root, void 0, baseId);
  } else if (schema !== void 0) {
    v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile2.call(this, schema, root, void 0, baseId);
  }
  return v;
}
function resolveSchema(root, ref2) {
  var p = URI$1.parse(ref2), refPath = _getFullPath(p), baseId = getFullPath(this._getId(root.schema));
  if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == "string") {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject$1) {
      if (!refVal.validate)
        this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject$1) {
        if (!refVal.validate)
          this._compile(refVal);
        if (id == normalizeId(ref2))
          return { schema: refVal, root, baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema)
      return;
    baseId = getFullPath(this._getId(root.schema));
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}
function resolveRecursive(root, ref2, parsedRef) {
  var res = resolveSchema.call(this, root, ref2);
  if (res) {
    var schema = res.schema;
    var baseId = res.baseId;
    root = res.root;
    var id = this._getId(schema);
    if (id)
      baseId = resolveUrl(baseId, id);
    return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  }
}
var PREVENT_SCOPE_CHANGE = util$3.toHash(["properties", "patternProperties", "enum", "dependencies", "definitions"]);
function getJsonPointer(parsedRef, baseId, schema, root) {
  parsedRef.fragment = parsedRef.fragment || "";
  if (parsedRef.fragment.slice(0, 1) != "/")
    return;
  var parts = parsedRef.fragment.split("/");
  for (var i = 1; i < parts.length; i++) {
    var part = parts[i];
    if (part) {
      part = util$3.unescapeFragment(part);
      schema = schema[part];
      if (schema === void 0)
        break;
      var id;
      if (!PREVENT_SCOPE_CHANGE[part]) {
        id = this._getId(schema);
        if (id)
          baseId = resolveUrl(baseId, id);
        if (schema.$ref) {
          var $ref2 = resolveUrl(baseId, schema.$ref);
          var res = resolveSchema.call(this, root, $ref2);
          if (res) {
            schema = res.schema;
            root = res.root;
            baseId = res.baseId;
          }
        }
      }
    }
  }
  if (schema !== void 0 && schema !== root.schema)
    return { schema, root, baseId };
}
var SIMPLE_INLINED = util$3.toHash([
  "type",
  "format",
  "pattern",
  "maxLength",
  "minLength",
  "maxProperties",
  "minProperties",
  "maxItems",
  "minItems",
  "maximum",
  "minimum",
  "uniqueItems",
  "multipleOf",
  "required",
  "enum"
]);
function inlineRef(schema, limit) {
  if (limit === false)
    return false;
  if (limit === void 0 || limit === true)
    return checkNoRef(schema);
  else if (limit)
    return countKeys(schema) <= limit;
}
function checkNoRef(schema) {
  var item;
  if (Array.isArray(schema)) {
    for (var i = 0; i < schema.length; i++) {
      item = schema[i];
      if (typeof item == "object" && !checkNoRef(item))
        return false;
    }
  } else {
    for (var key in schema) {
      if (key == "$ref")
        return false;
      item = schema[key];
      if (typeof item == "object" && !checkNoRef(item))
        return false;
    }
  }
  return true;
}
function countKeys(schema) {
  var count2 = 0, item;
  if (Array.isArray(schema)) {
    for (var i = 0; i < schema.length; i++) {
      item = schema[i];
      if (typeof item == "object")
        count2 += countKeys(item);
      if (count2 == Infinity)
        return Infinity;
    }
  } else {
    for (var key in schema) {
      if (key == "$ref")
        return Infinity;
      if (SIMPLE_INLINED[key]) {
        count2++;
      } else {
        item = schema[key];
        if (typeof item == "object")
          count2 += countKeys(item) + 1;
        if (count2 == Infinity)
          return Infinity;
      }
    }
  }
  return count2;
}
function getFullPath(id, normalize) {
  if (normalize !== false)
    id = normalizeId(id);
  var p = URI$1.parse(id);
  return _getFullPath(p);
}
function _getFullPath(p) {
  return URI$1.serialize(p).split("#")[0] + "#";
}
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
  return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
function resolveUrl(baseId, id) {
  id = normalizeId(id);
  return URI$1.resolve(baseId, id);
}
function resolveIds(schema) {
  var schemaId = normalizeId(this._getId(schema));
  var baseIds = { "": schemaId };
  var fullPaths = { "": getFullPath(schemaId, false) };
  var localRefs = {};
  var self2 = this;
  traverse(schema, { allKeys: true }, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
    if (jsonPtr === "")
      return;
    var id = self2._getId(sch);
    var baseId = baseIds[parentJsonPtr];
    var fullPath = fullPaths[parentJsonPtr] + "/" + parentKeyword;
    if (keyIndex !== void 0)
      fullPath += "/" + (typeof keyIndex == "number" ? keyIndex : util$3.escapeFragment(keyIndex));
    if (typeof id == "string") {
      id = baseId = normalizeId(baseId ? URI$1.resolve(baseId, id) : id);
      var refVal = self2._refs[id];
      if (typeof refVal == "string")
        refVal = self2._refs[refVal];
      if (refVal && refVal.schema) {
        if (!equal$1(sch, refVal.schema))
          throw new Error('id "' + id + '" resolves to more than one schema');
      } else if (id != normalizeId(fullPath)) {
        if (id[0] == "#") {
          if (localRefs[id] && !equal$1(sch, localRefs[id]))
            throw new Error('id "' + id + '" resolves to more than one schema');
          localRefs[id] = sch;
        } else {
          self2._refs[id] = fullPath;
        }
      }
    }
    baseIds[jsonPtr] = baseId;
    fullPaths[jsonPtr] = fullPath;
  });
  return localRefs;
}
var resolve$2 = resolve_1;
var error_classes = {
  Validation: errorSubclass(ValidationError$1),
  MissingRef: errorSubclass(MissingRefError$1)
};
function ValidationError$1(errors) {
  this.message = "validation failed";
  this.errors = errors;
  this.ajv = this.validation = true;
}
MissingRefError$1.message = function(baseId, ref2) {
  return "can't resolve reference " + ref2 + " from id " + baseId;
};
function MissingRefError$1(baseId, ref2, message) {
  this.message = message || MissingRefError$1.message(baseId, ref2);
  this.missingRef = resolve$2.url(baseId, ref2);
  this.missingSchema = resolve$2.normalizeId(resolve$2.fullPath(this.missingRef));
}
function errorSubclass(Subclass) {
  Subclass.prototype = Object.create(Error.prototype);
  Subclass.prototype.constructor = Subclass;
  return Subclass;
}
var fastJsonStableStringify = function(data2, opts) {
  if (!opts)
    opts = {};
  if (typeof opts === "function")
    opts = { cmp: opts };
  var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false;
  var cmp = opts.cmp && function(f2) {
    return function(node) {
      return function(a, b) {
        var aobj = { key: a, value: node[a] };
        var bobj = { key: b, value: node[b] };
        return f2(aobj, bobj);
      };
    };
  }(opts.cmp);
  var seen = [];
  return function stringify2(node) {
    if (node && node.toJSON && typeof node.toJSON === "function") {
      node = node.toJSON();
    }
    if (node === void 0)
      return;
    if (typeof node == "number")
      return isFinite(node) ? "" + node : "null";
    if (typeof node !== "object")
      return JSON.stringify(node);
    var i, out;
    if (Array.isArray(node)) {
      out = "[";
      for (i = 0; i < node.length; i++) {
        if (i)
          out += ",";
        out += stringify2(node[i]) || "null";
      }
      return out + "]";
    }
    if (node === null)
      return "null";
    if (seen.indexOf(node) !== -1) {
      if (cycles)
        return JSON.stringify("__cycle__");
      throw new TypeError("Converting circular structure to JSON");
    }
    var seenIndex = seen.push(node) - 1;
    var keys = Object.keys(node).sort(cmp && cmp(node));
    out = "";
    for (i = 0; i < keys.length; i++) {
      var key = keys[i];
      var value = stringify2(node[key]);
      if (!value)
        continue;
      if (out)
        out += ",";
      out += JSON.stringify(key) + ":" + value;
    }
    seen.splice(seenIndex, 1);
    return "{" + out + "}";
  }(data2);
};
var validate$1 = function generate_validate(it, $keyword, $ruleType) {
  var out = "";
  var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, "$ref"), $id2 = it.self._getId(it.schema);
  if (it.opts.strictKeywords) {
    var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
    if ($unknownKwd) {
      var $keywordsMsg = "unknown keyword: " + $unknownKwd;
      if (it.opts.strictKeywords === "log")
        it.logger.warn($keywordsMsg);
      else
        throw new Error($keywordsMsg);
    }
  }
  if (it.isTop) {
    out += " var validate = ";
    if ($async) {
      it.async = true;
      out += "async ";
    }
    out += "function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";
    if ($id2 && (it.opts.sourceCode || it.opts.processCode)) {
      out += " " + ("/*# sourceURL=" + $id2 + " */") + " ";
    }
  }
  if (typeof it.schema == "boolean" || !($refKeywords || it.schema.$ref)) {
    var $keyword = "false schema";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    if (it.schema === false) {
      if (it.isTop) {
        $breakOnError = true;
      } else {
        out += " var " + $valid + " = false; ";
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "false schema") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it.opts.messages !== false) {
          out += " , message: 'boolean schema is false' ";
        }
        if (it.opts.verbose) {
          out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
    } else {
      if (it.isTop) {
        if ($async) {
          out += " return data; ";
        } else {
          out += " validate.errors = null; return true; ";
        }
      } else {
        out += " var " + $valid + " = true; ";
      }
    }
    if (it.isTop) {
      out += " }; return validate; ";
    }
    return out;
  }
  if (it.isTop) {
    var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = "data";
    it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
    it.baseId = it.baseId || it.rootId;
    delete it.isTop;
    it.dataPathArr = [""];
    if (it.schema.default !== void 0 && it.opts.useDefaults && it.opts.strictDefaults) {
      var $defaultMsg = "default is ignored in the schema root";
      if (it.opts.strictDefaults === "log")
        it.logger.warn($defaultMsg);
      else
        throw new Error($defaultMsg);
    }
    out += " var vErrors = null; ";
    out += " var errors = 0;     ";
    out += " if (rootData === undefined) rootData = data; ";
  } else {
    var $lvl = it.level, $dataLvl = it.dataLevel, $data = "data" + ($dataLvl || "");
    if ($id2)
      it.baseId = it.resolve.url(it.baseId, $id2);
    if ($async && !it.async)
      throw new Error("async schema in sync schema");
    out += " var errs_" + $lvl + " = errors;";
  }
  var $valid = "valid" + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = "", $closingBraces2 = "";
  var $errorKeyword;
  var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema);
  if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
    if ($typeIsArray) {
      if ($typeSchema.indexOf("null") == -1)
        $typeSchema = $typeSchema.concat("null");
    } else if ($typeSchema != "null") {
      $typeSchema = [$typeSchema, "null"];
      $typeIsArray = true;
    }
  }
  if ($typeIsArray && $typeSchema.length == 1) {
    $typeSchema = $typeSchema[0];
    $typeIsArray = false;
  }
  if (it.schema.$ref && $refKeywords) {
    if (it.opts.extendRefs == "fail") {
      throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
    } else if (it.opts.extendRefs !== true) {
      $refKeywords = false;
      it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    }
  }
  if (it.schema.$comment && it.opts.$comment) {
    out += " " + it.RULES.all.$comment.code(it, "$comment");
  }
  if ($typeSchema) {
    if (it.opts.coerceTypes) {
      var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
    }
    var $rulesGroup = it.RULES.types[$typeSchema];
    if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
      var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type";
      var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type", $method = $typeIsArray ? "checkDataTypes" : "checkDataType";
      out += " if (" + it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) + ") { ";
      if ($coerceToTypes) {
        var $dataType = "dataType" + $lvl, $coerced = "coerced" + $lvl;
        out += " var " + $dataType + " = typeof " + $data + "; var " + $coerced + " = undefined; ";
        if (it.opts.coerceTypes == "array") {
          out += " if (" + $dataType + " == 'object' && Array.isArray(" + $data + ") && " + $data + ".length == 1) { " + $data + " = " + $data + "[0]; " + $dataType + " = typeof " + $data + "; if (" + it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers) + ") " + $coerced + " = " + $data + "; } ";
        }
        out += " if (" + $coerced + " !== undefined) ; ";
        var arr1 = $coerceToTypes;
        if (arr1) {
          var $type, $i = -1, l1 = arr1.length - 1;
          while ($i < l1) {
            $type = arr1[$i += 1];
            if ($type == "string") {
              out += " else if (" + $dataType + " == 'number' || " + $dataType + " == 'boolean') " + $coerced + " = '' + " + $data + "; else if (" + $data + " === null) " + $coerced + " = ''; ";
            } else if ($type == "number" || $type == "integer") {
              out += " else if (" + $dataType + " == 'boolean' || " + $data + " === null || (" + $dataType + " == 'string' && " + $data + " && " + $data + " == +" + $data + " ";
              if ($type == "integer") {
                out += " && !(" + $data + " % 1)";
              }
              out += ")) " + $coerced + " = +" + $data + "; ";
            } else if ($type == "boolean") {
              out += " else if (" + $data + " === 'false' || " + $data + " === 0 || " + $data + " === null) " + $coerced + " = false; else if (" + $data + " === 'true' || " + $data + " === 1) " + $coerced + " = true; ";
            } else if ($type == "null") {
              out += " else if (" + $data + " === '' || " + $data + " === 0 || " + $data + " === false) " + $coerced + " = null; ";
            } else if (it.opts.coerceTypes == "array" && $type == "array") {
              out += " else if (" + $dataType + " == 'string' || " + $dataType + " == 'number' || " + $dataType + " == 'boolean' || " + $data + " == null) " + $coerced + " = [" + $data + "]; ";
            }
          }
        }
        out += " else {   ";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
          if ($typeIsArray) {
            out += "" + $typeSchema.join(",");
          } else {
            out += "" + $typeSchema;
          }
          out += "' } ";
          if (it.opts.messages !== false) {
            out += " , message: 'should be ";
            if ($typeIsArray) {
              out += "" + $typeSchema.join(",");
            } else {
              out += "" + $typeSchema;
            }
            out += "' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } if (" + $coerced + " !== undefined) {  ";
        var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
        out += " " + $data + " = " + $coerced + "; ";
        if (!$dataLvl) {
          out += "if (" + $parentData + " !== undefined)";
        }
        out += " " + $parentData + "[" + $parentDataProperty + "] = " + $coerced + "; } ";
      } else {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
          if ($typeIsArray) {
            out += "" + $typeSchema.join(",");
          } else {
            out += "" + $typeSchema;
          }
          out += "' } ";
          if (it.opts.messages !== false) {
            out += " , message: 'should be ";
            if ($typeIsArray) {
              out += "" + $typeSchema.join(",");
            } else {
              out += "" + $typeSchema;
            }
            out += "' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
      }
      out += " } ";
    }
  }
  if (it.schema.$ref && !$refKeywords) {
    out += " " + it.RULES.all.$ref.code(it, "$ref") + " ";
    if ($breakOnError) {
      out += " } if (errors === ";
      if ($top) {
        out += "0";
      } else {
        out += "errs_" + $lvl;
      }
      out += ") { ";
      $closingBraces2 += "}";
    }
  } else {
    var arr2 = it.RULES;
    if (arr2) {
      var $rulesGroup, i2 = -1, l2 = arr2.length - 1;
      while (i2 < l2) {
        $rulesGroup = arr2[i2 += 1];
        if ($shouldUseGroup($rulesGroup)) {
          if ($rulesGroup.type) {
            out += " if (" + it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) + ") { ";
          }
          if (it.opts.useDefaults) {
            if ($rulesGroup.type == "object" && it.schema.properties) {
              var $schema2 = it.schema.properties, $schemaKeys = Object.keys($schema2);
              var arr3 = $schemaKeys;
              if (arr3) {
                var $propertyKey, i3 = -1, l3 = arr3.length - 1;
                while (i3 < l3) {
                  $propertyKey = arr3[i3 += 1];
                  var $sch = $schema2[$propertyKey];
                  if ($sch.default !== void 0) {
                    var $passData = $data + it.util.getProperty($propertyKey);
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = "default is ignored for: " + $passData;
                        if (it.opts.strictDefaults === "log")
                          it.logger.warn($defaultMsg);
                        else
                          throw new Error($defaultMsg);
                      }
                    } else {
                      out += " if (" + $passData + " === undefined ";
                      if (it.opts.useDefaults == "empty") {
                        out += " || " + $passData + " === null || " + $passData + " === '' ";
                      }
                      out += " ) " + $passData + " = ";
                      if (it.opts.useDefaults == "shared") {
                        out += " " + it.useDefault($sch.default) + " ";
                      } else {
                        out += " " + JSON.stringify($sch.default) + " ";
                      }
                      out += "; ";
                    }
                  }
                }
              }
            } else if ($rulesGroup.type == "array" && Array.isArray(it.schema.items)) {
              var arr4 = it.schema.items;
              if (arr4) {
                var $sch, $i = -1, l4 = arr4.length - 1;
                while ($i < l4) {
                  $sch = arr4[$i += 1];
                  if ($sch.default !== void 0) {
                    var $passData = $data + "[" + $i + "]";
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = "default is ignored for: " + $passData;
                        if (it.opts.strictDefaults === "log")
                          it.logger.warn($defaultMsg);
                        else
                          throw new Error($defaultMsg);
                      }
                    } else {
                      out += " if (" + $passData + " === undefined ";
                      if (it.opts.useDefaults == "empty") {
                        out += " || " + $passData + " === null || " + $passData + " === '' ";
                      }
                      out += " ) " + $passData + " = ";
                      if (it.opts.useDefaults == "shared") {
                        out += " " + it.useDefault($sch.default) + " ";
                      } else {
                        out += " " + JSON.stringify($sch.default) + " ";
                      }
                      out += "; ";
                    }
                  }
                }
              }
            }
          }
          var arr5 = $rulesGroup.rules;
          if (arr5) {
            var $rule, i5 = -1, l5 = arr5.length - 1;
            while (i5 < l5) {
              $rule = arr5[i5 += 1];
              if ($shouldUseRule($rule)) {
                var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                if ($code) {
                  out += " " + $code + " ";
                  if ($breakOnError) {
                    $closingBraces1 += "}";
                  }
                }
              }
            }
          }
          if ($breakOnError) {
            out += " " + $closingBraces1 + " ";
            $closingBraces1 = "";
          }
          if ($rulesGroup.type) {
            out += " } ";
            if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
              out += " else { ";
              var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type";
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = "";
              if (it.createErrors !== false) {
                out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
                if ($typeIsArray) {
                  out += "" + $typeSchema.join(",");
                } else {
                  out += "" + $typeSchema;
                }
                out += "' } ";
                if (it.opts.messages !== false) {
                  out += " , message: 'should be ";
                  if ($typeIsArray) {
                    out += "" + $typeSchema.join(",");
                  } else {
                    out += "" + $typeSchema;
                  }
                  out += "' ";
                }
                if (it.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                if (it.async) {
                  out += " throw new ValidationError([" + __err + "]); ";
                } else {
                  out += " validate.errors = [" + __err + "]; return false; ";
                }
              } else {
                out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
              }
              out += " } ";
            }
          }
          if ($breakOnError) {
            out += " if (errors === ";
            if ($top) {
              out += "0";
            } else {
              out += "errs_" + $lvl;
            }
            out += ") { ";
            $closingBraces2 += "}";
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += " " + $closingBraces2 + " ";
  }
  if ($top) {
    if ($async) {
      out += " if (errors === 0) return data;           ";
      out += " else throw new ValidationError(vErrors); ";
    } else {
      out += " validate.errors = vErrors; ";
      out += " return errors === 0;       ";
    }
    out += " }; return validate;";
  } else {
    out += " var " + $valid + " = errors === errs_" + $lvl + ";";
  }
  function $shouldUseGroup($rulesGroup2) {
    var rules3 = $rulesGroup2.rules;
    for (var i = 0; i < rules3.length; i++)
      if ($shouldUseRule(rules3[i]))
        return true;
  }
  function $shouldUseRule($rule2) {
    return it.schema[$rule2.keyword] !== void 0 || $rule2.implements && $ruleImplementsSomeKeyword($rule2);
  }
  function $ruleImplementsSomeKeyword($rule2) {
    var impl = $rule2.implements;
    for (var i = 0; i < impl.length; i++)
      if (it.schema[impl[i]] !== void 0)
        return true;
  }
  return out;
};
var resolve$1 = resolve_1, util$2 = util$5, errorClasses$1 = error_classes, stableStringify$1 = fastJsonStableStringify;
var validateGenerator = validate$1;
var ucs2length2 = util$2.ucs2length;
var equal2 = fastDeepEqual;
var ValidationError = errorClasses$1.Validation;
var compile_1 = compile$2;
function compile$2(schema, root, localRefs, baseId) {
  var self2 = this, opts = this._opts, refVal = [void 0], refs = {}, patterns = [], patternsHash = {}, defaults = [], defaultsHash = {}, customRules = [];
  root = root || { schema, refVal, refs };
  var c = checkCompiling.call(this, schema, root, baseId);
  var compilation = this._compilations[c.index];
  if (c.compiling)
    return compilation.callValidate = callValidate;
  var formats2 = this._formats;
  var RULES = this.RULES;
  try {
    var v = localCompile(schema, root, localRefs, baseId);
    compilation.validate = v;
    var cv = compilation.callValidate;
    if (cv) {
      cv.schema = v.schema;
      cv.errors = null;
      cv.refs = v.refs;
      cv.refVal = v.refVal;
      cv.root = v.root;
      cv.$async = v.$async;
      if (opts.sourceCode)
        cv.source = v.source;
    }
    return v;
  } finally {
    endCompiling.call(this, schema, root, baseId);
  }
  function callValidate() {
    var validate2 = compilation.validate;
    var result = validate2.apply(this, arguments);
    callValidate.errors = validate2.errors;
    return result;
  }
  function localCompile(_schema, _root, localRefs2, baseId2) {
    var isRoot = !_root || _root && _root.schema == _schema;
    if (_root.schema != root.schema)
      return compile$2.call(self2, _schema, _root, localRefs2, baseId2);
    var $async = _schema.$async === true;
    var sourceCode = validateGenerator({
      isTop: true,
      schema: _schema,
      isRoot,
      baseId: baseId2,
      root: _root,
      schemaPath: "",
      errSchemaPath: "#",
      errorPath: '""',
      MissingRefError: errorClasses$1.MissingRef,
      RULES,
      validate: validateGenerator,
      util: util$2,
      resolve: resolve$1,
      resolveRef,
      usePattern,
      useDefault,
      useCustomRule,
      opts,
      formats: formats2,
      logger: self2.logger,
      self: self2
    });
    sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode$1) + sourceCode;
    if (opts.processCode)
      sourceCode = opts.processCode(sourceCode, _schema);
    var validate2;
    try {
      var makeValidate = new Function("self", "RULES", "formats", "root", "refVal", "defaults", "customRules", "equal", "ucs2length", "ValidationError", sourceCode);
      validate2 = makeValidate(self2, RULES, formats2, root, refVal, defaults, customRules, equal2, ucs2length2, ValidationError);
      refVal[0] = validate2;
    } catch (e) {
      self2.logger.error("Error compiling schema, function code:", sourceCode);
      throw e;
    }
    validate2.schema = _schema;
    validate2.errors = null;
    validate2.refs = refs;
    validate2.refVal = refVal;
    validate2.root = isRoot ? validate2 : _root;
    if ($async)
      validate2.$async = true;
    if (opts.sourceCode === true) {
      validate2.source = {
        code: sourceCode,
        patterns,
        defaults
      };
    }
    return validate2;
  }
  function resolveRef(baseId2, ref2, isRoot) {
    ref2 = resolve$1.url(baseId2, ref2);
    var refIndex = refs[ref2];
    var _refVal, refCode;
    if (refIndex !== void 0) {
      _refVal = refVal[refIndex];
      refCode = "refVal[" + refIndex + "]";
      return resolvedRef(_refVal, refCode);
    }
    if (!isRoot && root.refs) {
      var rootRefId = root.refs[ref2];
      if (rootRefId !== void 0) {
        _refVal = root.refVal[rootRefId];
        refCode = addLocalRef(ref2, _refVal);
        return resolvedRef(_refVal, refCode);
      }
    }
    refCode = addLocalRef(ref2);
    var v2 = resolve$1.call(self2, localCompile, root, ref2);
    if (v2 === void 0) {
      var localSchema = localRefs && localRefs[ref2];
      if (localSchema) {
        v2 = resolve$1.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile$2.call(self2, localSchema, root, localRefs, baseId2);
      }
    }
    if (v2 === void 0) {
      removeLocalRef(ref2);
    } else {
      replaceLocalRef(ref2, v2);
      return resolvedRef(v2, refCode);
    }
  }
  function addLocalRef(ref2, v2) {
    var refId = refVal.length;
    refVal[refId] = v2;
    refs[ref2] = refId;
    return "refVal" + refId;
  }
  function removeLocalRef(ref2) {
    delete refs[ref2];
  }
  function replaceLocalRef(ref2, v2) {
    var refId = refs[ref2];
    refVal[refId] = v2;
  }
  function resolvedRef(refVal2, code) {
    return typeof refVal2 == "object" || typeof refVal2 == "boolean" ? { code, schema: refVal2, inline: true } : { code, $async: refVal2 && !!refVal2.$async };
  }
  function usePattern(regexStr) {
    var index = patternsHash[regexStr];
    if (index === void 0) {
      index = patternsHash[regexStr] = patterns.length;
      patterns[index] = regexStr;
    }
    return "pattern" + index;
  }
  function useDefault(value) {
    switch (typeof value) {
      case "boolean":
      case "number":
        return "" + value;
      case "string":
        return util$2.toQuotedString(value);
      case "object":
        if (value === null)
          return "null";
        var valueStr = stableStringify$1(value);
        var index = defaultsHash[valueStr];
        if (index === void 0) {
          index = defaultsHash[valueStr] = defaults.length;
          defaults[index] = value;
        }
        return "default" + index;
    }
  }
  function useCustomRule(rule, schema2, parentSchema, it) {
    if (self2._opts.validateSchema !== false) {
      var deps = rule.definition.dependencies;
      if (deps && !deps.every(function(keyword2) {
        return Object.prototype.hasOwnProperty.call(parentSchema, keyword2);
      }))
        throw new Error("parent schema must have all required keywords: " + deps.join(","));
      var validateSchema2 = rule.definition.validateSchema;
      if (validateSchema2) {
        var valid = validateSchema2(schema2);
        if (!valid) {
          var message = "keyword schema is invalid: " + self2.errorsText(validateSchema2.errors);
          if (self2._opts.validateSchema == "log")
            self2.logger.error(message);
          else
            throw new Error(message);
        }
      }
    }
    var compile2 = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro;
    var validate2;
    if (compile2) {
      validate2 = compile2.call(self2, schema2, parentSchema, it);
    } else if (macro) {
      validate2 = macro.call(self2, schema2, parentSchema, it);
      if (opts.validateSchema !== false)
        self2.validateSchema(validate2, true);
    } else if (inline) {
      validate2 = inline.call(self2, it, rule.keyword, schema2, parentSchema);
    } else {
      validate2 = rule.definition.validate;
      if (!validate2)
        return;
    }
    if (validate2 === void 0)
      throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
    var index = customRules.length;
    customRules[index] = validate2;
    return {
      code: "customRule" + index,
      validate: validate2
    };
  }
}
function checkCompiling(schema, root, baseId) {
  var index = compIndex.call(this, schema, root, baseId);
  if (index >= 0)
    return { index, compiling: true };
  index = this._compilations.length;
  this._compilations[index] = {
    schema,
    root,
    baseId
  };
  return { index, compiling: false };
}
function endCompiling(schema, root, baseId) {
  var i = compIndex.call(this, schema, root, baseId);
  if (i >= 0)
    this._compilations.splice(i, 1);
}
function compIndex(schema, root, baseId) {
  for (var i = 0; i < this._compilations.length; i++) {
    var c = this._compilations[i];
    if (c.schema == schema && c.root == root && c.baseId == baseId)
      return i;
  }
  return -1;
}
function patternCode(i, patterns) {
  return "var pattern" + i + " = new RegExp(" + util$2.toQuotedString(patterns[i]) + ");";
}
function defaultCode(i) {
  return "var default" + i + " = defaults[" + i + "];";
}
function refValCode(i, refVal) {
  return refVal[i] === void 0 ? "" : "var refVal" + i + " = refVal[" + i + "];";
}
function customRuleCode$1(i) {
  return "var customRule" + i + " = customRules[" + i + "];";
}
function vars(arr, statement) {
  if (!arr.length)
    return "";
  var code = "";
  for (var i = 0; i < arr.length; i++)
    code += statement(i, arr);
  return code;
}
var cache = { exports: {} };
var Cache$1 = cache.exports = function Cache() {
  this._cache = {};
};
Cache$1.prototype.put = function Cache_put(key, value) {
  this._cache[key] = value;
};
Cache$1.prototype.get = function Cache_get(key) {
  return this._cache[key];
};
Cache$1.prototype.del = function Cache_del(key) {
  delete this._cache[key];
};
Cache$1.prototype.clear = function Cache_clear() {
  this._cache = {};
};
var util$1 = util$5;
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
var URL$1 = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
var formats_1 = formats$1;
function formats$1(mode) {
  mode = mode == "full" ? "full" : "fast";
  return util$1.copy(formats$1[mode]);
}
formats$1.fast = {
  date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
  "date-time": /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
  uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
  "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
  "uri-template": URITEMPLATE,
  url: URL$1,
  email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  hostname: HOSTNAME,
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex,
  uuid: UUID,
  "json-pointer": JSON_POINTER,
  "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
  "relative-json-pointer": RELATIVE_JSON_POINTER
};
formats$1.full = {
  date: gosling_es_date,
  time,
  "date-time": date_time,
  uri,
  "uri-reference": URIREF,
  "uri-template": URITEMPLATE,
  url: URL$1,
  email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  hostname: HOSTNAME,
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex,
  uuid: UUID,
  "json-pointer": JSON_POINTER,
  "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
  "relative-json-pointer": RELATIVE_JSON_POINTER
};
function isLeapYear(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function gosling_es_date(str) {
  var matches = str.match(DATE);
  if (!matches)
    return false;
  var year = +matches[1];
  var month = +matches[2];
  var day = +matches[3];
  return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}
function time(str, full) {
  var matches = str.match(TIME);
  if (!matches)
    return false;
  var hour = matches[1];
  var minute = matches[2];
  var second = matches[3];
  var timeZone = matches[5];
  return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone);
}
var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
  var dateTime = str.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && gosling_es_date(dateTime[0]) && time(dateTime[1], true);
}
var NOT_URI_FRAGMENT = /\/|:/;
function uri(str) {
  return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
  if (Z_ANCHOR.test(str))
    return false;
  try {
    new RegExp(str);
    return true;
  } catch (e) {
    return false;
  }
}
var ref = function generate_ref(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $async, $refCode;
  if ($schema2 == "#" || $schema2 == "#/") {
    if (it.isRoot) {
      $async = it.async;
      $refCode = "validate";
    } else {
      $async = it.root.schema.$async === true;
      $refCode = "root.refVal[0]";
    }
  } else {
    var $refVal = it.resolveRef(it.baseId, $schema2, it.isRoot);
    if ($refVal === void 0) {
      var $message = it.MissingRefError.message(it.baseId, $schema2);
      if (it.opts.missingRefs == "fail") {
        it.logger.error($message);
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { ref: '" + it.util.escapeQuotes($schema2) + "' } ";
          if (it.opts.messages !== false) {
            out += " , message: 'can\\'t resolve reference " + it.util.escapeQuotes($schema2) + "' ";
          }
          if (it.opts.verbose) {
            out += " , schema: " + it.util.toQuotedString($schema2) + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        if ($breakOnError) {
          out += " if (false) { ";
        }
      } else if (it.opts.missingRefs == "ignore") {
        it.logger.warn($message);
        if ($breakOnError) {
          out += " if (true) { ";
        }
      } else {
        throw new it.MissingRefError(it.baseId, $schema2, $message);
      }
    } else if ($refVal.inline) {
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = "valid" + $it.level;
      $it.schema = $refVal.schema;
      $it.schemaPath = "";
      $it.errSchemaPath = $schema2;
      var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
      out += " " + $code + " ";
      if ($breakOnError) {
        out += " if (" + $nextValid + ") { ";
      }
    } else {
      $async = $refVal.$async === true || it.async && $refVal.$async !== false;
      $refCode = $refVal.code;
    }
  }
  if ($refCode) {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.opts.passContext) {
      out += " " + $refCode + ".call(this, ";
    } else {
      out += " " + $refCode + "( ";
    }
    out += " " + $data + ", (dataPath || '')";
    if (it.errorPath != '""') {
      out += " + " + it.errorPath;
    }
    var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
    out += " , " + $parentData + " , " + $parentDataProperty + ", rootData)  ";
    var __callValidate = out;
    out = $$outStack.pop();
    if ($async) {
      if (!it.async)
        throw new Error("async schema referenced by sync schema");
      if ($breakOnError) {
        out += " var " + $valid + "; ";
      }
      out += " try { await " + __callValidate + "; ";
      if ($breakOnError) {
        out += " " + $valid + " = true; ";
      }
      out += " } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ";
      if ($breakOnError) {
        out += " " + $valid + " = false; ";
      }
      out += " } ";
      if ($breakOnError) {
        out += " if (" + $valid + ") { ";
      }
    } else {
      out += " if (!" + __callValidate + ") { if (vErrors === null) vErrors = " + $refCode + ".errors; else vErrors = vErrors.concat(" + $refCode + ".errors); errors = vErrors.length; } ";
      if ($breakOnError) {
        out += " else { ";
      }
    }
  }
  return out;
};
var allOf = function generate_allOf(it, $keyword, $ruleType) {
  var out = " ";
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $currentBaseId = $it.baseId, $allSchemasEmpty = true;
  var arr1 = $schema2;
  if (arr1) {
    var $sch, $i = -1, l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
        $allSchemasEmpty = false;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + "[" + $i + "]";
        $it.errSchemaPath = $errSchemaPath + "/" + $i;
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
          $closingBraces += "}";
        }
      }
    }
  }
  if ($breakOnError) {
    if ($allSchemasEmpty) {
      out += " if (true) { ";
    } else {
      out += " " + $closingBraces.slice(0, -1) + " ";
    }
  }
  return out;
};
var anyOf = function generate_anyOf(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $noEmptySchema = $schema2.every(function($sch2) {
    return it.opts.strictKeywords ? typeof $sch2 == "object" && Object.keys($sch2).length > 0 || $sch2 === false : it.util.schemaHasRules($sch2, it.RULES.all);
  });
  if ($noEmptySchema) {
    var $currentBaseId = $it.baseId;
    out += " var " + $errs + " = errors; var " + $valid + " = false;  ";
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema2;
    if (arr1) {
      var $sch, $i = -1, l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + "[" + $i + "]";
        $it.errSchemaPath = $errSchemaPath + "/" + $i;
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
        out += " " + $valid + " = " + $valid + " || " + $nextValid + "; if (!" + $valid + ") { ";
        $closingBraces += "}";
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += " " + $closingBraces + " if (!" + $valid + ") {   var err =   ";
    if (it.createErrors !== false) {
      out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
      if (it.opts.messages !== false) {
        out += " , message: 'should match some schema in anyOf' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError(vErrors); ";
      } else {
        out += " validate.errors = vErrors; return false; ";
      }
    }
    out += " } else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
    if (it.opts.allErrors) {
      out += " } ";
    }
  } else {
    if ($breakOnError) {
      out += " if (true) { ";
    }
  }
  return out;
};
var comment = function generate_comment(it, $keyword, $ruleType) {
  var out = " ";
  var $schema2 = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  !it.opts.allErrors;
  var $comment = it.util.toQuotedString($schema2);
  if (it.opts.$comment === true) {
    out += " console.log(" + $comment + ");";
  } else if (typeof it.opts.$comment == "function") {
    out += " self._opts.$comment(" + $comment + ", " + it.util.toQuotedString($errSchemaPath) + ", validate.root.schema);";
  }
  return out;
};
var _const = function generate_const(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $isData = it.opts.$data && $schema2 && $schema2.$data;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
  }
  if (!$isData) {
    out += " var schema" + $lvl + " = validate.schema" + $schemaPath + ";";
  }
  out += "var " + $valid + " = equal(" + $data + ", schema" + $lvl + "); if (!" + $valid + ") {   ";
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValue: schema" + $lvl + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should be equal to constant' ";
    }
    if (it.opts.verbose) {
      out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += " }";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var contains = function generate_contains(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all);
  out += "var " + $errs + " = errors;var " + $valid + ";";
  if ($nonEmptySchema) {
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.schema = $schema2;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += " var " + $nextValid + " = false; for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + "[" + $idx + "]";
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
    } else {
      out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
    }
    out += " if (" + $nextValid + ") break; }  ";
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += " " + $closingBraces + " if (!" + $nextValid + ") {";
  } else {
    out += " if (" + $data + ".length == 0) {";
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
    if (it.opts.messages !== false) {
      out += " , message: 'should contain a valid item' ";
    }
    if (it.opts.verbose) {
      out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += " } else { ";
  if ($nonEmptySchema) {
    out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
  }
  if (it.opts.allErrors) {
    out += " } ";
  }
  return out;
};
var dependencies = function generate_dependencies(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties;
  for ($property in $schema2) {
    if ($property == "__proto__")
      continue;
    var $sch = $schema2[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
  out += "var " + $errs + " = errors;";
  var $currentErrorPath = it.errorPath;
  out += "var missing" + $lvl + ";";
  for (var $property in $propertyDeps) {
    $deps = $propertyDeps[$property];
    if ($deps.length) {
      out += " if ( " + $data + it.util.getProperty($property) + " !== undefined ";
      if ($ownProperties) {
        out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') ";
      }
      if ($breakOnError) {
        out += " && ( ";
        var arr1 = $deps;
        if (arr1) {
          var $propertyKey, $i = -1, l1 = arr1.length - 1;
          while ($i < l1) {
            $propertyKey = arr1[$i += 1];
            if ($i) {
              out += " || ";
            }
            var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
            out += " ( ( " + $useData + " === undefined ";
            if ($ownProperties) {
              out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
            }
            out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
          }
        }
        out += ")) {  ";
        var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
          if (it.opts.messages !== false) {
            out += " , message: 'should have ";
            if ($deps.length == 1) {
              out += "property " + it.util.escapeQuotes($deps[0]);
            } else {
              out += "properties " + it.util.escapeQuotes($deps.join(", "));
            }
            out += " when property " + it.util.escapeQuotes($property) + " is present' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
      } else {
        out += " ) { ";
        var arr2 = $deps;
        if (arr2) {
          var $propertyKey, i2 = -1, l2 = arr2.length - 1;
          while (i2 < l2) {
            $propertyKey = arr2[i2 += 1];
            var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += " if ( " + $useData + " === undefined ";
            if ($ownProperties) {
              out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
            }
            out += ") {  var err =   ";
            if (it.createErrors !== false) {
              out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: 'should have ";
                if ($deps.length == 1) {
                  out += "property " + it.util.escapeQuotes($deps[0]);
                } else {
                  out += "properties " + it.util.escapeQuotes($deps.join(", "));
                }
                out += " when property " + it.util.escapeQuotes($property) + " is present' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
          }
        }
      }
      out += " }   ";
      if ($breakOnError) {
        $closingBraces += "}";
        out += " else { ";
      }
    }
  }
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
  for (var $property in $schemaDeps) {
    var $sch = $schemaDeps[$property];
    if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
      out += " " + $nextValid + " = true; if ( " + $data + it.util.getProperty($property) + " !== undefined ";
      if ($ownProperties) {
        out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') ";
      }
      out += ") { ";
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + it.util.getProperty($property);
      $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($property);
      out += "  " + it.validate($it) + " ";
      $it.baseId = $currentBaseId;
      out += " }  ";
      if ($breakOnError) {
        out += " if (" + $nextValid + ") { ";
        $closingBraces += "}";
      }
    }
  }
  if ($breakOnError) {
    out += "   " + $closingBraces + " if (" + $errs + " == errors) {";
  }
  return out;
};
var _enum = function generate_enum(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $isData = it.opts.$data && $schema2 && $schema2.$data;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
  }
  var $i = "i" + $lvl, $vSchema = "schema" + $lvl;
  if (!$isData) {
    out += " var " + $vSchema + " = validate.schema" + $schemaPath + ";";
  }
  out += "var " + $valid + ";";
  if ($isData) {
    out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {";
  }
  out += "" + $valid + " = false;for (var " + $i + "=0; " + $i + "<" + $vSchema + ".length; " + $i + "++) if (equal(" + $data + ", " + $vSchema + "[" + $i + "])) { " + $valid + " = true; break; }";
  if ($isData) {
    out += "  }  ";
  }
  out += " if (!" + $valid + ") {   ";
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValues: schema" + $lvl + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should be equal to one of the allowed values' ";
    }
    if (it.opts.verbose) {
      out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += " }";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var gosling_es_format = function generate_format(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  if (it.opts.format === false) {
    if ($breakOnError) {
      out += " if (true) { ";
    }
    return out;
  }
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats);
  if ($isData) {
    var $format = "format" + $lvl, $isObject = "isObject" + $lvl, $formatType = "formatType" + $lvl;
    out += " var " + $format + " = formats[" + $schemaValue + "]; var " + $isObject + " = typeof " + $format + " == 'object' && !(" + $format + " instanceof RegExp) && " + $format + ".validate; var " + $formatType + " = " + $isObject + " && " + $format + ".type || 'string'; if (" + $isObject + ") { ";
    if (it.async) {
      out += " var async" + $lvl + " = " + $format + ".async; ";
    }
    out += " " + $format + " = " + $format + ".validate; } if (  ";
    if ($isData) {
      out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
    }
    out += " (";
    if ($unknownFormats != "ignore") {
      out += " (" + $schemaValue + " && !" + $format + " ";
      if ($allowUnknown) {
        out += " && self._opts.unknownFormats.indexOf(" + $schemaValue + ") == -1 ";
      }
      out += ") || ";
    }
    out += " (" + $format + " && " + $formatType + " == '" + $ruleType + "' && !(typeof " + $format + " == 'function' ? ";
    if (it.async) {
      out += " (async" + $lvl + " ? await " + $format + "(" + $data + ") : " + $format + "(" + $data + ")) ";
    } else {
      out += " " + $format + "(" + $data + ") ";
    }
    out += " : " + $format + ".test(" + $data + "))))) {";
  } else {
    var $format = it.formats[$schema2];
    if (!$format) {
      if ($unknownFormats == "ignore") {
        it.logger.warn('unknown format "' + $schema2 + '" ignored in schema at path "' + it.errSchemaPath + '"');
        if ($breakOnError) {
          out += " if (true) { ";
        }
        return out;
      } else if ($allowUnknown && $unknownFormats.indexOf($schema2) >= 0) {
        if ($breakOnError) {
          out += " if (true) { ";
        }
        return out;
      } else {
        throw new Error('unknown format "' + $schema2 + '" is used in schema at path "' + it.errSchemaPath + '"');
      }
    }
    var $isObject = typeof $format == "object" && !($format instanceof RegExp) && $format.validate;
    var $formatType = $isObject && $format.type || "string";
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
    if ($formatType != $ruleType) {
      if ($breakOnError) {
        out += " if (true) { ";
      }
      return out;
    }
    if ($async) {
      if (!it.async)
        throw new Error("async format in sync schema");
      var $formatRef = "formats" + it.util.getProperty($schema2) + ".validate";
      out += " if (!(await " + $formatRef + "(" + $data + "))) { ";
    } else {
      out += " if (! ";
      var $formatRef = "formats" + it.util.getProperty($schema2);
      if ($isObject)
        $formatRef += ".validate";
      if (typeof $format == "function") {
        out += " " + $formatRef + "(" + $data + ") ";
      } else {
        out += " " + $formatRef + ".test(" + $data + ") ";
      }
      out += ") { ";
    }
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { format:  ";
    if ($isData) {
      out += "" + $schemaValue;
    } else {
      out += "" + it.util.toQuotedString($schema2);
    }
    out += "  } ";
    if (it.opts.messages !== false) {
      out += ` , message: 'should match format "`;
      if ($isData) {
        out += "' + " + $schemaValue + " + '";
      } else {
        out += "" + it.util.escapeQuotes($schema2);
      }
      out += `"' `;
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + it.util.toQuotedString($schema2);
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += " } ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var _if = function generate_if(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $thenSch = it.schema["then"], $elseSch = it.schema["else"], $thenPresent = $thenSch !== void 0 && (it.opts.strictKeywords ? typeof $thenSch == "object" && Object.keys($thenSch).length > 0 || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== void 0 && (it.opts.strictKeywords ? typeof $elseSch == "object" && Object.keys($elseSch).length > 0 || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId;
  if ($thenPresent || $elsePresent) {
    var $ifClause;
    $it.createErrors = false;
    $it.schema = $schema2;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += " var " + $errs + " = errors; var " + $valid + " = true;  ";
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    out += "  " + it.validate($it) + " ";
    $it.baseId = $currentBaseId;
    $it.createErrors = true;
    out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }  ";
    it.compositeRule = $it.compositeRule = $wasComposite;
    if ($thenPresent) {
      out += " if (" + $nextValid + ") {  ";
      $it.schema = it.schema["then"];
      $it.schemaPath = it.schemaPath + ".then";
      $it.errSchemaPath = it.errSchemaPath + "/then";
      out += "  " + it.validate($it) + " ";
      $it.baseId = $currentBaseId;
      out += " " + $valid + " = " + $nextValid + "; ";
      if ($thenPresent && $elsePresent) {
        $ifClause = "ifClause" + $lvl;
        out += " var " + $ifClause + " = 'then'; ";
      } else {
        $ifClause = "'then'";
      }
      out += " } ";
      if ($elsePresent) {
        out += " else { ";
      }
    } else {
      out += " if (!" + $nextValid + ") { ";
    }
    if ($elsePresent) {
      $it.schema = it.schema["else"];
      $it.schemaPath = it.schemaPath + ".else";
      $it.errSchemaPath = it.errSchemaPath + "/else";
      out += "  " + it.validate($it) + " ";
      $it.baseId = $currentBaseId;
      out += " " + $valid + " = " + $nextValid + "; ";
      if ($thenPresent && $elsePresent) {
        $ifClause = "ifClause" + $lvl;
        out += " var " + $ifClause + " = 'else'; ";
      } else {
        $ifClause = "'else'";
      }
      out += " } ";
    }
    out += " if (!" + $valid + ") {   var err =   ";
    if (it.createErrors !== false) {
      out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { failingKeyword: " + $ifClause + " } ";
      if (it.opts.messages !== false) {
        out += ` , message: 'should match "' + ` + $ifClause + ` + '" schema' `;
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError(vErrors); ";
      } else {
        out += " validate.errors = vErrors; return false; ";
      }
    }
    out += " }   ";
    if ($breakOnError) {
      out += " else { ";
    }
  } else {
    if ($breakOnError) {
      out += " if (true) { ";
    }
  }
  return out;
};
var items = function generate_items(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId;
  out += "var " + $errs + " = errors;var " + $valid + ";";
  if (Array.isArray($schema2)) {
    var $additionalItems = it.schema.additionalItems;
    if ($additionalItems === false) {
      out += " " + $valid + " = " + $data + ".length <= " + $schema2.length + "; ";
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + "/additionalItems";
      out += "  if (!" + $valid + ") {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schema2.length + " } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT have more than " + $schema2.length + " items' ";
        }
        if (it.opts.verbose) {
          out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } ";
      $errSchemaPath = $currErrSchemaPath;
      if ($breakOnError) {
        $closingBraces += "}";
        out += " else { ";
      }
    }
    var arr1 = $schema2;
    if (arr1) {
      var $sch, $i = -1, l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
          out += " " + $nextValid + " = true; if (" + $data + ".length > " + $i + ") { ";
          var $passData = $data + "[" + $i + "]";
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
          } else {
            out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
          }
          out += " }  ";
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
            $closingBraces += "}";
          }
        }
      }
    }
    if (typeof $additionalItems == "object" && (it.opts.strictKeywords ? typeof $additionalItems == "object" && Object.keys($additionalItems).length > 0 || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + ".additionalItems";
      $it.errSchemaPath = it.errSchemaPath + "/additionalItems";
      out += " " + $nextValid + " = true; if (" + $data + ".length > " + $schema2.length + ") {  for (var " + $idx + " = " + $schema2.length + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + "[" + $idx + "]";
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
      } else {
        out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
      }
      if ($breakOnError) {
        out += " if (!" + $nextValid + ") break; ";
      }
      out += " } }  ";
      if ($breakOnError) {
        out += " if (" + $nextValid + ") { ";
        $closingBraces += "}";
      }
    }
  } else if (it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all)) {
    $it.schema = $schema2;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += "  for (var " + $idx + " = " + 0 + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + "[" + $idx + "]";
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
    } else {
      out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
    }
    if ($breakOnError) {
      out += " if (!" + $nextValid + ") break; ";
    }
    out += " }";
  }
  if ($breakOnError) {
    out += " " + $closingBraces + " if (" + $errs + " == errors) {";
  }
  return out;
};
var _limit = function generate__limit(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = "data" + ($dataLvl || "");
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  var $isMax = $keyword == "maximum", $exclusiveKeyword = $isMax ? "exclusiveMaximum" : "exclusiveMinimum", $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? "<" : ">", $notOp = $isMax ? ">" : "<", $errorKeyword = void 0;
  if (!($isData || typeof $schema2 == "number" || $schema2 === void 0)) {
    throw new Error($keyword + " must be number");
  }
  if (!($isDataExcl || $schemaExcl === void 0 || typeof $schemaExcl == "number" || typeof $schemaExcl == "boolean")) {
    throw new Error($exclusiveKeyword + " must be number or boolean");
  }
  if ($isDataExcl) {
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = "exclusive" + $lvl, $exclType = "exclType" + $lvl, $exclIsNumber = "exclIsNumber" + $lvl, $opExpr = "op" + $lvl, $opStr = "' + " + $opExpr + " + '";
    out += " var schemaExcl" + $lvl + " = " + $schemaValueExcl + "; ";
    $schemaValueExcl = "schemaExcl" + $lvl;
    out += " var " + $exclusive + "; var " + $exclType + " = typeof " + $schemaValueExcl + "; if (" + $exclType + " != 'boolean' && " + $exclType + " != 'undefined' && " + $exclType + " != 'number') { ";
    var $errorKeyword = $exclusiveKeyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_exclusiveLimit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
      if (it.opts.messages !== false) {
        out += " , message: '" + $exclusiveKeyword + " should be boolean' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " } else if ( ";
    if ($isData) {
      out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
    }
    out += " " + $exclType + " == 'number' ? ( (" + $exclusive + " = " + $schemaValue + " === undefined || " + $schemaValueExcl + " " + $op + "= " + $schemaValue + ") ? " + $data + " " + $notOp + "= " + $schemaValueExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) : ( (" + $exclusive + " = " + $schemaValueExcl + " === true) ? " + $data + " " + $notOp + "= " + $schemaValue + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { var op" + $lvl + " = " + $exclusive + " ? '" + $op + "' : '" + $op + "='; ";
    if ($schema2 === void 0) {
      $errorKeyword = $exclusiveKeyword;
      $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
      $schemaValue = $schemaValueExcl;
      $isData = $isDataExcl;
    }
  } else {
    var $exclIsNumber = typeof $schemaExcl == "number", $opStr = $op;
    if ($exclIsNumber && $isData) {
      var $opExpr = "'" + $opStr + "'";
      out += " if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
      }
      out += " ( " + $schemaValue + " === undefined || " + $schemaExcl + " " + $op + "= " + $schemaValue + " ? " + $data + " " + $notOp + "= " + $schemaExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { ";
    } else {
      if ($exclIsNumber && $schema2 === void 0) {
        $exclusive = true;
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
        $schemaValue = $schemaExcl;
        $notOp += "=";
      } else {
        if ($exclIsNumber)
          $schemaValue = Math[$isMax ? "min" : "max"]($schemaExcl, $schema2);
        if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
          $exclusive = true;
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
          $notOp += "=";
        } else {
          $exclusive = false;
          $opStr += "=";
        }
      }
      var $opExpr = "'" + $opStr + "'";
      out += " if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
      }
      out += " " + $data + " " + $notOp + " " + $schemaValue + " || " + $data + " !== " + $data + ") { ";
    }
  }
  $errorKeyword = $errorKeyword || $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: '" + ($errorKeyword || "_limit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { comparison: " + $opExpr + ", limit: " + $schemaValue + ", exclusive: " + $exclusive + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should be " + $opStr + " ";
      if ($isData) {
        out += "' + " + $schemaValue;
      } else {
        out += "" + $schemaValue + "'";
      }
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + $schema2;
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += " } ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var _limitItems = function generate__limitItems(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = "data" + ($dataLvl || "");
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  if (!($isData || typeof $schema2 == "number")) {
    throw new Error($keyword + " must be number");
  }
  var $op = $keyword == "maxItems" ? ">" : "<";
  out += "if ( ";
  if ($isData) {
    out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
  }
  out += " " + $data + ".length " + $op + " " + $schemaValue + ") { ";
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: '" + ($errorKeyword || "_limitItems") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should NOT have ";
      if ($keyword == "maxItems") {
        out += "more";
      } else {
        out += "fewer";
      }
      out += " than ";
      if ($isData) {
        out += "' + " + $schemaValue + " + '";
      } else {
        out += "" + $schema2;
      }
      out += " items' ";
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + $schema2;
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += "} ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var _limitLength = function generate__limitLength(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = "data" + ($dataLvl || "");
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  if (!($isData || typeof $schema2 == "number")) {
    throw new Error($keyword + " must be number");
  }
  var $op = $keyword == "maxLength" ? ">" : "<";
  out += "if ( ";
  if ($isData) {
    out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
  }
  if (it.opts.unicode === false) {
    out += " " + $data + ".length ";
  } else {
    out += " ucs2length(" + $data + ") ";
  }
  out += " " + $op + " " + $schemaValue + ") { ";
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: '" + ($errorKeyword || "_limitLength") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should NOT be ";
      if ($keyword == "maxLength") {
        out += "longer";
      } else {
        out += "shorter";
      }
      out += " than ";
      if ($isData) {
        out += "' + " + $schemaValue + " + '";
      } else {
        out += "" + $schema2;
      }
      out += " characters' ";
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + $schema2;
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += "} ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var _limitProperties = function generate__limitProperties(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = "data" + ($dataLvl || "");
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  if (!($isData || typeof $schema2 == "number")) {
    throw new Error($keyword + " must be number");
  }
  var $op = $keyword == "maxProperties" ? ">" : "<";
  out += "if ( ";
  if ($isData) {
    out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
  }
  out += " Object.keys(" + $data + ").length " + $op + " " + $schemaValue + ") { ";
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: '" + ($errorKeyword || "_limitProperties") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should NOT have ";
      if ($keyword == "maxProperties") {
        out += "more";
      } else {
        out += "fewer";
      }
      out += " than ";
      if ($isData) {
        out += "' + " + $schemaValue + " + '";
      } else {
        out += "" + $schema2;
      }
      out += " properties' ";
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + $schema2;
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += "} ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var multipleOf = function generate_multipleOf(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  if (!($isData || typeof $schema2 == "number")) {
    throw new Error($keyword + " must be number");
  }
  out += "var division" + $lvl + ";if (";
  if ($isData) {
    out += " " + $schemaValue + " !== undefined && ( typeof " + $schemaValue + " != 'number' || ";
  }
  out += " (division" + $lvl + " = " + $data + " / " + $schemaValue + ", ";
  if (it.opts.multipleOfPrecision) {
    out += " Math.abs(Math.round(division" + $lvl + ") - division" + $lvl + ") > 1e-" + it.opts.multipleOfPrecision + " ";
  } else {
    out += " division" + $lvl + " !== parseInt(division" + $lvl + ") ";
  }
  out += " ) ";
  if ($isData) {
    out += "  )  ";
  }
  out += " ) {   ";
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { multipleOf: " + $schemaValue + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should be multiple of ";
      if ($isData) {
        out += "' + " + $schemaValue;
      } else {
        out += "" + $schemaValue + "'";
      }
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + $schema2;
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += "} ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var not2 = function generate_not(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = "valid" + $it.level;
  if (it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all)) {
    $it.schema = $schema2;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += " var " + $errs + " = errors;  ";
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
    out += " " + it.validate($it) + " ";
    $it.createErrors = true;
    if ($allErrorsOption)
      $it.opts.allErrors = $allErrorsOption;
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += " if (" + $nextValid + ") {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
      if (it.opts.messages !== false) {
        out += " , message: 'should NOT be valid' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " } else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
    if (it.opts.allErrors) {
      out += " } ";
    }
  } else {
    out += "  var err =   ";
    if (it.createErrors !== false) {
      out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
      if (it.opts.messages !== false) {
        out += " , message: 'should NOT be valid' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    if ($breakOnError) {
      out += " if (false) { ";
    }
  }
  return out;
};
var oneOf = function generate_oneOf(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $currentBaseId = $it.baseId, $prevValid = "prevValid" + $lvl, $passingSchemas = "passingSchemas" + $lvl;
  out += "var " + $errs + " = errors , " + $prevValid + " = false , " + $valid + " = false , " + $passingSchemas + " = null; ";
  var $wasComposite = it.compositeRule;
  it.compositeRule = $it.compositeRule = true;
  var arr1 = $schema2;
  if (arr1) {
    var $sch, $i = -1, l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + "[" + $i + "]";
        $it.errSchemaPath = $errSchemaPath + "/" + $i;
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
      } else {
        out += " var " + $nextValid + " = true; ";
      }
      if ($i) {
        out += " if (" + $nextValid + " && " + $prevValid + ") { " + $valid + " = false; " + $passingSchemas + " = [" + $passingSchemas + ", " + $i + "]; } else { ";
        $closingBraces += "}";
      }
      out += " if (" + $nextValid + ") { " + $valid + " = " + $prevValid + " = true; " + $passingSchemas + " = " + $i + "; }";
    }
  }
  it.compositeRule = $it.compositeRule = $wasComposite;
  out += "" + $closingBraces + "if (!" + $valid + ") {   var err =   ";
  if (it.createErrors !== false) {
    out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { passingSchemas: " + $passingSchemas + " } ";
    if (it.opts.messages !== false) {
      out += " , message: 'should match exactly one schema in oneOf' ";
    }
    if (it.opts.verbose) {
      out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError(vErrors); ";
    } else {
      out += " validate.errors = vErrors; return false; ";
    }
  }
  out += "} else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }";
  if (it.opts.allErrors) {
    out += " } ";
  }
  return out;
};
var pattern = function generate_pattern(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  var $regexp = $isData ? "(new RegExp(" + $schemaValue + "))" : it.usePattern($schema2);
  out += "if ( ";
  if ($isData) {
    out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
  }
  out += " !" + $regexp + ".test(" + $data + ") ) {   ";
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = "";
  if (it.createErrors !== false) {
    out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { pattern:  ";
    if ($isData) {
      out += "" + $schemaValue;
    } else {
      out += "" + it.util.toQuotedString($schema2);
    }
    out += "  } ";
    if (it.opts.messages !== false) {
      out += ` , message: 'should match pattern "`;
      if ($isData) {
        out += "' + " + $schemaValue + " + '";
      } else {
        out += "" + it.util.escapeQuotes($schema2);
      }
      out += `"' `;
    }
    if (it.opts.verbose) {
      out += " , schema:  ";
      if ($isData) {
        out += "validate.schema" + $schemaPath;
      } else {
        out += "" + it.util.toQuotedString($schema2);
      }
      out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
    }
    out += " } ";
  } else {
    out += " {} ";
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    if (it.async) {
      out += " throw new ValidationError([" + __err + "]); ";
    } else {
      out += " validate.errors = [" + __err + "]; return false; ";
    }
  } else {
    out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
  }
  out += "} ";
  if ($breakOnError) {
    out += " else { ";
  }
  return out;
};
var properties$2 = function generate_properties(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  var $key = "key" + $lvl, $idx = "idx" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl;
  var $schemaKeys = Object.keys($schema2 || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == "object" && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
  var $required = it.schema.required;
  if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
    var $requiredHash = it.util.toHash($required);
  }
  function notProto(p) {
    return p !== "__proto__";
  }
  out += "var " + $errs + " = errors;var " + $nextValid + " = true;";
  if ($ownProperties) {
    out += " var " + $dataProperties + " = undefined;";
  }
  if ($checkAdditional) {
    if ($ownProperties) {
      out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
    } else {
      out += " for (var " + $key + " in " + $data + ") { ";
    }
    if ($someProperties) {
      out += " var isAdditional" + $lvl + " = !(false ";
      if ($schemaKeys.length) {
        if ($schemaKeys.length > 8) {
          out += " || validate.schema" + $schemaPath + ".hasOwnProperty(" + $key + ") ";
        } else {
          var arr1 = $schemaKeys;
          if (arr1) {
            var $propertyKey, i1 = -1, l1 = arr1.length - 1;
            while (i1 < l1) {
              $propertyKey = arr1[i1 += 1];
              out += " || " + $key + " == " + it.util.toQuotedString($propertyKey) + " ";
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr2 = $pPropertyKeys;
        if (arr2) {
          var $pProperty, $i = -1, l2 = arr2.length - 1;
          while ($i < l2) {
            $pProperty = arr2[$i += 1];
            out += " || " + it.usePattern($pProperty) + ".test(" + $key + ") ";
          }
        }
      }
      out += " ); if (isAdditional" + $lvl + ") { ";
    }
    if ($removeAdditional == "all") {
      out += " delete " + $data + "[" + $key + "]; ";
    } else {
      var $currentErrorPath = it.errorPath;
      var $additionalProperty = "' + " + $key + " + '";
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
      }
      if ($noAdditional) {
        if ($removeAdditional) {
          out += " delete " + $data + "[" + $key + "]; ";
        } else {
          out += " " + $nextValid + " = false; ";
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + "/additionalProperties";
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { additionalProperty: '" + $additionalProperty + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: '";
              if (it.opts._errorDataPathProperty) {
                out += "is an invalid additional property";
              } else {
                out += "should NOT have additional properties";
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            out += " break; ";
          }
        }
      } else if ($additionalIsSchema) {
        if ($removeAdditional == "failing") {
          out += " var " + $errs + " = errors;  ";
          var $wasComposite = it.compositeRule;
          it.compositeRule = $it.compositeRule = true;
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + ".additionalProperties";
          $it.errSchemaPath = it.errSchemaPath + "/additionalProperties";
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + "[" + $key + "]";
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
          } else {
            out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
          }
          out += " if (!" + $nextValid + ") { errors = " + $errs + "; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete " + $data + "[" + $key + "]; }  ";
          it.compositeRule = $it.compositeRule = $wasComposite;
        } else {
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + ".additionalProperties";
          $it.errSchemaPath = it.errSchemaPath + "/additionalProperties";
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + "[" + $key + "]";
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
          } else {
            out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
          }
          if ($breakOnError) {
            out += " if (!" + $nextValid + ") break; ";
          }
        }
      }
      it.errorPath = $currentErrorPath;
    }
    if ($someProperties) {
      out += " } ";
    }
    out += " }  ";
    if ($breakOnError) {
      out += " if (" + $nextValid + ") { ";
      $closingBraces += "}";
    }
  }
  var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  if ($schemaKeys.length) {
    var arr3 = $schemaKeys;
    if (arr3) {
      var $propertyKey, i3 = -1, l3 = arr3.length - 1;
      while (i3 < l3) {
        $propertyKey = arr3[i3 += 1];
        var $sch = $schema2[$propertyKey];
        if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
          var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== void 0;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + $prop;
          $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($propertyKey);
          $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
          $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            $code = it.util.varReplace($code, $nextData, $passData);
            var $useData = $passData;
          } else {
            var $useData = $nextData;
            out += " var " + $nextData + " = " + $passData + "; ";
          }
          if ($hasDefault) {
            out += " " + $code + " ";
          } else {
            if ($requiredHash && $requiredHash[$propertyKey]) {
              out += " if ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") { " + $nextValid + " = false; ";
              var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + "/required";
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = "";
              if (it.createErrors !== false) {
                out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                if (it.opts.messages !== false) {
                  out += " , message: '";
                  if (it.opts._errorDataPathProperty) {
                    out += "is a required property";
                  } else {
                    out += "should have required property \\'" + $missingProperty + "\\'";
                  }
                  out += "' ";
                }
                if (it.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                if (it.async) {
                  out += " throw new ValidationError([" + __err + "]); ";
                } else {
                  out += " validate.errors = [" + __err + "]; return false; ";
                }
              } else {
                out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
              }
              $errSchemaPath = $currErrSchemaPath;
              it.errorPath = $currentErrorPath;
              out += " } else { ";
            } else {
              if ($breakOnError) {
                out += " if ( " + $useData + " === undefined ";
                if ($ownProperties) {
                  out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") { " + $nextValid + " = true; } else { ";
              } else {
                out += " if (" + $useData + " !== undefined ";
                if ($ownProperties) {
                  out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += " ) { ";
              }
            }
            out += " " + $code + " } ";
          }
        }
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
          $closingBraces += "}";
        }
      }
    }
  }
  if ($pPropertyKeys.length) {
    var arr4 = $pPropertyKeys;
    if (arr4) {
      var $pProperty, i4 = -1, l4 = arr4.length - 1;
      while (i4 < l4) {
        $pProperty = arr4[i4 += 1];
        var $sch = $pProperties[$pProperty];
        if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + ".patternProperties" + it.util.getProperty($pProperty);
          $it.errSchemaPath = it.errSchemaPath + "/patternProperties/" + it.util.escapeFragment($pProperty);
          if ($ownProperties) {
            out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
          } else {
            out += " for (var " + $key + " in " + $data + ") { ";
          }
          out += " if (" + it.usePattern($pProperty) + ".test(" + $key + ")) { ";
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + "[" + $key + "]";
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
          } else {
            out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
          }
          if ($breakOnError) {
            out += " if (!" + $nextValid + ") break; ";
          }
          out += " } ";
          if ($breakOnError) {
            out += " else " + $nextValid + " = true; ";
          }
          out += " }  ";
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
            $closingBraces += "}";
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += " " + $closingBraces + " if (" + $errs + " == errors) {";
  }
  return out;
};
var propertyNames = function generate_propertyNames(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $errs = "errs__" + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = "";
  $it.level++;
  var $nextValid = "valid" + $it.level;
  out += "var " + $errs + " = errors;";
  if (it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all)) {
    $it.schema = $schema2;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    var $key = "key" + $lvl, $idx = "idx" + $lvl, $i = "i" + $lvl, $invalidName = "' + " + $key + " + '", $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
    if ($ownProperties) {
      out += " var " + $dataProperties + " = undefined; ";
    }
    if ($ownProperties) {
      out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
    } else {
      out += " for (var " + $key + " in " + $data + ") { ";
    }
    out += " var startErrs" + $lvl + " = errors; ";
    var $passData = $key;
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
    } else {
      out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += " if (!" + $nextValid + ") { for (var " + $i + "=startErrs" + $lvl + "; " + $i + "<errors; " + $i + "++) { vErrors[" + $i + "].propertyName = " + $key + "; }   var err =   ";
    if (it.createErrors !== false) {
      out += " { keyword: 'propertyNames' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { propertyName: '" + $invalidName + "' } ";
      if (it.opts.messages !== false) {
        out += " , message: 'property name \\'" + $invalidName + "\\' is invalid' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError(vErrors); ";
      } else {
        out += " validate.errors = vErrors; return false; ";
      }
    }
    if ($breakOnError) {
      out += " break; ";
    }
    out += " } }";
  }
  if ($breakOnError) {
    out += " " + $closingBraces + " if (" + $errs + " == errors) {";
  }
  return out;
};
var required$1 = function generate_required(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $isData = it.opts.$data && $schema2 && $schema2.$data;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
  }
  var $vSchema = "schema" + $lvl;
  if (!$isData) {
    if ($schema2.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
      var $required = [];
      var arr1 = $schema2;
      if (arr1) {
        var $property, i1 = -1, l1 = arr1.length - 1;
        while (i1 < l1) {
          $property = arr1[i1 += 1];
          var $propertySch = it.schema.properties[$property];
          if (!($propertySch && (it.opts.strictKeywords ? typeof $propertySch == "object" && Object.keys($propertySch).length > 0 || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
            $required[$required.length] = $property;
          }
        }
      }
    } else {
      var $required = $schema2;
    }
  }
  if ($isData || $required.length) {
    var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties;
    if ($breakOnError) {
      out += " var missing" + $lvl + "; ";
      if ($loopRequired) {
        if (!$isData) {
          out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
        }
        var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '";
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        out += " var " + $valid + " = true; ";
        if ($isData) {
          out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {";
        }
        out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { " + $valid + " = " + $data + "[" + $vSchema + "[" + $i + "]] !== undefined ";
        if ($ownProperties) {
          out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) ";
        }
        out += "; if (!" + $valid + ") break; } ";
        if ($isData) {
          out += "  }  ";
        }
        out += "  if (!" + $valid + ") {   ";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
          if (it.opts.messages !== false) {
            out += " , message: '";
            if (it.opts._errorDataPathProperty) {
              out += "is a required property";
            } else {
              out += "should have required property \\'" + $missingProperty + "\\'";
            }
            out += "' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } else { ";
      } else {
        out += " if ( ";
        var arr2 = $required;
        if (arr2) {
          var $propertyKey, $i = -1, l2 = arr2.length - 1;
          while ($i < l2) {
            $propertyKey = arr2[$i += 1];
            if ($i) {
              out += " || ";
            }
            var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
            out += " ( ( " + $useData + " === undefined ";
            if ($ownProperties) {
              out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
            }
            out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
          }
        }
        out += ") {  ";
        var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
          if (it.opts.messages !== false) {
            out += " , message: '";
            if (it.opts._errorDataPathProperty) {
              out += "is a required property";
            } else {
              out += "should have required property \\'" + $missingProperty + "\\'";
            }
            out += "' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } else { ";
      }
    } else {
      if ($loopRequired) {
        if (!$isData) {
          out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
        }
        var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '";
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        if ($isData) {
          out += " if (" + $vSchema + " && !Array.isArray(" + $vSchema + ")) {  var err =   ";
          if (it.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: '";
              if (it.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (" + $vSchema + " !== undefined) { ";
        }
        out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { if (" + $data + "[" + $vSchema + "[" + $i + "]] === undefined ";
        if ($ownProperties) {
          out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) ";
        }
        out += ") {  var err =   ";
        if (it.createErrors !== false) {
          out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
          if (it.opts.messages !== false) {
            out += " , message: '";
            if (it.opts._errorDataPathProperty) {
              out += "is a required property";
            } else {
              out += "should have required property \\'" + $missingProperty + "\\'";
            }
            out += "' ";
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ";
        if ($isData) {
          out += "  }  ";
        }
      } else {
        var arr3 = $required;
        if (arr3) {
          var $propertyKey, i3 = -1, l3 = arr3.length - 1;
          while (i3 < l3) {
            $propertyKey = arr3[i3 += 1];
            var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += " if ( " + $useData + " === undefined ";
            if ($ownProperties) {
              out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
            }
            out += ") {  var err =   ";
            if (it.createErrors !== false) {
              out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: '";
                if (it.opts._errorDataPathProperty) {
                  out += "is a required property";
                } else {
                  out += "should have required property \\'" + $missingProperty + "\\'";
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
          }
        }
      }
    }
    it.errorPath = $currentErrorPath;
  } else if ($breakOnError) {
    out += " if (true) {";
  }
  return out;
};
var uniqueItems = function generate_uniqueItems(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  if (($schema2 || $isData) && it.opts.uniqueItems !== false) {
    if ($isData) {
      out += " var " + $valid + "; if (" + $schemaValue + " === false || " + $schemaValue + " === undefined) " + $valid + " = true; else if (typeof " + $schemaValue + " != 'boolean') " + $valid + " = false; else { ";
    }
    out += " var i = " + $data + ".length , " + $valid + " = true , j; if (i > 1) { ";
    var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType);
    if (!$itemType || $itemType == "object" || $itemType == "array" || $typeIsArray && ($itemType.indexOf("object") >= 0 || $itemType.indexOf("array") >= 0)) {
      out += " outer: for (;i--;) { for (j = i; j--;) { if (equal(" + $data + "[i], " + $data + "[j])) { " + $valid + " = false; break outer; } } } ";
    } else {
      out += " var itemIndices = {}, item; for (;i--;) { var item = " + $data + "[i]; ";
      var $method = "checkDataType" + ($typeIsArray ? "s" : "");
      out += " if (" + it.util[$method]($itemType, "item", it.opts.strictNumbers, true) + ") continue; ";
      if ($typeIsArray) {
        out += ` if (typeof item == 'string') item = '"' + item; `;
      }
      out += " if (typeof itemIndices[item] == 'number') { " + $valid + " = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ";
    }
    out += " } ";
    if ($isData) {
      out += "  }  ";
    }
    out += " if (!" + $valid + ") {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { i: i, j: j } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " } ";
    if ($breakOnError) {
      out += " else { ";
    }
  } else {
    if ($breakOnError) {
      out += " if (true) { ";
    }
  }
  return out;
};
var dotjs = {
  "$ref": ref,
  allOf,
  anyOf,
  "$comment": comment,
  const: _const,
  contains,
  dependencies,
  "enum": _enum,
  format: gosling_es_format,
  "if": _if,
  items,
  maximum: _limit,
  minimum: _limit,
  maxItems: _limitItems,
  minItems: _limitItems,
  maxLength: _limitLength,
  minLength: _limitLength,
  maxProperties: _limitProperties,
  minProperties: _limitProperties,
  multipleOf,
  not: not2,
  oneOf,
  pattern,
  properties: properties$2,
  propertyNames,
  required: required$1,
  uniqueItems,
  validate: validate$1
};
var ruleModules = dotjs, toHash = util$5.toHash;
var rules$1 = function rules() {
  var RULES = [
    {
      type: "number",
      rules: [
        { "maximum": ["exclusiveMaximum"] },
        { "minimum": ["exclusiveMinimum"] },
        "multipleOf",
        "format"
      ]
    },
    {
      type: "string",
      rules: ["maxLength", "minLength", "pattern", "format"]
    },
    {
      type: "array",
      rules: ["maxItems", "minItems", "items", "contains", "uniqueItems"]
    },
    {
      type: "object",
      rules: [
        "maxProperties",
        "minProperties",
        "required",
        "dependencies",
        "propertyNames",
        { "properties": ["additionalProperties", "patternProperties"] }
      ]
    },
    { rules: ["$ref", "const", "enum", "not", "anyOf", "oneOf", "allOf", "if"] }
  ];
  var ALL = ["type", "$comment"];
  var KEYWORDS2 = [
    "$schema",
    "$id",
    "id",
    "$data",
    "$async",
    "title",
    "description",
    "default",
    "definitions",
    "examples",
    "readOnly",
    "writeOnly",
    "contentMediaType",
    "contentEncoding",
    "additionalItems",
    "then",
    "else"
  ];
  var TYPES = ["number", "integer", "string", "array", "object", "boolean", "null"];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);
  RULES.forEach(function(group2) {
    group2.rules = group2.rules.map(function(keyword2) {
      var implKeywords;
      if (typeof keyword2 == "object") {
        var key = Object.keys(keyword2)[0];
        implKeywords = keyword2[key];
        keyword2 = key;
        implKeywords.forEach(function(k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword2);
      var rule = RULES.all[keyword2] = {
        keyword: keyword2,
        code: ruleModules[keyword2],
        implements: implKeywords
      };
      return rule;
    });
    RULES.all.$comment = {
      keyword: "$comment",
      code: ruleModules.$comment
    };
    if (group2.type)
      RULES.types[group2.type] = group2;
  });
  RULES.keywords = toHash(ALL.concat(KEYWORDS2));
  RULES.custom = {};
  return RULES;
};
var KEYWORDS = [
  "multipleOf",
  "maximum",
  "exclusiveMaximum",
  "minimum",
  "exclusiveMinimum",
  "maxLength",
  "minLength",
  "pattern",
  "additionalItems",
  "maxItems",
  "minItems",
  "uniqueItems",
  "maxProperties",
  "minProperties",
  "required",
  "additionalProperties",
  "enum",
  "format",
  "const"
];
var data = function(metaSchema2, keywordsJsonPointers) {
  for (var i = 0; i < keywordsJsonPointers.length; i++) {
    metaSchema2 = JSON.parse(JSON.stringify(metaSchema2));
    var segments = keywordsJsonPointers[i].split("/");
    var keywords = metaSchema2;
    var j;
    for (j = 1; j < segments.length; j++)
      keywords = keywords[segments[j]];
    for (j = 0; j < KEYWORDS.length; j++) {
      var key = KEYWORDS[j];
      var schema = keywords[key];
      if (schema) {
        keywords[key] = {
          anyOf: [
            schema,
            { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }
          ]
        };
      }
    }
  }
  return metaSchema2;
};
var MissingRefError = error_classes.MissingRef;
var gosling_es_async = compileAsync;
function compileAsync(schema, meta, callback) {
  var self2 = this;
  if (typeof this._opts.loadSchema != "function")
    throw new Error("options.loadSchema should be a function");
  if (typeof meta == "function") {
    callback = meta;
    meta = void 0;
  }
  var p = loadMetaSchemaOf(schema).then(function() {
    var schemaObj = self2._addSchema(schema, void 0, meta);
    return schemaObj.validate || _compileAsync(schemaObj);
  });
  if (callback) {
    p.then(function(v) {
      callback(null, v);
    }, callback);
  }
  return p;
  function loadMetaSchemaOf(sch) {
    var $schema2 = sch.$schema;
    return $schema2 && !self2.getSchema($schema2) ? compileAsync.call(self2, { $ref: $schema2 }, true) : Promise.resolve();
  }
  function _compileAsync(schemaObj) {
    try {
      return self2._compile(schemaObj);
    } catch (e) {
      if (e instanceof MissingRefError)
        return loadMissingSchema(e);
      throw e;
    }
    function loadMissingSchema(e) {
      var ref2 = e.missingSchema;
      if (added(ref2))
        throw new Error("Schema " + ref2 + " is loaded but " + e.missingRef + " cannot be resolved");
      var schemaPromise = self2._loadingSchemas[ref2];
      if (!schemaPromise) {
        schemaPromise = self2._loadingSchemas[ref2] = self2._opts.loadSchema(ref2);
        schemaPromise.then(removePromise, removePromise);
      }
      return schemaPromise.then(function(sch) {
        if (!added(ref2)) {
          return loadMetaSchemaOf(sch).then(function() {
            if (!added(ref2))
              self2.addSchema(sch, ref2, void 0, meta);
          });
        }
      }).then(function() {
        return _compileAsync(schemaObj);
      });
      function removePromise() {
        delete self2._loadingSchemas[ref2];
      }
      function added(ref3) {
        return self2._refs[ref3] || self2._schemas[ref3];
      }
    }
  }
}
var custom = function generate_custom(it, $keyword, $ruleType) {
  var out = " ";
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema2 = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = "data" + ($dataLvl || "");
  var $valid = "valid" + $lvl;
  var $errs = "errs__" + $lvl;
  var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
  if ($isData) {
    out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    $schemaValue = "schema" + $lvl;
  } else {
    $schemaValue = $schema2;
  }
  var $rule = this, $definition = "definition" + $lvl, $rDef = $rule.definition, $closingBraces = "";
  var $compile, $inline, $macro, $ruleValidate, $validateCode;
  if ($isData && $rDef.$data) {
    $validateCode = "keywordValidate" + $lvl;
    var $validateSchema = $rDef.validateSchema;
    out += " var " + $definition + " = RULES.custom['" + $keyword + "'].definition; var " + $validateCode + " = " + $definition + ".validate;";
  } else {
    $ruleValidate = it.useCustomRule($rule, $schema2, it.schema, it);
    if (!$ruleValidate)
      return;
    $schemaValue = "validate.schema" + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }
  var $ruleErrs = $validateCode + ".errors", $i = "i" + $lvl, $ruleErr = "ruleErr" + $lvl, $asyncKeyword = $rDef.async;
  if ($asyncKeyword && !it.async)
    throw new Error("async keyword in sync schema");
  if (!($inline || $macro)) {
    out += "" + $ruleErrs + " = null;";
  }
  out += "var " + $errs + " = errors;var " + $valid + ";";
  if ($isData && $rDef.$data) {
    $closingBraces += "}";
    out += " if (" + $schemaValue + " === undefined) { " + $valid + " = true; } else { ";
    if ($validateSchema) {
      $closingBraces += "}";
      out += " " + $valid + " = " + $definition + ".validateSchema(" + $schemaValue + "); if (" + $valid + ") { ";
    }
  }
  if ($inline) {
    if ($rDef.statements) {
      out += " " + $ruleValidate.validate + " ";
    } else {
      out += " " + $valid + " = " + $ruleValidate.validate + "; ";
    }
  } else if ($macro) {
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = "";
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += " " + $code;
  } else {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    out += "  " + $validateCode + ".call( ";
    if (it.opts.passContext) {
      out += "this";
    } else {
      out += "self";
    }
    if ($compile || $rDef.schema === false) {
      out += " , " + $data + " ";
    } else {
      out += " , " + $schemaValue + " , " + $data + " , validate.schema" + it.schemaPath + " ";
    }
    out += " , (dataPath || '')";
    if (it.errorPath != '""') {
      out += " + " + it.errorPath;
    }
    var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
    out += " , " + $parentData + " , " + $parentDataProperty + " , rootData )  ";
    var def_callRuleValidate = out;
    out = $$outStack.pop();
    if ($rDef.errors === false) {
      out += " " + $valid + " = ";
      if ($asyncKeyword) {
        out += "await ";
      }
      out += "" + def_callRuleValidate + "; ";
    } else {
      if ($asyncKeyword) {
        $ruleErrs = "customErrors" + $lvl;
        out += " var " + $ruleErrs + " = null; try { " + $valid + " = await " + def_callRuleValidate + "; } catch (e) { " + $valid + " = false; if (e instanceof ValidationError) " + $ruleErrs + " = e.errors; else throw e; } ";
      } else {
        out += " " + $ruleErrs + " = null; " + $valid + " = " + def_callRuleValidate + "; ";
      }
    }
  }
  if ($rDef.modifying) {
    out += " if (" + $parentData + ") " + $data + " = " + $parentData + "[" + $parentDataProperty + "];";
  }
  out += "" + $closingBraces;
  if ($rDef.valid) {
    if ($breakOnError) {
      out += " if (true) { ";
    }
  } else {
    out += " if ( ";
    if ($rDef.valid === void 0) {
      out += " !";
      if ($macro) {
        out += "" + $nextValid;
      } else {
        out += "" + $valid;
      }
    } else {
      out += " " + !$rDef.valid + " ";
    }
    out += ") { ";
    $errorKeyword = $rule.keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
      if (it.opts.messages !== false) {
        out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    var def_customError = out;
    out = $$outStack.pop();
    if ($inline) {
      if ($rDef.errors) {
        if ($rDef.errors != "full") {
          out += "  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
          if (it.opts.verbose) {
            out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
          }
          out += " } ";
        }
      } else {
        if ($rDef.errors === false) {
          out += " " + def_customError + " ";
        } else {
          out += " if (" + $errs + " == errors) { " + def_customError + " } else {  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
          if (it.opts.verbose) {
            out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
          }
          out += " } } ";
        }
      }
    } else if ($macro) {
      out += "   var err =   ";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
        if (it.opts.messages !== false) {
          out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError(vErrors); ";
        } else {
          out += " validate.errors = vErrors; return false; ";
        }
      }
    } else {
      if ($rDef.errors === false) {
        out += " " + def_customError + " ";
      } else {
        out += " if (Array.isArray(" + $ruleErrs + ")) { if (vErrors === null) vErrors = " + $ruleErrs + "; else vErrors = vErrors.concat(" + $ruleErrs + "); errors = vErrors.length;  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + ";  " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '";  ';
        if (it.opts.verbose) {
          out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
        }
        out += " } } else { " + def_customError + " } ";
      }
    }
    out += " } ";
    if ($breakOnError) {
      out += " else { ";
    }
  }
  return out;
};
const $schema$2 = "http://json-schema.org/draft-07/schema#";
const $id$1 = "http://json-schema.org/draft-07/schema#";
const title = "Core schema meta-schema";
const definitions$1 = {
  schemaArray: {
    type: "array",
    minItems: 1,
    items: {
      $ref: "#"
    }
  },
  nonNegativeInteger: {
    type: "integer",
    minimum: 0
  },
  nonNegativeIntegerDefault0: {
    allOf: [
      {
        $ref: "#/definitions/nonNegativeInteger"
      },
      {
        "default": 0
      }
    ]
  },
  simpleTypes: {
    "enum": [
      "array",
      "boolean",
      "integer",
      "null",
      "number",
      "object",
      "string"
    ]
  },
  stringArray: {
    type: "array",
    items: {
      type: "string"
    },
    uniqueItems: true,
    "default": []
  }
};
const type$1 = [
  "object",
  "boolean"
];
const properties$1 = {
  $id: {
    type: "string",
    format: "uri-reference"
  },
  $schema: {
    type: "string",
    format: "uri"
  },
  $ref: {
    type: "string",
    format: "uri-reference"
  },
  $comment: {
    type: "string"
  },
  title: {
    type: "string"
  },
  description: {
    type: "string"
  },
  "default": true,
  readOnly: {
    type: "boolean",
    "default": false
  },
  examples: {
    type: "array",
    items: true
  },
  multipleOf: {
    type: "number",
    exclusiveMinimum: 0
  },
  maximum: {
    type: "number"
  },
  exclusiveMaximum: {
    type: "number"
  },
  minimum: {
    type: "number"
  },
  exclusiveMinimum: {
    type: "number"
  },
  maxLength: {
    $ref: "#/definitions/nonNegativeInteger"
  },
  minLength: {
    $ref: "#/definitions/nonNegativeIntegerDefault0"
  },
  pattern: {
    type: "string",
    format: "regex"
  },
  additionalItems: {
    $ref: "#"
  },
  items: {
    anyOf: [
      {
        $ref: "#"
      },
      {
        $ref: "#/definitions/schemaArray"
      }
    ],
    "default": true
  },
  maxItems: {
    $ref: "#/definitions/nonNegativeInteger"
  },
  minItems: {
    $ref: "#/definitions/nonNegativeIntegerDefault0"
  },
  uniqueItems: {
    type: "boolean",
    "default": false
  },
  contains: {
    $ref: "#"
  },
  maxProperties: {
    $ref: "#/definitions/nonNegativeInteger"
  },
  minProperties: {
    $ref: "#/definitions/nonNegativeIntegerDefault0"
  },
  required: {
    $ref: "#/definitions/stringArray"
  },
  additionalProperties: {
    $ref: "#"
  },
  definitions: {
    type: "object",
    additionalProperties: {
      $ref: "#"
    },
    "default": {}
  },
  properties: {
    type: "object",
    additionalProperties: {
      $ref: "#"
    },
    "default": {}
  },
  patternProperties: {
    type: "object",
    additionalProperties: {
      $ref: "#"
    },
    propertyNames: {
      format: "regex"
    },
    "default": {}
  },
  dependencies: {
    type: "object",
    additionalProperties: {
      anyOf: [
        {
          $ref: "#"
        },
        {
          $ref: "#/definitions/stringArray"
        }
      ]
    }
  },
  propertyNames: {
    $ref: "#"
  },
  "const": true,
  "enum": {
    type: "array",
    items: true,
    minItems: 1,
    uniqueItems: true
  },
  type: {
    anyOf: [
      {
        $ref: "#/definitions/simpleTypes"
      },
      {
        type: "array",
        items: {
          $ref: "#/definitions/simpleTypes"
        },
        minItems: 1,
        uniqueItems: true
      }
    ]
  },
  format: {
    type: "string"
  },
  contentMediaType: {
    type: "string"
  },
  contentEncoding: {
    type: "string"
  },
  "if": {
    $ref: "#"
  },
  then: {
    $ref: "#"
  },
  "else": {
    $ref: "#"
  },
  allOf: {
    $ref: "#/definitions/schemaArray"
  },
  anyOf: {
    $ref: "#/definitions/schemaArray"
  },
  oneOf: {
    $ref: "#/definitions/schemaArray"
  },
  not: {
    $ref: "#"
  }
};
var require$$13 = {
  $schema: $schema$2,
  $id: $id$1,
  title,
  definitions: definitions$1,
  type: type$1,
  properties: properties$1,
  "default": true
};
var metaSchema = require$$13;
var definition_schema = {
  $id: "https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",
  definitions: {
    simpleTypes: metaSchema.definitions.simpleTypes
  },
  type: "object",
  dependencies: {
    schema: ["validate"],
    $data: ["validate"],
    statements: ["inline"],
    valid: { not: { required: ["macro"] } }
  },
  properties: {
    type: metaSchema.properties.type,
    schema: { type: "boolean" },
    statements: { type: "boolean" },
    dependencies: {
      type: "array",
      items: { type: "string" }
    },
    metaSchema: { type: "object" },
    modifying: { type: "boolean" },
    valid: { type: "boolean" },
    $data: { type: "boolean" },
    async: { type: "boolean" },
    errors: {
      anyOf: [
        { type: "boolean" },
        { const: "full" }
      ]
    }
  }
};
var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
var customRuleCode = custom;
var definitionSchema = definition_schema;
var keyword = {
  add: addKeyword,
  get: getKeyword,
  remove: removeKeyword,
  validate: validateKeyword
};
function addKeyword(keyword2, definition) {
  var RULES = this.RULES;
  if (RULES.keywords[keyword2])
    throw new Error("Keyword " + keyword2 + " is already defined");
  if (!IDENTIFIER.test(keyword2))
    throw new Error("Keyword " + keyword2 + " is not a valid identifier");
  if (definition) {
    this.validateKeyword(definition, true);
    var dataType = definition.type;
    if (Array.isArray(dataType)) {
      for (var i = 0; i < dataType.length; i++)
        _addRule(keyword2, dataType[i], definition);
    } else {
      _addRule(keyword2, dataType, definition);
    }
    var metaSchema2 = definition.metaSchema;
    if (metaSchema2) {
      if (definition.$data && this._opts.$data) {
        metaSchema2 = {
          anyOf: [
            metaSchema2,
            { "$ref": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }
          ]
        };
      }
      definition.validateSchema = this.compile(metaSchema2, true);
    }
  }
  RULES.keywords[keyword2] = RULES.all[keyword2] = true;
  function _addRule(keyword3, dataType2, definition2) {
    var ruleGroup;
    for (var i2 = 0; i2 < RULES.length; i2++) {
      var rg = RULES[i2];
      if (rg.type == dataType2) {
        ruleGroup = rg;
        break;
      }
    }
    if (!ruleGroup) {
      ruleGroup = { type: dataType2, rules: [] };
      RULES.push(ruleGroup);
    }
    var rule = {
      keyword: keyword3,
      definition: definition2,
      custom: true,
      code: customRuleCode,
      implements: definition2.implements
    };
    ruleGroup.rules.push(rule);
    RULES.custom[keyword3] = rule;
  }
  return this;
}
function getKeyword(keyword2) {
  var rule = this.RULES.custom[keyword2];
  return rule ? rule.definition : this.RULES.keywords[keyword2] || false;
}
function removeKeyword(keyword2) {
  var RULES = this.RULES;
  delete RULES.keywords[keyword2];
  delete RULES.all[keyword2];
  delete RULES.custom[keyword2];
  for (var i = 0; i < RULES.length; i++) {
    var rules3 = RULES[i].rules;
    for (var j = 0; j < rules3.length; j++) {
      if (rules3[j].keyword == keyword2) {
        rules3.splice(j, 1);
        break;
      }
    }
  }
  return this;
}
function validateKeyword(definition, throwError2) {
  validateKeyword.errors = null;
  var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true);
  if (v(definition))
    return true;
  validateKeyword.errors = v.errors;
  if (throwError2)
    throw new Error("custom keyword definition is invalid: " + this.errorsText(v.errors));
  else
    return false;
}
const $schema$1 = "http://json-schema.org/draft-07/schema#";
const $id = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description = "Meta-schema for $data reference (JSON Schema extension proposal)";
const type = "object";
const required = [
  "$data"
];
const properties = {
  $data: {
    type: "string",
    anyOf: [
      {
        format: "relative-json-pointer"
      },
      {
        format: "json-pointer"
      }
    ]
  }
};
const additionalProperties = false;
var require$$12 = {
  $schema: $schema$1,
  $id,
  description,
  type,
  required,
  properties,
  additionalProperties
};
var compileSchema = compile_1, resolve = resolve_1, Cache2 = cache.exports, SchemaObject = schema_obj, stableStringify = fastJsonStableStringify, formats = formats_1, rules2 = rules$1, $dataMetaSchema = data, util = util$5;
var ajv = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile$1;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = gosling_es_async;
var customKeyword = keyword;
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = error_classes;
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes", "strictDefaults"];
var META_SUPPORT_DATA = ["/properties"];
function Ajv(opts) {
  if (!(this instanceof Ajv))
    return new Ajv(opts);
  opts = this._opts = util.copy(opts) || {};
  setLogger(this);
  this._schemas = {};
  this._refs = {};
  this._fragments = {};
  this._formats = formats(opts.format);
  this._cache = opts.cache || new Cache2();
  this._loadingSchemas = {};
  this._compilations = [];
  this.RULES = rules2();
  this._getId = chooseGetId(opts);
  opts.loopRequired = opts.loopRequired || Infinity;
  if (opts.errorDataPath == "property")
    opts._errorDataPathProperty = true;
  if (opts.serialize === void 0)
    opts.serialize = stableStringify;
  this._metaOpts = getMetaSchemaOptions(this);
  if (opts.formats)
    addInitialFormats(this);
  if (opts.keywords)
    addInitialKeywords(this);
  addDefaultMetaSchema(this);
  if (typeof opts.meta == "object")
    this.addMetaSchema(opts.meta);
  if (opts.nullable)
    this.addKeyword("nullable", { metaSchema: { type: "boolean" } });
  addInitialSchemas(this);
}
function validate(schemaKeyRef, data2) {
  var v;
  if (typeof schemaKeyRef == "string") {
    v = this.getSchema(schemaKeyRef);
    if (!v)
      throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  } else {
    var schemaObj = this._addSchema(schemaKeyRef);
    v = schemaObj.validate || this._compile(schemaObj);
  }
  var valid = v(data2);
  if (v.$async !== true)
    this.errors = v.errors;
  return valid;
}
function compile$1(schema, _meta) {
  var schemaObj = this._addSchema(schema, void 0, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}
function addSchema(schema, key, _skipValidation, _meta) {
  if (Array.isArray(schema)) {
    for (var i = 0; i < schema.length; i++)
      this.addSchema(schema[i], void 0, _skipValidation, _meta);
    return this;
  }
  var id = this._getId(schema);
  if (id !== void 0 && typeof id != "string")
    throw new Error("schema id must be string");
  key = resolve.normalizeId(key || id);
  checkUnique(this, key);
  this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
  return this;
}
function addMetaSchema(schema, key, skipValidation) {
  this.addSchema(schema, key, skipValidation, true);
  return this;
}
function validateSchema(schema, throwOrLogError) {
  var $schema2 = schema.$schema;
  if ($schema2 !== void 0 && typeof $schema2 != "string")
    throw new Error("$schema must be a string");
  $schema2 = $schema2 || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema2) {
    this.logger.warn("meta-schema not available");
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema2, schema);
  if (!valid && throwOrLogError) {
    var message = "schema is invalid: " + this.errorsText();
    if (this._opts.validateSchema == "log")
      this.logger.error(message);
    else
      throw new Error(message);
  }
  return valid;
}
function defaultMeta(self2) {
  var meta = self2._opts.meta;
  self2._opts.defaultMeta = typeof meta == "object" ? self2._getId(meta) || meta : self2.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0;
  return self2._opts.defaultMeta;
}
function getSchema(keyRef) {
  var schemaObj = _getSchemaObj(this, keyRef);
  switch (typeof schemaObj) {
    case "object":
      return schemaObj.validate || this._compile(schemaObj);
    case "string":
      return this.getSchema(schemaObj);
    case "undefined":
      return _getSchemaFragment(this, keyRef);
  }
}
function _getSchemaFragment(self2, ref2) {
  var res = resolve.schema.call(self2, { schema: {} }, ref2);
  if (res) {
    var schema = res.schema, root = res.root, baseId = res.baseId;
    var v = compileSchema.call(self2, schema, root, void 0, baseId);
    self2._fragments[ref2] = new SchemaObject({
      ref: ref2,
      fragment: true,
      schema,
      root,
      baseId,
      validate: v
    });
    return v;
  }
}
function _getSchemaObj(self2, keyRef) {
  keyRef = resolve.normalizeId(keyRef);
  return self2._schemas[keyRef] || self2._refs[keyRef] || self2._fragments[keyRef];
}
function removeSchema(schemaKeyRef) {
  if (schemaKeyRef instanceof RegExp) {
    _removeAllSchemas(this, this._schemas, schemaKeyRef);
    _removeAllSchemas(this, this._refs, schemaKeyRef);
    return this;
  }
  switch (typeof schemaKeyRef) {
    case "undefined":
      _removeAllSchemas(this, this._schemas);
      _removeAllSchemas(this, this._refs);
      this._cache.clear();
      return this;
    case "string":
      var schemaObj = _getSchemaObj(this, schemaKeyRef);
      if (schemaObj)
        this._cache.del(schemaObj.cacheKey);
      delete this._schemas[schemaKeyRef];
      delete this._refs[schemaKeyRef];
      return this;
    case "object":
      var serialize = this._opts.serialize;
      var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
      this._cache.del(cacheKey);
      var id = this._getId(schemaKeyRef);
      if (id) {
        id = resolve.normalizeId(id);
        delete this._schemas[id];
        delete this._refs[id];
      }
  }
  return this;
}
function _removeAllSchemas(self2, schemas, regex2) {
  for (var keyRef in schemas) {
    var schemaObj = schemas[keyRef];
    if (!schemaObj.meta && (!regex2 || regex2.test(keyRef))) {
      self2._cache.del(schemaObj.cacheKey);
      delete schemas[keyRef];
    }
  }
}
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  if (typeof schema != "object" && typeof schema != "boolean")
    throw new Error("schema should be object or boolean");
  var serialize = this._opts.serialize;
  var cacheKey = serialize ? serialize(schema) : schema;
  var cached = this._cache.get(cacheKey);
  if (cached)
    return cached;
  shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
  var id = resolve.normalizeId(this._getId(schema));
  if (id && shouldAddSchema)
    checkUnique(this, id);
  var willValidate = this._opts.validateSchema !== false && !skipValidation;
  var recursiveMeta;
  if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
    this.validateSchema(schema, true);
  var localRefs = resolve.ids.call(this, schema);
  var schemaObj = new SchemaObject({
    id,
    schema,
    localRefs,
    cacheKey,
    meta
  });
  if (id[0] != "#" && shouldAddSchema)
    this._refs[id] = schemaObj;
  this._cache.put(cacheKey, schemaObj);
  if (willValidate && recursiveMeta)
    this.validateSchema(schema, true);
  return schemaObj;
}
function _compile(schemaObj, root) {
  if (schemaObj.compiling) {
    schemaObj.validate = callValidate;
    callValidate.schema = schemaObj.schema;
    callValidate.errors = null;
    callValidate.root = root ? root : callValidate;
    if (schemaObj.schema.$async === true)
      callValidate.$async = true;
    return callValidate;
  }
  schemaObj.compiling = true;
  var currentOpts;
  if (schemaObj.meta) {
    currentOpts = this._opts;
    this._opts = this._metaOpts;
  }
  var v;
  try {
    v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs);
  } catch (e) {
    delete schemaObj.validate;
    throw e;
  } finally {
    schemaObj.compiling = false;
    if (schemaObj.meta)
      this._opts = currentOpts;
  }
  schemaObj.validate = v;
  schemaObj.refs = v.refs;
  schemaObj.refVal = v.refVal;
  schemaObj.root = v.root;
  return v;
  function callValidate() {
    var _validate = schemaObj.validate;
    var result = _validate.apply(this, arguments);
    callValidate.errors = _validate.errors;
    return result;
  }
}
function chooseGetId(opts) {
  switch (opts.schemaId) {
    case "auto":
      return _get$IdOrId;
    case "id":
      return _getId;
    default:
      return _get$Id;
  }
}
function _getId(schema) {
  if (schema.$id)
    this.logger.warn("schema $id ignored", schema.$id);
  return schema.id;
}
function _get$Id(schema) {
  if (schema.id)
    this.logger.warn("schema id ignored", schema.id);
  return schema.$id;
}
function _get$IdOrId(schema) {
  if (schema.$id && schema.id && schema.$id != schema.id)
    throw new Error("schema $id is different from id");
  return schema.$id || schema.id;
}
function errorsText(errors, options) {
  errors = errors || this.errors;
  if (!errors)
    return "No errors";
  options = options || {};
  var separator = options.separator === void 0 ? ", " : options.separator;
  var dataVar = options.dataVar === void 0 ? "data" : options.dataVar;
  var text = "";
  for (var i = 0; i < errors.length; i++) {
    var e = errors[i];
    if (e)
      text += dataVar + e.dataPath + " " + e.message + separator;
  }
  return text.slice(0, -separator.length);
}
function addFormat(name2, format2) {
  if (typeof format2 == "string")
    format2 = new RegExp(format2);
  this._formats[name2] = format2;
  return this;
}
function addDefaultMetaSchema(self2) {
  var $dataSchema;
  if (self2._opts.$data) {
    $dataSchema = require$$12;
    self2.addMetaSchema($dataSchema, $dataSchema.$id, true);
  }
  if (self2._opts.meta === false)
    return;
  var metaSchema2 = require$$13;
  if (self2._opts.$data)
    metaSchema2 = $dataMetaSchema(metaSchema2, META_SUPPORT_DATA);
  self2.addMetaSchema(metaSchema2, META_SCHEMA_ID, true);
  self2._refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
}
function addInitialSchemas(self2) {
  var optsSchemas = self2._opts.schemas;
  if (!optsSchemas)
    return;
  if (Array.isArray(optsSchemas))
    self2.addSchema(optsSchemas);
  else
    for (var key in optsSchemas)
      self2.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self2) {
  for (var name2 in self2._opts.formats) {
    var format2 = self2._opts.formats[name2];
    self2.addFormat(name2, format2);
  }
}
function addInitialKeywords(self2) {
  for (var name2 in self2._opts.keywords) {
    var keyword2 = self2._opts.keywords[name2];
    self2.addKeyword(name2, keyword2);
  }
}
function checkUnique(self2, id) {
  if (self2._schemas[id] || self2._refs[id])
    throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self2) {
  var metaOpts = util.copy(self2._opts);
  for (var i = 0; i < META_IGNORE_OPTIONS.length; i++)
    delete metaOpts[META_IGNORE_OPTIONS[i]];
  return metaOpts;
}
function setLogger(self2) {
  var logger = self2._opts.logger;
  if (logger === false) {
    self2.logger = { log: gosling_es_noop, warn: gosling_es_noop, error: gosling_es_noop };
  } else {
    if (logger === void 0)
      logger = console;
    if (!(typeof logger == "object" && logger.log && logger.warn && logger.error))
      throw new Error("logger must implement log, warn and error methods");
    self2.logger = logger;
  }
}
function gosling_es_noop() {
}
function validateGoslingSpec(spec) {
  return validateSpec(GoslingSchema, spec);
}
function validateSpec(schema, spec, silence = false) {
  const validate2 = new ajv({ extendRefs: true }).compile(schema);
  const valid = validate2(spec);
  let message = "";
  let details = "";
  if (validate2.errors) {
    details = JSON.stringify(validate2.errors, null, 2);
    if (!silence) {
      console.warn(details);
    }
    message = "\u26A0\uFE0F Some properties are incorrectly used.";
  }
  return { state: valid ? "success" : "warn", message, details };
}
function validateTrack(track) {
  let valid = true;
  const errorMessages = [];
  const resolvedTrack = resolveSuperposedTracks(track);
  resolvedTrack.forEach((spec) => {
    if (!getGenomicChannelFromTrack(spec) && spec.mark !== "brush" && spec.mark !== "rule") {
      errorMessages.push("genomic type is not encoded to either a x- or y- axis");
      valid = false;
    }
    const color2 = spec.color;
    if (spec.mark === "line" && IsChannelDeep(color2) && color2.type === "quantitative") {
      errorMessages.push("`line` mark cannot be used with `quantitative` value");
      valid = false;
    }
  });
  return { valid, errorMessages };
}
function getGenomicChannelFromTrack(track) {
  let genomicChannel = void 0;
  ["x", "y", "xe", "ye", "x1", "y1", "x1e", "y1e"].reverse().forEach((channelType) => {
    const channel = track[channelType];
    if (IsChannelDeep(channel) && channel.type === "genomic") {
      genomicChannel = channel;
    }
  });
  return genomicChannel;
}
function getGenomicChannelKeyFromTrack(track) {
  let genomicChannelKey = void 0;
  ["x", "xe", "y", "ye", "x1", "y1", "x1e", "y1e"].reverse().forEach((channelKey) => {
    const channel = track[channelKey];
    if (IsChannelDeep(channel) && channel.type === "genomic") {
      genomicChannelKey = channelKey;
    }
  });
  return genomicChannelKey;
}
const $ref = "#/definitions/HiGlassSpec";
const $schema = "http://json-schema.org/draft-07/schema#";
const definitions = {
  Assembly: {
    "enum": [
      "hg38",
      "hg19",
      "hg18",
      "hg17",
      "hg16",
      "mm10",
      "mm9",
      "unknown"
    ],
    type: "string"
  },
  CombinedTrack: {
    additionalProperties: false,
    properties: {
      contents: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      height: {
        type: "number"
      },
      options: {},
      position: {
        type: "string"
      },
      type: {
        "const": "combined",
        type: "string"
      },
      uid: {
        type: "string"
      },
      width: {
        type: "number"
      }
    },
    required: [
      "type",
      "contents"
    ],
    type: "object"
  },
  Data: {
    additionalProperties: false,
    properties: {
      assembly: {
        $ref: "#/definitions/Assembly"
      },
      children: {
        items: {},
        type: "array"
      },
      filter: {
        items: {
          $ref: "#/definitions/FilterTransform"
        },
        type: "array"
      },
      tiles: {},
      tilesetInfo: {},
      type: {
        type: "string"
      },
      url: {
        type: "string"
      }
    },
    type: "object"
  },
  EnumTrack: {
    additionalProperties: false,
    properties: {
      chromInfoPath: {
        type: "string"
      },
      data: {
        $ref: "#/definitions/Data"
      },
      fromViewUid: {
        type: [
          "null",
          "string"
        ]
      },
      height: {
        type: "number"
      },
      options: {},
      server: {
        type: "string"
      },
      tilesetUid: {
        type: "string"
      },
      type: {
        $ref: "#/definitions/EnumTrackType"
      },
      uid: {
        type: "string"
      },
      width: {
        type: "number"
      },
      x: {
        type: "number"
      },
      y: {
        type: "number"
      }
    },
    required: [
      "type"
    ],
    type: "object"
  },
  EnumTrackType: {
    "enum": [
      "heatmap",
      "2d-annotations",
      "2d-chromosome-annotations",
      "2d-chromosome-grid",
      "2d-chromosome-labels",
      "2d-rectangle-domains",
      "2d-tiles",
      "arrowhead-domains",
      "bedlike",
      "cross-rule",
      "dummy",
      "horizontal-1d-annotations",
      "horizontal-1d-heatmap",
      "horizontal-1d-tiles",
      "horizontal-1d-value-interval",
      "horizontal-2d-rectangle-domains",
      "horizontal-bar",
      "horizontal-chromosome-grid",
      "horizontal-chromosome-labels",
      "horizontal-divergent-bar",
      "horizontal-gene-annotations",
      "horizontal-heatmap",
      "horizontal-line",
      "horizontal-multivec",
      "horizontal-point",
      "horizontal-rule",
      "horizontal-vector-heatmap",
      "image-tiles",
      "left-axis",
      "left-stacked-interval",
      "mapbox-tiles",
      "osm-2d-tile-ids",
      "osm-tiles",
      "raster-tiles",
      "simple-svg",
      "square-markers",
      "top-axis",
      "top-stacked-interval",
      "vertical-1d-annotations",
      "vertical-1d-heatmap",
      "vertical-1d-tiles",
      "vertical-1d-value-interval",
      "vertical-2d-rectangle-domains",
      "vertical-bar",
      "vertical-bedlike",
      "vertical-chromosome-grid",
      "vertical-chromosome-labels",
      "vertical-gene-annotations",
      "vertical-heatmap",
      "vertical-line",
      "vertical-multivec",
      "vertical-point",
      "vertical-rule",
      "vertical-vector-heatmap",
      "viewport-projection-center",
      "viewport-projection-horizontal",
      "viewport-projection-vertical",
      "gosling-track",
      "gosling-2d-track",
      "axis-track",
      "text"
    ],
    type: "string"
  },
  FilterTransform: {
    anyOf: [
      {
        $ref: "#/definitions/OneOfFilter"
      },
      {
        $ref: "#/definitions/RangeFilter"
      },
      {
        $ref: "#/definitions/IncludeFilter"
      }
    ]
  },
  GenericLocks: {
    additionalProperties: false,
    properties: {
      locksByViewUid: {
        $ref: "#/definitions/LocksByViewUid"
      },
      locksDict: {}
    },
    required: [
      "locksByViewUid",
      "locksDict"
    ],
    type: "object"
  },
  GenomePositionSearchBox: {
    additionalProperties: false,
    properties: {
      autocompleteId: {
        type: "string"
      },
      autocompleteServer: {
        type: "string"
      },
      chromInfoId: {
        type: "string"
      },
      chromInfoServer: {
        type: "string"
      },
      visible: {
        type: "boolean"
      }
    },
    required: [
      "chromInfoId",
      "chromInfoServer"
    ],
    type: "object"
  },
  HeatmapTrack: {
    additionalProperties: false,
    properties: {
      data: {
        $ref: "#/definitions/Data"
      },
      height: {
        type: "number"
      },
      options: {},
      position: {
        type: "string"
      },
      server: {
        type: "string"
      },
      tilesetUid: {
        type: "string"
      },
      type: {
        "const": "heatmap",
        type: "string"
      },
      uid: {
        type: "string"
      },
      width: {
        type: "number"
      }
    },
    required: [
      "type"
    ],
    type: "object"
  },
  HiGlassSpec: {
    additionalProperties: false,
    properties: {
      chromInfoPath: {
        type: "string"
      },
      compactLayout: {
        type: "boolean"
      },
      editable: {
        type: "boolean"
      },
      exportViewUrl: {
        type: "string"
      },
      locationLocks: {
        $ref: "#/definitions/GenericLocks"
      },
      trackSourceServers: {
        items: {
          type: "string"
        },
        type: "array"
      },
      tracksEditable: {
        type: "boolean"
      },
      valueScaleLocks: {
        $ref: "#/definitions/ValueScaleLocks"
      },
      viewEditable: {
        type: "boolean"
      },
      views: {
        items: {
          $ref: "#/definitions/View"
        },
        type: "array"
      },
      zoomFixed: {
        type: "boolean"
      },
      zoomLocks: {
        $ref: "#/definitions/GenericLocks"
      }
    },
    required: [
      "views",
      "zoomLocks",
      "locationLocks"
    ],
    type: "object"
  },
  IncludeFilter: {
    additionalProperties: false,
    properties: {
      field: {
        description: "A filter is applied based on the values of the specified data field",
        type: "string"
      },
      include: {
        description: "Check whether the value includes a substring.",
        type: "string"
      },
      not: {
        description: 'when `{"not": true}`, apply a NOT logical operation to the filter.\n\n__Default:__ `false`',
        type: "boolean"
      },
      type: {
        "const": "filter",
        type: "string"
      }
    },
    required: [
      "field",
      "include",
      "type"
    ],
    type: "object"
  },
  IndependentViewportProjectionTrack: {
    additionalProperties: false,
    properties: {
      fromViewUid: {
        type: "null"
      },
      options: {},
      projectionXDomain: {
        items: {
          type: "number"
        },
        type: "array"
      },
      projectionYDomain: {
        items: {
          type: "number"
        },
        type: "array"
      },
      transforms: {
        items: {},
        type: "array"
      },
      type: {
        "enum": [
          "viewport-projection-horizontal",
          "viewport-projection-vertical",
          "viewport-projection-center"
        ],
        type: "string"
      },
      uid: {
        type: "string"
      },
      width: {
        type: "number"
      },
      x: {
        type: "number"
      },
      y: {
        type: "number"
      }
    },
    required: [
      "type"
    ],
    type: "object"
  },
  Layout: {
    additionalProperties: false,
    properties: {
      h: {
        type: "number"
      },
      w: {
        type: "number"
      },
      x: {
        type: "number"
      },
      y: {
        type: "number"
      }
    },
    required: [
      "h",
      "w",
      "x",
      "y"
    ],
    type: "object"
  },
  LocksByViewUid: {
    additionalProperties: {
      type: "string"
    },
    type: "object"
  },
  OneOfFilter: {
    additionalProperties: false,
    properties: {
      field: {
        description: "A filter is applied based on the values of the specified data field",
        type: "string"
      },
      not: {
        description: 'when `{"not": true}`, apply a NOT logical operation to the filter.\n\n__Default:__ `false`',
        type: "boolean"
      },
      oneOf: {
        anyOf: [
          {
            items: {
              type: "string"
            },
            type: "array"
          },
          {
            items: {
              type: "number"
            },
            type: "array"
          }
        ],
        description: "Check whether the value is an element in the provided list."
      },
      type: {
        "const": "filter",
        type: "string"
      }
    },
    required: [
      "field",
      "oneOf",
      "type"
    ],
    type: "object"
  },
  Overlay: {
    additionalProperties: false,
    properties: {
      chromInfoPath: {
        type: "string"
      },
      includes: {
        items: {},
        type: "array"
      },
      options: {
        $ref: "#/definitions/OverlayOptions"
      },
      type: {
        type: "string"
      },
      uid: {
        type: "string"
      }
    },
    type: "object"
  },
  OverlayOptions: {
    additionalProperties: false,
    properties: {
      extent: {
        items: {},
        type: "array"
      },
      fill: {
        type: "string"
      },
      fillOpacity: {
        type: "number"
      },
      minWidth: {
        type: "number"
      },
      outline: {
        type: "string"
      },
      outlineOpacity: {
        type: "number"
      },
      outlinePos: {
        anyOf: [
          {
            items: {},
            type: "array"
          },
          {
            type: "string"
          }
        ]
      },
      outlineWidth: {
        type: "number"
      },
      stroke: {
        type: "string"
      },
      strokeOpacity: {
        type: "number"
      },
      strokePos: {
        anyOf: [
          {
            items: {},
            type: "array"
          },
          {
            type: "string"
          }
        ]
      },
      strokeWidth: {
        type: "number"
      }
    },
    type: "object"
  },
  RangeFilter: {
    additionalProperties: false,
    properties: {
      field: {
        description: "A filter is applied based on the values of the specified data field",
        type: "string"
      },
      inRange: {
        description: "Check whether the value is in a number range.",
        items: {
          type: "number"
        },
        type: "array"
      },
      not: {
        description: 'when `{"not": true}`, apply a NOT logical operation to the filter.\n\n__Default:__ `false`',
        type: "boolean"
      },
      type: {
        "const": "filter",
        type: "string"
      }
    },
    required: [
      "field",
      "inRange",
      "type"
    ],
    type: "object"
  },
  Track: {
    anyOf: [
      {
        $ref: "#/definitions/HeatmapTrack"
      },
      {
        $ref: "#/definitions/CombinedTrack"
      },
      {
        $ref: "#/definitions/IndependentViewportProjectionTrack"
      },
      {
        $ref: "#/definitions/EnumTrack"
      }
    ]
  },
  Tracks: {
    additionalProperties: false,
    properties: {
      bottom: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      center: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      gallery: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      left: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      right: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      top: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      },
      whole: {
        items: {
          $ref: "#/definitions/Track"
        },
        type: "array"
      }
    },
    required: [
      "top",
      "left",
      "center",
      "right",
      "bottom",
      "gallery",
      "whole"
    ],
    type: "object"
  },
  ValueScaleLocks: {
    additionalProperties: false,
    properties: {
      locksByViewUid: {
        $ref: "#/definitions/LocksByViewUid"
      },
      locksDict: {}
    },
    required: [
      "locksByViewUid"
    ],
    type: "object"
  },
  View: {
    additionalProperties: false,
    properties: {
      autocompleteSource: {
        type: "string"
      },
      chromInfoPath: {
        type: "string"
      },
      genomePositionSearchBox: {
        $ref: "#/definitions/GenomePositionSearchBox"
      },
      genomePositionSearchBoxVisible: {
        type: "boolean"
      },
      initialXDomain: {
        items: {
          type: "number"
        },
        type: "array"
      },
      initialYDomain: {
        items: {
          type: "number"
        },
        type: "array"
      },
      layout: {
        $ref: "#/definitions/Layout"
      },
      overlays: {
        items: {
          $ref: "#/definitions/Overlay"
        },
        type: "array"
      },
      selectionView: {
        type: "boolean"
      },
      tracks: {
        $ref: "#/definitions/Tracks"
      },
      uid: {
        type: "string"
      },
      zoomFixed: {
        type: "boolean"
      },
      zoomLimits: {
        items: [
          {
            type: [
              "number",
              "null"
            ]
          },
          {
            type: [
              "number",
              "null"
            ]
          }
        ],
        maxItems: 2,
        minItems: 2,
        type: "array"
      }
    },
    required: [
      "tracks",
      "layout"
    ],
    type: "object"
  }
};
var HiGlassSchema = {
  $ref,
  $schema,
  definitions
};
function getNumericDomain(domain, assembly) {
  if ("chromosome" in domain) {
    if (domain.chromosome.includes("chr")) {
      domain.chromosome = domain.chromosome.replace("chr", "");
    }
    if (!Object.keys(GET_CHROM_SIZES().interval).find((chr) => chr === `chr${domain.chromosome}`)) {
      domain.chromosome = "1";
    }
  }
  if (IsDomainChr(domain)) {
    return [
      GET_CHROM_SIZES(assembly).interval[`chr${domain.chromosome}`][0] + 1,
      GET_CHROM_SIZES(assembly).interval[`chr${domain.chromosome}`][1]
    ];
  } else if (IsDomainInterval(domain)) {
    return domain.interval;
  } else if (IsDomainChrInterval(domain)) {
    const chrStart = GET_CHROM_SIZES(assembly).interval[`chr${domain.chromosome}`][0];
    const [start, end] = domain.interval;
    return [chrStart + start, chrStart + end];
  } else
    ;
}
function shareScaleAcrossTracks(trackModels, force) {
  const globalDomain = {};
  const channelKeys = SUPPORTED_CHANNELS;
  trackModels.forEach((model) => {
    channelKeys.forEach((channelKey) => {
      const channel = model.spec()[channelKey];
      if (!IsChannelDeep(channel) || channel.domain === void 0) {
        return;
      }
      const { domain, type: type2 } = channel;
      if (type2 === "quantitative") {
        const numericDomain = Array.from(domain);
        if (!globalDomain[channelKey]) {
          globalDomain[channelKey] = numericDomain;
        } else {
          if (globalDomain[channelKey][0] > numericDomain[0]) {
            globalDomain[channelKey][0] = numericDomain[0];
          }
          if (globalDomain[channelKey][1] < numericDomain[1]) {
            globalDomain[channelKey][1] = numericDomain[1];
          }
        }
      } else if (type2 === "nominal") {
        const nominalDomain = Array.from(domain);
        if (!globalDomain[channelKey]) {
          globalDomain[channelKey] = nominalDomain;
        } else {
          globalDomain[channelKey] = Array.from(new Set([...globalDomain[channelKey], ...nominalDomain]));
        }
      }
    });
  });
  trackModels.forEach((model) => {
    channelKeys.forEach((channelKey) => {
      const channel = model.spec()[channelKey];
      if (IsChannelDeep(channel) && channel.type === "genomic")
        return;
      model.setChannelDomain(channelKey, globalDomain[channelKey], force);
      model.generateScales();
    });
    model.updateChannelValue();
  });
}
const example = {
  compactLayout: false,
  trackSourceServers: ["https://server.gosling-lang.org/api/v1/"],
  views: [
    {
      genomePositionSearchBoxVisible: false,
      genomePositionSearchBox: {
        autocompleteServer: "https://higlass.io/api/v1",
        autocompleteId: "P0PLbQMwTYGy-5uPIQid7A",
        chromInfoServer: "https://higlass.io/api/v1",
        chromInfoId: "hg38"
      },
      layout: { x: 0, y: 0, w: 6.4, h: 600 },
      tracks: {
        top: [],
        left: [
          {
            type: "combined",
            width: 130,
            height: 600,
            contents: [
              {
                type: "gosling-track",
                server: "https://server.gosling-lang.org/api/v1/",
                tilesetUid: "cistrome-multivec",
                width: 130,
                height: 600,
                options: {
                  showMousePosition: true,
                  mousePositionColor: "#000000",
                  fontSize: 24,
                  labelPosition: "none",
                  labelShowResolution: false,
                  labelColor: "black",
                  labelBackgroundColor: "white",
                  labelTextOpacity: 1,
                  labelLeftMargin: 1,
                  labelTopMargin: 1,
                  labelRightMargin: 0,
                  labelBottomMargin: 0,
                  backgroundColor: "transparent",
                  spec: {
                    spacing: 10,
                    orientation: "vertical",
                    assembly: "hg38",
                    layout: "linear",
                    static: false,
                    xDomain: { interval: [0, 1e9] },
                    centerRadius: 0.3,
                    xOffset: 0,
                    yOffset: 0,
                    style: { outlineWidth: 0.5 },
                    data: {
                      url: "https://server.gosling-lang.org/api/v1/tileset_info/?d=cistrome-multivec",
                      type: "multivec",
                      row: "sample",
                      column: "position",
                      value: "peak",
                      categories: ["sample 1", "sample 2", "sample 3", "sample 4"],
                      binSize: 4
                    },
                    mark: "rect",
                    x: {
                      field: "start",
                      type: "genomic",
                      axis: "left",
                      domain: { interval: [0, 1e9] },
                      linkingId: "7f94b74e-25ec-4e67-8c75-3dc0f1b0d6bd"
                    },
                    xe: { field: "end", type: "genomic" },
                    row: {
                      field: "sample",
                      type: "nominal",
                      legend: true
                    },
                    color: {
                      field: "peak",
                      type: "quantitative",
                      legend: true
                    },
                    tooltip: [
                      {
                        field: "start",
                        type: "genomic",
                        alt: "Start Position"
                      },
                      {
                        field: "end",
                        type: "genomic",
                        alt: "End Position"
                      },
                      {
                        field: "peak",
                        type: "quantitative",
                        alt: "Value",
                        format: ".2"
                      },
                      { field: "sample", type: "nominal", alt: "Sample" }
                    ],
                    width: 160,
                    height: 600,
                    overlayOnPreviousTrack: false
                  },
                  theme: {
                    base: "light",
                    root: {
                      background: "white",
                      titleColor: "black",
                      titleBackgroundColor: "transparent",
                      titleFontSize: 18,
                      titleFontFamily: "Arial",
                      titleAlign: "left",
                      titleFontWeight: "bold",
                      subtitleColor: "gray",
                      subtitleBackgroundColor: "transparent",
                      subtitleFontSize: 16,
                      subtitleFontFamily: "Arial",
                      subtitleFontWeight: "normal",
                      subtitleAlign: "left",
                      mousePositionColor: "#000000"
                    },
                    track: {
                      background: "transparent",
                      alternatingBackground: "transparent",
                      titleColor: "black",
                      titleBackground: "white",
                      titleFontSize: 24,
                      titleAlign: "left",
                      outline: "black",
                      outlineWidth: 1
                    },
                    legend: {
                      position: "top",
                      background: "white",
                      backgroundOpacity: 0.7,
                      labelColor: "black",
                      labelFontSize: 12,
                      labelFontWeight: "normal",
                      labelFontFamily: "Arial",
                      backgroundStroke: "#DBDBDB",
                      tickColor: "black"
                    },
                    axis: {
                      tickColor: "black",
                      labelColor: "black",
                      labelFontSize: 12,
                      labelFontWeight: "normal",
                      labelFontFamily: "Arial",
                      baselineColor: "black",
                      gridColor: "#E3E3E3",
                      gridStrokeWidth: 1,
                      gridStrokeType: "solid",
                      gridStrokeDash: [4, 4]
                    },
                    markCommon: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    point: {
                      color: "#E79F00",
                      size: 3,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    rect: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    triangle: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    area: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    line: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    bar: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    rule: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 1,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    link: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 1,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    text: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6],
                      textAnchor: "middle",
                      textFontWeight: "normal"
                    },
                    brush: {
                      color: "gray",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 1,
                      opacity: 0.3,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    }
                  }
                }
              }
            ]
          },
          {
            uid: "15483511-f6fb-11eb-914b-976b6ecda162",
            type: "axis-track",
            chromInfoPath: "https://s3.amazonaws.com/gosling-lang.org/data/hg38.chrom.sizes",
            options: {
              layout: "linear",
              outerRadius: null,
              width: 160,
              height: 600,
              theme: {
                base: "light",
                root: {
                  background: "white",
                  titleColor: "black",
                  titleBackgroundColor: "transparent",
                  titleFontSize: 18,
                  titleFontFamily: "Arial",
                  titleAlign: "left",
                  titleFontWeight: "bold",
                  subtitleColor: "gray",
                  subtitleBackgroundColor: "transparent",
                  subtitleFontSize: 16,
                  subtitleFontFamily: "Arial",
                  subtitleFontWeight: "normal",
                  subtitleAlign: "left",
                  mousePositionColor: "#000000"
                },
                track: {
                  background: "transparent",
                  alternatingBackground: "transparent",
                  titleColor: "black",
                  titleBackground: "white",
                  titleFontSize: 24,
                  titleAlign: "left",
                  outline: "black",
                  outlineWidth: 1
                },
                legend: {
                  position: "top",
                  background: "white",
                  backgroundOpacity: 0.7,
                  labelColor: "black",
                  labelFontSize: 12,
                  labelFontWeight: "normal",
                  labelFontFamily: "Arial",
                  backgroundStroke: "#DBDBDB",
                  tickColor: "black"
                },
                axis: {
                  tickColor: "black",
                  labelColor: "black",
                  labelFontSize: 12,
                  labelFontWeight: "normal",
                  labelFontFamily: "Arial",
                  baselineColor: "black",
                  gridColor: "#E3E3E3",
                  gridStrokeWidth: 1,
                  gridStrokeType: "solid",
                  gridStrokeDash: [4, 4]
                },
                markCommon: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                point: {
                  color: "#E79F00",
                  size: 3,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                rect: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                triangle: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                area: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                line: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                bar: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                rule: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 1,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                link: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 1,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                },
                text: {
                  color: "#E79F00",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 0,
                  opacity: 1,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6],
                  textAnchor: "middle",
                  textFontWeight: "normal"
                },
                brush: {
                  color: "gray",
                  size: 1,
                  stroke: "black",
                  strokeWidth: 1,
                  opacity: 0.3,
                  nominalColorRange: [
                    "#E79F00",
                    "#029F73",
                    "#0072B2",
                    "#CB7AA7",
                    "#D45E00",
                    "#57B4E9",
                    "#EFE441"
                  ],
                  quantitativeSizeRange: [2, 6]
                }
              },
              assembly: "hg38",
              stroke: "transparent",
              color: "black",
              fontSize: 12,
              fontFamily: "Arial",
              fontWeight: "normal",
              tickColor: "black",
              tickFormat: "plain",
              tickPositions: "even",
              reverseOrientation: false
            },
            width: 30
          }
        ],
        center: [],
        right: [],
        bottom: [],
        gallery: [],
        whole: []
      },
      initialXDomain: [0, 1e9],
      initialYDomain: [0, 1e9],
      zoomFixed: false,
      zoomLimits: [1, null],
      uid: "15483510-f6fb-11eb-914b-976b6ecda162",
      chromInfoPath: "https://s3.amazonaws.com/gosling-lang.org/data/hg38.chrom.sizes"
    },
    {
      genomePositionSearchBoxVisible: false,
      genomePositionSearchBox: {
        autocompleteServer: "https://higlass.io/api/v1",
        autocompleteId: "P0PLbQMwTYGy-5uPIQid7A",
        chromInfoServer: "https://higlass.io/api/v1",
        chromInfoId: "hg38"
      },
      layout: { x: 6.8, y: 0, w: 5.2, h: 600 },
      tracks: {
        top: [],
        left: [
          {
            type: "combined",
            width: 130,
            height: 600,
            contents: [
              {
                type: "gosling-track",
                server: "https://server.gosling-lang.org/api/v1/",
                tilesetUid: "cistrome-multivec",
                width: 130,
                height: 600,
                options: {
                  showMousePosition: true,
                  mousePositionColor: "#000000",
                  fontSize: 24,
                  labelPosition: "none",
                  labelShowResolution: false,
                  labelColor: "black",
                  labelBackgroundColor: "white",
                  labelTextOpacity: 1,
                  labelLeftMargin: 1,
                  labelTopMargin: 1,
                  labelRightMargin: 0,
                  labelBottomMargin: 0,
                  backgroundColor: "transparent",
                  spec: {
                    spacing: 10,
                    orientation: "vertical",
                    assembly: "hg38",
                    layout: "linear",
                    static: false,
                    xDomain: { interval: [0, 1e9] },
                    centerRadius: 0.3,
                    xOffset: 0,
                    yOffset: 0,
                    style: { outlineWidth: 0.5 },
                    data: {
                      url: "https://server.gosling-lang.org/api/v1/tileset_info/?d=cistrome-multivec",
                      type: "multivec",
                      row: "sample",
                      column: "position",
                      value: "peak",
                      categories: ["sample 1", "sample 2", "sample 3", "sample 4"],
                      binSize: 4
                    },
                    mark: "rect",
                    x: {
                      field: "start",
                      type: "genomic",
                      domain: { interval: [0, 1e9] },
                      linkingId: "7f94b74e-25ec-4e67-8c75-3dc0f1b0d6bd"
                    },
                    xe: { field: "end", type: "genomic" },
                    row: {
                      field: "sample",
                      type: "nominal",
                      legend: true
                    },
                    color: {
                      field: "peak",
                      type: "quantitative",
                      legend: true
                    },
                    tooltip: [
                      {
                        field: "start",
                        type: "genomic",
                        alt: "Start Position"
                      },
                      {
                        field: "end",
                        type: "genomic",
                        alt: "End Position"
                      },
                      {
                        field: "peak",
                        type: "quantitative",
                        alt: "Value",
                        format: ".2"
                      },
                      { field: "sample", type: "nominal", alt: "Sample" }
                    ],
                    width: 130,
                    height: 600
                  },
                  theme: {
                    base: "light",
                    root: {
                      background: "white",
                      titleColor: "black",
                      titleBackgroundColor: "transparent",
                      titleFontSize: 18,
                      titleFontFamily: "Arial",
                      titleAlign: "left",
                      titleFontWeight: "bold",
                      subtitleColor: "gray",
                      subtitleBackgroundColor: "transparent",
                      subtitleFontSize: 16,
                      subtitleFontFamily: "Arial",
                      subtitleFontWeight: "normal",
                      subtitleAlign: "left",
                      mousePositionColor: "#000000"
                    },
                    track: {
                      background: "transparent",
                      alternatingBackground: "transparent",
                      titleColor: "black",
                      titleBackground: "white",
                      titleFontSize: 24,
                      titleAlign: "left",
                      outline: "black",
                      outlineWidth: 1
                    },
                    legend: {
                      position: "top",
                      background: "white",
                      backgroundOpacity: 0.7,
                      labelColor: "black",
                      labelFontSize: 12,
                      labelFontWeight: "normal",
                      labelFontFamily: "Arial",
                      backgroundStroke: "#DBDBDB",
                      tickColor: "black"
                    },
                    axis: {
                      tickColor: "black",
                      labelColor: "black",
                      labelFontSize: 12,
                      labelFontWeight: "normal",
                      labelFontFamily: "Arial",
                      baselineColor: "black",
                      gridColor: "#E3E3E3",
                      gridStrokeWidth: 1,
                      gridStrokeType: "solid",
                      gridStrokeDash: [4, 4]
                    },
                    markCommon: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    point: {
                      color: "#E79F00",
                      size: 3,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    rect: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    triangle: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    area: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    line: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    bar: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    rule: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 1,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    link: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 1,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    },
                    text: {
                      color: "#E79F00",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 0,
                      opacity: 1,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6],
                      textAnchor: "middle",
                      textFontWeight: "normal"
                    },
                    brush: {
                      color: "gray",
                      size: 1,
                      stroke: "black",
                      strokeWidth: 1,
                      opacity: 0.3,
                      nominalColorRange: [
                        "#E79F00",
                        "#029F73",
                        "#0072B2",
                        "#CB7AA7",
                        "#D45E00",
                        "#57B4E9",
                        "#EFE441"
                      ],
                      quantitativeSizeRange: [2, 6]
                    }
                  }
                }
              }
            ]
          }
        ],
        center: [],
        right: [],
        bottom: [],
        gallery: [],
        whole: []
      },
      initialXDomain: [0, 1e9],
      initialYDomain: [0, 1e9],
      zoomFixed: false,
      zoomLimits: [1, null],
      uid: "154b1b40-f6fb-11eb-914b-976b6ecda162"
    }
  ],
  zoomLocks: { locksByViewUid: {}, locksDict: {} },
  locationLocks: { locksByViewUid: {}, locksDict: {} },
  editable: false,
  chromInfoPath: "https://s3.amazonaws.com/gosling-lang.org/data/hg38.chrom.sizes"
};
function insertItemToArray(array, index, item) {
  if (!array)
    array = [];
  return [...array.slice(0, index), item, ...array.slice(index)];
}
const HIGLASS_AXIS_SIZE = 30;
const getViewTemplate = (assembly) => {
  return {
    genomePositionSearchBoxVisible: false,
    genomePositionSearchBox: {
      autocompleteServer: "https://higlass.io/api/v1",
      autocompleteId: "P0PLbQMwTYGy-5uPIQid7A",
      chromInfoServer: "https://higlass.io/api/v1",
      chromInfoId: assembly != null ? assembly : "hg38"
    },
    layout: { w: 12, h: 12, x: 0, y: 0 },
    tracks: {
      top: [],
      left: [],
      center: [],
      right: [],
      bottom: [],
      gallery: [],
      whole: []
    },
    initialXDomain: [0, GET_CHROM_SIZES(assembly).total],
    initialYDomain: [0, GET_CHROM_SIZES(assembly).total],
    zoomFixed: false
  };
};
class HiGlassModel {
  constructor() {
    this.assembly = "hg38";
    this.hg = {
      compactLayout: false,
      trackSourceServers: [],
      views: [],
      zoomLocks: {
        locksByViewUid: {},
        locksDict: {}
      },
      locationLocks: {
        locksByViewUid: {},
        locksDict: {}
      }
    };
    this.setEditable(false);
  }
  spec() {
    return this.hg;
  }
  setViewOrientation(orientation) {
    this.orientation = orientation;
    return this;
  }
  addDefaultView(uid, assembly) {
    this.hg.views.push(JSON.parse(JSON.stringify({ ...getViewTemplate(assembly), uid })));
    return this;
  }
  setAssembly(assembly) {
    this.assembly = assembly;
    this.setChromInfoPath(GET_CHROM_SIZES(this.assembly).path);
    return this;
  }
  getAssembly() {
    return this.assembly;
  }
  setTextTrack(width, height, text, textColor = "black", fontSize = 14, fontWeight = "normal", align = "left", backgroundColor = "transparent", fontFamily = "Arial") {
    var _a;
    if (this.getLastView()) {
      (_a = this.getLastView().tracks.top) == null ? void 0 : _a.push({
        type: "text",
        width,
        height,
        options: {
          backgroundColor,
          textColor,
          fontSize,
          fontWeight,
          fontFamily,
          offsetY: 0,
          align,
          text
        }
      });
    }
    return this;
  }
  addBrush(layout, viewId, theme, fromViewUid, style) {
    var _a, _b, _c, _d, _e, _f;
    if (!fromViewUid)
      return;
    (_f = this.getView(viewId)) == null ? void 0 : _f.tracks.whole.push({
      type: layout === "circular" ? "brush-track" : "viewport-projection-horizontal",
      uid: v4(),
      fromViewUid,
      options: {
        projectionFillColor: (_a = style == null ? void 0 : style.color) != null ? _a : theme.brush.color,
        projectionStrokeColor: (_b = style == null ? void 0 : style.stroke) != null ? _b : theme.brush.stroke,
        projectionFillOpacity: (_c = style == null ? void 0 : style.opacity) != null ? _c : theme.brush.opacity,
        projectionStrokeOpacity: (_d = style == null ? void 0 : style.opacity) != null ? _d : theme.brush.opacity,
        strokeWidth: (_e = style == null ? void 0 : style.strokeWidth) != null ? _e : theme.brush.strokeWidth,
        startAngle: style == null ? void 0 : style.startAngle,
        endAngle: style == null ? void 0 : style.endAngle,
        innerRadius: style == null ? void 0 : style.innerRadius,
        outerRadius: style == null ? void 0 : style.outerRadius
      }
    });
    return this;
  }
  getLastView() {
    return this.hg.views[this.hg.views.length - 1];
  }
  getMainTrackPosition() {
    return this.orientation === "vertical" ? "left" : "center";
  }
  getLastVisView() {
    const vs = this.hg.views.filter((v) => {
      var _a, _b;
      return ((_b = (_a = v.tracks[this.getMainTrackPosition()]) == null ? void 0 : _a[0]) == null ? void 0 : _b.type) === "combined";
    });
    return vs[vs.length - 1];
  }
  getView(viewId) {
    return this.hg.views.find((d) => d.uid === viewId);
  }
  validateSpec(silence = false) {
    return validateSpec(HiGlassSchema, this.spec(), silence).state === "success";
  }
  setDomain(xDomain, yDomain) {
    if (xDomain) {
      this.getLastView().initialXDomain = getNumericDomain(xDomain, this.getAssembly());
    }
    if (yDomain) {
      this.getLastView().initialYDomain = getNumericDomain(yDomain, this.getAssembly());
    }
    return this;
  }
  adjustDomain(orientation = "horizontal", width, height) {
    if (orientation !== "vertical") {
      return this;
    }
    const domain = this.getLastView().initialXDomain;
    if (!domain) {
      return this;
    }
    const [start, end] = domain;
    const size = end - start;
    const center = (start + end) / 2;
    this.getLastView().initialXDomain = [
      center - size / width / 2 / height * width,
      center + size / width / 2 / height * width
    ];
    return this;
  }
  setZoomFixed(zoomFixed) {
    this.getLastView().zoomFixed = zoomFixed;
    return this;
  }
  setZoomLimits(zoomLimits) {
    this.getLastView().zoomLimits = zoomLimits;
    return this;
  }
  setLayout(layout) {
    this.getLastView().layout = layout;
    return this;
  }
  setEditable(editable) {
    this.hg.editable = editable;
    return this;
  }
  setChromInfoPath(chromInfoPath) {
    if (this.getLastView()) {
      this.getLastView().chromInfoPath = chromInfoPath;
    }
    this.hg.chromInfoPath = chromInfoPath;
    return this;
  }
  addTrackSourceServers(trackSourceServers) {
    var _a, _b;
    if (trackSourceServers && ((_a = this.hg.trackSourceServers) == null ? void 0 : _a.indexOf(trackSourceServers)) === -1)
      (_b = this.hg.trackSourceServers) == null ? void 0 : _b.push(trackSourceServers);
    return this;
  }
  setMainTrack(track) {
    var _a;
    if (!this.getLastView())
      return this;
    this.getLastView().tracks[this.getMainTrackPosition()] = [
      {
        type: "combined",
        uid: `${(_a = track.uid) != null ? _a : v4()}-${this.getMainTrackPosition()}-combined`,
        width: track.width - 1,
        height: track.height,
        contents: [track]
      }
    ];
    return this;
  }
  addTrackToCombined(track) {
    var _a;
    if (!this.getLastVisView())
      return this;
    (_a = this.getLastVisView().tracks[this.getMainTrackPosition()][0]) == null ? void 0 : _a.contents.push(track);
    return this;
  }
  setAxisTrack(position, type2 = "regular", options) {
    var _a;
    if (!this.hg.views)
      return this;
    const widthOrHeight = position === "left" || position === "right" ? "width" : "height";
    const axisTrackTemplate = {
      uid: (_a = options.id) != null ? _a : v1(),
      type: "axis-track",
      chromInfoPath: this.hg.chromInfoPath,
      options: {
        ...options,
        assembly: this.getAssembly(),
        stroke: "transparent",
        color: options.theme.axis.labelColor,
        fontSize: options.theme.axis.labelFontSize,
        fontFamily: options.theme.axis.labelFontFamily,
        fontWeight: options.theme.axis.labelFontWeight,
        tickColor: options.theme.axis.tickColor,
        tickFormat: type2 === "narrower" ? "si" : "plain",
        tickPositions: type2 === "regular" ? "even" : "ends",
        reverseOrientation: position === "bottom" || position === "right" ? true : false
      }
    };
    if (options.layout === "circular") {
      this.addTrackToCombined({
        ...axisTrackTemplate,
        options: { ...axisTrackTemplate.options, layout: "circular" }
      });
    } else {
      const axisTrack = { ...axisTrackTemplate, [widthOrHeight]: HIGLASS_AXIS_SIZE };
      if (position === "left") {
        if (this.getLastView().tracks.left.filter((d) => d.type === "axis-track").length !== 0) {
          return this;
        }
        this.getLastView().tracks.left = insertItemToArray(this.getLastView().tracks.left, 0, axisTrack);
      } else if (position === "right") {
        if (this.getLastView().tracks.right.filter((d) => d.type === "axis-track").length !== 0) {
          return this;
        }
        this.getLastView().tracks.right.push(axisTrack);
      } else {
        if (this.getLastView().tracks[position].filter((d) => d.type === "axis-track").length !== 0) {
          return this;
        }
        this.getLastView().tracks[position].push(axisTrack);
      }
    }
    return this;
  }
  setExampleHiglassViewConfig() {
    this.hg = example;
  }
}
function logicalComparison(value, op, ref2, transitionPadding) {
  const padding = transitionPadding && transitionPadding !== 0 ? transitionPadding : void 0;
  let alpha = 0;
  switch (op) {
    case "less-than":
    case "LT":
    case "lt":
      alpha = ref2 > value ? padding ? (ref2 - value) / padding : 1 : 0;
      break;
    case "less-than-or-equal-to":
    case "LTET":
    case "ltet":
      alpha = ref2 >= value ? padding ? (ref2 - value) / padding : 1 : 0;
      break;
    case "greater-than":
    case "GT":
    case "gt":
      alpha = ref2 < value ? padding ? (value - ref2) / padding : 1 : 0;
      break;
    case "greater-than-or-equal-to":
    case "GTET":
    case "gtet":
      alpha = ref2 <= value ? padding ? (value - ref2) / padding : 1 : 0;
      break;
  }
  return Math.max(Math.min(1, alpha), 0);
}
const CHANNEL_DEFAULTS = {
  NOMINAL_COLOR: ["#E79F00", "#029F73", "#0072B2", "#CB7AA7", "#D45E00", "#57B4E9", "#EFE441"],
  NOMINAL_COLOR_EXTENDED: [
    "#d60000",
    "#018700",
    "#b500ff",
    "#05acc6",
    "#97ff00",
    "#ffa52f",
    "#ff8ec8",
    "#79525e",
    "#00fdcf",
    "#afa5ff",
    "#93ac83",
    "#9a6900",
    "#366962",
    "#d3008c",
    "#fdf490",
    "#c86e66",
    "#9ee2ff",
    "#00c846",
    "#a877ac",
    "#b8ba01",
    "#f4bfb1",
    "#ff28fd",
    "#f2cdff",
    "#009e7c",
    "#ff6200",
    "#56642a",
    "#953f1f",
    "#90318e",
    "#ff3464",
    "#a0e491",
    "#8c9ab1",
    "#829026",
    "#ae083f",
    "#77c6ba",
    "#bc9157",
    "#e48eff",
    "#72b8ff",
    "#c6a5c1",
    "#ff9070",
    "#d3c37c",
    "#bceddb",
    "#6b8567",
    "#916e56",
    "#f9ff00",
    "#bac1df",
    "#ac567c",
    "#ffcd03",
    "#ff49b1",
    "#c15603",
    "#5d8c90",
    "#c144bc",
    "#00753f",
    "#ba6efd",
    "#00d493",
    "#00ff75",
    "#49a150",
    "#cc9790",
    "#00ebed",
    "#db7e01",
    "#f77589",
    "#b89500",
    "#c84248",
    "#00cff9",
    "#755726",
    "#85d401",
    "#ebffd4",
    "#a77b87",
    "#db72c8",
    "#cae256",
    "#8abf5d",
    "#a1216b",
    "#855b89",
    "#89bacf",
    "#ffbad6",
    "#b6cfaa",
    "#97414d",
    "#67aa00",
    "#fde1b1",
    "#ff3628",
    "#80793d",
    "#d6e8ff",
    "#a795c6",
    "#7ea59a",
    "#d182a3",
    "#54823b",
    "#e6a872",
    "#9cffff",
    "#da5480",
    "#05b3aa",
    "#ffaaf6",
    "#d1afef",
    "#da015d",
    "#ac1a13",
    "#60b385",
    "#d442fd",
    "#acaa59",
    "#fb9ca7",
    "#b3723b",
    "#f26952",
    "#aed1d4",
    "#9affc3",
    "#dbb333",
    "#eb01c3",
    "#9900c4",
    "#cfff9e",
    "#a55949",
    "#3b6d01",
    "#008579",
    "#959167",
    "#89dbb3",
    "#6d7400",
    "#aa5dca",
    "#07ef00",
    "#804f3d",
    "#d88052",
    "#ffc862",
    "#b8009e",
    "#99acdd",
    "#904f00",
    "#8c4470",
    "#4f6e52",
    "#ff8734",
    "#c68ecd",
    "#d4e29e",
    "#b1826d",
    "#9cfb75",
    "#56dd77",
    "#f90087",
    "#a1cdff",
    "#13cad1",
    "#118e54",
    "#d154a5",
    "#00dfc3",
    "#a3832f",
    "#77975b",
    "#baaa80",
    "#70a3af",
    "#d6fbff",
    "#e8013a",
    "#d84621",
    "#ff82ed",
    "#b63862",
    "#b6cd72",
    "#97626b",
    "#897490",
    "#00a316",
    "#00f4a1",
    "#bf90f2",
    "#89e4d8",
    "#a34d95",
    "#6e5d00",
    "#8cc68e",
    "#95aa2a",
    "#c672dd",
    "#b33b01",
    "#d69a36",
    "#dfacb6",
    "#009aa0",
    "#599000",
    "#97bca8",
    "#ac8ca8",
    "#dad4ff",
    "#547c72",
    "#00ba69",
    "#ffc38e",
    "#b800d4",
    "#dfcf5b",
    "#629a7b",
    "#bfedbc",
    "#c1bdfd",
    "#80d3dd",
    "#e2857e",
    "#f9eb4d",
    "#bf6d82",
    "#caff4f",
    "#ef72aa",
    "#ed67ff",
    "#9946ae",
    "#6d6942",
    "#e25660",
    "#dd662d",
    "#9cdb5d",
    "#e29ccf",
    "#b87500",
    "#c6002d",
    "#dfbcda",
    "#59b5df",
    "#ff59da",
    "#38c1a1",
    "#9e698c",
    "#acaac8",
    "#95622f",
    "#b55662",
    "#2b7e60",
    "#b1e400",
    "#eda590",
    "#95fde2",
    "#ff548e",
    "#bd6ea1",
    "#aa3b36",
    "#d8cf00",
    "#aa80cd",
    "#a08052",
    "#e100e8",
    "#c35b3d",
    "#b53a85",
    "#8c7700",
    "#dbbc95",
    "#529e93",
    "#afbc82",
    "#91b5b6",
    "#a75423",
    "#ffd4ef",
    "#79ae6b",
    "#5db54b",
    "#80fb9a",
    "#48ffef",
    "#979548",
    "#9387a7",
    "#31d400",
    "#6ee956",
    "#b6d4eb",
    "#705470",
    "#f2db8a",
    "#aad4c1",
    "#7ecdf2",
    "#89ba00",
    "#64b6ba",
    "#ffb500",
    "#c38285",
    "#caaa5e",
    "#647748",
    "#59e2ff",
    "#df4dcd",
    "#e9ff79",
    "#bc66b8",
    "#c395a5",
    "#64c674",
    "#d19570",
    "#70cf4f",
    "#aa6e66",
    "#9c60a5",
    "#00b800",
    "#e299b3",
    "#bc006b",
    "#b3e8ef",
    "#cdbfe4",
    "#77a342",
    "#856277",
    "#568e5b",
    "#9eafc4",
    "#e82fa0",
    "#247c2a",
    "#826723",
    "#bfbc4d",
    "#ddd3a5"
  ],
  QUANTITATIVE_COLOR: "viridis",
  SIZE: 3,
  SIZE_RANGE: [2, 6]
};
var Themes;
(function(Themes2) {
  Themes2["light"] = "light";
  Themes2["dark"] = "dark";
})(Themes || (Themes = {}));
function getTheme(theme = "light") {
  if (typeof theme === "string") {
    if (v(theme)) {
      return O(theme);
    } else if (theme === "dark" || theme === "light") {
      return THEMES[theme];
    } else {
      return THEMES["light"];
    }
  } else {
    let baseSpec = JSON.parse(JSON.stringify(THEMES["light"]));
    if (v(theme.base)) {
      baseSpec = O(theme.base);
    } else if (theme.base === "light" || theme.base === "dark") {
      baseSpec = JSON.parse(JSON.stringify(THEMES[theme.base]));
    }
    Object.keys(baseSpec).forEach((k) => {
      if (theme[k] && k !== "base") {
        baseSpec[k] = lodash_es_assign(JSON.parse(JSON.stringify(baseSpec[k])), JSON.parse(JSON.stringify(theme[k])));
      }
    });
    return baseSpec;
  }
}
const LightThemeMarkCommonStyle = {
  color: CHANNEL_DEFAULTS.NOMINAL_COLOR[0],
  size: 1,
  stroke: "black",
  strokeWidth: 0,
  opacity: 1,
  nominalColorRange: CHANNEL_DEFAULTS.NOMINAL_COLOR,
  quantitativeSizeRange: [2, 6]
};
const DarkThemeMarkCommonStyle = { ...LightThemeMarkCommonStyle, stroke: "white" };
const THEMES = {
  light: {
    base: "light",
    root: {
      background: "white",
      titleColor: "black",
      titleBackgroundColor: "transparent",
      titleFontSize: 18,
      titleFontFamily: "Arial",
      titleAlign: "left",
      titleFontWeight: "bold",
      subtitleColor: "gray",
      subtitleBackgroundColor: "transparent",
      subtitleFontSize: 16,
      subtitleFontFamily: "Arial",
      subtitleFontWeight: "normal",
      subtitleAlign: "left",
      showMousePosition: true,
      mousePositionColor: "#000000"
    },
    track: {
      background: "transparent",
      alternatingBackground: "transparent",
      titleColor: "black",
      titleBackground: "white",
      titleFontSize: 24,
      titleAlign: "left",
      outline: "black",
      outlineWidth: 1
    },
    legend: {
      position: "top",
      background: "white",
      backgroundOpacity: 0.7,
      labelColor: "black",
      labelFontSize: 12,
      labelFontWeight: "normal",
      labelFontFamily: "Arial",
      backgroundStroke: "#DBDBDB",
      tickColor: "black"
    },
    axis: {
      tickColor: "black",
      labelColor: "black",
      labelFontSize: 12,
      labelFontWeight: "normal",
      labelFontFamily: "Arial",
      baselineColor: "black",
      gridColor: "#E3E3E3",
      gridStrokeWidth: 1,
      gridStrokeType: "solid",
      gridStrokeDash: [4, 4]
    },
    markCommon: {
      ...LightThemeMarkCommonStyle
    },
    point: {
      ...LightThemeMarkCommonStyle,
      size: 3
    },
    rect: {
      ...LightThemeMarkCommonStyle
    },
    triangle: {
      ...LightThemeMarkCommonStyle
    },
    area: {
      ...LightThemeMarkCommonStyle
    },
    line: {
      ...LightThemeMarkCommonStyle
    },
    bar: {
      ...LightThemeMarkCommonStyle
    },
    rule: {
      ...LightThemeMarkCommonStyle,
      strokeWidth: 1
    },
    link: {
      ...LightThemeMarkCommonStyle,
      strokeWidth: 1
    },
    text: {
      ...LightThemeMarkCommonStyle,
      textAnchor: "middle",
      textFontWeight: "normal"
    },
    brush: {
      ...LightThemeMarkCommonStyle,
      color: "gray",
      opacity: 0.3,
      stroke: "black",
      strokeWidth: 1
    }
  },
  dark: {
    base: "dark",
    root: {
      background: "black",
      titleColor: "white",
      titleBackgroundColor: "transparent",
      titleFontSize: 18,
      titleFontFamily: "Arial",
      titleAlign: "middle",
      titleFontWeight: "bold",
      subtitleColor: "lightgray",
      subtitleBackgroundColor: "transparent",
      subtitleFontSize: 16,
      subtitleFontFamily: "Arial",
      subtitleAlign: "middle",
      subtitleFontWeight: "normal",
      showMousePosition: true,
      mousePositionColor: "#FFFFFF"
    },
    track: {
      background: "transparent",
      alternatingBackground: "transparent",
      titleColor: "white",
      titleBackground: "black",
      titleFontSize: 18,
      titleAlign: "left",
      outline: "white",
      outlineWidth: 1
    },
    legend: {
      position: "right",
      background: "black",
      backgroundOpacity: 0.7,
      labelColor: "white",
      labelFontSize: 12,
      labelFontWeight: "normal",
      labelFontFamily: "Arial",
      backgroundStroke: "#DBDBDB",
      tickColor: "white"
    },
    axis: {
      tickColor: "white",
      labelColor: "white",
      labelFontSize: 10,
      labelFontWeight: "normal",
      labelFontFamily: "Arial",
      baselineColor: "white",
      gridColor: "gray",
      gridStrokeWidth: 1,
      gridStrokeType: "solid",
      gridStrokeDash: [4, 4]
    },
    markCommon: {
      ...DarkThemeMarkCommonStyle
    },
    point: {
      ...DarkThemeMarkCommonStyle,
      size: 3
    },
    rect: {
      ...DarkThemeMarkCommonStyle
    },
    triangle: {
      ...DarkThemeMarkCommonStyle
    },
    area: {
      ...DarkThemeMarkCommonStyle
    },
    line: {
      ...DarkThemeMarkCommonStyle
    },
    bar: {
      ...DarkThemeMarkCommonStyle
    },
    rule: {
      ...DarkThemeMarkCommonStyle,
      strokeWidth: 1
    },
    link: {
      ...DarkThemeMarkCommonStyle,
      strokeWidth: 1
    },
    text: {
      ...DarkThemeMarkCommonStyle,
      textAnchor: "middle",
      textFontWeight: "normal"
    },
    brush: {
      ...DarkThemeMarkCommonStyle,
      color: "lightgray",
      opacity: 0.3,
      stroke: "white",
      strokeWidth: 1
    }
  }
};
class GoslingTrackModel {
  constructor(spec, data2, theme) {
    this.id = v1();
    this.theme = theme != null ? theme : getTheme();
    this.dataOriginal = JSON.parse(JSON.stringify(data2));
    this.dataAggregated = JSON.parse(JSON.stringify(data2));
    this.specOriginal = JSON.parse(JSON.stringify(spec));
    this.specComplete = JSON.parse(JSON.stringify(spec));
    this.channelScales = {};
    const validity = this.validateSpec();
    if (!validity.valid) {
      console.warn("Gosling specification is not valid!", validity.errorMessages);
      return;
    }
    this.generateCompleteSpec(this.specComplete);
    this.flipRanges(this.specComplete);
    this.generateScales();
    this.dataAggregated = aggregateData(this.spec(), this.dataAggregated);
  }
  getId() {
    return this.id;
  }
  getRenderingId() {
    var _a;
    return (_a = this.spec()._renderingId) != null ? _a : this.getId();
  }
  originalSpec() {
    return this.specOriginal;
  }
  spec() {
    return this.specComplete;
  }
  data() {
    return this.dataAggregated;
  }
  generateCompleteSpec(spec) {
    if (!spec.width || !spec.height) {
      console.warn("Size of track is not determined yet.");
      return;
    }
    if (spec.orientation === "vertical") {
      const width = spec.width;
      spec.width = spec.height;
      spec.height = width;
    }
    const xOrY = this.getGenomicChannelKey();
    let isAxisShown = false;
    if (xOrY === "x") {
      isAxisShown = IsChannelDeep(spec.x) && spec.x.axis !== void 0 && spec.x.axis !== "none";
    }
    if (xOrY === "y") {
      isAxisShown = IsChannelDeep(spec.y) && spec.y.axis !== void 0 && spec.y.axis !== "none";
    }
    if (spec.layout !== "circular") {
      if (IsChannelDeep(spec.x) && spec.x.axis !== void 0 && spec.x.axis !== "none") {
        spec.height -= HIGLASS_AXIS_SIZE;
      }
    } else {
      if (xOrY === "x" && isAxisShown && IsChannelDeep(spec.x) && spec.x.axis === "top") {
        spec["outerRadius"] = spec["outerRadius"] - HIGLASS_AXIS_SIZE;
      } else if (xOrY === "x" && isAxisShown && IsChannelDeep(spec.x) && spec.x.axis === "bottom") {
        spec["innerRadius"] = spec["innerRadius"] + HIGLASS_AXIS_SIZE;
      }
    }
    SUPPORTED_CHANNELS.forEach((channelKey) => {
      const channel = spec[channelKey];
      if (IsChannelDeep(channel) && !("zeroBaseline" in channel) && channel.type === "quantitative") {
        channel.zeroBaseline = true;
      }
    });
    this.addScaleMaterials(spec);
  }
  flipRanges(spec) {
    if (IsChannelDeep(spec.y) && spec.y.flip && Array.isArray(spec.y.range)) {
      spec.y.range = spec.y.range.reverse();
    }
  }
  getGenomicChannelKey() {
    return getGenomicChannelKeyFromTrack(this.spec());
  }
  getGenomicChannel() {
    return getGenomicChannelFromTrack(this.spec());
  }
  setChannelDomain(channelKey, domain, force) {
    const channelRaw = this.originalSpec()[channelKey];
    if (!force && IsChannelDeep(channelRaw) && channelRaw.domain !== void 0) {
      return;
    }
    const channel = this.specComplete[channelKey];
    if (IsChannelDeep(channel)) {
      channel.domain = domain;
    }
  }
  setChannelRange(channelKey, range2) {
    const channel = this.specComplete[channelKey];
    if (IsChannelDeep(channel)) {
      channel.range = range2;
    }
  }
  updateChannelValue() {
    if (this.originalSpec().y === void 0) {
      const y = this.spec().y;
      const rowCategories = this.getChannelDomainArray("row");
      if (y && IsChannelValue(y) && rowCategories) {
        y.value = this.spec().height / rowCategories.length / 2;
      }
    }
  }
  encodedValue(channelKey, value) {
    if (channelKey === "text" && value !== void 0) {
      return `${+value ? ~~value : value}`;
    }
    const channel = this.spec()[channelKey];
    const channelFieldType = IsChannelDeep(channel) ? channel.type : IsChannelValue(channel) ? "constant" : void 0;
    if (!channelFieldType) {
      return void 0;
    }
    if (channelFieldType === "constant") {
      return this.channelScales[channelKey]();
    }
    if (value === void 0) {
      return void 0;
    }
    if (typeof this.channelScales[channelKey] !== "function") {
      return void 0;
    }
    switch (channelKey) {
      case "x":
      case "y":
      case "x1":
      case "y1":
      case "xe":
      case "ye":
      case "x1e":
        if (channelFieldType === "quantitative" || channelFieldType === "genomic") {
          return this.channelScales[channelKey](value);
        }
        if (channelFieldType === "nominal") {
          return this.channelScales[channelKey](value);
        }
        break;
      case "color":
      case "stroke":
        if (channelFieldType === "quantitative") {
          return this.channelScales[channelKey](value);
        }
        if (channelFieldType === "nominal") {
          return this.channelScales[channelKey](value);
        }
        break;
      case "size":
        if (channelFieldType === "quantitative") {
          return this.channelScales[channelKey](value);
        }
        if (channelFieldType === "nominal") {
          return this.channelScales[channelKey](value);
        }
        break;
      case "row":
        if (channelFieldType === "nominal") {
          return this.channelScales[channelKey](value);
        }
        break;
      case "strokeWidth":
      case "opacity":
        if (channelFieldType === "quantitative") {
          return this.channelScales[channelKey](value);
        }
        break;
      default:
        console.warn(`${channelKey} is not supported for encoding values, so returning a undefined value`);
        return void 0;
    }
  }
  trackVisibility(currentStage) {
    const spec = this.spec();
    if (!spec.visibility || spec.visibility.length === 0 || spec.visibility.filter((d) => d.target === "track").length === 0) {
      return true;
    }
    let visibility = true;
    spec.visibility.filter((d) => d.target === "track").forEach((d) => {
      const { operation, measure, threshold } = d;
      let compareValue;
      if (measure === "zoomLevel") {
        compareValue = currentStage[measure];
      } else {
        compareValue = spec[measure];
      }
      if (compareValue !== void 0) {
        visibility = visibility && logicalComparison(compareValue, operation, threshold) === 1;
      }
    });
    return visibility;
  }
  markVisibility(datum, metrics) {
    const spec = this.spec();
    if (!spec.visibility || spec.visibility.length === 0 || spec.visibility.filter((d) => d.target === "mark").length === 0) {
      return 1;
    }
    let visibility = 1;
    spec.visibility.filter((d) => d.target === "mark").forEach((d) => {
      const { operation, threshold, conditionPadding, transitionPadding, measure } = d;
      const padding = conditionPadding != null ? conditionPadding : 0;
      const mark = spec.mark;
      let newVisibility = 1;
      if (mark === "text" && threshold === "|xe-x|" && measure === "width") {
        const xe = this.encodedPIXIProperty("xe", datum);
        const x = this.encodedPIXIProperty("x", datum);
        if (xe !== void 0 && (metrics == null ? void 0 : metrics.width)) {
          newVisibility = logicalComparison(metrics.width + padding, operation, Math.abs(xe - x), transitionPadding);
        }
      } else if (measure === "width" && typeof threshold === "number" && (metrics == null ? void 0 : metrics.width)) {
        newVisibility = logicalComparison(metrics.width + padding, operation, threshold, transitionPadding);
      } else if (measure === "zoomLevel" && typeof threshold === "number" && (metrics == null ? void 0 : metrics.zoomLevel)) {
        newVisibility = logicalComparison(metrics.zoomLevel, operation, threshold, transitionPadding);
      }
      if (visibility > newVisibility) {
        visibility = newVisibility;
      }
    });
    return visibility;
  }
  visualPropertyByChannel(channelKey, datum) {
    const value = datum !== void 0 ? getValueUsingChannel(datum, this.spec()[channelKey]) : void 0;
    return this.encodedValue(channelKey, value);
  }
  encodedPIXIProperty(propertyKey, datum, additionalInfo) {
    const mark = this.spec().mark;
    if ([
      "text",
      "color",
      "row",
      "stroke",
      "opacity",
      "strokeWidth",
      "x",
      "y",
      "xe",
      "x1",
      "x1e",
      "ye",
      "size"
    ].includes(propertyKey)) {
      return this.visualPropertyByChannel(propertyKey, datum);
    }
    switch (mark) {
      case "bar":
        return barProperty(this, propertyKey, datum, additionalInfo);
      case "point":
      case "text":
        return pointProperty(this, propertyKey, datum);
      case "rect":
        return rectProperty(this, propertyKey, datum, additionalInfo);
      default:
        return void 0;
    }
  }
  addScaleMaterials(spec) {
    const data2 = this.data();
    const genomicChannel = this.getGenomicChannel();
    if (!genomicChannel || !genomicChannel.field) {
      console.warn("Genomic field is not provided in the specification");
      return;
    }
    if (typeof spec.width === "undefined" || typeof spec.height === "undefined") {
      console.warn("Track size is not determined yet");
      return;
    }
    SUPPORTED_CHANNELS.forEach((channelKey) => {
      var _a, _b, _c, _d;
      const channel = spec[channelKey];
      if (IsStackedChannel(spec, channelKey) && IsChannelDeep(channel)) {
        const pivotedData = group(data2, (d) => d[genomicChannel.field]);
        const xKeys = [...pivotedData.keys()];
        if (!channel.domain) {
          const min2 = "zeroBaseline" in channel && channel.zeroBaseline ? 0 : min(xKeys.map((d) => sum(pivotedData.get(d).map((_d2) => channel.field ? _d2[channel.field] : void 0))));
          const max2 = max(xKeys.map((d) => sum(pivotedData.get(d).map((_d2) => channel.field ? _d2[channel.field] : void 0))));
          channel.domain = [min2, max2];
        }
        if (!channel.range) {
          const rowChannel = spec.row;
          const rowField = IsChannelDeep(rowChannel) ? rowChannel.field : void 0;
          const rowCategories = (_a = this.getChannelDomainArray("row")) != null ? _a : rowField ? Array.from(new Set(data2.map((d) => d[rowField]))) : [1];
          const rowHeight = spec.height / rowCategories.length;
          switch (channelKey) {
            case "x":
              channel.range = [0, spec.width];
              break;
            case "y":
              channel.range = [0, rowHeight];
              break;
          }
        }
      } else {
        const rowChannel = spec.row;
        const rowField = IsChannelDeep(rowChannel) ? rowChannel.field : void 0;
        const rowCategories = (_b = this.getChannelDomainArray("row")) != null ? _b : rowField ? Array.from(new Set(data2.map((d) => d[rowField]))) : [1];
        const rowHeight = spec.height / rowCategories.length;
        if (!channel) {
          let value;
          switch (channelKey) {
            case "x":
              value = spec.width / 2;
              break;
            case "y":
              value = rowHeight / 2;
              break;
            case "size":
              if (spec.mark === "line")
                value = this.theme.line.size;
              else if (spec.mark === "bar")
                value = void 0;
              else if (spec.mark === "rect")
                value = void 0;
              else if (spec.mark === "triangleRight")
                value = void 0;
              else if (spec.mark === "triangleLeft")
                value = void 0;
              else if (spec.mark === "triangleBottom")
                value = void 0;
              else if (spec.stretch && spec.mark === "point" && IsChannelDeep(spec.x) && IsChannelDeep(spec.xe))
                value = void 0;
              else if (spec.mark === "text")
                value = 12;
              else
                value = this.theme.point.size;
              break;
            case "color":
              value = this.theme.markCommon.color;
              break;
            case "row":
              value = 0;
              break;
            case "stroke":
              if (spec.mark === "text")
                value = this.theme.text.stroke;
              else
                value = this.theme.markCommon.stroke;
              break;
            case "strokeWidth":
              if (spec.mark === "rule")
                value = this.theme.rule.strokeWidth;
              else if (spec.mark === "withinLink" || spec.mark === "betweenLink")
                value = this.theme.link.strokeWidth;
              else if (spec.mark === "text")
                value = this.theme.text.strokeWidth;
              else
                value = this.theme.markCommon.strokeWidth;
              break;
            case "opacity":
              value = this.theme.markCommon.opacity;
              break;
            case "text":
              value = "";
              break;
          }
          if (typeof value !== "undefined") {
            spec[channelKey] = { value };
          }
        } else if (IsChannelDeep(channel) && (channel.type === "quantitative" || channel.type === "genomic")) {
          if (channel.domain === void 0) {
            const min2 = "zeroBaseline" in channel && channel.zeroBaseline ? 0 : (_c = min(data2.map((d) => +d[channel.field]))) != null ? _c : 0;
            const max2 = (_d = max(data2.map((d) => +d[channel.field]))) != null ? _d : 0;
            channel.domain = [min2, max2];
          } else if (channel.type === "genomic" && !IsDomainArray(channel.domain)) {
            channel.domain = getNumericDomain(channel.domain);
          }
          if (!channel.range) {
            let range2;
            switch (channelKey) {
              case "x":
              case "xe":
              case "x1":
              case "x1e":
                range2 = [0, spec.width];
                break;
              case "y":
              case "ye":
                range2 = [0, rowHeight];
                break;
              case "color":
              case "stroke":
                range2 = CHANNEL_DEFAULTS.QUANTITATIVE_COLOR;
                break;
              case "size":
                range2 = this.theme.markCommon.quantitativeSizeRange;
                break;
              case "strokeWidth":
                range2 = [1, 3];
                break;
              case "opacity":
                range2 = [0, 1];
                break;
            }
            if (range2) {
              channel.range = range2;
            }
          }
        } else if (IsChannelDeep(channel) && channel.type === "nominal") {
          if (channel.domain === void 0) {
            channel.domain = Array.from(new Set(data2.map((d) => d[channel.field])));
          }
          if (!channel.range) {
            let startSize = 2;
            let range2;
            switch (channelKey) {
              case "x":
              case "xe":
                range2 = [0, spec.width];
                break;
              case "y":
              case "ye":
                range2 = [rowHeight, 0];
                break;
              case "color":
              case "stroke":
                range2 = this.theme.markCommon.nominalColorRange;
                break;
              case "row":
                range2 = [0, spec.height];
                break;
              case "size":
                range2 = channel.domain.map(() => startSize++);
                break;
            }
            if (range2) {
              channel.range = range2;
            }
          }
        }
      }
    });
    [
      ["x", "xe"],
      ["y", "ye"]
    ].forEach((pair) => {
      const [k1, k2] = pair;
      const c1 = spec[k1], c2 = spec[k2];
      if (IsChannelDeep(c1) && IsChannelDeep(c2) && c1.type === c2.type && c1.domain && c2.domain && Array.isArray(c1.domain) && Array.isArray(c2.domain)) {
        if (c1.type === "genomic" || c1.type === "quantitative") {
          const min2 = min([c1.domain[0], c2.domain[0]]);
          const max2 = max([c1.domain[1], c2.domain[1]]);
          c1.domain = c2.domain = [min2, max2];
        } else if (c1.type === "nominal") {
          const range2 = Array.from(new Set([...c1.domain, ...c2.domain]));
          c1.range = c2.range = range2;
        }
      }
    });
  }
  generateScales() {
    const spec = this.spec();
    SUPPORTED_CHANNELS.forEach((channelKey) => {
      const channel = spec[channelKey];
      if (IsChannelValue(channel)) {
        this.channelScales[channelKey] = () => channel.value;
      } else if (IsChannelDeep(channel)) {
        if (channelKey === "text") {
          return;
        }
        const domain = channel.domain;
        const range2 = channel.range;
        if (domain === void 0 || range2 === void 0) {
          return;
        }
        if (channel.type === "quantitative" || channel.type === "genomic") {
          switch (channelKey) {
            case "x":
            case "x1":
            case "xe":
            case "x1e":
            case "y":
            case "ye":
            case "size":
            case "opacity":
            case "strokeWidth":
              this.channelScales[channelKey] = linear_linear().domain(domain).range(range2);
              break;
            case "color":
            case "stroke":
              let interpolate = viridis;
              if (Object.keys(PREDEFINED_COLOR_STR_MAP).includes(range2)) {
                interpolate = PREDEFINED_COLOR_STR_MAP[range2];
              }
              this.channelScales[channelKey] = sequential(interpolate).domain(domain);
              break;
          }
        } else if (channel.type === "nominal") {
          switch (channelKey) {
            case "x":
            case "xe":
            case "y":
            case "ye":
            case "row":
              this.channelScales[channelKey] = band().domain(domain).range(range2);
              break;
            case "size":
              this.channelScales[channelKey] = ordinal().domain(domain).range(range2);
              break;
            case "color":
            case "stroke":
              this.channelScales[channelKey] = ordinal(range2).domain(domain);
              break;
          }
        }
      }
    });
  }
  getChannelScale(channelKey) {
    return this.channelScales[channelKey];
  }
  setChannelScale(channelKey, scale) {
    this.channelScales[channelKey] = scale;
  }
  addDataRows(_) {
    this.dataAggregated = [...this.dataAggregated, ..._];
  }
  isShowYAxis() {
    const spec = this.spec();
    const yDomain = this.getChannelDomainArray("y");
    const yRange = this.getChannelRangeArray("y");
    return IsChannelDeep(spec.y) && spec.y.axis !== "none" && spec.y.type === "quantitative" && !!yDomain && !!yRange;
  }
  getChannelDomainArray(channelKey) {
    const c = this.spec()[channelKey];
    return IsChannelDeep(c) && IsDomainArray(c.domain) ? c.domain : void 0;
  }
  getChannelRangeArray(channelKey) {
    const c = this.spec()[channelKey];
    return IsChannelDeep(c) && IsRangeArray(c.range) ? c.range : void 0;
  }
  validateSpec() {
    return validateTrack(this.originalSpec());
  }
}
function getTabularData(spec, data2) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const tabularData = [];
  if (!IsDataDeepTileset(spec.data)) {
    console.warn("No data is specified");
    return;
  }
  if (spec.data.type === "vector" || spec.data.type === "bigwig") {
    if (!spec.data.column || !spec.data.value) {
      console.warn("Proper data configuration is not provided. Please specify the name of data fields.");
      return;
    }
    if (!data2.dense) {
      return;
    }
    const bin = (_a = spec.data.binSize) != null ? _a : 1;
    const numericValues = data2.dense;
    const numOfGenomicPositions = data2.tileSize;
    const tileUnitSize = data2.tileWidth / data2.tileSize;
    const valueName = spec.data.value;
    const columnName = spec.data.column;
    const startName = (_b = spec.data.start) != null ? _b : "start";
    const endName = (_c = spec.data.end) != null ? _c : "end";
    const minValueName = `${valueName}_min`;
    const maxValueName = `${valueName}_max`;
    const agg = (_d = spec.data.aggregation) != null ? _d : "mean";
    let cumVal = 0;
    let minVal = Number.MAX_SAFE_INTEGER;
    let maxVal = Number.MIN_SAFE_INTEGER;
    let binStart = Number.MIN_SAFE_INTEGER;
    let binEnd = Number.MAX_SAFE_INTEGER;
    Array.from(Array(numOfGenomicPositions).keys()).forEach((g, j) => {
      if (bin === 1) {
        const value = numericValues[j] / (agg === "mean" ? tileUnitSize : 1);
        tabularData.push({
          [valueName]: value,
          [columnName]: data2.tileX + (j + 0.5) * tileUnitSize,
          [startName]: data2.tileX + j * tileUnitSize,
          [endName]: data2.tileX + (j + 1) * tileUnitSize,
          [minValueName]: value,
          [maxValueName]: value
        });
      } else {
        if (j % bin === 0) {
          cumVal = minVal = maxVal = numericValues[j];
          binStart = j;
          binEnd = j + bin;
        } else if (j % bin === bin - 1) {
          tabularData.push({
            [valueName]: cumVal / bin / (agg === "mean" ? tileUnitSize : 1),
            [columnName]: data2.tileX + (binStart + bin / 2) * tileUnitSize,
            [startName]: data2.tileX + binStart * tileUnitSize,
            [endName]: data2.tileX + binEnd * tileUnitSize,
            [minValueName]: minVal,
            [maxValueName]: maxVal
          });
        } else if (j === numOfGenomicPositions - 1) {
          const smallBin = numOfGenomicPositions % bin;
          const correctedBinEnd = binStart + smallBin;
          tabularData.push({
            [valueName]: cumVal / smallBin / (agg === "mean" ? tileUnitSize : 1),
            [columnName]: data2.tileX + (binStart + smallBin / 2) * tileUnitSize,
            [startName]: data2.tileX + binStart * tileUnitSize,
            [endName]: data2.tileX + correctedBinEnd * tileUnitSize,
            [minValueName]: minVal,
            [maxValueName]: maxVal
          });
        } else {
          cumVal += numericValues[j];
          if (minVal > numericValues[j])
            minVal = numericValues[j];
          if (maxVal < numericValues[j])
            maxVal = numericValues[j];
        }
      }
    });
  } else if (spec.data.type === "multivec") {
    if (!spec.data.row || !spec.data.column || !spec.data.value) {
      console.warn("Proper data configuration is not provided. Please specify the name of data fields.");
      return;
    }
    if (!data2.dense || data2.shape === void 0) {
      return;
    }
    const bin = (_e = spec.data.binSize) != null ? _e : 1;
    const numOfTotalCategories = data2.shape[0];
    const categories = (_f = spec.data.categories) != null ? _f : [...Array(numOfTotalCategories).keys()];
    const numericValues = data2.dense;
    const numOfGenomicPositions = data2.shape[1];
    const tileUnitSize = data2.tileWidth / data2.tileSize;
    const rowName = spec.data.row;
    const valueName = spec.data.value;
    const columnName = spec.data.column;
    const startName = (_g = spec.data.start) != null ? _g : "start";
    const endName = (_h = spec.data.end) != null ? _h : "end";
    const minValueName = `${valueName}_min`;
    const maxValueName = `${valueName}_max`;
    const agg = (_i = spec.data.aggregation) != null ? _i : "mean";
    categories.forEach((c, i) => {
      let cumVal = 0;
      let binStart = Number.MIN_SAFE_INTEGER;
      let binEnd = Number.MAX_SAFE_INTEGER;
      let minVal = Number.MAX_SAFE_INTEGER;
      let maxVal = Number.MIN_SAFE_INTEGER;
      Array.from(Array(numOfGenomicPositions).keys()).forEach((g, j) => {
        if (bin === 1) {
          const value = numericValues[numOfGenomicPositions * i + j] / (agg === "mean" ? tileUnitSize : 1);
          tabularData.push({
            [rowName]: c,
            [valueName]: value,
            [columnName]: data2.tileX + (j + 0.5) * tileUnitSize,
            [startName]: data2.tileX + j * tileUnitSize,
            [endName]: data2.tileX + (j + 1) * tileUnitSize,
            [minValueName]: value,
            [maxValueName]: value
          });
        } else {
          if (j % bin === 0) {
            cumVal = minVal = maxVal = numericValues[numOfGenomicPositions * i + j];
            binStart = j;
            binEnd = j + bin;
          } else if (j % bin === bin - 1) {
            tabularData.push({
              [rowName]: c,
              [valueName]: agg === "mean" ? cumVal / bin / tileUnitSize : cumVal,
              [columnName]: data2.tileX + (binStart + bin / 2) * tileUnitSize,
              [startName]: data2.tileX + binStart * tileUnitSize,
              [endName]: data2.tileX + binEnd * tileUnitSize,
              [minValueName]: minVal,
              [maxValueName]: maxVal
            });
          } else if (j === numOfGenomicPositions - 1) {
            const smallBin = numOfGenomicPositions % bin;
            const correctedBinEnd = binStart + smallBin;
            tabularData.push({
              [rowName]: c,
              [valueName]: agg === "mean" ? cumVal / smallBin / tileUnitSize : cumVal,
              [columnName]: data2.tileX + (binStart + smallBin / 2) * tileUnitSize,
              [startName]: data2.tileX + binStart * tileUnitSize,
              [endName]: data2.tileX + correctedBinEnd * tileUnitSize,
              [minValueName]: minVal,
              [maxValueName]: maxVal
            });
          } else {
            const value = numericValues[numOfGenomicPositions * i + j];
            cumVal += value;
            if (minVal > value)
              minVal = value;
            if (maxVal < value)
              maxVal = value;
          }
        }
      });
    });
  } else if (spec.data.type === "matrix") {
    if (!data2.dense || typeof data2.tileY === "undefined" || typeof data2.tileHeight === "undefined") {
      return;
    }
    const numBins = Math.sqrt(data2.dense.length);
    const { tileX, tileY, tileWidth, tileHeight } = data2;
    const numericValues = data2.dense;
    const tileXUnitSize = tileWidth / numBins;
    const tileYUnitSize = tileHeight / numBins;
    const columnField = (_j = spec.data.column) != null ? _j : "x";
    const rowField = (_k = spec.data.row) != null ? _k : "y";
    const aggSize = 16;
    for (let i = 0; i < numericValues.length / aggSize; i++) {
      const aggLen = Math.sqrt(aggSize);
      const xIndex = i * aggLen % numBins;
      const yIndex = Math.floor(i * aggLen / numBins) * aggLen;
      let value = NaN;
      for (let c = 0; c < aggLen; c++) {
        for (let r = 0; r < aggLen; r++) {
          const curVal = numericValues[(yIndex + r) * numBins + (xIndex + c)];
          if (!isNaN(+curVal)) {
            if (isNaN(value)) {
              value = 0;
            }
            value += curVal;
          }
        }
      }
      if (isNaN(value)) {
        continue;
      }
      const xs = tileX + xIndex * tileXUnitSize;
      const xe = tileX + (xIndex + aggLen) * tileXUnitSize;
      const ys = tileY + yIndex * tileYUnitSize;
      const ye = tileY + (yIndex + aggLen) * tileYUnitSize;
      const x = (xs + xe) / 2;
      const y = (ys + ye) / 2;
      tabularData.push({
        value,
        [columnField]: x,
        [`${columnField}s`]: xs,
        [`${columnField}e`]: xe,
        [rowField]: y,
        [`${rowField}s`]: ys,
        [`${rowField}e`]: ye
      });
    }
  } else if (spec.data.type === "beddb") {
    if (!data2.raw) {
      return;
    }
    const { genomicFields, exonIntervalFields, valueFields } = spec.data;
    data2.raw.forEach((d) => {
      const { chrOffset, fields } = d;
      const datum = {};
      genomicFields.forEach((g) => {
        datum[g.name] = +fields[g.index] + chrOffset;
      });
      valueFields == null ? void 0 : valueFields.forEach((v) => {
        datum[v.name] = v.type === "quantitative" ? +fields[v.index] : fields[v.index];
      });
      tabularData.push({
        ...datum,
        type: "gene"
      });
      if (exonIntervalFields) {
        const [exonStartField, exonEndField] = exonIntervalFields;
        const exonStartStrs = fields[exonStartField.index].split(",");
        const exonEndStrs = fields[exonEndField.index].split(",");
        exonStartStrs.forEach((es, i) => {
          const ee = exonEndStrs[i];
          tabularData.push({
            ...datum,
            [exonStartField.name]: +es + chrOffset,
            [exonEndField.name]: +ee + chrOffset,
            type: "exon"
          });
          if (i + 1 < exonStartStrs.length) {
            const nextEs = exonStartStrs[i + 1];
            tabularData.push({
              ...datum,
              [exonStartField.name]: +ee + chrOffset,
              [exonEndField.name]: +nextEs + chrOffset,
              type: "intron"
            });
          }
        });
      }
    });
  }
  return tabularData;
}
const DEBOUNCE_TIME = 200;
class BAMDataFetcher {
  constructor(HGC, dataConfig, worker) {
    this.worker = worker;
    this.dataConfig = dataConfig;
    this.uid = HGC.libraries.slugid.nice();
    this.assembly = "hg38";
    this.fetchTimeout = null;
    this.toFetch = new Set();
    this.initPromise = this.worker.then((tileFunctions) => {
      var _a;
      if (dataConfig.url && !dataConfig.bamUrl) {
        dataConfig["bamUrl"] = dataConfig.url;
      }
      if (!dataConfig.baiUrl) {
        dataConfig["baiUrl"] = (_a = dataConfig.indexUrl) != null ? _a : `${dataConfig["bamUrl"]}.bai`;
      }
      return tileFunctions.init(this.uid, dataConfig).then(() => this.worker);
    });
  }
  tilesetInfo(callback) {
    this.worker.then((tileFunctions) => {
      tileFunctions.tilesetInfo(this.uid).then(callback);
    });
  }
  fetchTilesDebounced(receivedTiles, tileIds) {
    const { toFetch } = this;
    const thisZoomLevel = tileIds[0].split(".")[0];
    const toFetchZoomLevel = toFetch.size ? [...toFetch][0].split(".")[0] : null;
    if (thisZoomLevel !== toFetchZoomLevel) {
      for (const tileId of this.toFetch) {
        this.track.fetching.delete(tileId);
      }
      this.toFetch.clear();
    }
    tileIds.forEach((x) => this.toFetch.add(x));
    if (this.fetchTimeout) {
      clearTimeout(this.fetchTimeout);
    }
    this.fetchTimeout = setTimeout(() => {
      this.sendFetch(receivedTiles, [...this.toFetch]);
      this.toFetch.clear();
    }, DEBOUNCE_TIME);
  }
  sendFetch(receivedTiles, tileIds) {
    this.worker.then((tileFunctions) => {
      tileFunctions.fetchTilesDebounced(this.uid, tileIds).then(receivedTiles);
    });
  }
}
const encodedJs = " ";
const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
function BamWorker() {
  const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
  try {
    return objURL ? new Worker(objURL) : new Worker("data:application/javascript;base64," + encodedJs, { type: "module" });
  } finally {
    objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
  }
}
function usePrereleaseRendering(spec) {
  var _a;
  return ((_a = spec.data) == null ? void 0 : _a.type) === "bam";
}
function GoslingTrack(HGC, ...args) {
  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
  }
  const { tileProxy } = HGC.services;
  const { showMousePosition } = HGC.utils;
  class GoslingTrackClass extends HGC.tracks.BarTrack {
    constructor(params) {
      var _a, _b, _c, _d, _e;
      const [context2, options] = params;
      let bamWorker;
      if (usePrereleaseRendering(options.spec)) {
        try {
          bamWorker = spawn(new BamWorker());
          context2.dataFetcher = new BAMDataFetcher(HGC, context2.dataConfig, bamWorker);
        } catch (e) {
          console.warn("Error loading worker", e);
        }
      }
      super(context2, options);
      this.worker = bamWorker;
      context2.dataFetcher.track = this;
      this.context = context2;
      if ("overlay" in this.options.spec) {
        this.options.spec.overlay = this.options.spec.overlay.map((o) => {
          return { ...o, _renderingId: v1() };
        });
      } else {
        this.options.spec._renderingId = v1();
      }
      this.tileSize = (_b = (_a = this.tilesetInfo) == null ? void 0 : _a.tile_size) != null ? _b : 1024;
      this.drawnAtScale = HGC.libraries.d3Scale.scaleLinear();
      this.scalableGraphics = {};
      const { valid, errorMessages } = validateTrack(this.options.spec);
      if (!valid) {
        console.warn("The specification of the following track is invalid", errorMessages, this.options.spec);
      }
      this.extent = { min: Number.MAX_SAFE_INTEGER, max: Number.MIN_SAFE_INTEGER };
      this.mouseOverGraphics = new HGC.libraries.PIXI.Graphics();
      this.pMain.addChild(this.mouseOverGraphics);
      this.pMask.interactive = true;
      this.pMask.mousedown = (e) => this.onMouseDown(e.data.getLocalPosition(this.pMain).x, e.data.getLocalPosition(this.pMain).y);
      this.pMask.mouseup = (e) => this.onClick(e.data.getLocalPosition(this.pMain).x, e.data.getLocalPosition(this.pMain).y);
      this.pMask.mousemove = () => this.onMouseOut();
      this.flipText = this.options.spec.orientation === "vertical";
      if (this.hideMousePosition) {
        this.hideMousePosition();
        this.hideMousePosition = void 0;
      }
      if (((_c = this.options) == null ? void 0 : _c.showMousePosition) && !this.hideMousePosition) {
        this.hideMousePosition = showMousePosition(this, Is2DTrack(resolveSuperposedTracks(this.options.spec)[0]), this.isShowGlobalMousePosition());
      }
      this.pLabel.removeChild(this.trackNotFoundText);
      const loadingTextStyle = getTextStyle({ color: "black", size: 12 });
      this.loadingTextStyleObj = new HGC.libraries.PIXI.TextStyle(loadingTextStyle);
      this.loadingTextBg = new HGC.libraries.PIXI.Graphics();
      this.loadingText = new HGC.libraries.PIXI.Text("", loadingTextStyle);
      this.loadingText.anchor.x = 1;
      this.loadingText.anchor.y = 1;
      this.pLabel.addChild(this.loadingTextBg);
      this.pLabel.addChild(this.loadingText);
      this.tooltips = [];
      this.svgData = [];
      this.textGraphics = [];
      this.textsBeingUsed = 0;
      this.loadingStatus = { loading: 0, processing: 0, rendering: 0 };
      HGC.libraries.PIXI.GRAPHICS_CURVES.adaptive = (_e = (_d = this.options.spec.style) == null ? void 0 : _d.enableSmoothPath) != null ? _e : false;
      if (HGC.libraries.PIXI.GRAPHICS_CURVES.adaptive) {
        HGC.libraries.PIXI.GRAPHICS_CURVES.maxLength = 1;
        HGC.libraries.PIXI.GRAPHICS_CURVES.maxSegments = 2048 * 10;
      }
    }
    draw() {
      var _a;
      this.tooltips = [];
      this.svgData = [];
      this.textsBeingUsed = 0;
      (_a = this.mouseOverGraphics) == null ? void 0 : _a.clear();
      const processTilesAndDraw = () => {
        this.preprocessAllTiles();
        super.draw();
        this.prevVisibleAndFetchedTiles = this.visibleAndFetchedTiles();
      };
      if (usePrereleaseRendering(this.options.spec) && !lodash_es_isEqual(this.visibleAndFetchedTiles(), this.prevVisibleAndFetchedTiles)) {
        this.updateTileAsync(processTilesAndDraw);
      } else {
        processTilesAndDraw();
      }
    }
    initTile(tile) {
      this.drawTile(tile);
    }
    updateTile() {
    }
    renderTile() {
    }
    drawTile(tile) {
      tile.drawnAtScale = this._xScale.copy();
      if (!tile.goslingModels) {
        return;
      }
      tile.graphics.clear();
      tile.graphics.removeChildren();
      tile.goslingModels.forEach((tm) => {
        const trackWidth = this.dimensions[0];
        const zoomLevel = this._xScale.invert(trackWidth) - this._xScale.invert(0);
        if (!tm.trackVisibility({ zoomLevel })) {
          return;
        }
        drawPreEmbellishment(HGC, this, tile, tm, this.options.theme);
        drawMark(HGC, this, tile, tm);
        drawPostEmbellishment(HGC, this, tile, tm, this.options.theme);
      });
      this.forceDraw();
    }
    rerender(newOptions) {
      this.options = newOptions;
      this.tooltips = [];
      this.svgData = [];
      this.textsBeingUsed = 0;
      this.preprocessAllTiles(true);
      this.draw();
      this.forceDraw();
    }
    setDimensions(newDimensions) {
      this.oldDimensions = this.dimensions;
      super.setDimensions(newDimensions);
    }
    setPosition(newPosition) {
      super.setPosition(newPosition);
      [this.pMain.position.x, this.pMain.position.y] = this.position;
    }
    forceDraw() {
      this.animate();
    }
    zoomed(newXScale, newYScale) {
      this.xScale(newXScale);
      this.yScale(newYScale);
      this.refreshTiles();
      this.draw();
      this.forceDraw();
    }
    updateTileAsync(callback) {
      this.xDomain = this._xScale.domain();
      this.xRange = this._xScale.range();
      this.drawLoadingCue("loading");
      this.worker.then((tileFunctions) => {
        tileFunctions.getTabularData(this.dataFetcher.uid, Object.values(this.fetchedTiles).map((x) => x.remoteId)).then((toRender) => {
          this.drawLoadingCue("processing");
          const tiles = this.visibleAndFetchedTiles();
          const tabularData = JSON.parse(Buffer.from(toRender).toString());
          if (tiles == null ? void 0 : tiles[0]) {
            const tile = tiles[0];
            tile.tileData.tabularData = tabularData;
            const [refTile] = HGC.utils.trackUtils.calculate1DVisibleTiles(this.tilesetInfo, this._xScale);
            tile.tileData.zoomLevel = refTile[0];
            tile.tileData.tilePos = [refTile[1]];
          }
          this.drawLoadingCue("rendering");
          callback();
          this.drawLoadingCue("done");
        });
      });
    }
    scaleScalableGraphics(graphics, xScale, drawnAtScale) {
      const drawnAtScaleExtent = drawnAtScale.domain()[1] - drawnAtScale.domain()[0];
      const xScaleExtent = xScale.domain()[1] - xScale.domain()[0];
      const tileK = drawnAtScaleExtent / xScaleExtent;
      const newRange = xScale.domain().map(drawnAtScale);
      const posOffset = newRange[0];
      graphics.forEach((g) => {
        g.scale.x = tileK;
        g.position.x = -posOffset * tileK;
      });
    }
    visibleAndFetchedIds() {
      return Object.keys(this.fetchedTiles).filter((x) => this.visibleTileIds.has(x));
    }
    visibleAndFetchedTiles() {
      return this.visibleAndFetchedIds().map((x) => this.fetchedTiles[x]);
    }
    calculateVisibleTiles() {
      if (usePrereleaseRendering(this.options.spec)) {
        const tiles = HGC.utils.trackUtils.calculate1DVisibleTiles(this.tilesetInfo, this._xScale);
        for (const tile of tiles) {
          const { tileWidth } = this.getTilePosAndDimensions(tile[0], [tile[1], tile[1]], this.tilesetInfo.tile_size);
          const DEFAULT_MAX_TILE_WIDTH = 2e4;
          if (tileWidth > (this.tilesetInfo.max_tile_width || DEFAULT_MAX_TILE_WIDTH)) {
            this.forceDraw();
            return;
          }
          this.forceDraw();
        }
        this.setVisibleTiles(tiles);
      } else {
        if (!this.tilesetInfo) {
          return;
        }
        this.zoomLevel = this.calculateZoomLevel();
        if (this.tilesetInfo.resolutions) {
          const sortedResolutions = this.tilesetInfo.resolutions.map((x) => +x).sort((a, b) => b - a);
          this.xTiles = tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
          if (Is2DTrack(resolveSuperposedTracks(this.options.spec)[0])) {
            this.yTiles = tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], this._yScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
          }
          const tiles = this.tilesToId(this.xTiles, this.yTiles, this.zoomLevel);
          this.setVisibleTiles(tiles);
        } else {
          this.xTiles = tileProxy.calculateTiles(this.zoomLevel, this.relevantScale(), this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);
          if (Is2DTrack(resolveSuperposedTracks(this.options.spec)[0])) {
            this.yTiles = tileProxy.calculateTiles(this.zoomLevel, this._yScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width1 || this.tilesetInfo.max_width);
          }
          const tiles = this.tilesToId(this.xTiles, this.yTiles, this.zoomLevel);
          this.setVisibleTiles(tiles);
        }
      }
    }
    getTilePosAndDimensions(zoomLevel, tilePos, binsPerTileIn) {
      const binsPerTile = binsPerTileIn || this.tilesetInfo.bins_per_dimension || 256;
      if (this.tilesetInfo.resolutions) {
        const sortedResolutions = this.tilesetInfo.resolutions.map((x) => +x).sort((a, b) => b - a);
        const chosenResolution = sortedResolutions[zoomLevel];
        const [xTilePos, yTilePos] = tilePos;
        const tileWidth = chosenResolution * binsPerTile;
        const tileHeight = tileWidth;
        const tileX = tileWidth * xTilePos;
        const tileY = tileHeight * yTilePos;
        return {
          tileX,
          tileY,
          tileWidth,
          tileHeight
        };
      } else {
        const [xTilePos, yTilePos] = tilePos;
        const minX = this.tilesetInfo.min_pos[0];
        const minY = this.options.reverseYAxis ? -this.tilesetInfo.max_pos[1] : this.tilesetInfo.min_pos[1];
        const tileWidth = this.tilesetInfo.max_width / 2 ** zoomLevel;
        const tileHeight = this.tilesetInfo.max_width / 2 ** zoomLevel;
        const tileX = minX + xTilePos * tileWidth;
        const tileY = minY + yTilePos * tileHeight;
        return {
          tileX,
          tileY,
          tileWidth,
          tileHeight
        };
      }
    }
    tilesToId(xTiles, yTiles, zoomLevel) {
      if (xTiles && !yTiles) {
        return xTiles.map((x) => [zoomLevel, x]);
      } else {
        const tiles = [];
        xTiles.forEach((x) => yTiles.forEach((y) => tiles.push([zoomLevel, x, y])));
        return tiles;
      }
    }
    drawLoadingCue(stage) {
      let curStage = stage;
      if (this.loadingStatus) {
        if (stage === "done") {
          this.loadingStatus.loading--;
          this.loadingStatus.processing--;
          this.loadingStatus.rendering--;
          if (this.loadingStatus.loading !== 0) {
            curStage = "loading";
          }
        } else {
          this.loadingStatus[stage]++;
        }
      }
      setTimeout(() => {
        this.loadingText.x = this.position[0] + this.dimensions[0] - 1;
        this.loadingText.y = this.position[1] + this.dimensions[1] - 0;
        const text = {
          loading: "Loading Tiles...",
          processing: "Processing Tiles...",
          rendering: "Rendering Tiles...",
          done: ""
        }[curStage];
        this.loadingText.text = text;
        this.forceDraw();
      }, 10);
    }
    reorganizeTileInfo() {
      var _a, _b;
      const tiles = this.visibleAndFetchedTiles();
      this.tileSize = (_b = (_a = this.tilesetInfo) == null ? void 0 : _a.tile_size) != null ? _b : 1024;
      tiles.forEach((t) => {
        t.gos = {};
        const keys = Object.keys(t.tileData).filter((d) => !+d && d !== "0");
        keys.forEach((k) => {
          t.gos[k] = t.tileData[k];
        });
        t.gos.raw = Array.from(t.tileData);
      });
    }
    shouldCombineTiles() {
      var _a, _b, _c, _d, _e, _f;
      return ((_a = this.options.spec.dataTransform) == null ? void 0 : _a.find((t) => t.type === "displace")) && ((_c = (_b = this.visibleAndFetchedTiles()) == null ? void 0 : _b[0]) == null ? void 0 : _c.tileData) && !((_e = (_d = this.visibleAndFetchedTiles()) == null ? void 0 : _d[0]) == null ? void 0 : _e.tileData.dense) || ((_f = this.options.spec.data) == null ? void 0 : _f.type) === "bam";
    }
    combineAllTilesIfNeeded() {
      var _a, _b, _c;
      if (!this.shouldCombineTiles()) {
        return;
      }
      const tiles = this.visibleAndFetchedTiles();
      if (!tiles || tiles.length === 0) {
        return;
      }
      this.tileSize = ((_b = (_a = this.tilesetInfo) == null ? void 0 : _a.tile_size) != null ? _b : 1024) * tiles.length;
      let newData = [];
      tiles.forEach((t, i) => {
        newData = [...newData, ...t.tileData];
        t.mergedToAnotherTile = i !== 0;
      });
      tiles[0].gos.raw = newData;
      if ((_c = tiles[0].gos.raw[0]) == null ? void 0 : _c.uid) {
        tiles[0].gos.raw = lodash_es_uniqBy(tiles[0].gos.raw, "uid");
      }
    }
    preprocessAllTiles(force = false) {
      const gms = [];
      this.reorganizeTileInfo();
      this.combineAllTilesIfNeeded();
      this.visibleAndFetchedTiles().forEach((tile) => {
        if (force) {
          tile.goslingModels = [];
        }
        const tileModels = this.preprocessTile(tile);
        tileModels == null ? void 0 : tileModels.forEach((m) => {
          gms.push(m);
        });
      });
      shareScaleAcrossTracks(gms);
      const flatTileData = [].concat(...gms.map((d) => d.data()));
      if (flatTileData.length !== 0) {
        pubsub_default().publish("rawdata", {
          id: this.options.spec.id,
          data: flatTileData
        });
      }
    }
    preprocessTile(tile) {
      if (tile.mergedToAnotherTile) {
        tile.goslingModels = [];
        return;
      }
      if (tile.goslingModels && tile.goslingModels.length !== 0) {
        return tile.goslingModels;
      }
      if (!tile.gos.tilePos) {
        return;
      }
      tile.goslingModels = [];
      const spec = JSON.parse(JSON.stringify(this.options.spec));
      const [trackWidth, trackHeight] = this.dimensions;
      resolveSuperposedTracks(spec).forEach((resolved) => {
        var _a;
        if (resolved.mark === "brush") {
          return;
        }
        if (!tile.gos.tabularData) {
          const { tileX, tileY, tileWidth, tileHeight } = this.getTilePosAndDimensions(tile.gos.zoomLevel, tile.gos.tilePos, this.tilesetInfo.bins_per_dimension || ((_a = this.tilesetInfo) == null ? void 0 : _a.tile_size));
          tile.gos.tabularData = getTabularData(resolved, {
            ...tile.gos,
            tileX,
            tileY,
            tileWidth,
            tileHeight,
            tileSize: this.tileSize
          });
        }
        tile.gos.tabularDataFiltered = Array.from(tile.gos.tabularData);
        if (resolved.dataTransform) {
          resolved.dataTransform.forEach((t) => {
            switch (t.type) {
              case "filter":
                tile.gos.tabularDataFiltered = filterData(t, tile.gos.tabularDataFiltered);
                break;
              case "concat":
                tile.gos.tabularDataFiltered = concatString(t, tile.gos.tabularDataFiltered);
                break;
              case "replace":
                tile.gos.tabularDataFiltered = replaceString(t, tile.gos.tabularDataFiltered);
                break;
              case "log":
                tile.gos.tabularDataFiltered = calculateData(t, tile.gos.tabularDataFiltered);
                break;
              case "exonSplit":
                tile.gos.tabularDataFiltered = splitExon(t, tile.gos.tabularDataFiltered, resolved.assembly);
                break;
              case "genomicLength":
                tile.gos.tabularDataFiltered = calculateGenomicLength(t, tile.gos.tabularDataFiltered);
                break;
              case "coverage":
                tile.gos.tabularDataFiltered = aggregateCoverage(t, tile.gos.tabularDataFiltered, this._xScale.copy());
                break;
              case "subjson":
                tile.gos.tabularDataFiltered = parseSubJSON(t, tile.gos.tabularDataFiltered);
                break;
              case "displace":
                tile.gos.tabularDataFiltered = displace(t, tile.gos.tabularDataFiltered, this._xScale.copy());
                break;
            }
          });
        }
        try {
          if ((pubsub_default())) {
            const NUM_OF_ROWS_IN_PREVIEW = 100;
            const numOrRows = tile.gos.tabularDataFiltered.length;
            pubsub_default().publish("data-preview", {
              id: this.context.id,
              dataConfig: JSON.stringify({ data: resolved.data }),
              data: NUM_OF_ROWS_IN_PREVIEW > numOrRows ? tile.gos.tabularDataFiltered : lodash_es_sampleSize(tile.gos.tabularDataFiltered, NUM_OF_ROWS_IN_PREVIEW)
            });
          }
        } catch (e) {
        }
        const axisSize = IsXAxis(resolved) ? HIGLASS_AXIS_SIZE : 0;
        const [w, h] = [trackWidth, trackHeight + axisSize];
        const circularFactor = Math.min(w, h) / Math.min(resolved.width, resolved.height);
        if (resolved.innerRadius) {
          resolved.innerRadius = resolved.innerRadius * circularFactor;
        }
        if (resolved.outerRadius) {
          resolved.outerRadius = resolved.outerRadius * circularFactor;
        }
        resolved.width = w;
        resolved.height = h;
        const gm = new GoslingTrackModel(resolved, tile.gos.tabularDataFiltered, this.options.theme);
        tile.goslingModels.push(gm);
      });
      return tile.goslingModels;
    }
    getIndicesOfVisibleDataInTile(tile) {
      var _a, _b, _c;
      const visible = this._xScale.range();
      if (!this.tilesetInfo)
        return [null, null];
      const { tileX, tileWidth } = this.getTilePosAndDimensions(tile.gos.zoomLevel, tile.gos.tilePos, this.tilesetInfo.bins_per_dimension || ((_a = this.tilesetInfo) == null ? void 0 : _a.tile_size));
      const tileXScale = linear_linear().domain([0, ((_b = this.tilesetInfo) == null ? void 0 : _b.tile_size) || ((_c = this.tilesetInfo) == null ? void 0 : _c.bins_per_dimension)]).range([tileX, tileX + tileWidth]);
      const start = Math.max(0, Math.round(tileXScale.invert(this._xScale.invert(visible[0]))));
      const end = Math.min(tile.gos.dense.length, Math.round(tileXScale.invert(this._xScale.invert(visible[1]))));
      return [start, end];
    }
    minVisibleValue() {
    }
    maxVisibleValue() {
    }
    exportSVG() {
    }
    onMouseOut() {
      document.body.style.cursor = "default";
    }
    onMouseDown(mouseX, mouseY) {
      this.mouseDownX = mouseX;
      this.mouseDownY = mouseY;
    }
    onClick(mouseX, mouseY) {
      if (!this.tilesetInfo || !this.tooltips) {
        return;
      }
      if (Math.sqrt((this.mouseDownX - mouseX) ** 2 + (this.mouseDownY - mouseY) ** 2) > 1) {
        return;
      }
      const tooltip = this.tooltips.find((d) => d.isMouseOver(mouseX, mouseY));
      if (tooltip) {
        pubsub_default().publish("click", {
          data: { ...tooltip.datum },
          genomicPosition: getRelativeGenomicPosition(Math.floor(this._xScale.invert(mouseX)))
        });
      }
    }
    getMouseOverHtml(mouseX, mouseY) {
      const isMouseOverPrepared = false;
      if (!this.tilesetInfo || !this.tooltips) {
        return;
      }
      this.mouseOverGraphics.clear();
      this.pMain.removeChild(this.mouseOverGraphics);
      this.pMain.addChild(this.mouseOverGraphics);
      const tooltip = this.tooltips.find((d) => d.isMouseOver(mouseX, mouseY));
      if (tooltip) {
        document.body.style.cursor = "pointer";
      } else {
        document.body.style.cursor = "default";
      }
      if (tooltip) {
        pubsub_default().publish("mouseover", {
          data: { ...tooltip.datum },
          genomicPosition: getRelativeGenomicPosition(Math.floor(this._xScale.invert(mouseX)))
        });
      }
      if (tooltip) {
        if (tooltip.markInfo.type === "rect" && isMouseOverPrepared) {
          this.mouseOverGraphics.lineStyle(1, colorToHex("black"), 1, 1);
          this.mouseOverGraphics.beginFill(colorToHex("white"), 0);
          {
            this.mouseOverGraphics.drawRect(tooltip.markInfo.x, tooltip.markInfo.y, tooltip.markInfo.width, tooltip.markInfo.height);
          }
        }
        if (this.options.spec.tooltip) {
          const content = this.options.spec.tooltip.map((d) => {
            var _a;
            const rawValue = tooltip.datum[d.field];
            let value = rawValue;
            if (d.type === "quantitative" && d.format) {
              value = format$1(d.format)(+rawValue);
            } else if (d.type === "genomic") {
              value = getRelativeGenomicPosition(+rawValue);
            }
            return `<tr><td style='padding: 4px 8px'>${(_a = d.alt) != null ? _a : d.field}</td><td style='padding: 4px 8px'><b>${value}</b></td></tr>`;
          }).join("");
          return `<table style='text-align: left; margin-top: 12px'>${content}</table>`;
        }
      }
    }
  }
  return new GoslingTrackClass(args);
}
const goslingIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" width={30} height={30}>
    <rect style={{ fill: 'none' }} width="400" height="400" />
    <circle cx="110.62" cy="129.64" r="41.69" />
    <circle style={{ fill: '#fff' }} cx="124.14" cy="114.12" r="10.76" />
    <circle cx="288.56" cy="129.64" r="41.69" />
    <circle style={{ fill: '#fff' }} cx="302.07" cy="114.12" r="10.76" />
    <path
        style={{ fill: '#e18241' }}
        d="M313.1,241.64l8.61-22.09a430.11,430.11,0,0,0-88-15.87L224,225.63A384.54,384.54,0,0,1,313.1,241.64Z"
    />
    <path
        style={{ fill: '#e18241' }}
        d="M208.63,260.53a299.77,299.77,0,0,1,90.56,16.79L308,254.79a371.68,371.68,0,0,0-90-15.47Z"
    />
    <path
        style={{ fill: '#e18241' }}
        d="M174.4,225.56l-9-22a431.34,431.34,0,0,0-88,15.43l8.9,22A385.08,385.08,0,0,1,174.4,225.56Z"
    />
    <path
        style={{ fill: '#e18241' }}
        d="M100.71,276.35a300.51,300.51,0,0,1,87.91-15.82L180,239.29a372.51,372.51,0,0,0-88.3,14.76Z"
    />
    <path
        style={{ fill: '#e18241' }}
        d="M106.52,290.71c27.53,13.92,59.05,21.34,92.05,21.34h0c33.68,0,65.83-7.72,93.75-22.2a291.31,291.31,0,0,0-186.33-.4Z"
    />
</svg>`;
GoslingTrack.config = {
  type: "gosling-track",
  datatype: ["multivec", "epilogos"],
  rotatable: true,
  local: false,
  orientation: "1d-horizontal",
  thumbnail: new DOMParser().parseFromString(goslingIcon, "text/xml").documentElement,
  availableOptions: [
    "labelPosition",
    "labelColor",
    "labelTextOpacity",
    "labelBackgroundOpacity",
    "trackBorderWidth",
    "trackBorderColor",
    "trackType",
    "scaledHeight",
    "backgroundColor",
    "barBorder",
    "sortLargestOnTop",
    "theme",
    "axisPositionHorizontal"
  ],
  defaultOptions: {
    labelPosition: "none",
    labelColor: "black",
    labelTextOpacity: 0.4,
    trackBorderWidth: 0,
    trackBorderColor: "black",
    backgroundColor: "white",
    barBorder: false,
    sortLargestOnTop: true,
    axisPositionHorizontal: "left",
    theme: "light"
  }
};
let once = false;
function init() {
  if (once)
    return;
  src({
    name: "GoslingTrack",
    track: GoslingTrack,
    config: GoslingTrack.config
  });
  src({
    name: "Gosling2DTrack",
    track: GoslingTrack,
    config: {
      ...GoslingTrack.config,
      type: "gosling-2d-track",
      orientation: "2d"
    }
  });
  src({
    name: "AxisTrack",
    track: AxisTrack,
    config: AxisTrack.config
  });
  src({
    name: "TextTrack",
    track: es_TextTrack,
    config: es_TextTrack.config
  });
  src({
    name: "BrushTrack",
    track: BrushTrack,
    config: BrushTrack.config
  });
  src({ dataFetcher: CSVDataFetcher, config: CSVDataFetcher.config }, { pluginType: "dataFetcher" });
  src({ dataFetcher: RawDataFetcher, config: RawDataFetcher.config }, { pluginType: "dataFetcher" });
  src({ dataFetcher: BBIDataFetcher, config: BBIDataFetcher.config }, { pluginType: "dataFetcher" });
  once = true;
}
function getBoundingBox(trackInfos) {
  let width = 0;
  let height = 0;
  trackInfos.forEach((_) => {
    const w = _.boundingBox.x + _.boundingBox.width;
    const h = _.boundingBox.y + _.boundingBox.height;
    if (height < h) {
      height = h;
    }
    if (width < w) {
      width = w;
    }
  });
  return { width, height };
}
function getRelativeTrackInfo(spec, theme) {
  var _a, _b;
  let trackInfos = [];
  traverseAndCollectTrackInfo(spec, trackInfos);
  const size = getBoundingBox(trackInfos);
  if (spec.title || spec.subtitle) {
    const titleHeight = (spec.title ? ((_a = theme.root.titleFontSize) != null ? _a : 18) + DEWFAULT_TITLE_PADDING_ON_TOP_AND_BOTTOM : 0) + (spec.subtitle ? ((_b = theme.root.subtitleFontSize) != null ? _b : 14) + DEWFAULT_TITLE_PADDING_ON_TOP_AND_BOTTOM : 0);
    const marginBottom = 4;
    size.height += titleHeight + marginBottom;
    size.height = size.height + (8 - size.height % 8);
    trackInfos.forEach((_) => {
      _.boundingBox.y += titleHeight + marginBottom;
    });
    trackInfos = [
      {
        track: getTextTrack({ width: size.width, height: titleHeight }, spec.title, spec.subtitle),
        boundingBox: { x: 0, y: 0, width: size.width, height: titleHeight },
        layout: { x: 0, y: 0, w: 12, h: titleHeight / size.height * 12 }
      },
      ...trackInfos
    ];
  } else {
    size.height = size.height + (8 - size.height % 8);
  }
  const pixelPreciseMarginPadding = typeof spec.responsiveSize !== "object" ? !spec.responsiveSize : !spec.responsiveSize.height;
  trackInfos.forEach((_) => {
    _.layout.x = _.boundingBox.x / size.width * 12;
    _.layout.w = _.boundingBox.width / size.width * 12;
    _.layout.y = pixelPreciseMarginPadding ? _.boundingBox.y : _.boundingBox.y / size.height * 12;
    _.layout.h = pixelPreciseMarginPadding ? _.boundingBox.height : _.boundingBox.height / size.height * 12;
  });
  return trackInfos;
}
function traverseAndCollectTrackInfo(spec, output, dx = 0, dy = 0, circularRootNotFound = true) {
  let cumWidth = 0;
  let cumHeight = 0;
  let allChildCircularLayout = true;
  let traversedAtLeastOnce = false;
  traverseTracksAndViews(spec, (tv) => {
    traversedAtLeastOnce = true;
    if (tv.layout !== "circular") {
      allChildCircularLayout = false;
    }
  });
  let noChildConcatArrangement = true;
  traverseViewArrangements(spec, (a) => {
    if (a.arrangement === "vertical" || a.arrangement === "horizontal") {
      noChildConcatArrangement = false;
    }
  });
  const isThisCircularRoot = circularRootNotFound && allChildCircularLayout && traversedAtLeastOnce && noChildConcatArrangement && ("views" in spec && (spec.arrangement === "parallel" || spec.arrangement === "serial") || "tracks" in spec);
  const numTracksBeforeInsert = output.length;
  if ("tracks" in spec) {
    const tracks = spec.tracks;
    if (spec.orientation === "vertical") {
      cumHeight = Math.max(...tracks.map((d) => d.height));
      tracks.forEach((track, i, array) => {
        if (getNumOfXAxes([track]) === 1) {
          track.width += HIGLASS_AXIS_SIZE;
        }
        track.height = cumHeight;
        output.push({
          track,
          boundingBox: {
            x: dx + cumWidth,
            y: dy,
            width: track.width,
            height: cumHeight
          },
          layout: { x: 0, y: 0, w: 0, h: 0 }
        });
        if (array[i + 1] && array[i + 1].overlayOnPreviousTrack)
          ;
        else {
          cumWidth += track.width;
          if (i !== array.length - 1) {
            cumWidth += spec.spacing !== void 0 ? spec.spacing : 0;
          }
        }
      });
    } else {
      cumWidth = Math.max(...tracks.map((d) => d.width));
      tracks.forEach((track, i, array) => {
        if (getNumOfXAxes([track]) === 1) {
          track.height += HIGLASS_AXIS_SIZE;
        }
        if (Is2DTrack(resolveSuperposedTracks(track)[0]) && getNumOfYAxes([track]) === 1) {
          cumWidth += HIGLASS_AXIS_SIZE;
        }
        track.width = cumWidth;
        output.push({
          track,
          boundingBox: {
            x: dx,
            y: dy + cumHeight,
            width: cumWidth,
            height: track.height
          },
          layout: { x: 0, y: 0, w: 0, h: 0 }
        });
        if (array[i + 1] && array[i + 1].overlayOnPreviousTrack)
          ;
        else {
          cumHeight += track.height;
          if (i !== array.length - 1) {
            cumHeight += spec.spacing !== void 0 ? spec.spacing : 0;
          }
        }
      });
    }
  } else {
    if (spec.arrangement === "parallel" || spec.arrangement === "vertical") {
      const spacing = spec.spacing !== void 0 ? spec.spacing : DEFAULT_VIEW_SPACING;
      spec.views.forEach((v, i, array) => {
        var _a, _b, _c, _d, _e;
        const viewBB = traverseAndCollectTrackInfo(v, output, dx + ((_a = v.xOffset) != null ? _a : 0), dy + ((_b = v.yOffset) != null ? _b : 0) + cumHeight, !isThisCircularRoot && circularRootNotFound);
        if (cumWidth < ((_c = v.xOffset) != null ? _c : 0) + viewBB.width) {
          cumWidth = ((_d = v.xOffset) != null ? _d : 0) + viewBB.width;
        }
        if (i !== array.length - 1) {
          cumHeight += spacing;
        }
        cumHeight += ((_e = v.yOffset) != null ? _e : 0) + viewBB.height;
      });
    } else if (spec.arrangement === "serial" || spec.arrangement === "horizontal") {
      spec.views.forEach((v, i, array) => {
        var _a, _b, _c, _d, _e;
        const spacing = spec.spacing !== void 0 ? spec.spacing : DEFAULT_VIEW_SPACING;
        const viewBB = traverseAndCollectTrackInfo(v, output, dx + ((_a = v.xOffset) != null ? _a : 0) + cumWidth, dy + ((_b = v.yOffset) != null ? _b : 0), !isThisCircularRoot && circularRootNotFound);
        if (cumHeight < ((_c = v.xOffset) != null ? _c : 0) + viewBB.height) {
          cumHeight = ((_d = v.xOffset) != null ? _d : 0) + viewBB.height;
        }
        if (i !== array.length - 1) {
          cumWidth += spacing;
        }
        cumWidth += ((_e = v.xOffset) != null ? _e : 0) + viewBB.width;
      });
    }
  }
  if (isThisCircularRoot) {
    const cTracks = output.slice(numTracksBeforeInsert);
    const ifMultipleViews = "views" in spec && (spec.arrangement === "parallel" || spec.arrangement === "serial") && spec.views.length > 1;
    const SPACING = spec.spacing !== void 0 ? spec.spacing : DEFAULT_VIEW_SPACING;
    const PADDING = DEFAULT_CIRCULAR_VIEW_PADDING;
    const INNER_RADIUS = spec.centerRadius !== void 0 ? spec.centerRadius : DEFAULT_INNER_RADIUS_PROP;
    const TOTAL_RADIUS = cumWidth / 2 + PADDING;
    const TOTAL_RING_SIZE = TOTAL_RADIUS * (1 - INNER_RADIUS);
    cTracks.forEach((t, i) => {
      var _a, _b;
      t.track.layout = "circular";
      t.track.outerRadius = TOTAL_RADIUS - PADDING - (t.boundingBox.y - dy) / cumHeight * TOTAL_RING_SIZE;
      t.track.innerRadius = TOTAL_RADIUS - PADDING - (t.boundingBox.y + t.boundingBox.height - dy) / cumHeight * TOTAL_RING_SIZE;
      const spacingAngle = SPACING / cumWidth * 360;
      t.track.startAngle = spacingAngle + (t.boundingBox.x - dx) / cumWidth * (cumWidth - SPACING) / cumWidth * 360;
      t.track.endAngle = (t.boundingBox.x + t.boundingBox.width - dx) / cumWidth * (cumWidth - SPACING) / cumWidth * 360;
      t.boundingBox.x = dx + ((_a = t.track.xOffset) != null ? _a : 0);
      t.boundingBox.y = dy + ((_b = t.track.yOffset) != null ? _b : 0);
      t.boundingBox.height = t.track.height = t.boundingBox.width = t.track.width = TOTAL_RADIUS * 2;
      if (i !== 0) {
        t.track.overlayOnPreviousTrack = true;
      }
      if (ifMultipleViews) {
        if (IsOverlaidTrack(t.track)) {
          t.track.overlay = t.track.overlay.filter((o) => o.mark !== "brush");
        }
      }
    });
    cumHeight = TOTAL_RADIUS * 2;
  }
  return { x: dx, y: dy, width: cumWidth, height: cumHeight };
}
function getNumOfXAxes(tracks) {
  return tracks.filter((t) => IsXAxis(t)).length;
}
function getNumOfYAxes(tracks) {
  return tracks.filter((t) => IsYAxis(t)).length;
}
const getTextTrack = (size, title2, subtitle) => {
  return JSON.parse(JSON.stringify({
    mark: "header",
    width: size.width,
    height: size.height,
    title: title2,
    subtitle
  }));
};
function parseServerAndTilesetUidFromUrl(url) {
  if (!url.includes("tileset_info/?d=") || !url.includes("https:") && !url.includes("http:")) {
    console.warn(`Data url format is incorrect:${url}`);
    return { server: void 0, tilesetUid: void 0 };
  }
  const server = url.split("tileset_info/?d=")[0];
  const tilesetUid = url.split("tileset_info/?d=")[1];
  return { server, tilesetUid };
}
function goslingToHiGlass(hgModel, gosTrack, bb, layout, theme) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
  const firstResolvedSpec = resolveSuperposedTracks(gosTrack)[0];
  if (!firstResolvedSpec.id) {
    firstResolvedSpec.id = v4();
  }
  const assembly = firstResolvedSpec.assembly;
  if (IsDataDeep(firstResolvedSpec.data)) {
    let server, tilesetUid;
    if (IsDataDeepTileset(firstResolvedSpec.data)) {
      const parsed = parseServerAndTilesetUidFromUrl(firstResolvedSpec.data.url);
      server = parsed.server;
      tilesetUid = parsed.tilesetUid;
    }
    const genomicChannel = getGenomicChannelFromTrack(firstResolvedSpec);
    const genomicChannelKey = getGenomicChannelKeyFromTrack(firstResolvedSpec);
    const isXGenomic = genomicChannelKey === "x" || genomicChannelKey === "xe";
    const xDomain = isXGenomic && IsChannelDeep(genomicChannel) ? genomicChannel.domain : void 0;
    const yDomain = Is2DTrack(firstResolvedSpec) && IsChannelDeep(firstResolvedSpec.y) ? firstResolvedSpec.y.domain : void 0;
    const width = bb.width - (firstResolvedSpec.layout !== "circular" && firstResolvedSpec.orientation === "vertical" && IsXAxis(firstResolvedSpec) ? HIGLASS_AXIS_SIZE : 0);
    const height = bb.height - (firstResolvedSpec.layout !== "circular" && firstResolvedSpec.orientation === "horizontal" && IsXAxis(firstResolvedSpec) ? HIGLASS_AXIS_SIZE : 0);
    const hgTrack = {
      uid: `${firstResolvedSpec.id}-track`,
      type: Is2DTrack(firstResolvedSpec) ? "gosling-2d-track" : "gosling-track",
      server,
      tilesetUid,
      width,
      height,
      options: {
        showMousePosition: firstResolvedSpec.layout === "circular" ? false : theme.root.showMousePosition,
        mousePositionColor: theme.root.mousePositionColor,
        name: firstResolvedSpec.layout === "linear" ? firstResolvedSpec.title : " ",
        labelPosition: firstResolvedSpec.title ? theme.track.titleAlign === "left" ? "topLeft" : "topRight" : "none",
        labelShowResolution: false,
        labelColor: theme.track.titleColor,
        labelBackgroundColor: theme.track.titleBackground,
        labelBackgroundOpacity: 0.5,
        labelTextOpacity: 1,
        labelLeftMargin: 1,
        labelTopMargin: 1,
        labelRightMargin: 0,
        labelBottomMargin: 0,
        backgroundColor: "transparent",
        spec: { ...gosTrack },
        theme
      }
    };
    if (firstResolvedSpec.data && IsDataDeep(firstResolvedSpec.data) && (firstResolvedSpec.data.type === "csv" || firstResolvedSpec.data.type === "json" || firstResolvedSpec.data.type === "bigwig" || firstResolvedSpec.data.type === "bam")) {
      hgTrack.data = {
        ...firstResolvedSpec.data,
        assembly
      };
    }
    if (IsHiGlassMatrix(firstResolvedSpec)) {
      hgTrack.type = "heatmap";
      const colorStr = IsChannelDeep(firstResolvedSpec.color) && typeof firstResolvedSpec.color.range === "string" ? firstResolvedSpec.color.range : "viridis";
      hgTrack.options.colorRange = getHiGlassColorRange(colorStr);
      hgTrack.options.trackBorderWidth = (_b = (_a = firstResolvedSpec.style) == null ? void 0 : _a.outlineWidth) != null ? _b : theme.track.outlineWidth;
      hgTrack.options.trackBorderColor = (_d = (_c = firstResolvedSpec.style) == null ? void 0 : _c.outline) != null ? _d : theme.track.outline;
      hgTrack.options.colorbarPosition = ((_e = firstResolvedSpec.color) == null ? void 0 : _e.legend) ? "topRight" : "hidden";
    }
    if (firstResolvedSpec.overlayOnPreviousTrack) {
      hgModel.setViewOrientation(firstResolvedSpec.orientation).addTrackToCombined(hgTrack);
    } else {
      hgModel.setViewOrientation(firstResolvedSpec.orientation).setAssembly(assembly).addDefaultView(firstResolvedSpec.id, assembly).setDomain(xDomain, yDomain != null ? yDomain : xDomain).adjustDomain(firstResolvedSpec.orientation, width, height).setMainTrack(hgTrack).addTrackSourceServers(server).setZoomFixed(firstResolvedSpec.static === true).setZoomLimits((_f = firstResolvedSpec.zoomLimits) != null ? _f : [1, null]).setLayout(layout);
    }
    const getAxisNarrowType = (c, orientation = "horizontal", width2, height2) => {
      const narrowSizeThreshold = 400;
      const narrowerSizeThreshold = 200;
      if (orientation === "horizontal") {
        if (c === "x" && width2 <= narrowerSizeThreshold || c === "y" && height2 <= narrowerSizeThreshold) {
          return "narrower";
        } else if (c === "x" && width2 <= narrowSizeThreshold || c === "y" && height2 <= narrowSizeThreshold) {
          return "narrow";
        } else {
          return "regular";
        }
      } else {
        if (c === "x" && height2 <= narrowerSizeThreshold || c === "y" && width2 <= narrowerSizeThreshold) {
          return "narrower";
        } else if (c === "x" && height2 <= narrowSizeThreshold || c === "y" && width2 <= narrowSizeThreshold) {
          return "narrow";
        } else {
          return "regular";
        }
      }
    };
    ["x", "y"].forEach((c) => {
      const channel = firstResolvedSpec[c];
      if (IsChannelDeep(channel) && "axis" in channel && channel.axis && channel.axis !== "none" && channel.type === "genomic") {
        const narrowType = getAxisNarrowType(c, gosTrack.orientation, bb.width, bb.height);
        hgModel.setAxisTrack(channel.axis, narrowType, {
          id: `${firstResolvedSpec.id}-${channel.axis}-axis`,
          layout: firstResolvedSpec.layout,
          innerRadius: channel.axis === "top" ? firstResolvedSpec.outerRadius - HIGLASS_AXIS_SIZE : firstResolvedSpec.innerRadius,
          outerRadius: channel.axis === "top" ? firstResolvedSpec.outerRadius : firstResolvedSpec.innerRadius + HIGLASS_AXIS_SIZE,
          width: firstResolvedSpec.width,
          height: firstResolvedSpec.height,
          startAngle: firstResolvedSpec.startAngle,
          endAngle: firstResolvedSpec.endAngle,
          theme
        });
      }
    });
    hgModel.validateSpec(true);
  } else if (firstResolvedSpec.mark === "header") {
    hgModel.addDefaultView(`${firstResolvedSpec.id}-title`).setLayout(layout);
    if (typeof firstResolvedSpec.title === "string") {
      hgModel.setTextTrack(bb.width, ((_g = theme.root.titleFontSize) != null ? _g : 18) + DEWFAULT_TITLE_PADDING_ON_TOP_AND_BOTTOM, firstResolvedSpec.title, theme.root.titleColor, (_h = theme.root.titleFontSize) != null ? _h : 18, theme.root.titleFontWeight, theme.root.titleAlign, theme.root.titleBackgroundColor, (_i = theme.root.titleFontFamily) != null ? _i : DEFAULT_TEXT_STYLE.fontFamily);
    }
    if (typeof firstResolvedSpec.subtitle === "string") {
      hgModel.setTextTrack(bb.width, ((_j = theme.root.subtitleFontSize) != null ? _j : 14) + DEWFAULT_TITLE_PADDING_ON_TOP_AND_BOTTOM, firstResolvedSpec.subtitle, theme.root.subtitleColor, (_k = theme.root.subtitleFontSize) != null ? _k : 14, theme.root.subtitleFontWeight, theme.root.subtitleAlign, theme.root.subtitleBackgroundColor, (_l = theme.root.subtitleFontFamily) != null ? _l : DEFAULT_TEXT_STYLE.fontFamily);
    }
  }
  return hgModel;
}
function getLinkingInfo(hgModel) {
  const linkingInfo = [];
  hgModel.spec().views.forEach((v) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
    const viewId = v.uid;
    let spec = (_e = (_d = (_c = (_b = (_a = v.tracks.center) == null ? void 0 : _a[0]) == null ? void 0 : _b.contents) == null ? void 0 : _c[0]) == null ? void 0 : _d.options) == null ? void 0 : _e.spec;
    if (!spec) {
      spec = (_j = (_i = (_h = (_g = (_f = v.tracks.left) == null ? void 0 : _f[0]) == null ? void 0 : _g.contents) == null ? void 0 : _h[0]) == null ? void 0 : _i.options) == null ? void 0 : _j.spec;
      if (!spec) {
        spec = (_o = (_n = (_m = (_l = (_k = v.tracks.left) == null ? void 0 : _k[1]) == null ? void 0 : _l.contents) == null ? void 0 : _m[0]) == null ? void 0 : _n.options) == null ? void 0 : _o.spec;
      }
    }
    if (!viewId || !spec)
      return;
    const resolved = resolveSuperposedTracks(spec);
    resolved.forEach((spec2) => {
      SUPPORTED_CHANNELS.forEach((cKey) => {
        var _a2, _b2, _c2, _d2;
        const channel = spec2[cKey];
        if (IsChannelDeep(channel) && "linkingId" in channel && channel.linkingId) {
          linkingInfo.push({
            layout: spec2.layout === "circular" ? "circular" : "linear",
            viewId,
            linkId: channel.linkingId,
            isBrush: spec2.mark === "brush",
            style: {
              color: (_a2 = spec2.color) == null ? void 0 : _a2.value,
              stroke: (_b2 = spec2.stroke) == null ? void 0 : _b2.value,
              strokeWidth: (_c2 = spec2.strokeWidth) == null ? void 0 : _c2.value,
              opacity: (_d2 = spec2.opacity) == null ? void 0 : _d2.value,
              startAngle: spec2.startAngle,
              endAngle: spec2.endAngle,
              innerRadius: spec2.innerRadius,
              outerRadius: spec2.outerRadius
            }
          });
          return;
        }
      });
    });
  });
  return linkingInfo;
}
function renderHiGlass(spec, trackInfos, setHg, theme) {
  if (trackInfos.length === 0) {
    return;
  }
  const hgModel = new HiGlassModel();
  trackInfos.forEach((tb) => {
    const { track, boundingBox: bb, layout } = tb;
    goslingToHiGlass(hgModel, track, bb, layout, theme);
  });
  const linkingInfos = getLinkingInfo(hgModel);
  linkingInfos.filter((d) => d.isBrush).forEach((info) => {
    var _a;
    hgModel.addBrush(info.layout, info.viewId, theme, (_a = linkingInfos.find((d) => !d.isBrush && d.linkId === info.linkId)) == null ? void 0 : _a.viewId, info.style);
  });
  linkingInfos.filter((d) => !d.isBrush).forEach((d) => {
    hgModel.spec().zoomLocks.locksByViewUid[d.viewId] = d.linkId;
    hgModel.spec().locationLocks.locksByViewUid[d.viewId] = d.linkId;
  });
  const uniqueLinkIds = Array.from(new Set(linkingInfos.map((d) => d.linkId)));
  uniqueLinkIds.forEach((linkId) => {
    hgModel.spec().zoomLocks.locksDict[linkId] = { uid: linkId };
    hgModel.spec().locationLocks.locksDict[linkId] = { uid: linkId };
    linkingInfos.filter((d) => !d.isBrush).filter((d) => d.linkId === linkId).forEach((d) => {
      hgModel.spec().zoomLocks.locksDict[linkId][d.viewId] = [1246253105e-1, 1246253105e-1, 249250.621];
      hgModel.spec().locationLocks.locksDict[linkId][d.viewId] = [1246253105e-1, 1246253105e-1, 249250.621];
    });
  });
  setHg(hgModel.spec(), getBoundingBox(trackInfos));
}
function compileLayout(spec, setHg, theme) {
  const trackInfo = getRelativeTrackInfo(spec, theme);
  renderHiGlass(spec, trackInfo, setHg, theme);
}
function compile(spec, setHg, templates, theme) {
  const _spec = JSON.parse(JSON.stringify(spec));
  overrideDataTemplates(_spec);
  replaceTrackTemplates(_spec, templates);
  traverseToFixSpecDownstream(_spec);
  compileLayout(_spec, setHg, theme);
}
init();
const HiGlassComponentWrapper = (0,consume_shared_module_default_react_17_0_singleton_.forwardRef)((props, ref2) => {
  var _a;
  const [wrapperDivId, setWrapperDivId] = (0,consume_shared_module_default_react_17_0_singleton_.useState)((_a = props.id) != null ? _a : v4());
  (0,consume_shared_module_default_react_17_0_singleton_.useEffect)(() => {
    var _a2;
    setWrapperDivId((_a2 = props.id) != null ? _a2 : v4());
  }, [props.id]);
  const viewConfig = props.viewConfig || {};
  const higlassComponent = (0,consume_shared_module_default_react_17_0_singleton_.useMemo)(() => /* @__PURE__ */ consume_shared_module_default_react_17_0_singleton_default().createElement(hglib.HiGlassComponent, {
    ref: ref2,
    options: {
      pixelPreciseMarginPadding: !props.options.responsiveHeight,
      containerPaddingX: 0,
      containerPaddingY: 0,
      viewMarginTop: 0,
      viewMarginBottom: 0,
      viewMarginLeft: 0,
      viewMarginRight: 0,
      viewPaddingTop: 0,
      viewPaddingBottom: 0,
      viewPaddingLeft: 0,
      viewPaddingRight: 0,
      sizeMode: "bounded",
      rangeSelectionOnAlt: true
    },
    viewConfig
  }), [viewConfig]);
  const { padding = 60, margin = 0, border = "none", background } = props.options || {};
  return /* @__PURE__ */ consume_shared_module_default_react_17_0_singleton_default().createElement((consume_shared_module_default_react_17_0_singleton_default()).Fragment, null, /* @__PURE__ */ consume_shared_module_default_react_17_0_singleton_default().createElement("div", {
    id: wrapperDivId,
    className: `gosling-component ${props.className || ""}`,
    style: {
      position: "relative",
      padding,
      margin,
      border,
      background,
      width: props.options.responsiveWidth ? `calc(100% - ${padding * 2}px)` : props.size.width,
      height: props.options.responsiveHeight ? `calc(100% - ${padding * 2}px)` : props.size.height,
      textAlign: "left"
    }
  }, /* @__PURE__ */ consume_shared_module_default_react_17_0_singleton_default().createElement("div", {
    key: JSON.stringify(viewConfig),
    id: "higlass-wrapper",
    className: "higlass-wrapper",
    style: {
      position: "relative",
      display: "block",
      background,
      margin: 0,
      padding: 0,
      width: props.options.responsiveWidth ? "100%" : props.size.width,
      height: props.options.responsiveHeight ? "100%" : props.size.height
    }
  }, higlassComponent)));
});
HiGlassComponentWrapper.displayName = "HiGlassComponentWrapper";
function traverseViewsInViewConfig(viewConf, callback) {
  if (viewConf && viewConf.views && Array.isArray(viewConf.views)) {
    viewConf.views.forEach((view) => {
      if (view && view.uid) {
        callback(view);
      }
    });
  }
}
function createApi(hgRef, hgSpec, theme) {
  const getHg = () => {
    if ("api" in hgRef)
      return hgRef;
    if (hgRef.current)
      return hgRef.current;
    throw new Error("HiGlass ref not initalized");
  };
  const getCanvas = (options) => {
    var _a, _b;
    const hg = getHg();
    const resolution = (_a = options == null ? void 0 : options.resolution) != null ? _a : 4;
    const transparentBackground = (_b = options == null ? void 0 : options.transparentBackground) != null ? _b : false;
    const renderer = hg.pixiRenderer;
    const renderTexture = pixi.RenderTexture.create({
      width: renderer.width / 2,
      height: renderer.height / 2,
      resolution
    });
    renderer.render(hg.pixiStage, renderTexture);
    const canvas = renderer.plugins.extract.canvas(renderTexture);
    const canvasWithBg = document.createElement("canvas");
    canvasWithBg.width = canvas.width;
    canvasWithBg.height = canvas.height;
    const ctx = canvasWithBg.getContext("2d");
    if (!transparentBackground) {
      ctx.fillStyle = theme.root.background;
      ctx.fillRect(0, 0, canvasWithBg.width, canvasWithBg.height);
    }
    ctx.drawImage(canvas, 0, 0);
    return {
      canvas: canvasWithBg,
      resolution,
      canvasWidth: canvas.width,
      canvasHeight: canvas.height
    };
  };
  return {
    subscribe: (type2, callback) => {
      switch (type2) {
        case "mouseover":
          return PubSub.subscribe(type2, callback);
        case "click":
          return PubSub.subscribe(type2, callback);
        case "rawdata":
          return PubSub.subscribe(type2, callback);
        default: {
          console.error(`Event type not recognized, got ${JSON.stringify(type2)}.`);
          return void 0;
        }
      }
    },
    unsubscribe: (tokenOrFunction) => PubSub.unsubscribe(tokenOrFunction),
    zoomTo: (viewId, position, padding = 0, duration = 1e3) => {
      var _a, _b, _c, _d;
      if (!position.includes("chr")) {
        console.warn("Genomic interval you entered is not in a correct form.");
        return;
      }
      const chr = position.split(":")[0];
      const chrStart = (_b = (_a = GET_CHROM_SIZES().interval) == null ? void 0 : _a[chr]) == null ? void 0 : _b[0];
      if (!chr || typeof chrStart === void 0) {
        console.warn("Chromosome name is not valid", chr);
        return;
      }
      const [s, e] = (_d = (_c = position.split(":")[1]) == null ? void 0 : _c.split("-")) != null ? _d : [0, GET_CHROM_SIZES().size[chr]];
      const start = +s + chrStart - padding;
      const end = +e + chrStart + padding;
      getHg().api.zoomTo(viewId, start, end, start, end, duration);
    },
    zoomToExtent: (viewId, duration = 1e3) => {
      const [start, end] = [0, GET_CHROM_SIZES().total];
      getHg().api.zoomTo(viewId, start, end, start, end, duration);
    },
    zoomToGene: (viewId, gene, padding = 0, duration = 1e3) => {
      getHg().api.zoomToGene(viewId, gene, padding, duration);
    },
    suggestGene: (viewId, keyword2, callback) => {
      getHg().api.suggestGene(viewId, keyword2, callback);
    },
    getViewIds: () => {
      if (!hgSpec)
        return [];
      const ids = [];
      traverseViewsInViewConfig(hgSpec, (view) => {
        if (view.uid)
          ids.push(view.uid);
      });
      return ids;
    },
    getCanvas,
    exportPng: (transparentBackground) => {
      const { canvas } = getCanvas({ resolution: 4, transparentBackground });
      canvas.toBlob((blob2) => {
        const a = document.createElement("a");
        document.body.append(a);
        a.download = "gosling-visualization";
        a.href = URL.createObjectURL(blob2);
        a.click();
        a.remove();
      }, "image/png");
    },
    exportPdf: async (transparentBackground) => {
      const { jsPDF } = await __webpack_require__.e(/* import() */ 771).then(__webpack_require__.bind(__webpack_require__, 1771));
      const { canvas } = getCanvas({ resolution: 4, transparentBackground });
      const imgData = canvas.toDataURL("image/jpeg", 1);
      const pdf = new jsPDF({
        orientation: canvas.width < canvas.height ? "p" : "l",
        unit: "pt",
        format: [canvas.width, canvas.height]
      });
      pdf.addImage(imgData, "JPEG", 0, 0, canvas.width, canvas.height);
      pdf.save("gosling-visualization.pdf");
    }
  };
}
const GoslingComponent = (0,consume_shared_module_default_react_17_0_singleton_.forwardRef)((props, ref2) => {
  const [viewConfig, setViewConfig] = (0,consume_shared_module_default_react_17_0_singleton_.useState)();
  const [size, setSize] = (0,consume_shared_module_default_react_17_0_singleton_.useState)({ width: 200, height: 200 });
  const hgRef = (0,consume_shared_module_default_react_17_0_singleton_.useRef)();
  const theme = getTheme(props.theme || "light");
  (0,consume_shared_module_default_react_17_0_singleton_.useEffect)(() => {
    if (!ref2)
      return;
    const api = createApi(hgRef, viewConfig, theme);
    if (typeof ref2 == "function") {
      ref2({ hgRef, api });
    } else {
      ref2.current = { hgRef, api };
    }
  }, [ref2, hgRef, viewConfig, theme]);
  (0,consume_shared_module_default_react_17_0_singleton_.useEffect)(() => {
    if (props.spec) {
      const valid = validateGoslingSpec(props.spec);
      if (valid.state === "error") {
        console.warn("Gosling spec is not valid. Please refer to the console message.");
        return;
      }
      compile(props.spec, (newHs, newSize) => {
        var _a, _b, _c;
        (_a = props.compiled) == null ? void 0 : _a.call(props, props.spec, newHs);
        setSize(newSize);
        const isMountedOnce = typeof viewConfig !== "undefined";
        if (((_b = props.experimental) == null ? void 0 : _b.reactive) && isMountedOnce) {
          (_c = hgRef.current) == null ? void 0 : _c.api.setViewConfig(newHs);
        } else {
          setViewConfig(newHs);
        }
      }, [...GoslingTemplates], theme);
    }
  }, [props.spec, theme]);
  const higlassComponent = (0,consume_shared_module_default_react_17_0_singleton_.useMemo)(() => {
    var _a, _b, _c, _d;
    return /* @__PURE__ */ consume_shared_module_default_react_17_0_singleton_default().createElement(HiGlassComponentWrapper, {
      ref: hgRef,
      viewConfig,
      size,
      id: props.id,
      className: props.className,
      options: {
        padding: props.padding,
        border: props.border,
        margin: props.margin,
        responsiveWidth: typeof ((_a = props.spec) == null ? void 0 : _a.responsiveSize) !== "object" ? (_b = props.spec) == null ? void 0 : _b.responsiveSize : props.spec.responsiveSize.width,
        responsiveHeight: typeof ((_c = props.spec) == null ? void 0 : _c.responsiveSize) !== "object" ? (_d = props.spec) == null ? void 0 : _d.responsiveSize : props.spec.responsiveSize.height,
        background: theme.root.background
      }
    });
  }, [viewConfig, size, theme]);
  return higlassComponent;
});
const MAX_TRIES = 20;
const INTERVAL = 200;
const launchHiglass = (element, viewConfig, size, opts) => {
  const ref2 = consume_shared_module_default_react_17_0_singleton_default().createRef();
  const component = consume_shared_module_default_react_17_0_singleton_default().createElement(HiGlassComponentWrapper, {
    ref: ref2,
    viewConfig,
    size,
    id: opts.id,
    className: opts.className,
    options: opts
  });
  consume_shared_module_default_react_dom_17_0_singleton_default().render(component, element);
  return new Promise((resolve2, reject) => {
    let tries = 0;
    const poll = setInterval(() => {
      if (ref2 && ref2.current) {
        clearInterval(poll);
        resolve2(ref2.current);
      }
      if (tries >= MAX_TRIES) {
        reject(new Error("Failed to initialize HiGlassApi."));
      }
      tries++;
    }, INTERVAL);
  });
};
function gosling_es_embed(element, spec, opts = {}) {
  return new Promise((resolve2, reject) => {
    const valid = validateGoslingSpec(spec);
    if (valid.state === "error") {
      reject(new Error("Gosling spec is not valid. Please refer to the console message."));
    }
    const theme = getTheme(opts.theme || "light");
    const options = { ...opts, background: theme.root.background };
    compile(spec, async (hsSpec, size) => {
      const hg = await launchHiglass(element, hsSpec, size, options);
      const api = createApi(hg, hsSpec, theme);
      resolve2(api);
    }, [...GoslingTemplates], theme);
  });
}
const { name: gosling_es_name, version } = pkg;

//# sourceMappingURL=gosling.es.js.map


/***/ }),

/***/ 1722:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

// The MIT License (MIT)
//
// Copyright (c) 2014 Jonas Finnemann Jensen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

module.exports = __webpack_require__(2063);


/***/ }),

/***/ 2063:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

// The MIT License (MIT)
//
// Copyright (c) 2014 Jonas Finnemann Jensen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

var uuidv4 = __webpack_require__(533);
var uuidParse = __webpack_require__(3162);

/**
 * Returns the given uuid as a 22 character slug. This can be a regular v4
 * slug or a "nice" slug.
 */
exports.encode = function(uuid_) {
  var bytes   = uuidParse.parse(uuid_);
  var base64  = (new Buffer(bytes)).toString('base64');
  var slug = base64
              .replace(/\+/g, '-')  // Replace + with - (see RFC 4648, sec. 5)
              .replace(/\//g, '_')  // Replace / with _ (see RFC 4648, sec. 5)
              .substring(0, 22);    // Drop '==' padding
  return slug;
};

/**
 * Returns the uuid represented by the given v4 or "nice" slug
 */
exports.decode = function(slug) {
  var base64 = slug
                  .replace(/-/g, '+')
                  .replace(/_/g, '/')
                  + '==';
  return uuidParse.unparse(new Buffer(base64, 'base64'));
};

/**
 * Returns a randomly generated uuid v4 compliant slug
 */
exports.v4 = function() {
  var bytes   = uuidv4(null, new Buffer(16));
  var base64  = bytes.toString('base64');
  var slug = base64
              .replace(/\+/g, '-')  // Replace + with - (see RFC 4648, sec. 5)
              .replace(/\//g, '_')  // Replace / with _ (see RFC 4648, sec. 5)
              .substring(0, 22);    // Drop '==' padding
  return slug;
};

/**
 * Returns a randomly generated uuid v4 compliant slug which conforms to a set
 * of "nice" properties, at the cost of some entropy. Currently this means one
 * extra fixed bit (the first bit of the uuid is set to 0) which guarantees the
 * slug will begin with [A-Za-f]. For example such slugs don't require special
 * handling when used as command line parameters (whereas non-nice slugs may
 * start with `-` which can confuse command line tools).
 *
 * Potentially other "nice" properties may be added in future to further
 * restrict the range of potential uuids that may be generated.
 */
exports.nice = function() {
  var bytes   = uuidv4(null, new Buffer(16));
  bytes[0] = bytes[0] & 0x7f;  // unset first bit to ensure [A-Za-f] first char
  var base64  = bytes.toString('base64');
  var slug = base64
              .replace(/\+/g, '-')  // Replace + with - (see RFC 4648, sec. 5)
              .replace(/\//g, '_')  // Replace / with _ (see RFC 4648, sec. 5)
              .substring(0, 22);    // Drop '==' padding
  return slug;
};


/***/ }),

/***/ 1216:
/***/ ((module) => {

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
  byteToHex[i] = (i + 0x100).toString(16).substr(1);
}

function bytesToUuid(buf, offset) {
  var i = offset || 0;
  var bth = byteToHex;
  // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  return ([
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]]
  ]).join('');
}

module.exports = bytesToUuid;


/***/ }),

/***/ 1519:
/***/ ((module) => {

// Unique ID creation requires a high quality random # generator.  In the
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API.  We do the best we can via
// feature-detection

// getRandomValues needs to be invoked in a context where "this" is a Crypto
// implementation. Also, find the complete implementation of crypto on IE11.
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
                      (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));

if (getRandomValues) {
  // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef

  module.exports = function whatwgRNG() {
    getRandomValues(rnds8);
    return rnds8;
  };
} else {
  // Math.random()-based (RNG)
  //
  // If all else fails, use Math.random().  It's fast, but is of unspecified
  // quality.
  var rnds = new Array(16);

  module.exports = function mathRNG() {
    for (var i = 0, r; i < 16; i++) {
      if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
      rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
    }

    return rnds;
  };
}


/***/ }),

/***/ 533:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var rng = __webpack_require__(1519);
var bytesToUuid = __webpack_require__(1216);

function v4(options, buf, offset) {
  var i = buf && offset || 0;

  if (typeof(options) == 'string') {
    buf = options === 'binary' ? new Array(16) : null;
    options = null;
  }
  options = options || {};

  var rnds = options.random || (options.rng || rng)();

  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = (rnds[6] & 0x0f) | 0x40;
  rnds[8] = (rnds[8] & 0x3f) | 0x80;

  // Copy bytes to buffer, if provided
  if (buf) {
    for (var ii = 0; ii < 16; ++ii) {
      buf[i + ii] = rnds[ii];
    }
  }

  return buf || bytesToUuid(rnds);
}

module.exports = v4;


/***/ }),

/***/ 7949:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

(function webpackUniversalModuleDefinition(root, factory) {
	if(true)
		module.exports = factory(__webpack_require__(6271), __webpack_require__(4456), __webpack_require__(9618));
	else {}
})(window, function(__WEBPACK_EXTERNAL_MODULE__1__, __WEBPACK_EXTERNAL_MODULE__42__, __WEBPACK_EXTERNAL_MODULE__325__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __nested_webpack_require_824__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __nested_webpack_require_824__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__nested_webpack_require_824__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__nested_webpack_require_824__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__nested_webpack_require_824__.d = function(exports, name, getter) {
/******/ 		if(!__nested_webpack_require_824__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__nested_webpack_require_824__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__nested_webpack_require_824__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __nested_webpack_require_824__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__nested_webpack_require_824__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __nested_webpack_require_824__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__nested_webpack_require_824__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__nested_webpack_require_824__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__nested_webpack_require_824__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__nested_webpack_require_824__.p = "/";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __nested_webpack_require_824__(__nested_webpack_require_824__.s = 317);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_4303__) {

"use strict";
__nested_webpack_require_4303__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";

/* harmony default export */ var namespaces = ({
  svg: "http://www.w3.org/2000/svg",
  xhtml: xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/namespace.js


/* harmony default export */ var namespace = (function(name) {
  var prefix = name += "", i = prefix.indexOf(":");
  if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
  return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/creator.js



function creatorInherit(name) {
  return function() {
    var document = this.ownerDocument,
        uri = this.namespaceURI;
    return uri === xhtml && document.documentElement.namespaceURI === xhtml
        ? document.createElement(name)
        : document.createElementNS(uri, name);
  };
}

function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}

/* harmony default export */ var creator = (function(name) {
  var fullname = namespace(name);
  return (fullname.local
      ? creatorFixed
      : creatorInherit)(fullname);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selector.js
function none() {}

/* harmony default export */ var src_selector = (function(selector) {
  return selector == null ? none : function() {
    return this.querySelector(selector);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/select.js



/* harmony default export */ var selection_select = (function(select) {
  if (typeof select !== "function") select = src_selector(select);

  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
      if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
      }
    }
  }

  return new Selection(subgroups, this._parents);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selectorAll.js
function empty() {
  return [];
}

/* harmony default export */ var selectorAll = (function(selector) {
  return selector == null ? empty : function() {
    return this.querySelectorAll(selector);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/selectAll.js



/* harmony default export */ var selectAll = (function(select) {
  if (typeof select !== "function") select = selectorAll(select);

  for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        subgroups.push(select.call(node, node.__data__, i, group));
        parents.push(node);
      }
    }
  }

  return new Selection(subgroups, parents);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/matcher.js
/* harmony default export */ var matcher = (function(selector) {
  return function() {
    return this.matches(selector);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/filter.js



/* harmony default export */ var filter = (function(match) {
  if (typeof match !== "function") match = matcher(match);

  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
      if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
        subgroup.push(node);
      }
    }
  }

  return new Selection(subgroups, this._parents);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/sparse.js
/* harmony default export */ var sparse = (function(update) {
  return new Array(update.length);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/enter.js



/* harmony default export */ var selection_enter = (function() {
  return new Selection(this._enter || this._groups.map(sparse), this._parents);
});

function EnterNode(parent, datum) {
  this.ownerDocument = parent.ownerDocument;
  this.namespaceURI = parent.namespaceURI;
  this._next = null;
  this._parent = parent;
  this.__data__ = datum;
}

EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child) { return this._parent.insertBefore(child, this._next); },
  insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },
  querySelector: function(selector) { return this._parent.querySelector(selector); },
  querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }
};

// CONCATENATED MODULE: ../node_modules/d3-selection/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/data.js




var keyPrefix = "$"; // Protect against keys like “__proto__”.

function bindIndex(parent, group, enter, update, exit, data) {
  var i = 0,
      node,
      groupLength = group.length,
      dataLength = data.length;

  // Put any non-null nodes that fit into update.
  // Put any null nodes into enter.
  // Put any remaining data into enter.
  for (; i < dataLength; ++i) {
    if (node = group[i]) {
      node.__data__ = data[i];
      update[i] = node;
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }

  // Put any non-null nodes that don’t fit into exit.
  for (; i < groupLength; ++i) {
    if (node = group[i]) {
      exit[i] = node;
    }
  }
}

function bindKey(parent, group, enter, update, exit, data, key) {
  var i,
      node,
      nodeByKeyValue = {},
      groupLength = group.length,
      dataLength = data.length,
      keyValues = new Array(groupLength),
      keyValue;

  // Compute the key for each node.
  // If multiple nodes have the same key, the duplicates are added to exit.
  for (i = 0; i < groupLength; ++i) {
    if (node = group[i]) {
      keyValues[i] = keyValue = keyPrefix + key.call(node, node.__data__, i, group);
      if (keyValue in nodeByKeyValue) {
        exit[i] = node;
      } else {
        nodeByKeyValue[keyValue] = node;
      }
    }
  }

  // Compute the key for each datum.
  // If there a node associated with this key, join and add it to update.
  // If there is not (or the key is a duplicate), add it to enter.
  for (i = 0; i < dataLength; ++i) {
    keyValue = keyPrefix + key.call(parent, data[i], i, data);
    if (node = nodeByKeyValue[keyValue]) {
      update[i] = node;
      node.__data__ = data[i];
      nodeByKeyValue[keyValue] = null;
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }

  // Add any remaining nodes that were not bound to data to exit.
  for (i = 0; i < groupLength; ++i) {
    if ((node = group[i]) && (nodeByKeyValue[keyValues[i]] === node)) {
      exit[i] = node;
    }
  }
}

/* harmony default export */ var selection_data = (function(value, key) {
  if (!value) {
    data = new Array(this.size()), j = -1;
    this.each(function(d) { data[++j] = d; });
    return data;
  }

  var bind = key ? bindKey : bindIndex,
      parents = this._parents,
      groups = this._groups;

  if (typeof value !== "function") value = constant(value);

  for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
    var parent = parents[j],
        group = groups[j],
        groupLength = group.length,
        data = value.call(parent, parent && parent.__data__, j, parents),
        dataLength = data.length,
        enterGroup = enter[j] = new Array(dataLength),
        updateGroup = update[j] = new Array(dataLength),
        exitGroup = exit[j] = new Array(groupLength);

    bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);

    // Now connect the enter nodes to their following update node, such that
    // appendChild can insert the materialized enter node before this node,
    // rather than at the end of the parent node.
    for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1) i1 = i0 + 1;
        while (!(next = updateGroup[i1]) && ++i1 < dataLength);
        previous._next = next || null;
      }
    }
  }

  update = new Selection(update, parents);
  update._enter = enter;
  update._exit = exit;
  return update;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/exit.js



/* harmony default export */ var selection_exit = (function() {
  return new Selection(this._exit || this._groups.map(sparse), this._parents);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/join.js
/* harmony default export */ var join = (function(onenter, onupdate, onexit) {
  var enter = this.enter(), update = this, exit = this.exit();
  enter = typeof onenter === "function" ? onenter(enter) : enter.append(onenter + "");
  if (onupdate != null) update = onupdate(update);
  if (onexit == null) exit.remove(); else onexit(exit);
  return enter && update ? enter.merge(update).order() : update;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/merge.js


/* harmony default export */ var selection_merge = (function(selection) {

  for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge[i] = node;
      }
    }
  }

  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }

  return new Selection(merges, this._parents);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/order.js
/* harmony default export */ var order = (function() {

  for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {
    for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {
      if (node = group[i]) {
        if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next);
        next = node;
      }
    }
  }

  return this;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/sort.js


/* harmony default export */ var sort = (function(compare) {
  if (!compare) compare = ascending;

  function compareNode(a, b) {
    return a && b ? compare(a.__data__, b.__data__) : !a - !b;
  }

  for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        sortgroup[i] = node;
      }
    }
    sortgroup.sort(compareNode);
  }

  return new Selection(sortgroups, this._parents).order();
});

function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/call.js
/* harmony default export */ var call = (function() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/nodes.js
/* harmony default export */ var nodes = (function() {
  var nodes = new Array(this.size()), i = -1;
  this.each(function() { nodes[++i] = this; });
  return nodes;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/node.js
/* harmony default export */ var selection_node = (function() {

  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
      var node = group[i];
      if (node) return node;
    }
  }

  return null;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/size.js
/* harmony default export */ var size = (function() {
  var size = 0;
  this.each(function() { ++size; });
  return size;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/empty.js
/* harmony default export */ var selection_empty = (function() {
  return !this.node();
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/each.js
/* harmony default export */ var each = (function(callback) {

  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
      if (node = group[i]) callback.call(node, node.__data__, i, group);
    }
  }

  return this;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/attr.js


function attrRemove(name) {
  return function() {
    this.removeAttribute(name);
  };
}

function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}

function attrConstant(name, value) {
  return function() {
    this.setAttribute(name, value);
  };
}

function attrConstantNS(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}

function attrFunction(name, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttribute(name);
    else this.setAttribute(name, v);
  };
}

function attrFunctionNS(fullname, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
    else this.setAttributeNS(fullname.space, fullname.local, v);
  };
}

/* harmony default export */ var attr = (function(name, value) {
  var fullname = namespace(name);

  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local
        ? node.getAttributeNS(fullname.space, fullname.local)
        : node.getAttribute(fullname);
  }

  return this.each((value == null
      ? (fullname.local ? attrRemoveNS : attrRemove) : (typeof value === "function"
      ? (fullname.local ? attrFunctionNS : attrFunction)
      : (fullname.local ? attrConstantNS : attrConstant)))(fullname, value));
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/window.js
/* harmony default export */ var src_window = (function(node) {
  return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node
      || (node.document && node) // node is a Window
      || node.defaultView; // node is a Document
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/style.js


function styleRemove(name) {
  return function() {
    this.style.removeProperty(name);
  };
}

function styleConstant(name, value, priority) {
  return function() {
    this.style.setProperty(name, value, priority);
  };
}

function styleFunction(name, value, priority) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.style.removeProperty(name);
    else this.style.setProperty(name, v, priority);
  };
}

/* harmony default export */ var style = (function(name, value, priority) {
  return arguments.length > 1
      ? this.each((value == null
            ? styleRemove : typeof value === "function"
            ? styleFunction
            : styleConstant)(name, value, priority == null ? "" : priority))
      : styleValue(this.node(), name);
});

function styleValue(node, name) {
  return node.style.getPropertyValue(name)
      || src_window(node).getComputedStyle(node, null).getPropertyValue(name);
}

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/property.js
function propertyRemove(name) {
  return function() {
    delete this[name];
  };
}

function propertyConstant(name, value) {
  return function() {
    this[name] = value;
  };
}

function propertyFunction(name, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) delete this[name];
    else this[name] = v;
  };
}

/* harmony default export */ var property = (function(name, value) {
  return arguments.length > 1
      ? this.each((value == null
          ? propertyRemove : typeof value === "function"
          ? propertyFunction
          : propertyConstant)(name, value))
      : this.node()[name];
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/classed.js
function classArray(string) {
  return string.trim().split(/^|\s+/);
}

function classList(node) {
  return node.classList || new ClassList(node);
}

function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}

ClassList.prototype = {
  add: function(name) {
    var i = this._names.indexOf(name);
    if (i < 0) {
      this._names.push(name);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name) {
    var i = this._names.indexOf(name);
    if (i >= 0) {
      this._names.splice(i, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name) {
    return this._names.indexOf(name) >= 0;
  }
};

function classedAdd(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n) list.add(names[i]);
}

function classedRemove(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n) list.remove(names[i]);
}

function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}

function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}

function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}

/* harmony default export */ var classed = (function(name, value) {
  var names = classArray(name + "");

  if (arguments.length < 2) {
    var list = classList(this.node()), i = -1, n = names.length;
    while (++i < n) if (!list.contains(names[i])) return false;
    return true;
  }

  return this.each((typeof value === "function"
      ? classedFunction : value
      ? classedTrue
      : classedFalse)(names, value));
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/text.js
function textRemove() {
  this.textContent = "";
}

function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}

function textFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.textContent = v == null ? "" : v;
  };
}

/* harmony default export */ var selection_text = (function(value) {
  return arguments.length
      ? this.each(value == null
          ? textRemove : (typeof value === "function"
          ? textFunction
          : textConstant)(value))
      : this.node().textContent;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
  this.innerHTML = "";
}

function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}

function htmlFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.innerHTML = v == null ? "" : v;
  };
}

/* harmony default export */ var html = (function(value) {
  return arguments.length
      ? this.each(value == null
          ? htmlRemove : (typeof value === "function"
          ? htmlFunction
          : htmlConstant)(value))
      : this.node().innerHTML;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/raise.js
function raise() {
  if (this.nextSibling) this.parentNode.appendChild(this);
}

/* harmony default export */ var selection_raise = (function() {
  return this.each(raise);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/lower.js
function lower() {
  if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}

/* harmony default export */ var selection_lower = (function() {
  return this.each(lower);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/append.js


/* harmony default export */ var append = (function(name) {
  var create = typeof name === "function" ? name : creator(name);
  return this.select(function() {
    return this.appendChild(create.apply(this, arguments));
  });
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/insert.js



function constantNull() {
  return null;
}

/* harmony default export */ var insert = (function(name, before) {
  var create = typeof name === "function" ? name : creator(name),
      select = before == null ? constantNull : typeof before === "function" ? before : src_selector(before);
  return this.select(function() {
    return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
  });
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/remove.js
function remove() {
  var parent = this.parentNode;
  if (parent) parent.removeChild(this);
}

/* harmony default export */ var selection_remove = (function() {
  return this.each(remove);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
  return this.parentNode.insertBefore(this.cloneNode(false), this.nextSibling);
}

function selection_cloneDeep() {
  return this.parentNode.insertBefore(this.cloneNode(true), this.nextSibling);
}

/* harmony default export */ var clone = (function(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/datum.js
/* harmony default export */ var datum = (function(value) {
  return arguments.length
      ? this.property("__data__", value)
      : this.node().__data__;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/on.js
var filterEvents = {};

var on_event = null;

if (typeof document !== "undefined") {
  var on_element = document.documentElement;
  if (!("onmouseenter" in on_element)) {
    filterEvents = {mouseenter: "mouseover", mouseleave: "mouseout"};
  }
}

function filterContextListener(listener, index, group) {
  listener = contextListener(listener, index, group);
  return function(event) {
    var related = event.relatedTarget;
    if (!related || (related !== this && !(related.compareDocumentPosition(this) & 8))) {
      listener.call(this, event);
    }
  };
}

function contextListener(listener, index, group) {
  return function(event1) {
    var event0 = on_event; // Events can be reentrant (e.g., focus).
    on_event = event1;
    try {
      listener.call(this, this.__data__, index, group);
    } finally {
      on_event = event0;
    }
  };
}

function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    return {type: t, name: name};
  });
}

function onRemove(typename) {
  return function() {
    var on = this.__on;
    if (!on) return;
    for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
      if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.capture);
      } else {
        on[++i] = o;
      }
    }
    if (++i) on.length = i;
    else delete this.__on;
  };
}

function onAdd(typename, value, capture) {
  var wrap = filterEvents.hasOwnProperty(typename.type) ? filterContextListener : contextListener;
  return function(d, i, group) {
    var on = this.__on, o, listener = wrap(value, i, group);
    if (on) for (var j = 0, m = on.length; j < m; ++j) {
      if ((o = on[j]).type === typename.type && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.capture);
        this.addEventListener(o.type, o.listener = listener, o.capture = capture);
        o.value = value;
        return;
      }
    }
    this.addEventListener(typename.type, listener, capture);
    o = {type: typename.type, name: typename.name, value: value, listener: listener, capture: capture};
    if (!on) this.__on = [o];
    else on.push(o);
  };
}

/* harmony default export */ var on = (function(typename, value, capture) {
  var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;

  if (arguments.length < 2) {
    var on = this.node().__on;
    if (on) for (var j = 0, m = on.length, o; j < m; ++j) {
      for (i = 0, o = on[j]; i < n; ++i) {
        if ((t = typenames[i]).type === o.type && t.name === o.name) {
          return o.value;
        }
      }
    }
    return;
  }

  on = value ? onAdd : onRemove;
  if (capture == null) capture = false;
  for (i = 0; i < n; ++i) this.each(on(typenames[i], value, capture));
  return this;
});

function customEvent(event1, listener, that, args) {
  var event0 = on_event;
  event1.sourceEvent = on_event;
  on_event = event1;
  try {
    return listener.apply(that, args);
  } finally {
    on_event = event0;
  }
}

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/dispatch.js


function dispatchEvent(node, type, params) {
  var window = src_window(node),
      event = window.CustomEvent;

  if (typeof event === "function") {
    event = new event(type, params);
  } else {
    event = window.document.createEvent("Event");
    if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
    else event.initEvent(type, false, false);
  }

  node.dispatchEvent(event);
}

function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}

function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}

/* harmony default export */ var dispatch = (function(type, params) {
  return this.each((typeof params === "function"
      ? dispatchFunction
      : dispatchConstant)(type, params));
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selection/index.js
































var root = [null];

function Selection(groups, parents) {
  this._groups = groups;
  this._parents = parents;
}

function selection_selection() {
  return new Selection([[document.documentElement]], root);
}

Selection.prototype = selection_selection.prototype = {
  constructor: Selection,
  select: selection_select,
  selectAll: selectAll,
  filter: filter,
  data: selection_data,
  enter: selection_enter,
  exit: selection_exit,
  join: join,
  merge: selection_merge,
  order: order,
  sort: sort,
  call: call,
  nodes: nodes,
  node: selection_node,
  size: size,
  empty: selection_empty,
  each: each,
  attr: attr,
  style: style,
  property: property,
  classed: classed,
  text: selection_text,
  html: html,
  raise: selection_raise,
  lower: selection_lower,
  append: append,
  insert: insert,
  remove: selection_remove,
  clone: clone,
  datum: datum,
  on: on,
  dispatch: dispatch
};

/* harmony default export */ var src_selection = (selection_selection);

// CONCATENATED MODULE: ../node_modules/d3-selection/src/select.js


/* harmony default export */ var src_select = (function(selector) {
  return typeof selector === "string"
      ? new Selection([[document.querySelector(selector)]], [document.documentElement])
      : new Selection([[selector]], root);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/create.js



/* harmony default export */ var src_create = (function(name) {
  return src_select(creator(name).call(document.documentElement));
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/local.js
var nextId = 0;

function local() {
  return new Local;
}

function Local() {
  this._ = "@" + (++nextId).toString(36);
}

Local.prototype = local.prototype = {
  constructor: Local,
  get: function(node) {
    var id = this._;
    while (!(id in node)) if (!(node = node.parentNode)) return;
    return node[id];
  },
  set: function(node, value) {
    return node[this._] = value;
  },
  remove: function(node) {
    return this._ in node && delete node[this._];
  },
  toString: function() {
    return this._;
  }
};

// CONCATENATED MODULE: ../node_modules/d3-selection/src/sourceEvent.js


/* harmony default export */ var sourceEvent = (function() {
  var current = on_event, source;
  while (source = current.sourceEvent) current = source;
  return current;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/point.js
/* harmony default export */ var point = (function(node, event) {
  var svg = node.ownerSVGElement || node;

  if (svg.createSVGPoint) {
    var point = svg.createSVGPoint();
    point.x = event.clientX, point.y = event.clientY;
    point = point.matrixTransform(node.getScreenCTM().inverse());
    return [point.x, point.y];
  }

  var rect = node.getBoundingClientRect();
  return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/mouse.js



/* harmony default export */ var mouse = (function(node) {
  var event = sourceEvent();
  if (event.changedTouches) event = event.changedTouches[0];
  return point(node, event);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/selectAll.js


/* harmony default export */ var src_selectAll = (function(selector) {
  return typeof selector === "string"
      ? new Selection([document.querySelectorAll(selector)], [document.documentElement])
      : new Selection([selector == null ? [] : selector], root);
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/touch.js



/* harmony default export */ var src_touch = (function(node, touches, identifier) {
  if (arguments.length < 3) identifier = touches, touches = sourceEvent().changedTouches;

  for (var i = 0, n = touches ? touches.length : 0, touch; i < n; ++i) {
    if ((touch = touches[i]).identifier === identifier) {
      return point(node, touch);
    }
  }

  return null;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/touches.js



/* harmony default export */ var src_touches = (function(node, touches) {
  if (touches == null) touches = sourceEvent().touches;

  for (var i = 0, n = touches ? touches.length : 0, points = new Array(n); i < n; ++i) {
    points[i] = point(node, touches[i]);
  }

  return points;
});

// CONCATENATED MODULE: ../node_modules/d3-selection/src/index.js
/* concated harmony reexport create */__nested_webpack_require_4303__.d(__webpack_exports__, "create", function() { return src_create; });
/* concated harmony reexport creator */__nested_webpack_require_4303__.d(__webpack_exports__, "creator", function() { return creator; });
/* concated harmony reexport local */__nested_webpack_require_4303__.d(__webpack_exports__, "local", function() { return local; });
/* concated harmony reexport matcher */__nested_webpack_require_4303__.d(__webpack_exports__, "matcher", function() { return matcher; });
/* concated harmony reexport mouse */__nested_webpack_require_4303__.d(__webpack_exports__, "mouse", function() { return mouse; });
/* concated harmony reexport namespace */__nested_webpack_require_4303__.d(__webpack_exports__, "namespace", function() { return namespace; });
/* concated harmony reexport namespaces */__nested_webpack_require_4303__.d(__webpack_exports__, "namespaces", function() { return namespaces; });
/* concated harmony reexport clientPoint */__nested_webpack_require_4303__.d(__webpack_exports__, "clientPoint", function() { return point; });
/* concated harmony reexport select */__nested_webpack_require_4303__.d(__webpack_exports__, "select", function() { return src_select; });
/* concated harmony reexport selectAll */__nested_webpack_require_4303__.d(__webpack_exports__, "selectAll", function() { return src_selectAll; });
/* concated harmony reexport selection */__nested_webpack_require_4303__.d(__webpack_exports__, "selection", function() { return src_selection; });
/* concated harmony reexport selector */__nested_webpack_require_4303__.d(__webpack_exports__, "selector", function() { return src_selector; });
/* concated harmony reexport selectorAll */__nested_webpack_require_4303__.d(__webpack_exports__, "selectorAll", function() { return selectorAll; });
/* concated harmony reexport style */__nested_webpack_require_4303__.d(__webpack_exports__, "style", function() { return styleValue; });
/* concated harmony reexport touch */__nested_webpack_require_4303__.d(__webpack_exports__, "touch", function() { return src_touch; });
/* concated harmony reexport touches */__nested_webpack_require_4303__.d(__webpack_exports__, "touches", function() { return src_touches; });
/* concated harmony reexport window */__nested_webpack_require_4303__.d(__webpack_exports__, "window", function() { return src_window; });
/* concated harmony reexport event */__nested_webpack_require_4303__.d(__webpack_exports__, "event", function() { return on_event; });
/* concated harmony reexport customEvent */__nested_webpack_require_4303__.d(__webpack_exports__, "customEvent", function() { return customEvent; });




















/***/ }),
/* 1 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE__1__;

/***/ }),
/* 2 */
/***/ (function(module, exports, __nested_webpack_require_37745__) {

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

if (false) { var throwOnDirectAccess, ReactIs; } else {
  // By explicitly using `prop-types` you are opting into new production behavior.
  // http://fb.me/prop-types-in-prod
  module.exports = __nested_webpack_require_37745__(570)();
}


/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.__esModule = true;

exports.default = function (instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
};

/***/ }),
/* 4 */
/***/ (function(module, exports, __nested_webpack_require_38517__) {

"use strict";


exports.__esModule = true;

var _defineProperty = __nested_webpack_require_38517__(131);

var _defineProperty2 = _interopRequireDefault(_defineProperty);

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

exports.default = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      (0, _defineProperty2.default)(target, descriptor.key, descriptor);
    }
  }

  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor;
  };
}();

/***/ }),
/* 5 */
/***/ (function(module, exports, __nested_webpack_require_39479__) {

module.exports = { "default": __nested_webpack_require_39479__(560), __esModule: true };

/***/ }),
/* 6 */
/***/ (function(module, exports, __nested_webpack_require_39631__) {

"use strict";


exports.__esModule = true;

var _typeof2 = __nested_webpack_require_39631__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

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

exports.default = function (self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};

/***/ }),
/* 7 */
/***/ (function(module, exports, __nested_webpack_require_40246__) {

"use strict";


exports.__esModule = true;

var _setPrototypeOf = __nested_webpack_require_40246__(331);

var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);

var _create = __nested_webpack_require_40246__(567);

var _create2 = _interopRequireDefault(_create);

var _typeof2 = __nested_webpack_require_40246__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

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

exports.default = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
  }

  subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};

/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_41409__) {

"use strict";
__nested_webpack_require_41409__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-array/src/ascending.js
/* harmony default export */ var ascending = (function(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/bisector.js


/* harmony default export */ var bisector = (function(compare) {
  if (compare.length === 1) compare = ascendingComparator(compare);
  return {
    left: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) < 0) lo = mid + 1;
        else hi = mid;
      }
      return lo;
    },
    right: function(a, x, lo, hi) {
      if (lo == null) lo = 0;
      if (hi == null) hi = a.length;
      while (lo < hi) {
        var mid = lo + hi >>> 1;
        if (compare(a[mid], x) > 0) hi = mid;
        else lo = mid + 1;
      }
      return lo;
    }
  };
});

function ascendingComparator(f) {
  return function(d, x) {
    return ascending(f(d), x);
  };
}

// CONCATENATED MODULE: ../node_modules/d3-array/src/bisect.js



var ascendingBisect = bisector(ascending);
var bisectRight = ascendingBisect.right;
var bisectLeft = ascendingBisect.left;
/* harmony default export */ var bisect = (bisectRight);

// CONCATENATED MODULE: ../node_modules/d3-array/src/pairs.js
/* harmony default export */ var pairs = (function(array, f) {
  if (f == null) f = pair;
  var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);
  while (i < n) pairs[i] = f(p, p = array[++i]);
  return pairs;
});

function pair(a, b) {
  return [a, b];
}

// CONCATENATED MODULE: ../node_modules/d3-array/src/cross.js


/* harmony default export */ var cross = (function(values0, values1, reduce) {
  var n0 = values0.length,
      n1 = values1.length,
      values = new Array(n0 * n1),
      i0,
      i1,
      i,
      value0;

  if (reduce == null) reduce = pair;

  for (i0 = i = 0; i0 < n0; ++i0) {
    for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {
      values[i] = reduce(value0, values1[i1]);
    }
  }

  return values;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/descending.js
/* harmony default export */ var descending = (function(a, b) {
  return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/number.js
/* harmony default export */ var number = (function(x) {
  return x === null ? NaN : +x;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/variance.js


/* harmony default export */ var variance = (function(values, valueof) {
  var n = values.length,
      m = 0,
      i = -1,
      mean = 0,
      value,
      delta,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) {
        delta = value - mean;
        mean += delta / ++m;
        sum += delta * (value - mean);
      }
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) {
        delta = value - mean;
        mean += delta / ++m;
        sum += delta * (value - mean);
      }
    }
  }

  if (m > 1) return sum / (m - 1);
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/deviation.js


/* harmony default export */ var deviation = (function(array, f) {
  var v = variance(array, f);
  return v ? Math.sqrt(v) : v;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/extent.js
/* harmony default export */ var extent = (function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      min,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        min = max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null) {
            if (min > value) min = value;
            if (max < value) max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        min = max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null) {
            if (min > value) min = value;
            if (max < value) max = value;
          }
        }
      }
    }
  }

  return [min, max];
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/array.js
var array_array = Array.prototype;

var slice = array_array.slice;
var map = array_array.map;

// CONCATENATED MODULE: ../node_modules/d3-array/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/identity.js
/* harmony default export */ var identity = (function(x) {
  return x;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/range.js
/* harmony default export */ var range = (function(start, stop, step) {
  start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;

  var i = -1,
      n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
      range = new Array(n);

  while (++i < n) {
    range[i] = start + i * step;
  }

  return range;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50),
    e5 = Math.sqrt(10),
    e2 = Math.sqrt(2);

/* harmony default export */ var ticks = (function(start, stop, count) {
  var reverse,
      i = -1,
      n,
      ticks,
      step;

  stop = +stop, start = +start, count = +count;
  if (start === stop && count > 0) return [start];
  if (reverse = stop < start) n = start, start = stop, stop = n;
  if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];

  if (step > 0) {
    start = Math.ceil(start / step);
    stop = Math.floor(stop / step);
    ticks = new Array(n = Math.ceil(stop - start + 1));
    while (++i < n) ticks[i] = (start + i) * step;
  } else {
    start = Math.floor(start * step);
    stop = Math.ceil(stop * step);
    ticks = new Array(n = Math.ceil(start - stop + 1));
    while (++i < n) ticks[i] = (start - i) / step;
  }

  if (reverse) ticks.reverse();

  return ticks;
});

function tickIncrement(start, stop, count) {
  var step = (stop - start) / Math.max(0, count),
      power = Math.floor(Math.log(step) / Math.LN10),
      error = step / Math.pow(10, power);
  return power >= 0
      ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
      : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}

function tickStep(start, stop, count) {
  var step0 = Math.abs(stop - start) / Math.max(0, count),
      step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
      error = step0 / step1;
  if (error >= e10) step1 *= 10;
  else if (error >= e5) step1 *= 5;
  else if (error >= e2) step1 *= 2;
  return stop < start ? -step1 : step1;
}

// CONCATENATED MODULE: ../node_modules/d3-array/src/threshold/sturges.js
/* harmony default export */ var sturges = (function(values) {
  return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/histogram.js









/* harmony default export */ var src_histogram = (function() {
  var value = identity,
      domain = extent,
      threshold = sturges;

  function histogram(data) {
    var i,
        n = data.length,
        x,
        values = new Array(n);

    for (i = 0; i < n; ++i) {
      values[i] = value(data[i], i, data);
    }

    var xz = domain(values),
        x0 = xz[0],
        x1 = xz[1],
        tz = threshold(values, x0, x1);

    // Convert number of thresholds into uniform thresholds.
    if (!Array.isArray(tz)) {
      tz = tickStep(x0, x1, tz);
      tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive
    }

    // Remove any thresholds outside the domain.
    var m = tz.length;
    while (tz[0] <= x0) tz.shift(), --m;
    while (tz[m - 1] > x1) tz.pop(), --m;

    var bins = new Array(m + 1),
        bin;

    // Initialize bins.
    for (i = 0; i <= m; ++i) {
      bin = bins[i] = [];
      bin.x0 = i > 0 ? tz[i - 1] : x0;
      bin.x1 = i < m ? tz[i] : x1;
    }

    // Assign data to bins by value, ignoring any outside the domain.
    for (i = 0; i < n; ++i) {
      x = values[i];
      if (x0 <= x && x <= x1) {
        bins[bisect(tz, x, 0, m)].push(data[i]);
      }
    }

    return bins;
  }

  histogram.value = function(_) {
    return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram) : value;
  };

  histogram.domain = function(_) {
    return arguments.length ? (domain = typeof _ === "function" ? _ : constant([_[0], _[1]]), histogram) : domain;
  };

  histogram.thresholds = function(_) {
    return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;
  };

  return histogram;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/quantile.js


/* harmony default export */ var quantile = (function(values, p, valueof) {
  if (valueof == null) valueof = number;
  if (!(n = values.length)) return;
  if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
  if (p >= 1) return +valueof(values[n - 1], n - 1, values);
  var n,
      i = (n - 1) * p,
      i0 = Math.floor(i),
      value0 = +valueof(values[i0], i0, values),
      value1 = +valueof(values[i0 + 1], i0 + 1, values);
  return value0 + (value1 - value0) * (i - i0);
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/threshold/freedmanDiaconis.js





/* harmony default export */ var freedmanDiaconis = (function(values, min, max) {
  values = map.call(values, number).sort(ascending);
  return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/threshold/scott.js


/* harmony default export */ var scott = (function(values, min, max) {
  return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/max.js
/* harmony default export */ var src_max = (function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  return max;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/mean.js


/* harmony default export */ var src_mean = (function(values, valueof) {
  var n = values.length,
      m = n,
      i = -1,
      value,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) sum += value;
      else --m;
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;
      else --m;
    }
  }

  if (m) return sum / m;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/median.js




/* harmony default export */ var median = (function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      numbers = [];

  if (valueof == null) {
    while (++i < n) {
      if (!isNaN(value = number(values[i]))) {
        numbers.push(value);
      }
    }
  }

  else {
    while (++i < n) {
      if (!isNaN(value = number(valueof(values[i], i, values)))) {
        numbers.push(value);
      }
    }
  }

  return quantile(numbers.sort(ascending), 0.5);
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/merge.js
/* harmony default export */ var merge = (function(arrays) {
  var n = arrays.length,
      m,
      i = -1,
      j = 0,
      merged,
      array;

  while (++i < n) j += arrays[i].length;
  merged = new Array(j);

  while (--n >= 0) {
    array = arrays[n];
    m = array.length;
    while (--m >= 0) {
      merged[--j] = array[m];
    }
  }

  return merged;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/min.js
/* harmony default export */ var src_min = (function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      min;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        min = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && min > value) {
            min = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        min = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && min > value) {
            min = value;
          }
        }
      }
    }
  }

  return min;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/permute.js
/* harmony default export */ var permute = (function(array, indexes) {
  var i = indexes.length, permutes = new Array(i);
  while (i--) permutes[i] = array[indexes[i]];
  return permutes;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/scan.js


/* harmony default export */ var scan = (function(values, compare) {
  if (!(n = values.length)) return;
  var n,
      i = 0,
      j = 0,
      xi,
      xj = values[j];

  if (compare == null) compare = ascending;

  while (++i < n) {
    if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {
      xj = xi, j = i;
    }
  }

  if (compare(xj, xj) === 0) return j;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/shuffle.js
/* harmony default export */ var shuffle = (function(array, i0, i1) {
  var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),
      t,
      i;

  while (m) {
    i = Math.random() * m-- | 0;
    t = array[m + i0];
    array[m + i0] = array[i + i0];
    array[i + i0] = t;
  }

  return array;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/sum.js
/* harmony default export */ var src_sum = (function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      sum = 0;

  if (valueof == null) {
    while (++i < n) {
      if (value = +values[i]) sum += value; // Note: zero and null are equivalent.
    }
  }

  else {
    while (++i < n) {
      if (value = +valueof(values[i], i, values)) sum += value;
    }
  }

  return sum;
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/transpose.js


/* harmony default export */ var src_transpose = (function(matrix) {
  if (!(n = matrix.length)) return [];
  for (var i = -1, m = src_min(matrix, transpose_length), transpose = new Array(m); ++i < m;) {
    for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {
      row[j] = matrix[j][i];
    }
  }
  return transpose;
});

function transpose_length(d) {
  return d.length;
}

// CONCATENATED MODULE: ../node_modules/d3-array/src/zip.js


/* harmony default export */ var zip = (function() {
  return src_transpose(arguments);
});

// CONCATENATED MODULE: ../node_modules/d3-array/src/index.js
/* concated harmony reexport bisect */__nested_webpack_require_41409__.d(__webpack_exports__, "bisect", function() { return bisect; });
/* concated harmony reexport bisectRight */__nested_webpack_require_41409__.d(__webpack_exports__, "bisectRight", function() { return bisectRight; });
/* concated harmony reexport bisectLeft */__nested_webpack_require_41409__.d(__webpack_exports__, "bisectLeft", function() { return bisectLeft; });
/* concated harmony reexport ascending */__nested_webpack_require_41409__.d(__webpack_exports__, "ascending", function() { return ascending; });
/* concated harmony reexport bisector */__nested_webpack_require_41409__.d(__webpack_exports__, "bisector", function() { return bisector; });
/* concated harmony reexport cross */__nested_webpack_require_41409__.d(__webpack_exports__, "cross", function() { return cross; });
/* concated harmony reexport descending */__nested_webpack_require_41409__.d(__webpack_exports__, "descending", function() { return descending; });
/* concated harmony reexport deviation */__nested_webpack_require_41409__.d(__webpack_exports__, "deviation", function() { return deviation; });
/* concated harmony reexport extent */__nested_webpack_require_41409__.d(__webpack_exports__, "extent", function() { return extent; });
/* concated harmony reexport histogram */__nested_webpack_require_41409__.d(__webpack_exports__, "histogram", function() { return src_histogram; });
/* concated harmony reexport thresholdFreedmanDiaconis */__nested_webpack_require_41409__.d(__webpack_exports__, "thresholdFreedmanDiaconis", function() { return freedmanDiaconis; });
/* concated harmony reexport thresholdScott */__nested_webpack_require_41409__.d(__webpack_exports__, "thresholdScott", function() { return scott; });
/* concated harmony reexport thresholdSturges */__nested_webpack_require_41409__.d(__webpack_exports__, "thresholdSturges", function() { return sturges; });
/* concated harmony reexport max */__nested_webpack_require_41409__.d(__webpack_exports__, "max", function() { return src_max; });
/* concated harmony reexport mean */__nested_webpack_require_41409__.d(__webpack_exports__, "mean", function() { return src_mean; });
/* concated harmony reexport median */__nested_webpack_require_41409__.d(__webpack_exports__, "median", function() { return median; });
/* concated harmony reexport merge */__nested_webpack_require_41409__.d(__webpack_exports__, "merge", function() { return merge; });
/* concated harmony reexport min */__nested_webpack_require_41409__.d(__webpack_exports__, "min", function() { return src_min; });
/* concated harmony reexport pairs */__nested_webpack_require_41409__.d(__webpack_exports__, "pairs", function() { return pairs; });
/* concated harmony reexport permute */__nested_webpack_require_41409__.d(__webpack_exports__, "permute", function() { return permute; });
/* concated harmony reexport quantile */__nested_webpack_require_41409__.d(__webpack_exports__, "quantile", function() { return quantile; });
/* concated harmony reexport range */__nested_webpack_require_41409__.d(__webpack_exports__, "range", function() { return range; });
/* concated harmony reexport scan */__nested_webpack_require_41409__.d(__webpack_exports__, "scan", function() { return scan; });
/* concated harmony reexport shuffle */__nested_webpack_require_41409__.d(__webpack_exports__, "shuffle", function() { return shuffle; });
/* concated harmony reexport sum */__nested_webpack_require_41409__.d(__webpack_exports__, "sum", function() { return src_sum; });
/* concated harmony reexport ticks */__nested_webpack_require_41409__.d(__webpack_exports__, "ticks", function() { return ticks; });
/* concated harmony reexport tickIncrement */__nested_webpack_require_41409__.d(__webpack_exports__, "tickIncrement", function() { return tickIncrement; });
/* concated harmony reexport tickStep */__nested_webpack_require_41409__.d(__webpack_exports__, "tickStep", function() { return tickStep; });
/* concated harmony reexport transpose */__nested_webpack_require_41409__.d(__webpack_exports__, "transpose", function() { return src_transpose; });
/* concated harmony reexport variance */__nested_webpack_require_41409__.d(__webpack_exports__, "variance", function() { return variance; });
/* concated harmony reexport zip */__nested_webpack_require_41409__.d(__webpack_exports__, "zip", function() { return zip; });





























/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_61419__) {

"use strict";
__nested_webpack_require_61419__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-color/src/define.js
/* harmony default export */ var define = (function(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
});

function extend(parent, definition) {
  var prototype = Object.create(parent.prototype);
  for (var key in definition) prototype[key] = definition[key];
  return prototype;
}

// CONCATENATED MODULE: ../node_modules/d3-color/src/color.js


function Color() {}

var darker = 0.7;
var brighter = 1 / darker;

var reI = "\\s*([+-]?\\d+)\\s*",
    reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
    reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
    reHex3 = /^#([0-9a-f]{3})$/,
    reHex6 = /^#([0-9a-f]{6})$/,
    reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
    reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
    reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
    reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
    reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
    reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");

var named = {
  aliceblue: 0xf0f8ff,
  antiquewhite: 0xfaebd7,
  aqua: 0x00ffff,
  aquamarine: 0x7fffd4,
  azure: 0xf0ffff,
  beige: 0xf5f5dc,
  bisque: 0xffe4c4,
  black: 0x000000,
  blanchedalmond: 0xffebcd,
  blue: 0x0000ff,
  blueviolet: 0x8a2be2,
  brown: 0xa52a2a,
  burlywood: 0xdeb887,
  cadetblue: 0x5f9ea0,
  chartreuse: 0x7fff00,
  chocolate: 0xd2691e,
  coral: 0xff7f50,
  cornflowerblue: 0x6495ed,
  cornsilk: 0xfff8dc,
  crimson: 0xdc143c,
  cyan: 0x00ffff,
  darkblue: 0x00008b,
  darkcyan: 0x008b8b,
  darkgoldenrod: 0xb8860b,
  darkgray: 0xa9a9a9,
  darkgreen: 0x006400,
  darkgrey: 0xa9a9a9,
  darkkhaki: 0xbdb76b,
  darkmagenta: 0x8b008b,
  darkolivegreen: 0x556b2f,
  darkorange: 0xff8c00,
  darkorchid: 0x9932cc,
  darkred: 0x8b0000,
  darksalmon: 0xe9967a,
  darkseagreen: 0x8fbc8f,
  darkslateblue: 0x483d8b,
  darkslategray: 0x2f4f4f,
  darkslategrey: 0x2f4f4f,
  darkturquoise: 0x00ced1,
  darkviolet: 0x9400d3,
  deeppink: 0xff1493,
  deepskyblue: 0x00bfff,
  dimgray: 0x696969,
  dimgrey: 0x696969,
  dodgerblue: 0x1e90ff,
  firebrick: 0xb22222,
  floralwhite: 0xfffaf0,
  forestgreen: 0x228b22,
  fuchsia: 0xff00ff,
  gainsboro: 0xdcdcdc,
  ghostwhite: 0xf8f8ff,
  gold: 0xffd700,
  goldenrod: 0xdaa520,
  gray: 0x808080,
  green: 0x008000,
  greenyellow: 0xadff2f,
  grey: 0x808080,
  honeydew: 0xf0fff0,
  hotpink: 0xff69b4,
  indianred: 0xcd5c5c,
  indigo: 0x4b0082,
  ivory: 0xfffff0,
  khaki: 0xf0e68c,
  lavender: 0xe6e6fa,
  lavenderblush: 0xfff0f5,
  lawngreen: 0x7cfc00,
  lemonchiffon: 0xfffacd,
  lightblue: 0xadd8e6,
  lightcoral: 0xf08080,
  lightcyan: 0xe0ffff,
  lightgoldenrodyellow: 0xfafad2,
  lightgray: 0xd3d3d3,
  lightgreen: 0x90ee90,
  lightgrey: 0xd3d3d3,
  lightpink: 0xffb6c1,
  lightsalmon: 0xffa07a,
  lightseagreen: 0x20b2aa,
  lightskyblue: 0x87cefa,
  lightslategray: 0x778899,
  lightslategrey: 0x778899,
  lightsteelblue: 0xb0c4de,
  lightyellow: 0xffffe0,
  lime: 0x00ff00,
  limegreen: 0x32cd32,
  linen: 0xfaf0e6,
  magenta: 0xff00ff,
  maroon: 0x800000,
  mediumaquamarine: 0x66cdaa,
  mediumblue: 0x0000cd,
  mediumorchid: 0xba55d3,
  mediumpurple: 0x9370db,
  mediumseagreen: 0x3cb371,
  mediumslateblue: 0x7b68ee,
  mediumspringgreen: 0x00fa9a,
  mediumturquoise: 0x48d1cc,
  mediumvioletred: 0xc71585,
  midnightblue: 0x191970,
  mintcream: 0xf5fffa,
  mistyrose: 0xffe4e1,
  moccasin: 0xffe4b5,
  navajowhite: 0xffdead,
  navy: 0x000080,
  oldlace: 0xfdf5e6,
  olive: 0x808000,
  olivedrab: 0x6b8e23,
  orange: 0xffa500,
  orangered: 0xff4500,
  orchid: 0xda70d6,
  palegoldenrod: 0xeee8aa,
  palegreen: 0x98fb98,
  paleturquoise: 0xafeeee,
  palevioletred: 0xdb7093,
  papayawhip: 0xffefd5,
  peachpuff: 0xffdab9,
  peru: 0xcd853f,
  pink: 0xffc0cb,
  plum: 0xdda0dd,
  powderblue: 0xb0e0e6,
  purple: 0x800080,
  rebeccapurple: 0x663399,
  red: 0xff0000,
  rosybrown: 0xbc8f8f,
  royalblue: 0x4169e1,
  saddlebrown: 0x8b4513,
  salmon: 0xfa8072,
  sandybrown: 0xf4a460,
  seagreen: 0x2e8b57,
  seashell: 0xfff5ee,
  sienna: 0xa0522d,
  silver: 0xc0c0c0,
  skyblue: 0x87ceeb,
  slateblue: 0x6a5acd,
  slategray: 0x708090,
  slategrey: 0x708090,
  snow: 0xfffafa,
  springgreen: 0x00ff7f,
  steelblue: 0x4682b4,
  tan: 0xd2b48c,
  teal: 0x008080,
  thistle: 0xd8bfd8,
  tomato: 0xff6347,
  turquoise: 0x40e0d0,
  violet: 0xee82ee,
  wheat: 0xf5deb3,
  white: 0xffffff,
  whitesmoke: 0xf5f5f5,
  yellow: 0xffff00,
  yellowgreen: 0x9acd32
};

define(Color, color, {
  displayable: function() {
    return this.rgb().displayable();
  },
  hex: function() {
    return this.rgb().hex();
  },
  toString: function() {
    return this.rgb() + "";
  }
});

function color(format) {
  var m;
  format = (format + "").trim().toLowerCase();
  return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
      : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
      : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
      : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
      : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
      : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
      : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
      : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
      : named.hasOwnProperty(format) ? rgbn(named[format])
      : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
      : null;
}

function rgbn(n) {
  return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}

function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}

function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb;
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}

function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}

function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}

define(Rgb, rgb, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb: function() {
    return this;
  },
  displayable: function() {
    return (0 <= this.r && this.r <= 255)
        && (0 <= this.g && this.g <= 255)
        && (0 <= this.b && this.b <= 255)
        && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: function() {
    return "#" + hex(this.r) + hex(this.g) + hex(this.b);
  },
  toString: function() {
    var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
    return (a === 1 ? "rgb(" : "rgba(")
        + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
        + Math.max(0, Math.min(255, Math.round(this.b) || 0))
        + (a === 1 ? ")" : ", " + a + ")");
  }
}));

function hex(value) {
  value = Math.max(0, Math.min(255, Math.round(value) || 0));
  return (value < 16 ? "0" : "") + value.toString(16);
}

function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}

function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl;
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      min = Math.min(r, g, b),
      max = Math.max(r, g, b),
      h = NaN,
      s = max - min,
      l = (max + min) / 2;
  if (s) {
    if (r === max) h = (g - b) / s + (g < b) * 6;
    else if (g === max) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max + min : 2 - max - min;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}

function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}

function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hsl, hsl, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = this.h % 360 + (this.h < 0) * 360,
        s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
        l = this.l,
        m2 = l + (l < 0.5 ? l : 1 - l) * s,
        m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  displayable: function() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s))
        && (0 <= this.l && this.l <= 1)
        && (0 <= this.opacity && this.opacity <= 1);
  }
}));

/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60
      : h < 180 ? m2
      : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
      : m1) * 255;
}

// CONCATENATED MODULE: ../node_modules/d3-color/src/math.js
var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;

// CONCATENATED MODULE: ../node_modules/d3-color/src/lab.js




// https://beta.observablehq.com/@mbostock/lab-and-rgb
var K = 18,
    Xn = 0.96422,
    Yn = 1,
    Zn = 0.82521,
    t0 = 4 / 29,
    t1 = 6 / 29,
    t2 = 3 * t1 * t1,
    t3 = t1 * t1 * t1;

function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) {
    if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
    var h = o.h * deg2rad;
    return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
  }
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r),
      g = rgb2lrgb(o.g),
      b = rgb2lrgb(o.b),
      y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
  if (r === g && g === b) x = z = y; else {
    x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}

function gray(l, opacity) {
  return new Lab(l, 0, 0, opacity == null ? 1 : opacity);
}

function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}

function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}

define(Lab, lab, extend(Color, {
  brighter: function(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker: function(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb: function() {
    var y = (this.l + 16) / 116,
        x = isNaN(this.a) ? y : y + this.a / 500,
        z = isNaN(this.b) ? y : y - this.b / 200;
    x = Xn * lab2xyz(x);
    y = Yn * lab2xyz(y);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
      lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));

function xyz2lab(t) {
  return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}

function lab2xyz(t) {
  return t > t1 ? t * t * t : t2 * (t - t0);
}

function lrgb2rgb(x) {
  return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}

function rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}

function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * rad2deg;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}

function lch(l, c, h, opacity) {
  return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}

function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}

define(Hcl, hcl, extend(Color, {
  brighter: function(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker: function(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb: function() {
    return labConvert(this).rgb();
  }
}));

// CONCATENATED MODULE: ../node_modules/d3-color/src/cubehelix.js




var A = -0.14861,
    B = +1.78277,
    C = -0.29227,
    D = -0.90649,
    E = +1.97294,
    ED = E * D,
    EB = E * B,
    BC_DA = B * C - D * A;

function cubehelixConvert(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255,
      g = o.g / 255,
      b = o.b / 255,
      l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
      bl = b - l,
      k = (E * (g - l) - C * bl) / D,
      s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
      h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}

function cubehelix(h, s, l, opacity) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}

function Cubehelix(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}

define(Cubehelix, cubehelix, extend(Color, {
  brighter: function(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  darker: function(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
  },
  rgb: function() {
    var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
        l = +this.l,
        a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
        cosh = Math.cos(h),
        sinh = Math.sin(h);
    return new Rgb(
      255 * (l + a * (A * cosh + B * sinh)),
      255 * (l + a * (C * cosh + D * sinh)),
      255 * (l + a * (E * cosh)),
      this.opacity
    );
  }
}));

// CONCATENATED MODULE: ../node_modules/d3-color/src/index.js
/* concated harmony reexport color */__nested_webpack_require_61419__.d(__webpack_exports__, "color", function() { return color; });
/* concated harmony reexport rgb */__nested_webpack_require_61419__.d(__webpack_exports__, "rgb", function() { return rgb; });
/* concated harmony reexport hsl */__nested_webpack_require_61419__.d(__webpack_exports__, "hsl", function() { return hsl; });
/* concated harmony reexport lab */__nested_webpack_require_61419__.d(__webpack_exports__, "lab", function() { return lab; });
/* concated harmony reexport hcl */__nested_webpack_require_61419__.d(__webpack_exports__, "hcl", function() { return hcl; });
/* concated harmony reexport lch */__nested_webpack_require_61419__.d(__webpack_exports__, "lch", function() { return lch; });
/* concated harmony reexport gray */__nested_webpack_require_61419__.d(__webpack_exports__, "gray", function() { return gray; });
/* concated harmony reexport cubehelix */__nested_webpack_require_61419__.d(__webpack_exports__, "cubehelix", function() { return cubehelix; });





/***/ }),
/* 10 */
/***/ (function(module, exports, __nested_webpack_require_77852__) {

"use strict";


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

var _absToChr = __nested_webpack_require_77852__(529);

Object.defineProperty(exports, 'absToChr', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_absToChr)['default'];
    }

    return get;
  }()
});

var _accessorTransposition = __nested_webpack_require_77852__(530);

Object.defineProperty(exports, 'accessorTransposition', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_accessorTransposition)['default'];
    }

    return get;
  }()
});

var _addArrays = __nested_webpack_require_77852__(531);

Object.defineProperty(exports, 'addArrays', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_addArrays)['default'];
    }

    return get;
  }()
});

var _addClass = __nested_webpack_require_77852__(532);

Object.defineProperty(exports, 'addClass', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_addClass)['default'];
    }

    return get;
  }()
});

var _base64ToCanvas = __nested_webpack_require_77852__(533);

Object.defineProperty(exports, 'base64ToCanvas', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_base64ToCanvas)['default'];
    }

    return get;
  }()
});

var _chromInfoBisector = __nested_webpack_require_77852__(534);

Object.defineProperty(exports, 'chromInfoBisector', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_chromInfoBisector)['default'];
    }

    return get;
  }()
});

var _chrToAbs = __nested_webpack_require_77852__(535);

Object.defineProperty(exports, 'chrToAbs', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_chrToAbs)['default'];
    }

    return get;
  }()
});

var _cloneEvent = __nested_webpack_require_77852__(323);

Object.defineProperty(exports, 'cloneEvent', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_cloneEvent)['default'];
    }

    return get;
  }()
});

var _colorDomainToRgbaArray = __nested_webpack_require_77852__(536);

Object.defineProperty(exports, 'colorDomainToRgbaArray', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_colorDomainToRgbaArray)['default'];
    }

    return get;
  }()
});

var _colorToHex = __nested_webpack_require_77852__(537);

Object.defineProperty(exports, 'colorToHex', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_colorToHex)['default'];
    }

    return get;
  }()
});

var _colorToRgba = __nested_webpack_require_77852__(538);

Object.defineProperty(exports, 'colorToRgba', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_colorToRgba)['default'];
    }

    return get;
  }()
});

var _dataToGenomicLoci = __nested_webpack_require_77852__(326);

Object.defineProperty(exports, 'dataToGenomicLoci', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_dataToGenomicLoci)['default'];
    }

    return get;
  }()
});

var _debounce = __nested_webpack_require_77852__(539);

Object.defineProperty(exports, 'debounce', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_debounce)['default'];
    }

    return get;
  }()
});

var _decToHexStr = __nested_webpack_require_77852__(540);

Object.defineProperty(exports, 'decToHexStr', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_decToHexStr)['default'];
    }

    return get;
  }()
});

var _dictFromTuples = __nested_webpack_require_77852__(541);

Object.defineProperty(exports, 'dictFromTuples', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_dictFromTuples)['default'];
    }

    return get;
  }()
});

var _dictItems = __nested_webpack_require_77852__(542);

Object.defineProperty(exports, 'dictItems', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_dictItems)['default'];
    }

    return get;
  }()
});

var _dictKeys = __nested_webpack_require_77852__(543);

Object.defineProperty(exports, 'dictKeys', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_dictKeys)['default'];
    }

    return get;
  }()
});

var _dictValues = __nested_webpack_require_77852__(544);

Object.defineProperty(exports, 'dictValues', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_dictValues)['default'];
    }

    return get;
  }()
});

var _download = __nested_webpack_require_77852__(545);

Object.defineProperty(exports, 'download', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_download)['default'];
    }

    return get;
  }()
});

var _fillInMinWidths = __nested_webpack_require_77852__(546);

Object.defineProperty(exports, 'fillInMinWidths', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_fillInMinWidths)['default'];
    }

    return get;
  }()
});

var _flatten = __nested_webpack_require_77852__(892);

Object.defineProperty(exports, 'flatten', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_flatten)['default'];
    }

    return get;
  }()
});

var _forEach = __nested_webpack_require_77852__(893);

Object.defineProperty(exports, 'forEach', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_forEach)['default'];
    }

    return get;
  }()
});

var _forwardEvent = __nested_webpack_require_77852__(894);

Object.defineProperty(exports, 'forwardEvent', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_forwardEvent)['default'];
    }

    return get;
  }()
});

var _genomeLociToPixels = __nested_webpack_require_77852__(895);

Object.defineProperty(exports, 'genomeLociToPixels', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_genomeLociToPixels)['default'];
    }

    return get;
  }()
});

var _genomicRangeToChromosomeChunks = __nested_webpack_require_77852__(896);

Object.defineProperty(exports, 'genomicRangeToChromosomeChunks', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_genomicRangeToChromosomeChunks)['default'];
    }

    return get;
  }()
});

var _getDefaultTrackForDatatype = __nested_webpack_require_77852__(897);

Object.defineProperty(exports, 'getDefaultTrackForDatatype', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getDefaultTrackForDatatype)['default'];
    }

    return get;
  }()
});

var _getElementDim = __nested_webpack_require_77852__(898);

Object.defineProperty(exports, 'getElementDim', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getElementDim)['default'];
    }

    return get;
  }()
});

var _getTrackByUid = __nested_webpack_require_77852__(899);

Object.defineProperty(exports, 'getTrackByUid', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getTrackByUid)['default'];
    }

    return get;
  }()
});

var _getTrackConfFromHgc = __nested_webpack_require_77852__(900);

Object.defineProperty(exports, 'getTrackConfFromHGC', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getTrackConfFromHgc)['default'];
    }

    return get;
  }()
});

var _getTrackObjById = __nested_webpack_require_77852__(901);

Object.defineProperty(exports, 'getTrackObjById', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getTrackObjById)['default'];
    }

    return get;
  }()
});

var _getTrackPositionByUid = __nested_webpack_require_77852__(902);

Object.defineProperty(exports, 'getTrackPositionByUid', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getTrackPositionByUid)['default'];
    }

    return get;
  }()
});

var _getXylofon = __nested_webpack_require_77852__(441);

Object.defineProperty(exports, 'getXylofon', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_getXylofon)['default'];
    }

    return get;
  }()
});

var _gradient = __nested_webpack_require_77852__(903);

Object.defineProperty(exports, 'gradient', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_gradient)['default'];
    }

    return get;
  }()
});

var _hasClass = __nested_webpack_require_77852__(221);

Object.defineProperty(exports, 'hasClass', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_hasClass)['default'];
    }

    return get;
  }()
});

var _hasParent = __nested_webpack_require_77852__(904);

Object.defineProperty(exports, 'hasParent', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_hasParent)['default'];
    }

    return get;
  }()
});

var _hexStringToInt = __nested_webpack_require_77852__(905);

Object.defineProperty(exports, 'hexStrToInt', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_hexStringToInt)['default'];
    }

    return get;
  }()
});

var _intoTheVoid = __nested_webpack_require_77852__(906);

Object.defineProperty(exports, 'intoTheVoid', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_intoTheVoid)['default'];
    }

    return get;
  }()
});

var _isTrackOrChildTrack = __nested_webpack_require_77852__(907);

Object.defineProperty(exports, 'isTrackOrChildTrack', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_isTrackOrChildTrack)['default'];
    }

    return get;
  }()
});

var _isWithin = __nested_webpack_require_77852__(908);

Object.defineProperty(exports, 'isWithin', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_isWithin)['default'];
    }

    return get;
  }()
});

var _latToY = __nested_webpack_require_77852__(909);

Object.defineProperty(exports, 'latToY', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_latToY)['default'];
    }

    return get;
  }()
});

var _loadChromInfos = __nested_webpack_require_77852__(910);

Object.defineProperty(exports, 'loadChromInfos', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_loadChromInfos)['default'];
    }

    return get;
  }()
});

var _lngToX = __nested_webpack_require_77852__(911);

Object.defineProperty(exports, 'lngToX', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_lngToX)['default'];
    }

    return get;
  }()
});

var _map = __nested_webpack_require_77852__(442);

Object.defineProperty(exports, 'map', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_map)['default'];
    }

    return get;
  }()
});

var _max = __nested_webpack_require_77852__(912);

Object.defineProperty(exports, 'max', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_max)['default'];
    }

    return get;
  }()
});

var _maxNonZero = __nested_webpack_require_77852__(913);

Object.defineProperty(exports, 'maxNonZero', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_maxNonZero)['default'];
    }

    return get;
  }()
});

var _min = __nested_webpack_require_77852__(914);

Object.defineProperty(exports, 'min', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_min)['default'];
    }

    return get;
  }()
});

var _minNonZero = __nested_webpack_require_77852__(915);

Object.defineProperty(exports, 'minNonZero', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_minNonZero)['default'];
    }

    return get;
  }()
});

var _mod = __nested_webpack_require_77852__(916);

Object.defineProperty(exports, 'mod', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_mod)['default'];
    }

    return get;
  }()
});

var _ndarrayAssign = __nested_webpack_require_77852__(917);

Object.defineProperty(exports, 'ndarrayAssign', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_ndarrayAssign)['default'];
    }

    return get;
  }()
});

var _ndarrayFlatten = __nested_webpack_require_77852__(923);

Object.defineProperty(exports, 'ndarrayFlatten', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_ndarrayFlatten)['default'];
    }

    return get;
  }()
});

var _ndarrayToList = __nested_webpack_require_77852__(447);

Object.defineProperty(exports, 'ndarrayToList', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_ndarrayToList)['default'];
    }

    return get;
  }()
});

var _numericifyVersion = __nested_webpack_require_77852__(924);

Object.defineProperty(exports, 'numericifyVersion', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_numericifyVersion)['default'];
    }

    return get;
  }()
});

var _objVals = __nested_webpack_require_77852__(925);

Object.defineProperty(exports, 'objVals', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_objVals)['default'];
    }

    return get;
  }()
});

var _or = __nested_webpack_require_77852__(926);

Object.defineProperty(exports, 'or', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_or)['default'];
    }

    return get;
  }()
});

var _parseChromsizesRows = __nested_webpack_require_77852__(927);

Object.defineProperty(exports, 'parseChromsizesRows', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_parseChromsizesRows)['default'];
    }

    return get;
  }()
});

var _pixiTextToSvg = __nested_webpack_require_77852__(928);

Object.defineProperty(exports, 'pixiTextToSvg', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_pixiTextToSvg)['default'];
    }

    return get;
  }()
});

var _q = __nested_webpack_require_77852__(929);

Object.defineProperty(exports, 'q', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_q)['default'];
    }

    return get;
  }()
});

var _reduce = __nested_webpack_require_77852__(439);

Object.defineProperty(exports, 'reduce', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_reduce)['default'];
    }

    return get;
  }()
});

var _rangeQuery2d = __nested_webpack_require_77852__(930);

Object.defineProperty(exports, 'rangeQuery2d', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_rangeQuery2d)['default'];
    }

    return get;
  }()
});

var _relToAbsChromPos = __nested_webpack_require_77852__(931);

Object.defineProperty(exports, 'relToAbsChromPos', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_relToAbsChromPos)['default'];
    }

    return get;
  }()
});

var _removeClass = __nested_webpack_require_77852__(932);

Object.defineProperty(exports, 'removeClass', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_removeClass)['default'];
    }

    return get;
  }()
});

var _resetD3BrushStyle = __nested_webpack_require_77852__(933);

Object.defineProperty(exports, 'resetD3BrushStyle', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_resetD3BrushStyle)['default'];
    }

    return get;
  }()
});

var _rgbToHex = __nested_webpack_require_77852__(934);

Object.defineProperty(exports, 'rgbToHex', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_rgbToHex)['default'];
    }

    return get;
  }()
});

var _scalesCenterAndK = __nested_webpack_require_77852__(935);

Object.defineProperty(exports, 'scalesCenterAndK', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_scalesCenterAndK)['default'];
    }

    return get;
  }()
});

var _scalesToGenomeLoci = __nested_webpack_require_77852__(936);

Object.defineProperty(exports, 'scalesToGenomeLoci', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_scalesToGenomeLoci)['default'];
    }

    return get;
  }()
});

var _showMousePosition = __nested_webpack_require_77852__(937);

Object.defineProperty(exports, 'showMousePosition', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_showMousePosition)['default'];
    }

    return get;
  }()
});

var _some = __nested_webpack_require_77852__(938);

Object.defineProperty(exports, 'some', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_some)['default'];
    }

    return get;
  }()
});

var _sum = __nested_webpack_require_77852__(939);

Object.defineProperty(exports, 'sum', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_sum)['default'];
    }

    return get;
  }()
});

var _svgLine = __nested_webpack_require_77852__(940);

Object.defineProperty(exports, 'svgLine', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_svgLine)['default'];
    }

    return get;
  }()
});

var _throttleAndDebounce = __nested_webpack_require_77852__(941);

Object.defineProperty(exports, 'throttleAndDebounce', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_throttleAndDebounce)['default'];
    }

    return get;
  }()
});

var _tileToCanvas = __nested_webpack_require_77852__(942);

Object.defineProperty(exports, 'tileToCanvas', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_tileToCanvas)['default'];
    }

    return get;
  }()
});

var _timeout = __nested_webpack_require_77852__(943);

Object.defineProperty(exports, 'timeout', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_timeout)['default'];
    }

    return get;
  }()
});

var _totalTrackPixelHeight = __nested_webpack_require_77852__(944);

Object.defineProperty(exports, 'totalTrackPixelHeight', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_totalTrackPixelHeight)['default'];
    }

    return get;
  }()
});

var _toVoid = __nested_webpack_require_77852__(171);

Object.defineProperty(exports, 'toVoid', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_toVoid)['default'];
    }

    return get;
  }()
});

var _trimTrailingSlash = __nested_webpack_require_77852__(945);

Object.defineProperty(exports, 'trimTrailingSlash', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_trimTrailingSlash)['default'];
    }

    return get;
  }()
});

var _valueToColor = __nested_webpack_require_77852__(946);

Object.defineProperty(exports, 'valueToColor', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_valueToColor)['default'];
    }

    return get;
  }()
});

var _expandCombinedTracks = __nested_webpack_require_77852__(947);

Object.defineProperty(exports, 'expandCombinedTracks', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_expandCombinedTracks)['default'];
    }

    return get;
  }()
});

var _segmentsToRows = __nested_webpack_require_77852__(948);

Object.defineProperty(exports, 'segmentsToRows', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_segmentsToRows)['default'];
    }

    return get;
  }()
});

var _visitPositionedTracks = __nested_webpack_require_77852__(443);

Object.defineProperty(exports, 'visitPositionedTracks', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_visitPositionedTracks)['default'];
    }

    return get;
  }()
});

var _visitTracks = __nested_webpack_require_77852__(444);

Object.defineProperty(exports, 'visitTracks', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_visitTracks)['default'];
    }

    return get;
  }()
});

var _trackUtils = __nested_webpack_require_77852__(950);

Object.defineProperty(exports, 'trackUtils', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_trackUtils)['default'];
    }

    return get;
  }()
});

var _DenseDataExtrema1D = __nested_webpack_require_77852__(137);

Object.defineProperty(exports, 'DenseDataExtrema1D', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_DenseDataExtrema1D)['default'];
    }

    return get;
  }()
});

var _DenseDataExtrema2D = __nested_webpack_require_77852__(138);

Object.defineProperty(exports, 'DenseDataExtrema2D', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_DenseDataExtrema2D)['default'];
    }

    return get;
  }()
});

var _getHiglassComponents = __nested_webpack_require_77852__(448);

Object.defineProperty(exports, 'getTrackObjectFromHGC', {
  enumerable: true,
  get: function () {
    function get() {
      return _getHiglassComponents.getTrackObjectFromHGC;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'getTrackRenderer', {
  enumerable: true,
  get: function () {
    function get() {
      return _getHiglassComponents.getTrackRenderer;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'getTiledPlot', {
  enumerable: true,
  get: function () {
    function get() {
      return _getHiglassComponents.getTiledPlot;
    }

    return get;
  }()
});

var _testHelpers = __nested_webpack_require_77852__(951);

Object.defineProperty(exports, 'changeOptions', {
  enumerable: true,
  get: function () {
    function get() {
      return _testHelpers.changeOptions;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'waitForJsonComplete', {
  enumerable: true,
  get: function () {
    function get() {
      return _testHelpers.waitForJsonComplete;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'waitForTilesLoaded', {
  enumerable: true,
  get: function () {
    function get() {
      return _testHelpers.waitForTilesLoaded;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'waitForTransitionsFinished', {
  enumerable: true,
  get: function () {
    function get() {
      return _testHelpers.waitForTransitionsFinished;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'mountHGComponent', {
  enumerable: true,
  get: function () {
    function get() {
      return _testHelpers.mountHGComponent;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'removeHGComponent', {
  enumerable: true,
  get: function () {
    function get() {
      return _testHelpers.removeHGComponent;
    }

    return get;
  }()
});

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

/***/ }),
/* 11 */
/***/ (function(module, exports, __nested_webpack_require_101181__) {

"use strict";


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

var _themes = __nested_webpack_require_101181__(327);

Object.defineProperty(exports, 'THEME_LIGHT', {
  enumerable: true,
  get: function () {
    function get() {
      return _themes.THEME_LIGHT;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'THEME_DARK', {
  enumerable: true,
  get: function () {
    function get() {
      return _themes.THEME_DARK;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'THEME_DEFAULT', {
  enumerable: true,
  get: function () {
    function get() {
      return _themes.THEME_DEFAULT;
    }

    return get;
  }()
});

var _globals = __nested_webpack_require_101181__(324);

Object.defineProperty(exports, 'GLOBALS', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_globals)['default'];
    }

    return get;
  }()
});

var _datatypeToTrackType = __nested_webpack_require_101181__(553);

Object.defineProperty(exports, 'DATATYPE_TO_TRACK_TYPE', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_datatypeToTrackType)['default'];
    }

    return get;
  }()
});

var _colormaps = __nested_webpack_require_101181__(554);

Object.defineProperty(exports, 'HEATED_OBJECT_MAP', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_colormaps)['default'];
    }

    return get;
  }()
});

var _isTrackRangeSelectable = __nested_webpack_require_101181__(555);

Object.defineProperty(exports, 'IS_TRACK_RANGE_SELECTABLE', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_isTrackRangeSelectable)['default'];
    }

    return get;
  }()
});

var _optionsInfo = __nested_webpack_require_101181__(556);

Object.defineProperty(exports, 'OPTIONS_INFO', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_optionsInfo)['default'];
    }

    return get;
  }()
});

var _tracksInfo = __nested_webpack_require_101181__(882);

Object.defineProperty(exports, 'TRACKS_INFO', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_tracksInfo)['default'];
    }

    return get;
  }()
});

var _tracksInfoByType = __nested_webpack_require_101181__(884);

Object.defineProperty(exports, 'TRACKS_INFO_BY_TYPE', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_tracksInfoByType)['default'];
    }

    return get;
  }()
});

var _positionsByDatatype = __nested_webpack_require_101181__(885);

Object.defineProperty(exports, 'POSITIONS_BY_DATATYPE', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_positionsByDatatype)['default'];
    }

    return get;
  }()
});

var _defaultTracksForDatatype = __nested_webpack_require_101181__(886);

Object.defineProperty(exports, 'DEFAULT_TRACKS_FOR_DATATYPE', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_defaultTracksForDatatype)['default'];
    }

    return get;
  }()
});

var _availableForPlugins = __nested_webpack_require_101181__(887);

Object.defineProperty(exports, 'AVAILABLE_FOR_PLUGINS', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_availableForPlugins)['default'];
    }

    return get;
  }()
});

var _availableTrackTypes = __nested_webpack_require_101181__(891);

Object.defineProperty(exports, 'AVAILABLE_TRACK_TYPES', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_availableTrackTypes)['default'];
    }

    return get;
  }()
});

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

/* ------------------------------- Primitives ------------------------------- */

var DEFAULT_VIEW_MARGIN = exports.DEFAULT_VIEW_MARGIN = 0;

var DEFAULT_VIEW_PADDING = exports.DEFAULT_VIEW_PADDING = 5;

var DEFAULT_CONTAINER_PADDING_X = exports.DEFAULT_CONTAINER_PADDING_X = 10;

var DEFAULT_CONTAINER_PADDING_Y = exports.DEFAULT_CONTAINER_PADDING_Y = 10;

var MAX_CLICK_DELAY = exports.MAX_CLICK_DELAY = 300;

var MOUSE_TOOL_MOVE = exports.MOUSE_TOOL_MOVE = 'move';

var MOUSE_TOOL_SELECT = exports.MOUSE_TOOL_SELECT = 'select';

var TILE_FETCH_DEBOUNCE = exports.TILE_FETCH_DEBOUNCE = 100;

// Number of milliseconds zoom-related actions (e.g., tile loading) are debounced
var ZOOM_DEBOUNCE = exports.ZOOM_DEBOUNCE = 10;

// the length of time to keep refreshing the view after a drag event
var SHORT_DRAG_TIMEOUT = exports.SHORT_DRAG_TIMEOUT = 110;

var LONG_DRAG_TIMEOUT = exports.LONG_DRAG_TIMEOUT = 3000;

var LOCATION_LISTENER_PREFIX = exports.LOCATION_LISTENER_PREFIX = 'locationListenerPrefix';

var ZOOM_TRANSITION_DURATION = exports.ZOOM_TRANSITION_DURATION = 1000;

var DEFAULT_SERVER = exports.DEFAULT_SERVER = 'http://higlass.io/api/v1';

var VIEW_HEADER_MED_WIDTH_SEARCH_BAR = exports.VIEW_HEADER_MED_WIDTH_SEARCH_BAR = 400;

var VIEW_HEADER_MIN_WIDTH_SEARCH_BAR = exports.VIEW_HEADER_MIN_WIDTH_SEARCH_BAR = 300;

var TRACK_LOCATIONS = exports.TRACK_LOCATIONS = ['top', 'left', 'right', 'bottom', 'center', 'whole', 'gallery'];

var MIN_HORIZONTAL_HEIGHT = exports.MIN_HORIZONTAL_HEIGHT = 20;

var MIN_VERTICAL_WIDTH = exports.MIN_VERTICAL_WIDTH = 20;

/* --------------------------------- Themes -------------------------------- */

/***/ }),
/* 12 */
/***/ (function(module, exports) {

var core = module.exports = { version: '2.6.5' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef


/***/ }),
/* 13 */
/***/ (function(module, exports, __nested_webpack_require_106804__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ReactCSS = exports.loop = exports.handleActive = exports.handleHover = exports.hover = undefined;

var _flattenNames = __nested_webpack_require_106804__(733);

var _flattenNames2 = _interopRequireDefault(_flattenNames);

var _mergeClasses = __nested_webpack_require_106804__(799);

var _mergeClasses2 = _interopRequireDefault(_mergeClasses);

var _autoprefix = __nested_webpack_require_106804__(818);

var _autoprefix2 = _interopRequireDefault(_autoprefix);

var _hover2 = __nested_webpack_require_106804__(819);

var _hover3 = _interopRequireDefault(_hover2);

var _active = __nested_webpack_require_106804__(820);

var _active2 = _interopRequireDefault(_active);

var _loop2 = __nested_webpack_require_106804__(821);

var _loop3 = _interopRequireDefault(_loop2);

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

exports.hover = _hover3.default;
exports.handleHover = _hover3.default;
exports.handleActive = _active2.default;
exports.loop = _loop3.default;
var ReactCSS = exports.ReactCSS = function ReactCSS(classes) {
  for (var _len = arguments.length, activations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    activations[_key - 1] = arguments[_key];
  }

  var activeNames = (0, _flattenNames2.default)(activations);
  var merged = (0, _mergeClasses2.default)(classes, activeNames);
  return (0, _autoprefix2.default)(merged);
};

exports.default = ReactCSS;

/***/ }),
/* 14 */
/***/ (function(module, exports, __nested_webpack_require_108325__) {

"use strict";


exports.__esModule = true;

var _getPrototypeOf = __nested_webpack_require_108325__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _getOwnPropertyDescriptor = __nested_webpack_require_108325__(614);

var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);

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

exports.default = function get(object, property, receiver) {
  if (object === null) object = Function.prototype;
  var desc = (0, _getOwnPropertyDescriptor2.default)(object, property);

  if (desc === undefined) {
    var parent = (0, _getPrototypeOf2.default)(object);

    if (parent === null) {
      return undefined;
    } else {
      return get(parent, property, receiver);
    }
  } else if ("value" in desc) {
    return desc.value;
  } else {
    var getter = desc.get;

    if (getter === undefined) {
      return undefined;
    }

    return getter.call(receiver);
  }
};

/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_109396__) {

"use strict";

// EXTERNAL MODULE: ../node_modules/d3-color/src/index.js + 5 modules
var src = __nested_webpack_require_109396__(9);

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/basis.js
function basis(t1, v0, v1, v2, v3) {
  var t2 = t1 * t1, t3 = t2 * t1;
  return ((1 - 3 * t1 + 3 * t2 - t3) * v0
      + (4 - 6 * t2 + 3 * t3) * v1
      + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
      + t3 * v3) / 6;
}

/* harmony default export */ var src_basis = (function(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
        v1 = values[i],
        v2 = values[i + 1],
        v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
        v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/basisClosed.js


/* harmony default export */ var basisClosed = (function(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
        v0 = values[(i + n - 1) % n],
        v1 = values[i % n],
        v2 = values[(i + 1) % n],
        v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/color.js


function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}

function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}

function color_hue(a, b) {
  var d = b - a;
  return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);
}

function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);
  };
}

function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant(isNaN(a) ? b : a);
}

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/rgb.js





/* harmony default export */ var src_rgb = ((function rgbGamma(y) {
  var color = gamma(y);

  function rgb(start, end) {
    var r = color((start = Object(src["rgb"])(start)).r, (end = Object(src["rgb"])(end)).r),
        g = color(start.g, end.g),
        b = color(start.b, end.b),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }

  rgb.gamma = rgbGamma;

  return rgb;
})(1));

function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length,
        r = new Array(n),
        g = new Array(n),
        b = new Array(n),
        i, color;
    for (i = 0; i < n; ++i) {
      color = Object(src["rgb"])(colors[i]);
      r[i] = color.r || 0;
      g[i] = color.g || 0;
      b[i] = color.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color.opacity = 1;
    return function(t) {
      color.r = r(t);
      color.g = g(t);
      color.b = b(t);
      return color + "";
    };
  };
}

var rgbBasis = rgbSpline(src_basis);
var rgbBasisClosed = rgbSpline(basisClosed);

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/array.js


/* harmony default export */ var array = (function(a, b) {
  var nb = b ? b.length : 0,
      na = a ? Math.min(nb, a.length) : 0,
      x = new Array(na),
      c = new Array(nb),
      i;

  for (i = 0; i < na; ++i) x[i] = src_value(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];

  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/date.js
/* harmony default export */ var date = (function(a, b) {
  var d = new Date;
  return a = +a, b -= a, function(t) {
    return d.setTime(a + b * t), d;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/number.js
/* harmony default export */ var number = (function(a, b) {
  return a = +a, b -= a, function(t) {
    return a + b * t;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/object.js


/* harmony default export */ var object = (function(a, b) {
  var i = {},
      c = {},
      k;

  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};

  for (k in b) {
    if (k in a) {
      i[k] = src_value(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }

  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/string.js


var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
    reB = new RegExp(reA.source, "g");

function zero(b) {
  return function() {
    return b;
  };
}

function one(b) {
  return function(t) {
    return b(t) + "";
  };
}

/* harmony default export */ var string = (function(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b
      am, // current match in a
      bm, // current match in b
      bs, // string preceding current number in b, if any
      i = -1, // index in s
      s = [], // string constants and placeholders
      q = []; // number interpolators

  // Coerce inputs to strings.
  a = a + "", b = b + "";

  // Interpolate pairs of numbers in a & b.
  while ((am = reA.exec(a))
      && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) { // a string precedes the next number in b
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs; // coalesce with previous string
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
      if (s[i]) s[i] += bm; // coalesce with previous string
      else s[++i] = bm;
    } else { // interpolate non-matching numbers
      s[++i] = null;
      q.push({i: i, x: number(am, bm)});
    }
    bi = reB.lastIndex;
  }

  // Add remains of b.
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs; // coalesce with previous string
    else s[++i] = bs;
  }

  // Special optimization for only a single match.
  // Otherwise, interpolate each of the numbers and rejoin the string.
  return s.length < 2 ? (q[0]
      ? one(q[0].x)
      : zero(b))
      : (b = q.length, function(t) {
          for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
          return s.join("");
        });
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/value.js









/* harmony default export */ var src_value = (function(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? constant(b)
      : (t === "number" ? number
      : t === "string" ? ((c = Object(src["color"])(b)) ? (b = c, src_rgb) : string)
      : b instanceof src["color"] ? src_rgb
      : b instanceof Date ? date
      : Array.isArray(b) ? array
      : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object
      : number)(a, b);
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/discrete.js
/* harmony default export */ var discrete = (function(range) {
  var n = range.length;
  return function(t) {
    return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/hue.js


/* harmony default export */ var src_hue = (function(a, b) {
  var i = color_hue(+a, +b);
  return function(t) {
    var x = i(t);
    return x - 360 * Math.floor(x / 360);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/round.js
/* harmony default export */ var round = (function(a, b) {
  return a = +a, b -= a, function(t) {
    return Math.round(a + b * t);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/transform/decompose.js
var degrees = 180 / Math.PI;

var identity = {
  translateX: 0,
  translateY: 0,
  rotate: 0,
  skewX: 0,
  scaleX: 1,
  scaleY: 1
};

/* harmony default export */ var decompose = (function(a, b, c, d, e, f) {
  var scaleX, scaleY, skewX;
  if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
  if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
  if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
  if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
  return {
    translateX: e,
    translateY: f,
    rotate: Math.atan2(b, a) * degrees,
    skewX: Math.atan(skewX) * degrees,
    scaleX: scaleX,
    scaleY: scaleY
  };
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/transform/parse.js


var cssNode,
    cssRoot,
    cssView,
    svgNode;

function parseCss(value) {
  if (value === "none") return identity;
  if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView;
  cssNode.style.transform = value;
  value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform");
  cssRoot.removeChild(cssNode);
  value = value.slice(7, -1).split(",");
  return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
}

function parseSvg(value) {
  if (value == null) return identity;
  if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
  svgNode.setAttribute("transform", value);
  if (!(value = svgNode.transform.baseVal.consolidate())) return identity;
  value = value.matrix;
  return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/transform/index.js



function interpolateTransform(parse, pxComma, pxParen, degParen) {

  function pop(s) {
    return s.length ? s.pop() + " " : "";
  }

  function translate(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push("translate(", null, pxComma, null, pxParen);
      q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
    } else if (xb || yb) {
      s.push("translate(" + xb + pxComma + yb + pxParen);
    }
  }

  function rotate(a, b, s, q) {
    if (a !== b) {
      if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path
      q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b)});
    } else if (b) {
      s.push(pop(s) + "rotate(" + b + degParen);
    }
  }

  function skewX(a, b, s, q) {
    if (a !== b) {
      q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b)});
    } else if (b) {
      s.push(pop(s) + "skewX(" + b + degParen);
    }
  }

  function scale(xa, ya, xb, yb, s, q) {
    if (xa !== xb || ya !== yb) {
      var i = s.push(pop(s) + "scale(", null, ",", null, ")");
      q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});
    } else if (xb !== 1 || yb !== 1) {
      s.push(pop(s) + "scale(" + xb + "," + yb + ")");
    }
  }

  return function(a, b) {
    var s = [], // string constants and placeholders
        q = []; // number interpolators
    a = parse(a), b = parse(b);
    translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
    rotate(a.rotate, b.rotate, s, q);
    skewX(a.skewX, b.skewX, s, q);
    scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
    a = b = null; // gc
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  };
}

var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/zoom.js
var rho = Math.SQRT2,
    rho2 = 2,
    rho4 = 4,
    epsilon2 = 1e-12;

function cosh(x) {
  return ((x = Math.exp(x)) + 1 / x) / 2;
}

function sinh(x) {
  return ((x = Math.exp(x)) - 1 / x) / 2;
}

function tanh(x) {
  return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}

// p0 = [ux0, uy0, w0]
// p1 = [ux1, uy1, w1]
/* harmony default export */ var zoom = (function(p0, p1) {
  var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],
      ux1 = p1[0], uy1 = p1[1], w1 = p1[2],
      dx = ux1 - ux0,
      dy = uy1 - uy0,
      d2 = dx * dx + dy * dy,
      i,
      S;

  // Special case for u0 ≅ u1.
  if (d2 < epsilon2) {
    S = Math.log(w1 / w0) / rho;
    i = function(t) {
      return [
        ux0 + t * dx,
        uy0 + t * dy,
        w0 * Math.exp(rho * t * S)
      ];
    }
  }

  // General case.
  else {
    var d1 = Math.sqrt(d2),
        b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),
        b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),
        r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),
        r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
    S = (r1 - r0) / rho;
    i = function(t) {
      var s = t * S,
          coshr0 = cosh(r0),
          u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));
      return [
        ux0 + u * dx,
        uy0 + u * dy,
        w0 * coshr0 / cosh(rho * s + r0)
      ];
    }
  }

  i.duration = S * 1000;

  return i;
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/hsl.js



function hsl(hue) {
  return function(start, end) {
    var h = hue((start = Object(src["hsl"])(start)).h, (end = Object(src["hsl"])(end)).h),
        s = nogamma(start.s, end.s),
        l = nogamma(start.l, end.l),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.s = s(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

/* harmony default export */ var src_hsl = (hsl(color_hue));
var hslLong = hsl(nogamma);

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/lab.js



function lab(start, end) {
  var l = nogamma((start = Object(src["lab"])(start)).l, (end = Object(src["lab"])(end)).l),
      a = nogamma(start.a, end.a),
      b = nogamma(start.b, end.b),
      opacity = nogamma(start.opacity, end.opacity);
  return function(t) {
    start.l = l(t);
    start.a = a(t);
    start.b = b(t);
    start.opacity = opacity(t);
    return start + "";
  };
}

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/hcl.js



function hcl(hue) {
  return function(start, end) {
    var h = hue((start = Object(src["hcl"])(start)).h, (end = Object(src["hcl"])(end)).h),
        c = nogamma(start.c, end.c),
        l = nogamma(start.l, end.l),
        opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.h = h(t);
      start.c = c(t);
      start.l = l(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
}

/* harmony default export */ var src_hcl = (hcl(color_hue));
var hclLong = hcl(nogamma);

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/cubehelix.js



function cubehelix_cubehelix(hue) {
  return (function cubehelixGamma(y) {
    y = +y;

    function cubehelix(start, end) {
      var h = hue((start = Object(src["cubehelix"])(start)).h, (end = Object(src["cubehelix"])(end)).h),
          s = nogamma(start.s, end.s),
          l = nogamma(start.l, end.l),
          opacity = nogamma(start.opacity, end.opacity);
      return function(t) {
        start.h = h(t);
        start.s = s(t);
        start.l = l(Math.pow(t, y));
        start.opacity = opacity(t);
        return start + "";
      };
    }

    cubehelix.gamma = cubehelixGamma;

    return cubehelix;
  })(1);
}

/* harmony default export */ var src_cubehelix = (cubehelix_cubehelix(color_hue));
var cubehelixLong = cubehelix_cubehelix(nogamma);

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/piecewise.js
function piecewise(interpolate, values) {
  var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
  while (i < n) I[i] = interpolate(v, v = values[++i]);
  return function(t) {
    var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
    return I[i](t - i);
  };
}

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/quantize.js
/* harmony default export */ var quantize = (function(interpolator, n) {
  var samples = new Array(n);
  for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
  return samples;
});

// CONCATENATED MODULE: ../node_modules/d3-interpolate/src/index.js
/* concated harmony reexport interpolate */__nested_webpack_require_109396__.d(__webpack_exports__, "a", function() { return src_value; });
/* unused concated harmony import interpolateArray */
/* unused concated harmony import interpolateBasis */
/* unused concated harmony import interpolateBasisClosed */
/* unused concated harmony import interpolateDate */
/* unused concated harmony import interpolateDiscrete */
/* unused concated harmony import interpolateHue */
/* concated harmony reexport interpolateNumber */__nested_webpack_require_109396__.d(__webpack_exports__, "c", function() { return number; });
/* unused concated harmony import interpolateObject */
/* concated harmony reexport interpolateRound */__nested_webpack_require_109396__.d(__webpack_exports__, "e", function() { return round; });
/* concated harmony reexport interpolateString */__nested_webpack_require_109396__.d(__webpack_exports__, "f", function() { return string; });
/* concated harmony reexport interpolateTransformCss */__nested_webpack_require_109396__.d(__webpack_exports__, "g", function() { return interpolateTransformCss; });
/* concated harmony reexport interpolateTransformSvg */__nested_webpack_require_109396__.d(__webpack_exports__, "h", function() { return interpolateTransformSvg; });
/* concated harmony reexport interpolateZoom */__nested_webpack_require_109396__.d(__webpack_exports__, "i", function() { return zoom; });
/* concated harmony reexport interpolateRgb */__nested_webpack_require_109396__.d(__webpack_exports__, "d", function() { return src_rgb; });
/* unused concated harmony import interpolateRgbBasis */
/* unused concated harmony import interpolateRgbBasisClosed */
/* unused concated harmony import interpolateHsl */
/* unused concated harmony import interpolateHslLong */
/* unused concated harmony import interpolateLab */
/* unused concated harmony import interpolateHcl */
/* unused concated harmony import interpolateHclLong */
/* unused concated harmony import interpolateCubehelix */
/* concated harmony reexport interpolateCubehelixLong */__nested_webpack_require_109396__.d(__webpack_exports__, "b", function() { return cubehelixLong; });
/* unused concated harmony import piecewise */
/* unused concated harmony import quantize */






















/***/ }),
/* 16 */
/***/ (function(module, exports, __nested_webpack_require_127985__) {

var global = __nested_webpack_require_127985__(23);
var core = __nested_webpack_require_127985__(12);
var ctx = __nested_webpack_require_127985__(49);
var hide = __nested_webpack_require_127985__(43);
var has = __nested_webpack_require_127985__(47);
var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var IS_WRAP = type & $export.W;
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE];
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  var key, own, out;
  if (IS_GLOBAL) source = name;
  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    if (own && has(exports, key)) continue;
    // export native or passed
    out = own ? target[key] : source[key];
    // prevent global pollution for namespaces
    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
    // bind timers to global for call from export context
    : IS_BIND && own ? ctx(out, global)
    // wrap global constructors for prevent change them in library
    : IS_WRAP && target[key] == out ? (function (C) {
      var F = function (a, b, c) {
        if (this instanceof C) {
          switch (arguments.length) {
            case 0: return new C();
            case 1: return new C(a);
            case 2: return new C(a, b);
          } return new C(a, b, c);
        } return C.apply(this, arguments);
      };
      F[PROTOTYPE] = C[PROTOTYPE];
      return F;
    // make static versions for prototype methods
    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
    if (IS_PROTO) {
      (exports.virtual || (exports.virtual = {}))[key] = out;
      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
      if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
    }
  }
};
// type bitmap
$export.F = 1;   // forced
$export.G = 2;   // global
$export.S = 4;   // static
$export.P = 8;   // proto
$export.B = 16;  // bind
$export.W = 32;  // wrap
$export.U = 64;  // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;


/***/ }),
/* 17 */
/***/ (function(module, exports, __nested_webpack_require_130437__) {

module.exports = { "default": __nested_webpack_require_130437__(216), __esModule: true };

/***/ }),
/* 18 */
/***/ (function(module, exports, __nested_webpack_require_130590__) {

module.exports = { "default": __nested_webpack_require_130590__(208), __esModule: true };

/***/ }),
/* 19 */
/***/ (function(module, exports, __nested_webpack_require_130743__) {

"use strict";


exports.__esModule = true;

var _isIterable2 = __nested_webpack_require_130743__(518);

var _isIterable3 = _interopRequireDefault(_isIterable2);

var _getIterator2 = __nested_webpack_require_130743__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

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

exports.default = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if ((0, _isIterable3.default)(Object(arr))) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();

/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_132018__) {

"use strict";
__nested_webpack_require_132018__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatDecimal.js
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
/* harmony default export */ var formatDecimal = (function(x, p) {
  if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
  var i, coefficient = x.slice(0, i);

  // The string returned by toExponential either has the form \d\.\d+e[-+]\d+
  // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
  return [
    coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
    +x.slice(i + 1)
  ];
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/exponent.js


/* harmony default export */ var src_exponent = (function(x) {
  return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatGroup.js
/* harmony default export */ var formatGroup = (function(grouping, thousands) {
  return function(value, width) {
    var i = value.length,
        t = [],
        j = 0,
        g = grouping[0],
        length = 0;

    while (i > 0 && g > 0) {
      if (length + g + 1 > width) g = Math.max(1, width - length);
      t.push(value.substring(i -= g, i + g));
      if ((length += g + 1) > width) break;
      g = grouping[j = (j + 1) % grouping.length];
    }

    return t.reverse().join(thousands);
  };
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ var formatNumerals = (function(numerals) {
  return function(value) {
    return value.replace(/[0-9]/g, function(i) {
      return numerals[+i];
    });
  };
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;

function formatSpecifier(specifier) {
  return new FormatSpecifier(specifier);
}

formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof

function FormatSpecifier(specifier) {
  if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
  var match;
  this.fill = match[1] || " ";
  this.align = match[2] || ">";
  this.sign = match[3] || "-";
  this.symbol = match[4] || "";
  this.zero = !!match[5];
  this.width = match[6] && +match[6];
  this.comma = !!match[7];
  this.precision = match[8] && +match[8].slice(1);
  this.trim = !!match[9];
  this.type = match[10] || "";
}

FormatSpecifier.prototype.toString = function() {
  return this.fill
      + this.align
      + this.sign
      + this.symbol
      + (this.zero ? "0" : "")
      + (this.width == null ? "" : Math.max(1, this.width | 0))
      + (this.comma ? "," : "")
      + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
      + (this.trim ? "~" : "")
      + this.type;
};

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ var formatTrim = (function(s) {
  out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
    switch (s[i]) {
      case ".": i0 = i1 = i; break;
      case "0": if (i0 === 0) i0 = i; i1 = i; break;
      default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break;
    }
  }
  return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatPrefixAuto.js


var prefixExponent;

/* harmony default export */ var formatPrefixAuto = (function(x, p) {
  var d = formatDecimal(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1],
      i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
      n = coefficient.length;
  return i === n ? coefficient
      : i > n ? coefficient + new Array(i - n + 1).join("0")
      : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
      : "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatRounded.js


/* harmony default export */ var formatRounded = (function(x, p) {
  var d = formatDecimal(x, p);
  if (!d) return x + "";
  var coefficient = d[0],
      exponent = d[1];
  return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
      : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
      : coefficient + new Array(exponent - coefficient.length + 2).join("0");
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/formatTypes.js



/* harmony default export */ var formatTypes = ({
  "%": function(x, p) { return (x * 100).toFixed(p); },
  "b": function(x) { return Math.round(x).toString(2); },
  "c": function(x) { return x + ""; },
  "d": function(x) { return Math.round(x).toString(10); },
  "e": function(x, p) { return x.toExponential(p); },
  "f": function(x, p) { return x.toFixed(p); },
  "g": function(x, p) { return x.toPrecision(p); },
  "o": function(x) { return Math.round(x).toString(8); },
  "p": function(x, p) { return formatRounded(x * 100, p); },
  "r": formatRounded,
  "s": formatPrefixAuto,
  "X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
  "x": function(x) { return Math.round(x).toString(16); }
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/identity.js
/* harmony default export */ var identity = (function(x) {
  return x;
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/locale.js









var prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];

/* harmony default export */ var src_locale = (function(locale) {
  var group = locale.grouping && locale.thousands ? formatGroup(locale.grouping, locale.thousands) : identity,
      currency = locale.currency,
      decimal = locale.decimal,
      numerals = locale.numerals ? formatNumerals(locale.numerals) : identity,
      percent = locale.percent || "%";

  function newFormat(specifier) {
    specifier = formatSpecifier(specifier);

    var fill = specifier.fill,
        align = specifier.align,
        sign = specifier.sign,
        symbol = specifier.symbol,
        zero = specifier.zero,
        width = specifier.width,
        comma = specifier.comma,
        precision = specifier.precision,
        trim = specifier.trim,
        type = specifier.type;

    // The "n" type is an alias for ",g".
    if (type === "n") comma = true, type = "g";

    // The "" type, and any invalid type, is an alias for ".12~g".
    else if (!formatTypes[type]) precision == null && (precision = 12), trim = true, type = "g";

    // If zero fill is specified, padding goes after sign and before digits.
    if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";

    // Compute the prefix and suffix.
    // For SI-prefix, the suffix is lazily computed.
    var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
        suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? percent : "";

    // What format function should we use?
    // Is this an integer type?
    // Can this type generate exponential notation?
    var formatType = formatTypes[type],
        maybeSuffix = /[defgprs%]/.test(type);

    // Set the default precision if not specified,
    // or clamp the specified precision to the supported range.
    // For significant precision, it must be in [1, 21].
    // For fixed precision, it must be in [0, 20].
    precision = precision == null ? 6
        : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
        : Math.max(0, Math.min(20, precision));

    function format(value) {
      var valuePrefix = prefix,
          valueSuffix = suffix,
          i, n, c;

      if (type === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;

        // Perform the initial formatting.
        var valueNegative = value < 0;
        value = formatType(Math.abs(value), precision);

        // Trim insignificant zeros.
        if (trim) value = formatTrim(value);

        // If a negative value rounds to zero during formatting, treat as positive.
        if (valueNegative && +value === 0) valueNegative = false;

        // Compute the prefix and suffix.
        valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
        valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");

        // Break the formatted value into the integer “value” part that can be
        // grouped, and fractional or exponential “suffix” part that is not.
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c = value.charCodeAt(i), 48 > c || c > 57) {
              valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }

      // If the fill character is not "0", grouping is applied before padding.
      if (comma && !zero) value = group(value, Infinity);

      // Compute the padding.
      var length = valuePrefix.length + value.length + valueSuffix.length,
          padding = length < width ? new Array(width - length + 1).join(fill) : "";

      // If the fill character is "0", grouping is applied after padding.
      if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";

      // Reconstruct the final output based on the desired alignment.
      switch (align) {
        case "<": value = valuePrefix + value + valueSuffix + padding; break;
        case "=": value = valuePrefix + padding + value + valueSuffix; break;
        case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
        default: value = padding + valuePrefix + value + valueSuffix; break;
      }

      return numerals(value);
    }

    format.toString = function() {
      return specifier + "";
    };

    return format;
  }

  function formatPrefix(specifier, value) {
    var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
        e = Math.max(-8, Math.min(8, Math.floor(src_exponent(value) / 3))) * 3,
        k = Math.pow(10, -e),
        prefix = prefixes[8 + e / 3];
    return function(value) {
      return f(k * value) + prefix;
    };
  }

  return {
    format: newFormat,
    formatPrefix: formatPrefix
  };
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/defaultLocale.js


var defaultLocale_locale;
var defaultLocale_format;
var defaultLocale_formatPrefix;

defaultLocale({
  decimal: ".",
  thousands: ",",
  grouping: [3],
  currency: ["$", ""]
});

function defaultLocale(definition) {
  defaultLocale_locale = src_locale(definition);
  defaultLocale_format = defaultLocale_locale.format;
  defaultLocale_formatPrefix = defaultLocale_locale.formatPrefix;
  return defaultLocale_locale;
}

// CONCATENATED MODULE: ../node_modules/d3-format/src/precisionFixed.js


/* harmony default export */ var precisionFixed = (function(step) {
  return Math.max(0, -src_exponent(Math.abs(step)));
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/precisionPrefix.js


/* harmony default export */ var precisionPrefix = (function(step, value) {
  return Math.max(0, Math.max(-8, Math.min(8, Math.floor(src_exponent(value) / 3))) * 3 - src_exponent(Math.abs(step)));
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/precisionRound.js


/* harmony default export */ var precisionRound = (function(step, max) {
  step = Math.abs(step), max = Math.abs(max) - step;
  return Math.max(0, src_exponent(max) - src_exponent(step)) + 1;
});

// CONCATENATED MODULE: ../node_modules/d3-format/src/index.js
/* concated harmony reexport formatDefaultLocale */__nested_webpack_require_132018__.d(__webpack_exports__, "formatDefaultLocale", function() { return defaultLocale; });
/* concated harmony reexport format */__nested_webpack_require_132018__.d(__webpack_exports__, "format", function() { return defaultLocale_format; });
/* concated harmony reexport formatPrefix */__nested_webpack_require_132018__.d(__webpack_exports__, "formatPrefix", function() { return defaultLocale_formatPrefix; });
/* concated harmony reexport formatLocale */__nested_webpack_require_132018__.d(__webpack_exports__, "formatLocale", function() { return src_locale; });
/* concated harmony reexport formatSpecifier */__nested_webpack_require_132018__.d(__webpack_exports__, "formatSpecifier", function() { return formatSpecifier; });
/* concated harmony reexport precisionFixed */__nested_webpack_require_132018__.d(__webpack_exports__, "precisionFixed", function() { return precisionFixed; });
/* concated harmony reexport precisionPrefix */__nested_webpack_require_132018__.d(__webpack_exports__, "precisionPrefix", function() { return precisionPrefix; });
/* concated harmony reexport precisionRound */__nested_webpack_require_132018__.d(__webpack_exports__, "precisionRound", function() { return precisionRound; });








/***/ }),
/* 21 */
/***/ (function(module, exports, __nested_webpack_require_145579__) {

var store = __nested_webpack_require_145579__(106)('wks');
var uid = __nested_webpack_require_145579__(91);
var Symbol = __nested_webpack_require_145579__(23).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';

var $exports = module.exports = function (name) {
  return store[name] || (store[name] =
    USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};

$exports.store = store;


/***/ }),
/* 22 */
/***/ (function(module, exports, __nested_webpack_require_146028__) {

"use strict";


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

var _Alpha = __nested_webpack_require_146028__(824);

Object.defineProperty(exports, 'Alpha', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Alpha).default;
  }
});

var _Checkboard = __nested_webpack_require_146028__(289);

Object.defineProperty(exports, 'Checkboard', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Checkboard).default;
  }
});

var _EditableInput = __nested_webpack_require_146028__(827);

Object.defineProperty(exports, 'EditableInput', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_EditableInput).default;
  }
});

var _Hue = __nested_webpack_require_146028__(828);

Object.defineProperty(exports, 'Hue', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Hue).default;
  }
});

var _Raised = __nested_webpack_require_146028__(830);

Object.defineProperty(exports, 'Raised', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Raised).default;
  }
});

var _Saturation = __nested_webpack_require_146028__(837);

Object.defineProperty(exports, 'Saturation', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Saturation).default;
  }
});

var _ColorWrap = __nested_webpack_require_146028__(437);

Object.defineProperty(exports, 'ColorWrap', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_ColorWrap).default;
  }
});

var _Swatch = __nested_webpack_require_146028__(843);

Object.defineProperty(exports, 'Swatch', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Swatch).default;
  }
});

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

/***/ }),
/* 23 */
/***/ (function(module, exports) {

// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
  ? window : typeof self != 'undefined' && self.Math == Math ? self
  // eslint-disable-next-line no-new-func
  : Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef


/***/ }),
/* 24 */
/***/ (function(module, exports, __nested_webpack_require_148263__) {

"use strict";


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

var _chromInfo = __nested_webpack_require_148263__(521);

Object.defineProperty(exports, 'chromInfo', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_chromInfo)['default'];
    }

    return get;
  }()
});

var _domEvent = __nested_webpack_require_148263__(1084);

Object.defineProperty(exports, 'createDomEvent', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_domEvent)['default'];
    }

    return get;
  }()
});

var _elementResizeListener = __nested_webpack_require_148263__(440);

Object.defineProperty(exports, 'ElementResizeListener', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_elementResizeListener)['default'];
    }

    return get;
  }()
});

var _tileProxy = __nested_webpack_require_148263__(1085);

Object.defineProperty(exports, 'tileProxy', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_tileProxy)['default'];
    }

    return get;
  }()
});
Object.defineProperty(exports, 'requestsInFlight', {
  enumerable: true,
  get: function () {
    function get() {
      return _tileProxy.requestsInFlight;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'setTileProxyAuthHeader', {
  enumerable: true,
  get: function () {
    function get() {
      return _tileProxy.setTileProxyAuthHeader;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'getTileProxyAuthHeader', {
  enumerable: true,
  get: function () {
    function get() {
      return _tileProxy.getTileProxyAuthHeader;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'authHeader', {
  enumerable: true,
  get: function () {
    function get() {
      return _tileProxy.authHeader;
    }

    return get;
  }()
});

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

/***/ }),
/* 25 */
/***/ (function(module, exports, __nested_webpack_require_150317__) {

"use strict";


exports.__esModule = true;

var _from = __nested_webpack_require_150317__(95);

var _from2 = _interopRequireDefault(_from);

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

exports.default = function (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 (0, _from2.default)(arr);
  }
};

/***/ }),
/* 26 */
/***/ (function(module, exports, __nested_webpack_require_150853__) {

// The MIT License (MIT)
//
// Copyright (c) 2014 Jonas Finnemann Jensen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

module.exports = __nested_webpack_require_150853__(589);


/***/ }),
/* 27 */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_152664__) {

"use strict";
__nested_webpack_require_152664__.r(__webpack_exports__);

// EXTERNAL MODULE: ../node_modules/d3-array/src/index.js + 31 modules
var src = __nested_webpack_require_152664__(8);

// EXTERNAL MODULE: ../node_modules/d3-collection/src/index.js + 6 modules
var d3_collection_src = __nested_webpack_require_152664__(72);

// CONCATENATED MODULE: ../node_modules/d3-scale/src/array.js
var array = Array.prototype;

var map = array.map;
var slice = array.slice;

// CONCATENATED MODULE: ../node_modules/d3-scale/src/ordinal.js



var implicit = {name: "implicit"};

function ordinal(range) {
  var index = Object(d3_collection_src["a" /* map */])(),
      domain = [],
      unknown = implicit;

  range = range == null ? [] : slice.call(range);

  function scale(d) {
    var key = d + "", i = index.get(key);
    if (!i) {
      if (unknown !== implicit) return unknown;
      index.set(key, i = domain.push(d));
    }
    return range[(i - 1) % range.length];
  }

  scale.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [], index = Object(d3_collection_src["a" /* map */])();
    var i = -1, n = _.length, d, key;
    while (++i < n) if (!index.has(key = (d = _[i]) + "")) index.set(key, domain.push(d));
    return scale;
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice.call(_), scale) : range.slice();
  };

  scale.unknown = function(_) {
    return arguments.length ? (unknown = _, scale) : unknown;
  };

  scale.copy = function() {
    return ordinal()
        .domain(domain)
        .range(range)
        .unknown(unknown);
  };

  return scale;
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/band.js



function band() {
  var scale = ordinal().unknown(undefined),
      domain = scale.domain,
      ordinalRange = scale.range,
      range = [0, 1],
      step,
      bandwidth,
      round = false,
      paddingInner = 0,
      paddingOuter = 0,
      align = 0.5;

  delete scale.unknown;

  function rescale() {
    var n = domain().length,
        reverse = range[1] < range[0],
        start = range[reverse - 0],
        stop = range[1 - reverse];
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round) step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = Object(src["range"])(n).map(function(i) { return start + step * i; });
    return ordinalRange(reverse ? values.reverse() : values);
  }

  scale.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };

  scale.range = function(_) {
    return arguments.length ? (range = [+_[0], +_[1]], rescale()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return range = [+_[0], +_[1]], round = true, rescale();
  };

  scale.bandwidth = function() {
    return bandwidth;
  };

  scale.step = function() {
    return step;
  };

  scale.round = function(_) {
    return arguments.length ? (round = !!_, rescale()) : round;
  };

  scale.padding = function(_) {
    return arguments.length ? (paddingInner = paddingOuter = Math.max(0, Math.min(1, _)), rescale()) : paddingInner;
  };

  scale.paddingInner = function(_) {
    return arguments.length ? (paddingInner = Math.max(0, Math.min(1, _)), rescale()) : paddingInner;
  };

  scale.paddingOuter = function(_) {
    return arguments.length ? (paddingOuter = Math.max(0, Math.min(1, _)), rescale()) : paddingOuter;
  };

  scale.align = function(_) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
  };

  scale.copy = function() {
    return band()
        .domain(domain())
        .range(range)
        .round(round)
        .paddingInner(paddingInner)
        .paddingOuter(paddingOuter)
        .align(align);
  };

  return rescale();
}

function pointish(scale) {
  var copy = scale.copy;

  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  delete scale.paddingOuter;

  scale.copy = function() {
    return pointish(copy());
  };

  return scale;
}

function point() {
  return pointish(band().paddingInner(1));
}

// EXTERNAL MODULE: ../node_modules/d3-interpolate/src/index.js + 24 modules
var d3_interpolate_src = __nested_webpack_require_152664__(15);

// CONCATENATED MODULE: ../node_modules/d3-scale/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/number.js
/* harmony default export */ var number = (function(x) {
  return +x;
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/continuous.js






var unit = [0, 1];

function deinterpolateLinear(a, b) {
  return (b -= (a = +a))
      ? function(x) { return (x - a) / b; }
      : constant(b);
}

function deinterpolateClamp(deinterpolate) {
  return function(a, b) {
    var d = deinterpolate(a = +a, b = +b);
    return function(x) { return x <= a ? 0 : x >= b ? 1 : d(x); };
  };
}

function reinterpolateClamp(reinterpolate) {
  return function(a, b) {
    var r = reinterpolate(a = +a, b = +b);
    return function(t) { return t <= 0 ? a : t >= 1 ? b : r(t); };
  };
}

function bimap(domain, range, deinterpolate, reinterpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
  if (d1 < d0) d0 = deinterpolate(d1, d0), r0 = reinterpolate(r1, r0);
  else d0 = deinterpolate(d0, d1), r0 = reinterpolate(r0, r1);
  return function(x) { return r0(d0(x)); };
}

function polymap(domain, range, deinterpolate, reinterpolate) {
  var j = Math.min(domain.length, range.length) - 1,
      d = new Array(j),
      r = new Array(j),
      i = -1;

  // Reverse descending domains.
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range = range.slice().reverse();
  }

  while (++i < j) {
    d[i] = deinterpolate(domain[i], domain[i + 1]);
    r[i] = reinterpolate(range[i], range[i + 1]);
  }

  return function(x) {
    var i = Object(src["bisect"])(domain, x, 1, j) - 1;
    return r[i](d[i](x));
  };
}

function copy(source, target) {
  return target
      .domain(source.domain())
      .range(source.range())
      .interpolate(source.interpolate())
      .clamp(source.clamp());
}

// deinterpolate(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// reinterpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding domain value x in [a,b].
function continuous(deinterpolate, reinterpolate) {
  var domain = unit,
      range = unit,
      interpolate = d3_interpolate_src["a" /* interpolate */],
      clamp = false,
      piecewise,
      output,
      input;

  function rescale() {
    piecewise = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }

  function scale(x) {
    return (output || (output = piecewise(domain, range, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate)))(+x);
  }

  scale.invert = function(y) {
    return (input || (input = piecewise(range, domain, deinterpolateLinear, clamp ? reinterpolateClamp(reinterpolate) : reinterpolate)))(+y);
  };

  scale.domain = function(_) {
    return arguments.length ? (domain = map.call(_, number), rescale()) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice.call(_), rescale()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return range = slice.call(_), interpolate = d3_interpolate_src["e" /* interpolateRound */], rescale();
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, rescale()) : clamp;
  };

  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };

  return rescale();
}

// EXTERNAL MODULE: ../node_modules/d3-format/src/index.js + 15 modules
var d3_format_src = __nested_webpack_require_152664__(20);

// CONCATENATED MODULE: ../node_modules/d3-scale/src/tickFormat.js



/* harmony default export */ var src_tickFormat = (function(domain, count, specifier) {
  var start = domain[0],
      stop = domain[domain.length - 1],
      step = Object(src["tickStep"])(start, stop, count == null ? 10 : count),
      precision;
  specifier = Object(d3_format_src["formatSpecifier"])(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = Object(d3_format_src["precisionPrefix"])(step, value))) specifier.precision = precision;
      return Object(d3_format_src["formatPrefix"])(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = Object(d3_format_src["precisionRound"])(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = Object(d3_format_src["precisionFixed"])(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return Object(d3_format_src["format"])(specifier);
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/linear.js





function linearish(scale) {
  var domain = scale.domain;

  scale.ticks = function(count) {
    var d = domain();
    return Object(src["ticks"])(d[0], d[d.length - 1], count == null ? 10 : count);
  };

  scale.tickFormat = function(count, specifier) {
    return src_tickFormat(domain(), count, specifier);
  };

  scale.nice = function(count) {
    if (count == null) count = 10;

    var d = domain(),
        i0 = 0,
        i1 = d.length - 1,
        start = d[i0],
        stop = d[i1],
        step;

    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }

    step = Object(src["tickIncrement"])(start, stop, count);

    if (step > 0) {
      start = Math.floor(start / step) * step;
      stop = Math.ceil(stop / step) * step;
      step = Object(src["tickIncrement"])(start, stop, count);
    } else if (step < 0) {
      start = Math.ceil(start * step) / step;
      stop = Math.floor(stop * step) / step;
      step = Object(src["tickIncrement"])(start, stop, count);
    }

    if (step > 0) {
      d[i0] = Math.floor(start / step) * step;
      d[i1] = Math.ceil(stop / step) * step;
      domain(d);
    } else if (step < 0) {
      d[i0] = Math.ceil(start * step) / step;
      d[i1] = Math.floor(stop * step) / step;
      domain(d);
    }

    return scale;
  };

  return scale;
}

function linear() {
  var scale = continuous(deinterpolateLinear, d3_interpolate_src["c" /* interpolateNumber */]);

  scale.copy = function() {
    return copy(scale, linear());
  };

  return linearish(scale);
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/identity.js




function identity() {
  var domain = [0, 1];

  function scale(x) {
    return +x;
  }

  scale.invert = scale;

  scale.domain = scale.range = function(_) {
    return arguments.length ? (domain = map.call(_, number), scale) : domain.slice();
  };

  scale.copy = function() {
    return identity().domain(domain);
  };

  return linearish(scale);
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/nice.js
/* harmony default export */ var nice = (function(domain, interval) {
  domain = domain.slice();

  var i0 = 0,
      i1 = domain.length - 1,
      x0 = domain[i0],
      x1 = domain[i1],
      t;

  if (x1 < x0) {
    t = i0, i0 = i1, i1 = t;
    t = x0, x0 = x1, x1 = t;
  }

  domain[i0] = interval.floor(x0);
  domain[i1] = interval.ceil(x1);
  return domain;
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/log.js






function log_deinterpolate(a, b) {
  return (b = Math.log(b / a))
      ? function(x) { return Math.log(x / a) / b; }
      : constant(b);
}

function log_reinterpolate(a, b) {
  return a < 0
      ? function(t) { return -Math.pow(-b, t) * Math.pow(-a, 1 - t); }
      : function(t) { return Math.pow(b, t) * Math.pow(a, 1 - t); };
}

function pow10(x) {
  return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x;
}

function powp(base) {
  return base === 10 ? pow10
      : base === Math.E ? Math.exp
      : function(x) { return Math.pow(base, x); };
}

function logp(base) {
  return base === Math.E ? Math.log
      : base === 10 && Math.log10
      || base === 2 && Math.log2
      || (base = Math.log(base), function(x) { return Math.log(x) / base; });
}

function reflect(f) {
  return function(x) {
    return -f(-x);
  };
}

function log() {
  var scale = continuous(log_deinterpolate, log_reinterpolate).domain([1, 10]),
      domain = scale.domain,
      base = 10,
      logs = logp(10),
      pows = powp(10);

  function rescale() {
    logs = logp(base), pows = powp(base);
    if (domain()[0] < 0) logs = reflect(logs), pows = reflect(pows);
    return scale;
  }

  scale.base = function(_) {
    return arguments.length ? (base = +_, rescale()) : base;
  };

  scale.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };

  scale.ticks = function(count) {
    var d = domain(),
        u = d[0],
        v = d[d.length - 1],
        r;

    if (r = v < u) i = u, u = v, v = i;

    var i = logs(u),
        j = logs(v),
        p,
        k,
        t,
        n = count == null ? 10 : +count,
        z = [];

    if (!(base % 1) && j - i < n) {
      i = Math.round(i) - 1, j = Math.round(j) + 1;
      if (u > 0) for (; i < j; ++i) {
        for (k = 1, p = pows(i); k < base; ++k) {
          t = p * k;
          if (t < u) continue;
          if (t > v) break;
          z.push(t);
        }
      } else for (; i < j; ++i) {
        for (k = base - 1, p = pows(i); k >= 1; --k) {
          t = p * k;
          if (t < u) continue;
          if (t > v) break;
          z.push(t);
        }
      }
    } else {
      z = Object(src["ticks"])(i, j, Math.min(j - i, n)).map(pows);
    }

    return r ? z.reverse() : z;
  };

  scale.tickFormat = function(count, specifier) {
    if (specifier == null) specifier = base === 10 ? ".0e" : ",";
    if (typeof specifier !== "function") specifier = Object(d3_format_src["format"])(specifier);
    if (count === Infinity) return specifier;
    if (count == null) count = 10;
    var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?
    return function(d) {
      var i = d / pows(Math.round(logs(d)));
      if (i * base < base - 0.5) i *= base;
      return i <= k ? specifier(d) : "";
    };
  };

  scale.nice = function() {
    return domain(nice(domain(), {
      floor: function(x) { return pows(Math.floor(logs(x))); },
      ceil: function(x) { return pows(Math.ceil(logs(x))); }
    }));
  };

  scale.copy = function() {
    return copy(scale, log().base(base));
  };

  return scale;
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/pow.js




function raise(x, exponent) {
  return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
}

function pow() {
  var exponent = 1,
      scale = continuous(deinterpolate, reinterpolate),
      domain = scale.domain;

  function deinterpolate(a, b) {
    return (b = raise(b, exponent) - (a = raise(a, exponent)))
        ? function(x) { return (raise(x, exponent) - a) / b; }
        : constant(b);
  }

  function reinterpolate(a, b) {
    b = raise(b, exponent) - (a = raise(a, exponent));
    return function(t) { return raise(a + b * t, 1 / exponent); };
  }

  scale.exponent = function(_) {
    return arguments.length ? (exponent = +_, domain(domain())) : exponent;
  };

  scale.copy = function() {
    return copy(scale, pow().exponent(exponent));
  };

  return linearish(scale);
}

function sqrt() {
  return pow().exponent(0.5);
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/quantile.js



function quantile() {
  var domain = [],
      range = [],
      thresholds = [];

  function rescale() {
    var i = 0, n = Math.max(1, range.length);
    thresholds = new Array(n - 1);
    while (++i < n) thresholds[i - 1] = Object(src["quantile"])(domain, i / n);
    return scale;
  }

  function scale(x) {
    if (!isNaN(x = +x)) return range[Object(src["bisect"])(thresholds, x)];
  }

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return i < 0 ? [NaN, NaN] : [
      i > 0 ? thresholds[i - 1] : domain[0],
      i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
    ];
  };

  scale.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [];
    for (var i = 0, n = _.length, d; i < n; ++i) if (d = _[i], d != null && !isNaN(d = +d)) domain.push(d);
    domain.sort(src["ascending"]);
    return rescale();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice.call(_), rescale()) : range.slice();
  };

  scale.quantiles = function() {
    return thresholds.slice();
  };

  scale.copy = function() {
    return quantile()
        .domain(domain)
        .range(range);
  };

  return scale;
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/quantize.js




function quantize() {
  var x0 = 0,
      x1 = 1,
      n = 1,
      domain = [0.5],
      range = [0, 1];

  function scale(x) {
    if (x <= x) return range[Object(src["bisect"])(domain, x, 0, n)];
  }

  function rescale() {
    var i = -1;
    domain = new Array(n);
    while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);
    return scale;
  }

  scale.domain = function(_) {
    return arguments.length ? (x0 = +_[0], x1 = +_[1], rescale()) : [x0, x1];
  };

  scale.range = function(_) {
    return arguments.length ? (n = (range = slice.call(_)).length - 1, rescale()) : range.slice();
  };

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return i < 0 ? [NaN, NaN]
        : i < 1 ? [x0, domain[0]]
        : i >= n ? [domain[n - 1], x1]
        : [domain[i - 1], domain[i]];
  };

  scale.copy = function() {
    return quantize()
        .domain([x0, x1])
        .range(range);
  };

  return linearish(scale);
}

// CONCATENATED MODULE: ../node_modules/d3-scale/src/threshold.js



function threshold() {
  var domain = [0.5],
      range = [0, 1],
      n = 1;

  function scale(x) {
    if (x <= x) return range[Object(src["bisect"])(domain, x, 0, n)];
  }

  scale.domain = function(_) {
    return arguments.length ? (domain = slice.call(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice.call(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();
  };

  scale.invertExtent = function(y) {
    var i = range.indexOf(y);
    return [domain[i - 1], domain[i]];
  };

  scale.copy = function() {
    return threshold()
        .domain(domain)
        .range(range);
  };

  return scale;
}

// CONCATENATED MODULE: ../node_modules/d3-time/src/interval.js
var t0 = new Date,
    t1 = new Date;

function newInterval(floori, offseti, count, field) {

  function interval(date) {
    return floori(date = new Date(+date)), date;
  }

  interval.floor = interval;

  interval.ceil = function(date) {
    return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
  };

  interval.round = function(date) {
    var d0 = interval(date),
        d1 = interval.ceil(date);
    return date - d0 < d1 - date ? d0 : d1;
  };

  interval.offset = function(date, step) {
    return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
  };

  interval.range = function(start, stop, step) {
    var range = [], previous;
    start = interval.ceil(start);
    step = step == null ? 1 : Math.floor(step);
    if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
    do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
    while (previous < start && start < stop);
    return range;
  };

  interval.filter = function(test) {
    return newInterval(function(date) {
      if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
    }, function(date, step) {
      if (date >= date) {
        if (step < 0) while (++step <= 0) {
          while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty
        } else while (--step >= 0) {
          while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty
        }
      }
    });
  };

  if (count) {
    interval.count = function(start, end) {
      t0.setTime(+start), t1.setTime(+end);
      floori(t0), floori(t1);
      return Math.floor(count(t0, t1));
    };

    interval.every = function(step) {
      step = Math.floor(step);
      return !isFinite(step) || !(step > 0) ? null
          : !(step > 1) ? interval
          : interval.filter(field
              ? function(d) { return field(d) % step === 0; }
              : function(d) { return interval.count(0, d) % step === 0; });
    };
  }

  return interval;
}

// CONCATENATED MODULE: ../node_modules/d3-time/src/millisecond.js


var millisecond_millisecond = newInterval(function() {
  // noop
}, function(date, step) {
  date.setTime(+date + step);
}, function(start, end) {
  return end - start;
});

// An optimized implementation for this simple case.
millisecond_millisecond.every = function(k) {
  k = Math.floor(k);
  if (!isFinite(k) || !(k > 0)) return null;
  if (!(k > 1)) return millisecond_millisecond;
  return newInterval(function(date) {
    date.setTime(Math.floor(date / k) * k);
  }, function(date, step) {
    date.setTime(+date + step * k);
  }, function(start, end) {
    return (end - start) / k;
  });
};

/* harmony default export */ var src_millisecond = (millisecond_millisecond);
var milliseconds = millisecond_millisecond.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/duration.js
var durationSecond = 1e3;
var durationMinute = 6e4;
var durationHour = 36e5;
var durationDay = 864e5;
var durationWeek = 6048e5;

// CONCATENATED MODULE: ../node_modules/d3-time/src/second.js



var second_second = newInterval(function(date) {
  date.setTime(date - date.getMilliseconds());
}, function(date, step) {
  date.setTime(+date + step * durationSecond);
}, function(start, end) {
  return (end - start) / durationSecond;
}, function(date) {
  return date.getUTCSeconds();
});

/* harmony default export */ var src_second = (second_second);
var seconds = second_second.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/minute.js



var minute_minute = newInterval(function(date) {
  date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);
}, function(date, step) {
  date.setTime(+date + step * durationMinute);
}, function(start, end) {
  return (end - start) / durationMinute;
}, function(date) {
  return date.getMinutes();
});

/* harmony default export */ var src_minute = (minute_minute);
var minutes = minute_minute.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/hour.js



var hour_hour = newInterval(function(date) {
  date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);
}, function(date, step) {
  date.setTime(+date + step * durationHour);
}, function(start, end) {
  return (end - start) / durationHour;
}, function(date) {
  return date.getHours();
});

/* harmony default export */ var src_hour = (hour_hour);
var hours = hour_hour.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/day.js



var day_day = newInterval(function(date) {
  date.setHours(0, 0, 0, 0);
}, function(date, step) {
  date.setDate(date.getDate() + step);
}, function(start, end) {
  return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay;
}, function(date) {
  return date.getDate() - 1;
});

/* harmony default export */ var src_day = (day_day);
var days = day_day.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/week.js



function weekday(i) {
  return newInterval(function(date) {
    date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
    date.setHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setDate(date.getDate() + step * 7);
  }, function(start, end) {
    return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;
  });
}

var sunday = weekday(0);
var monday = weekday(1);
var tuesday = weekday(2);
var wednesday = weekday(3);
var thursday = weekday(4);
var friday = weekday(5);
var saturday = weekday(6);

var sundays = sunday.range;
var mondays = monday.range;
var tuesdays = tuesday.range;
var wednesdays = wednesday.range;
var thursdays = thursday.range;
var fridays = friday.range;
var saturdays = saturday.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/month.js


var month_month = newInterval(function(date) {
  date.setDate(1);
  date.setHours(0, 0, 0, 0);
}, function(date, step) {
  date.setMonth(date.getMonth() + step);
}, function(start, end) {
  return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
  return date.getMonth();
});

/* harmony default export */ var src_month = (month_month);
var months = month_month.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/year.js


var year_year = newInterval(function(date) {
  date.setMonth(0, 1);
  date.setHours(0, 0, 0, 0);
}, function(date, step) {
  date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
  return end.getFullYear() - start.getFullYear();
}, function(date) {
  return date.getFullYear();
});

// An optimized implementation for this simple case.
year_year.every = function(k) {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
    date.setFullYear(Math.floor(date.getFullYear() / k) * k);
    date.setMonth(0, 1);
    date.setHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setFullYear(date.getFullYear() + step * k);
  });
};

/* harmony default export */ var src_year = (year_year);
var years = year_year.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/utcMinute.js



var utcMinute = newInterval(function(date) {
  date.setUTCSeconds(0, 0);
}, function(date, step) {
  date.setTime(+date + step * durationMinute);
}, function(start, end) {
  return (end - start) / durationMinute;
}, function(date) {
  return date.getUTCMinutes();
});

/* harmony default export */ var src_utcMinute = (utcMinute);
var utcMinutes = utcMinute.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/utcHour.js



var utcHour = newInterval(function(date) {
  date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
  date.setTime(+date + step * durationHour);
}, function(start, end) {
  return (end - start) / durationHour;
}, function(date) {
  return date.getUTCHours();
});

/* harmony default export */ var src_utcHour = (utcHour);
var utcHours = utcHour.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/utcDay.js



var utcDay = newInterval(function(date) {
  date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
  date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
  return (end - start) / durationDay;
}, function(date) {
  return date.getUTCDate() - 1;
});

/* harmony default export */ var src_utcDay = (utcDay);
var utcDays = utcDay.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/utcWeek.js



function utcWeekday(i) {
  return newInterval(function(date) {
    date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
    date.setUTCHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setUTCDate(date.getUTCDate() + step * 7);
  }, function(start, end) {
    return (end - start) / durationWeek;
  });
}

var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);

var utcSundays = utcSunday.range;
var utcMondays = utcMonday.range;
var utcTuesdays = utcTuesday.range;
var utcWednesdays = utcWednesday.range;
var utcThursdays = utcThursday.range;
var utcFridays = utcFriday.range;
var utcSaturdays = utcSaturday.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/utcMonth.js


var utcMonth = newInterval(function(date) {
  date.setUTCDate(1);
  date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
  date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
  return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
  return date.getUTCMonth();
});

/* harmony default export */ var src_utcMonth = (utcMonth);
var utcMonths = utcMonth.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/utcYear.js


var utcYear = newInterval(function(date) {
  date.setUTCMonth(0, 1);
  date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
  date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
  return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
  return date.getUTCFullYear();
});

// An optimized implementation for this simple case.
utcYear.every = function(k) {
  return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
    date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
    date.setUTCMonth(0, 1);
    date.setUTCHours(0, 0, 0, 0);
  }, function(date, step) {
    date.setUTCFullYear(date.getUTCFullYear() + step * k);
  });
};

/* harmony default export */ var src_utcYear = (utcYear);
var utcYears = utcYear.range;

// CONCATENATED MODULE: ../node_modules/d3-time/src/index.js






























// CONCATENATED MODULE: ../node_modules/d3-time-format/src/locale.js


function localDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
    date.setFullYear(d.y);
    return date;
  }
  return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}

function utcDate(d) {
  if (0 <= d.y && d.y < 100) {
    var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
    date.setUTCFullYear(d.y);
    return date;
  }
  return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}

function newYear(y) {
  return {y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0};
}

function formatLocale(locale) {
  var locale_dateTime = locale.dateTime,
      locale_date = locale.date,
      locale_time = locale.time,
      locale_periods = locale.periods,
      locale_weekdays = locale.days,
      locale_shortWeekdays = locale.shortDays,
      locale_months = locale.months,
      locale_shortMonths = locale.shortMonths;

  var periodRe = formatRe(locale_periods),
      periodLookup = formatLookup(locale_periods),
      weekdayRe = formatRe(locale_weekdays),
      weekdayLookup = formatLookup(locale_weekdays),
      shortWeekdayRe = formatRe(locale_shortWeekdays),
      shortWeekdayLookup = formatLookup(locale_shortWeekdays),
      monthRe = formatRe(locale_months),
      monthLookup = formatLookup(locale_months),
      shortMonthRe = formatRe(locale_shortMonths),
      shortMonthLookup = formatLookup(locale_shortMonths);

  var formats = {
    "a": formatShortWeekday,
    "A": formatWeekday,
    "b": formatShortMonth,
    "B": formatMonth,
    "c": null,
    "d": formatDayOfMonth,
    "e": formatDayOfMonth,
    "f": formatMicroseconds,
    "H": formatHour24,
    "I": formatHour12,
    "j": formatDayOfYear,
    "L": formatMilliseconds,
    "m": formatMonthNumber,
    "M": formatMinutes,
    "p": formatPeriod,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatSeconds,
    "u": formatWeekdayNumberMonday,
    "U": formatWeekNumberSunday,
    "V": formatWeekNumberISO,
    "w": formatWeekdayNumberSunday,
    "W": formatWeekNumberMonday,
    "x": null,
    "X": null,
    "y": locale_formatYear,
    "Y": formatFullYear,
    "Z": formatZone,
    "%": formatLiteralPercent
  };

  var utcFormats = {
    "a": formatUTCShortWeekday,
    "A": formatUTCWeekday,
    "b": formatUTCShortMonth,
    "B": formatUTCMonth,
    "c": null,
    "d": formatUTCDayOfMonth,
    "e": formatUTCDayOfMonth,
    "f": formatUTCMicroseconds,
    "H": formatUTCHour24,
    "I": formatUTCHour12,
    "j": formatUTCDayOfYear,
    "L": formatUTCMilliseconds,
    "m": formatUTCMonthNumber,
    "M": formatUTCMinutes,
    "p": formatUTCPeriod,
    "Q": formatUnixTimestamp,
    "s": formatUnixTimestampSeconds,
    "S": formatUTCSeconds,
    "u": formatUTCWeekdayNumberMonday,
    "U": formatUTCWeekNumberSunday,
    "V": formatUTCWeekNumberISO,
    "w": formatUTCWeekdayNumberSunday,
    "W": formatUTCWeekNumberMonday,
    "x": null,
    "X": null,
    "y": formatUTCYear,
    "Y": formatUTCFullYear,
    "Z": formatUTCZone,
    "%": formatLiteralPercent
  };

  var parses = {
    "a": parseShortWeekday,
    "A": parseWeekday,
    "b": parseShortMonth,
    "B": parseMonth,
    "c": parseLocaleDateTime,
    "d": parseDayOfMonth,
    "e": parseDayOfMonth,
    "f": parseMicroseconds,
    "H": parseHour24,
    "I": parseHour24,
    "j": parseDayOfYear,
    "L": parseMilliseconds,
    "m": parseMonthNumber,
    "M": parseMinutes,
    "p": parsePeriod,
    "Q": parseUnixTimestamp,
    "s": parseUnixTimestampSeconds,
    "S": parseSeconds,
    "u": parseWeekdayNumberMonday,
    "U": parseWeekNumberSunday,
    "V": parseWeekNumberISO,
    "w": parseWeekdayNumberSunday,
    "W": parseWeekNumberMonday,
    "x": parseLocaleDate,
    "X": parseLocaleTime,
    "y": parseYear,
    "Y": parseFullYear,
    "Z": parseZone,
    "%": parseLiteralPercent
  };

  // These recursive directive definitions must be deferred.
  formats.x = newFormat(locale_date, formats);
  formats.X = newFormat(locale_time, formats);
  formats.c = newFormat(locale_dateTime, formats);
  utcFormats.x = newFormat(locale_date, utcFormats);
  utcFormats.X = newFormat(locale_time, utcFormats);
  utcFormats.c = newFormat(locale_dateTime, utcFormats);

  function newFormat(specifier, formats) {
    return function(date) {
      var string = [],
          i = -1,
          j = 0,
          n = specifier.length,
          c,
          pad,
          format;

      if (!(date instanceof Date)) date = new Date(+date);

      while (++i < n) {
        if (specifier.charCodeAt(i) === 37) {
          string.push(specifier.slice(j, i));
          if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
          else pad = c === "e" ? " " : "0";
          if (format = formats[c]) c = format(date, pad);
          string.push(c);
          j = i + 1;
        }
      }

      string.push(specifier.slice(j, i));
      return string.join("");
    };
  }

  function newParse(specifier, newDate) {
    return function(string) {
      var d = newYear(1900),
          i = parseSpecifier(d, specifier, string += "", 0),
          week, day;
      if (i != string.length) return null;

      // If a UNIX timestamp is specified, return it.
      if ("Q" in d) return new Date(d.Q);

      // The am-pm flag is 0 for AM, and 1 for PM.
      if ("p" in d) d.H = d.H % 12 + d.p * 12;

      // Convert day-of-week and week-of-year to day-of-year.
      if ("V" in d) {
        if (d.V < 1 || d.V > 53) return null;
        if (!("w" in d)) d.w = 1;
        if ("Z" in d) {
          week = utcDate(newYear(d.y)), day = week.getUTCDay();
          week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);
          week = src_utcDay.offset(week, (d.V - 1) * 7);
          d.y = week.getUTCFullYear();
          d.m = week.getUTCMonth();
          d.d = week.getUTCDate() + (d.w + 6) % 7;
        } else {
          week = newDate(newYear(d.y)), day = week.getDay();
          week = day > 4 || day === 0 ? monday.ceil(week) : monday(week);
          week = src_day.offset(week, (d.V - 1) * 7);
          d.y = week.getFullYear();
          d.m = week.getMonth();
          d.d = week.getDate() + (d.w + 6) % 7;
        }
      } else if ("W" in d || "U" in d) {
        if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
        day = "Z" in d ? utcDate(newYear(d.y)).getUTCDay() : newDate(newYear(d.y)).getDay();
        d.m = 0;
        d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
      }

      // If a time zone is specified, all fields are interpreted as UTC and then
      // offset according to the specified time zone.
      if ("Z" in d) {
        d.H += d.Z / 100 | 0;
        d.M += d.Z % 100;
        return utcDate(d);
      }

      // Otherwise, all fields are in local time.
      return newDate(d);
    };
  }

  function parseSpecifier(d, specifier, string, j) {
    var i = 0,
        n = specifier.length,
        m = string.length,
        c,
        parse;

    while (i < n) {
      if (j >= m) return -1;
      c = specifier.charCodeAt(i++);
      if (c === 37) {
        c = specifier.charAt(i++);
        parse = parses[c in pads ? specifier.charAt(i++) : c];
        if (!parse || ((j = parse(d, string, j)) < 0)) return -1;
      } else if (c != string.charCodeAt(j++)) {
        return -1;
      }
    }

    return j;
  }

  function parsePeriod(d, string, i) {
    var n = periodRe.exec(string.slice(i));
    return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseShortWeekday(d, string, i) {
    var n = shortWeekdayRe.exec(string.slice(i));
    return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseWeekday(d, string, i) {
    var n = weekdayRe.exec(string.slice(i));
    return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseShortMonth(d, string, i) {
    var n = shortMonthRe.exec(string.slice(i));
    return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseMonth(d, string, i) {
    var n = monthRe.exec(string.slice(i));
    return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
  }

  function parseLocaleDateTime(d, string, i) {
    return parseSpecifier(d, locale_dateTime, string, i);
  }

  function parseLocaleDate(d, string, i) {
    return parseSpecifier(d, locale_date, string, i);
  }

  function parseLocaleTime(d, string, i) {
    return parseSpecifier(d, locale_time, string, i);
  }

  function formatShortWeekday(d) {
    return locale_shortWeekdays[d.getDay()];
  }

  function formatWeekday(d) {
    return locale_weekdays[d.getDay()];
  }

  function formatShortMonth(d) {
    return locale_shortMonths[d.getMonth()];
  }

  function formatMonth(d) {
    return locale_months[d.getMonth()];
  }

  function formatPeriod(d) {
    return locale_periods[+(d.getHours() >= 12)];
  }

  function formatUTCShortWeekday(d) {
    return locale_shortWeekdays[d.getUTCDay()];
  }

  function formatUTCWeekday(d) {
    return locale_weekdays[d.getUTCDay()];
  }

  function formatUTCShortMonth(d) {
    return locale_shortMonths[d.getUTCMonth()];
  }

  function formatUTCMonth(d) {
    return locale_months[d.getUTCMonth()];
  }

  function formatUTCPeriod(d) {
    return locale_periods[+(d.getUTCHours() >= 12)];
  }

  return {
    format: function(specifier) {
      var f = newFormat(specifier += "", formats);
      f.toString = function() { return specifier; };
      return f;
    },
    parse: function(specifier) {
      var p = newParse(specifier += "", localDate);
      p.toString = function() { return specifier; };
      return p;
    },
    utcFormat: function(specifier) {
      var f = newFormat(specifier += "", utcFormats);
      f.toString = function() { return specifier; };
      return f;
    },
    utcParse: function(specifier) {
      var p = newParse(specifier, utcDate);
      p.toString = function() { return specifier; };
      return p;
    }
  };
}

var pads = {"-": "", "_": " ", "0": "0"},
    numberRe = /^\s*\d+/, // note: ignores next directive
    percentRe = /^%/,
    requoteRe = /[\\^$*+?|[\]().{}]/g;

function pad(value, fill, width) {
  var sign = value < 0 ? "-" : "",
      string = (sign ? -value : value) + "",
      length = string.length;
  return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}

function requote(s) {
  return s.replace(requoteRe, "\\$&");
}

function formatRe(names) {
  return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}

function formatLookup(names) {
  var map = {}, i = -1, n = names.length;
  while (++i < n) map[names[i].toLowerCase()] = i;
  return map;
}

function parseWeekdayNumberSunday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 1));
  return n ? (d.w = +n[0], i + n[0].length) : -1;
}

function parseWeekdayNumberMonday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 1));
  return n ? (d.u = +n[0], i + n[0].length) : -1;
}

function parseWeekNumberSunday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.U = +n[0], i + n[0].length) : -1;
}

function parseWeekNumberISO(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.V = +n[0], i + n[0].length) : -1;
}

function parseWeekNumberMonday(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.W = +n[0], i + n[0].length) : -1;
}

function parseFullYear(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 4));
  return n ? (d.y = +n[0], i + n[0].length) : -1;
}

function parseYear(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}

function parseZone(d, string, i) {
  var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
  return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}

function parseMonthNumber(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}

function parseDayOfMonth(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.d = +n[0], i + n[0].length) : -1;
}

function parseDayOfYear(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 3));
  return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}

function parseHour24(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.H = +n[0], i + n[0].length) : -1;
}

function parseMinutes(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.M = +n[0], i + n[0].length) : -1;
}

function parseSeconds(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 2));
  return n ? (d.S = +n[0], i + n[0].length) : -1;
}

function parseMilliseconds(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 3));
  return n ? (d.L = +n[0], i + n[0].length) : -1;
}

function parseMicroseconds(d, string, i) {
  var n = numberRe.exec(string.slice(i, i + 6));
  return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}

function parseLiteralPercent(d, string, i) {
  var n = percentRe.exec(string.slice(i, i + 1));
  return n ? i + n[0].length : -1;
}

function parseUnixTimestamp(d, string, i) {
  var n = numberRe.exec(string.slice(i));
  return n ? (d.Q = +n[0], i + n[0].length) : -1;
}

function parseUnixTimestampSeconds(d, string, i) {
  var n = numberRe.exec(string.slice(i));
  return n ? (d.Q = (+n[0]) * 1000, i + n[0].length) : -1;
}

function formatDayOfMonth(d, p) {
  return pad(d.getDate(), p, 2);
}

function formatHour24(d, p) {
  return pad(d.getHours(), p, 2);
}

function formatHour12(d, p) {
  return pad(d.getHours() % 12 || 12, p, 2);
}

function formatDayOfYear(d, p) {
  return pad(1 + src_day.count(src_year(d), d), p, 3);
}

function formatMilliseconds(d, p) {
  return pad(d.getMilliseconds(), p, 3);
}

function formatMicroseconds(d, p) {
  return formatMilliseconds(d, p) + "000";
}

function formatMonthNumber(d, p) {
  return pad(d.getMonth() + 1, p, 2);
}

function formatMinutes(d, p) {
  return pad(d.getMinutes(), p, 2);
}

function formatSeconds(d, p) {
  return pad(d.getSeconds(), p, 2);
}

function formatWeekdayNumberMonday(d) {
  var day = d.getDay();
  return day === 0 ? 7 : day;
}

function formatWeekNumberSunday(d, p) {
  return pad(sunday.count(src_year(d), d), p, 2);
}

function formatWeekNumberISO(d, p) {
  var day = d.getDay();
  d = (day >= 4 || day === 0) ? thursday(d) : thursday.ceil(d);
  return pad(thursday.count(src_year(d), d) + (src_year(d).getDay() === 4), p, 2);
}

function formatWeekdayNumberSunday(d) {
  return d.getDay();
}

function formatWeekNumberMonday(d, p) {
  return pad(monday.count(src_year(d), d), p, 2);
}

function locale_formatYear(d, p) {
  return pad(d.getFullYear() % 100, p, 2);
}

function formatFullYear(d, p) {
  return pad(d.getFullYear() % 10000, p, 4);
}

function formatZone(d) {
  var z = d.getTimezoneOffset();
  return (z > 0 ? "-" : (z *= -1, "+"))
      + pad(z / 60 | 0, "0", 2)
      + pad(z % 60, "0", 2);
}

function formatUTCDayOfMonth(d, p) {
  return pad(d.getUTCDate(), p, 2);
}

function formatUTCHour24(d, p) {
  return pad(d.getUTCHours(), p, 2);
}

function formatUTCHour12(d, p) {
  return pad(d.getUTCHours() % 12 || 12, p, 2);
}

function formatUTCDayOfYear(d, p) {
  return pad(1 + src_utcDay.count(src_utcYear(d), d), p, 3);
}

function formatUTCMilliseconds(d, p) {
  return pad(d.getUTCMilliseconds(), p, 3);
}

function formatUTCMicroseconds(d, p) {
  return formatUTCMilliseconds(d, p) + "000";
}

function formatUTCMonthNumber(d, p) {
  return pad(d.getUTCMonth() + 1, p, 2);
}

function formatUTCMinutes(d, p) {
  return pad(d.getUTCMinutes(), p, 2);
}

function formatUTCSeconds(d, p) {
  return pad(d.getUTCSeconds(), p, 2);
}

function formatUTCWeekdayNumberMonday(d) {
  var dow = d.getUTCDay();
  return dow === 0 ? 7 : dow;
}

function formatUTCWeekNumberSunday(d, p) {
  return pad(utcSunday.count(src_utcYear(d), d), p, 2);
}

function formatUTCWeekNumberISO(d, p) {
  var day = d.getUTCDay();
  d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);
  return pad(utcThursday.count(src_utcYear(d), d) + (src_utcYear(d).getUTCDay() === 4), p, 2);
}

function formatUTCWeekdayNumberSunday(d) {
  return d.getUTCDay();
}

function formatUTCWeekNumberMonday(d, p) {
  return pad(utcMonday.count(src_utcYear(d), d), p, 2);
}

function formatUTCYear(d, p) {
  return pad(d.getUTCFullYear() % 100, p, 2);
}

function formatUTCFullYear(d, p) {
  return pad(d.getUTCFullYear() % 10000, p, 4);
}

function formatUTCZone() {
  return "+0000";
}

function formatLiteralPercent() {
  return "%";
}

function formatUnixTimestamp(d) {
  return +d;
}

function formatUnixTimestampSeconds(d) {
  return Math.floor(+d / 1000);
}

// CONCATENATED MODULE: ../node_modules/d3-time-format/src/defaultLocale.js


var defaultLocale_locale;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;

defaultLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});

function defaultLocale(definition) {
  defaultLocale_locale = formatLocale(definition);
  timeFormat = defaultLocale_locale.format;
  timeParse = defaultLocale_locale.parse;
  utcFormat = defaultLocale_locale.utcFormat;
  utcParse = defaultLocale_locale.utcParse;
  return defaultLocale_locale;
}

// CONCATENATED MODULE: ../node_modules/d3-time-format/src/isoFormat.js


var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ";

function formatIsoNative(date) {
  return date.toISOString();
}

var formatIso = Date.prototype.toISOString
    ? formatIsoNative
    : utcFormat(isoSpecifier);

/* harmony default export */ var isoFormat = (formatIso);

// CONCATENATED MODULE: ../node_modules/d3-time-format/src/isoParse.js



function parseIsoNative(string) {
  var date = new Date(string);
  return isNaN(date) ? null : date;
}

var parseIso = +new Date("2000-01-01T00:00:00.000Z")
    ? parseIsoNative
    : utcParse(isoSpecifier);

/* harmony default export */ var isoParse = (parseIso);

// CONCATENATED MODULE: ../node_modules/d3-time-format/src/index.js





// CONCATENATED MODULE: ../node_modules/d3-scale/src/time.js








var time_durationSecond = 1000,
    time_durationMinute = time_durationSecond * 60,
    time_durationHour = time_durationMinute * 60,
    time_durationDay = time_durationHour * 24,
    time_durationWeek = time_durationDay * 7,
    durationMonth = time_durationDay * 30,
    durationYear = time_durationDay * 365;

function time_date(t) {
  return new Date(t);
}

function time_number(t) {
  return t instanceof Date ? +t : +new Date(+t);
}

function calendar(year, month, week, day, hour, minute, second, millisecond, format) {
  var scale = continuous(deinterpolateLinear, d3_interpolate_src["c" /* interpolateNumber */]),
      invert = scale.invert,
      domain = scale.domain;

  var formatMillisecond = format(".%L"),
      formatSecond = format(":%S"),
      formatMinute = format("%I:%M"),
      formatHour = format("%I %p"),
      formatDay = format("%a %d"),
      formatWeek = format("%b %d"),
      formatMonth = format("%B"),
      formatYear = format("%Y");

  var tickIntervals = [
    [second,  1,      time_durationSecond],
    [second,  5,  5 * time_durationSecond],
    [second, 15, 15 * time_durationSecond],
    [second, 30, 30 * time_durationSecond],
    [minute,  1,      time_durationMinute],
    [minute,  5,  5 * time_durationMinute],
    [minute, 15, 15 * time_durationMinute],
    [minute, 30, 30 * time_durationMinute],
    [  hour,  1,      time_durationHour  ],
    [  hour,  3,  3 * time_durationHour  ],
    [  hour,  6,  6 * time_durationHour  ],
    [  hour, 12, 12 * time_durationHour  ],
    [   day,  1,      time_durationDay   ],
    [   day,  2,  2 * time_durationDay   ],
    [  week,  1,      time_durationWeek  ],
    [ month,  1,      durationMonth ],
    [ month,  3,  3 * durationMonth ],
    [  year,  1,      durationYear  ]
  ];

  function tickFormat(date) {
    return (second(date) < date ? formatMillisecond
        : minute(date) < date ? formatSecond
        : hour(date) < date ? formatMinute
        : day(date) < date ? formatHour
        : month(date) < date ? (week(date) < date ? formatDay : formatWeek)
        : year(date) < date ? formatMonth
        : formatYear)(date);
  }

  function tickInterval(interval, start, stop, step) {
    if (interval == null) interval = 10;

    // If a desired tick count is specified, pick a reasonable tick interval
    // based on the extent of the domain and a rough estimate of tick size.
    // Otherwise, assume interval is already a time interval and use it.
    if (typeof interval === "number") {
      var target = Math.abs(stop - start) / interval,
          i = Object(src["bisector"])(function(i) { return i[2]; }).right(tickIntervals, target);
      if (i === tickIntervals.length) {
        step = Object(src["tickStep"])(start / durationYear, stop / durationYear, interval);
        interval = year;
      } else if (i) {
        i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
        step = i[1];
        interval = i[0];
      } else {
        step = Math.max(Object(src["tickStep"])(start, stop, interval), 1);
        interval = millisecond;
      }
    }

    return step == null ? interval : interval.every(step);
  }

  scale.invert = function(y) {
    return new Date(invert(y));
  };

  scale.domain = function(_) {
    return arguments.length ? domain(map.call(_, time_number)) : domain().map(time_date);
  };

  scale.ticks = function(interval, step) {
    var d = domain(),
        t0 = d[0],
        t1 = d[d.length - 1],
        r = t1 < t0,
        t;
    if (r) t = t0, t0 = t1, t1 = t;
    t = tickInterval(interval, t0, t1, step);
    t = t ? t.range(t0, t1 + 1) : []; // inclusive stop
    return r ? t.reverse() : t;
  };

  scale.tickFormat = function(count, specifier) {
    return specifier == null ? tickFormat : format(specifier);
  };

  scale.nice = function(interval, step) {
    var d = domain();
    return (interval = tickInterval(interval, d[0], d[d.length - 1], step))
        ? domain(nice(d, interval))
        : scale;
  };

  scale.copy = function() {
    return copy(scale, calendar(year, month, week, day, hour, minute, second, millisecond, format));
  };

  return scale;
}

/* harmony default export */ var time = (function() {
  return calendar(src_year, src_month, sunday, src_day, src_hour, src_minute, src_second, src_millisecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]);
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/utcTime.js




/* harmony default export */ var utcTime = (function() {
  return calendar(src_utcYear, src_utcMonth, utcSunday, src_utcDay, src_utcHour, src_utcMinute, src_second, src_millisecond, utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]);
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/colors.js
/* harmony default export */ var colors = (function(s) {
  return s.match(/.{6}/g).map(function(x) {
    return "#" + x;
  });
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/category10.js


/* harmony default export */ var category10 = (colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"));

// CONCATENATED MODULE: ../node_modules/d3-scale/src/category20b.js


/* harmony default export */ var category20b = (colors("393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6"));

// CONCATENATED MODULE: ../node_modules/d3-scale/src/category20c.js


/* harmony default export */ var category20c = (colors("3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9"));

// CONCATENATED MODULE: ../node_modules/d3-scale/src/category20.js


/* harmony default export */ var category20 = (colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5"));

// EXTERNAL MODULE: ../node_modules/d3-color/src/index.js + 5 modules
var d3_color_src = __nested_webpack_require_152664__(9);

// CONCATENATED MODULE: ../node_modules/d3-scale/src/cubehelix.js



/* harmony default export */ var cubehelix = (Object(d3_interpolate_src["b" /* interpolateCubehelixLong */])(Object(d3_color_src["cubehelix"])(300, 0.5, 0.0), Object(d3_color_src["cubehelix"])(-240, 0.5, 1.0)));

// CONCATENATED MODULE: ../node_modules/d3-scale/src/rainbow.js



var warm = Object(d3_interpolate_src["b" /* interpolateCubehelixLong */])(Object(d3_color_src["cubehelix"])(-100, 0.75, 0.35), Object(d3_color_src["cubehelix"])(80, 1.50, 0.8));

var cool = Object(d3_interpolate_src["b" /* interpolateCubehelixLong */])(Object(d3_color_src["cubehelix"])(260, 0.75, 0.35), Object(d3_color_src["cubehelix"])(80, 1.50, 0.8));

var rainbow = Object(d3_color_src["cubehelix"])();

/* harmony default export */ var src_rainbow = (function(t) {
  if (t < 0 || t > 1) t -= Math.floor(t);
  var ts = Math.abs(t - 0.5);
  rainbow.h = 360 * t - 100;
  rainbow.s = 1.5 - 1.5 * ts;
  rainbow.l = 0.8 - 0.9 * ts;
  return rainbow + "";
});

// CONCATENATED MODULE: ../node_modules/d3-scale/src/viridis.js


function ramp(range) {
  var n = range.length;
  return function(t) {
    return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
}

/* harmony default export */ var viridis = (ramp(colors("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")));

var magma = ramp(colors("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf"));

var inferno = ramp(colors("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4"));

var plasma = ramp(colors("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));

// CONCATENATED MODULE: ../node_modules/d3-scale/src/sequential.js


function sequential(interpolator) {
  var x0 = 0,
      x1 = 1,
      clamp = false;

  function scale(x) {
    var t = (x - x0) / (x1 - x0);
    return interpolator(clamp ? Math.max(0, Math.min(1, t)) : t);
  }

  scale.domain = function(_) {
    return arguments.length ? (x0 = +_[0], x1 = +_[1], scale) : [x0, x1];
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale) : clamp;
  };

  scale.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale) : interpolator;
  };

  scale.copy = function() {
    return sequential(interpolator).domain([x0, x1]).clamp(clamp);
  };

  return linearish(scale);
}

// CONCATENATED MODULE: ../node_modules/d3-scale/index.js
/* concated harmony reexport scaleBand */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleBand", function() { return band; });
/* concated harmony reexport scalePoint */__nested_webpack_require_152664__.d(__webpack_exports__, "scalePoint", function() { return point; });
/* concated harmony reexport scaleIdentity */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleIdentity", function() { return identity; });
/* concated harmony reexport scaleLinear */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleLinear", function() { return linear; });
/* concated harmony reexport scaleLog */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleLog", function() { return log; });
/* concated harmony reexport scaleOrdinal */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleOrdinal", function() { return ordinal; });
/* concated harmony reexport scaleImplicit */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleImplicit", function() { return implicit; });
/* concated harmony reexport scalePow */__nested_webpack_require_152664__.d(__webpack_exports__, "scalePow", function() { return pow; });
/* concated harmony reexport scaleSqrt */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleSqrt", function() { return sqrt; });
/* concated harmony reexport scaleQuantile */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleQuantile", function() { return quantile; });
/* concated harmony reexport scaleQuantize */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleQuantize", function() { return quantize; });
/* concated harmony reexport scaleThreshold */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleThreshold", function() { return threshold; });
/* concated harmony reexport scaleTime */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleTime", function() { return time; });
/* concated harmony reexport scaleUtc */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleUtc", function() { return utcTime; });
/* concated harmony reexport schemeCategory10 */__nested_webpack_require_152664__.d(__webpack_exports__, "schemeCategory10", function() { return category10; });
/* concated harmony reexport schemeCategory20b */__nested_webpack_require_152664__.d(__webpack_exports__, "schemeCategory20b", function() { return category20b; });
/* concated harmony reexport schemeCategory20c */__nested_webpack_require_152664__.d(__webpack_exports__, "schemeCategory20c", function() { return category20c; });
/* concated harmony reexport schemeCategory20 */__nested_webpack_require_152664__.d(__webpack_exports__, "schemeCategory20", function() { return category20; });
/* concated harmony reexport interpolateCubehelixDefault */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateCubehelixDefault", function() { return cubehelix; });
/* concated harmony reexport interpolateRainbow */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateRainbow", function() { return src_rainbow; });
/* concated harmony reexport interpolateWarm */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateWarm", function() { return warm; });
/* concated harmony reexport interpolateCool */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateCool", function() { return cool; });
/* concated harmony reexport interpolateViridis */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateViridis", function() { return viridis; });
/* concated harmony reexport interpolateMagma */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateMagma", function() { return magma; });
/* concated harmony reexport interpolateInferno */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolateInferno", function() { return inferno; });
/* concated harmony reexport interpolatePlasma */__nested_webpack_require_152664__.d(__webpack_exports__, "interpolatePlasma", function() { return plasma; });
/* concated harmony reexport scaleSequential */__nested_webpack_require_152664__.d(__webpack_exports__, "scaleSequential", function() { return sequential; });







































/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


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


var DEFAULT_HANDLE_MISSING_STYLENAME_OPTION = 'throw';

var isNamespacedStyleName = function isNamespacedStyleName(styleName) {
  return styleName.indexOf('.') !== -1;
};

var getClassNameForNamespacedStyleName = function getClassNameForNamespacedStyleName(styleName, styleModuleImportMap, handleMissingStyleNameOption) {
  // Note:
  // Do not use the desctructing syntax with Babel.
  // Desctructing adds _slicedToArray helper.
  var styleNameParts = styleName.split('.');
  var importName = styleNameParts[0];
  var moduleName = styleNameParts[1];
  var handleMissingStyleName = handleMissingStyleNameOption || DEFAULT_HANDLE_MISSING_STYLENAME_OPTION;

  if (!moduleName) {
    if (handleMissingStyleName === 'throw') {
      throw new Error('Invalid style name: ' + styleName);
    } else if (handleMissingStyleName === 'warn') {
      // eslint-disable-next-line no-console
      console.warn('Invalid style name: ' + styleName);
    } else {
      return null;
    }
  }

  if (!styleModuleImportMap[importName]) {
    if (handleMissingStyleName === 'throw') {
      throw new Error('CSS module import does not exist: ' + importName);
    } else if (handleMissingStyleName === 'warn') {
      // eslint-disable-next-line no-console
      console.warn('CSS module import does not exist: ' + importName);
    } else {
      return null;
    }
  }

  if (!styleModuleImportMap[importName][moduleName]) {
    if (handleMissingStyleName === 'throw') {
      throw new Error('CSS module does not exist: ' + moduleName);
    } else if (handleMissingStyleName === 'warn') {
      // eslint-disable-next-line no-console
      console.warn('CSS module does not exist: ' + moduleName);
    } else {
      return null;
    }
  }

  return styleModuleImportMap[importName][moduleName];
};

exports.default = function (styleNameValue, styleModuleImportMap, options) {
  var styleModuleImportMapKeys = Object.keys(styleModuleImportMap);

  var handleMissingStyleName = options && options.handleMissingStyleName || DEFAULT_HANDLE_MISSING_STYLENAME_OPTION;

  return styleNameValue.split(' ').filter(function (styleName) {
    return styleName;
  }).map(function (styleName) {
    if (isNamespacedStyleName(styleName)) {
      return getClassNameForNamespacedStyleName(styleName, styleModuleImportMap, handleMissingStyleName);
    }

    if (styleModuleImportMapKeys.length === 0) {
      throw new Error('Cannot use styleName attribute for style name \'' + styleName + '\' without importing at least one stylesheet.');
    }

    if (styleModuleImportMapKeys.length > 1) {
      throw new Error('Cannot use anonymous style name \'' + styleName + '\' with more than one stylesheet import.');
    }

    var styleModuleMap = styleModuleImportMap[styleModuleImportMapKeys[0]];

    if (!styleModuleMap[styleName]) {
      if (handleMissingStyleName === 'throw') {
        throw new Error('Could not resolve the styleName \'' + styleName + '\'.');
      }
      if (handleMissingStyleName === 'warn') {
        // eslint-disable-next-line no-console
        console.warn('Could not resolve the styleName \'' + styleName + '\'.');
      }
    }

    return styleModuleMap[styleName];
  }).filter(function (className) {
    // Remove any styles which could not be found (if handleMissingStyleName === 'ignore')
    return className;
  }).join(' ');
};

//# sourceMappingURL=getClassName.js.map

/***/ }),
/* 30 */
/***/ (function(module, exports, __nested_webpack_require_223020__) {

module.exports = { "default": __nested_webpack_require_223020__(233), __esModule: true };

/***/ }),
/* 31 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

module.exports = isArray;


/***/ }),
/* 32 */
/***/ (function(module, exports, __nested_webpack_require_223718__) {

var anObject = __nested_webpack_require_223718__(39);
var IE8_DOM_DEFINE = __nested_webpack_require_223718__(159);
var toPrimitive = __nested_webpack_require_223718__(127);
var dP = Object.defineProperty;

exports.f = __nested_webpack_require_223718__(36) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
  anObject(O);
  P = toPrimitive(P, true);
  anObject(Attributes);
  if (IE8_DOM_DEFINE) try {
    return dP(O, P, Attributes);
  } catch (e) { /* empty */ }
  if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
  if ('value' in Attributes) O[P] = Attributes.value;
  return O;
};


/***/ }),
/* 33 */
/***/ (function(module, exports) {

module.exports = function (it) {
  return typeof it === 'object' ? it !== null : typeof it === 'function';
};


/***/ }),
/* 34 */
/***/ (function(module, exports, __nested_webpack_require_224555__) {

"use strict";


exports.__esModule = true;

var _assign = __nested_webpack_require_224555__(44);

var _assign2 = _interopRequireDefault(_assign);

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

exports.default = _assign2.default || function (target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];

    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }

  return target;
};

/***/ }),
/* 35 */
/***/ (function(module, exports, __nested_webpack_require_225166__) {

module.exports = { "default": __nested_webpack_require_225166__(229), __esModule: true };

/***/ }),
/* 36 */
/***/ (function(module, exports, __nested_webpack_require_225319__) {

// Thank's IE8 for his funny defineProperty
module.exports = !__nested_webpack_require_225319__(50)(function () {
  return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});


/***/ }),
/* 37 */
/***/ (function(module, exports, __nested_webpack_require_225585__) {

module.exports = { "default": __nested_webpack_require_225585__(557), __esModule: true };

/***/ }),
/* 38 */
/***/ (function(module, exports, __nested_webpack_require_225738__) {

module.exports = { "default": __nested_webpack_require_225738__(580), __esModule: true };

/***/ }),
/* 39 */
/***/ (function(module, exports, __nested_webpack_require_225891__) {

var isObject = __nested_webpack_require_225891__(33);
module.exports = function (it) {
  if (!isObject(it)) throw TypeError(it + ' is not an object!');
  return it;
};


/***/ }),
/* 40 */
/***/ (function(module, exports, __nested_webpack_require_226123__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_226123__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _assign = __nested_webpack_require_226123__(44);

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = __nested_webpack_require_226123__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_226123__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_226123__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_226123__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_226123__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_226123__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _isNan = __nested_webpack_require_226123__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _d3Format = __nested_webpack_require_226123__(20);

var _slugid = __nested_webpack_require_226123__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _Track2 = __nested_webpack_require_226123__(177);

var _Track3 = _interopRequireDefault(_Track2);

var _utils = __nested_webpack_require_226123__(10);

var _configs = __nested_webpack_require_226123__(11);

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

/**
 * Format a resolution relative to the highest possible resolution.
 *
 * The highest possible resolution determines the granularity of the
 * formatting (e.g. 20K vs 20000)
 * @param {int} resolution The resolution to format (e.g. 30000)
 * @param {int} maxResolutionSize The maximum possible resolution (e.g. 1000)
 *
 * @returns {string} A formatted resolution string (e.g. "30K")
 */
function formatResolutionText(resolution, maxResolutionSize) {
  var pp = (0, _d3Format.precisionPrefix)(maxResolutionSize, resolution);
  var f = (0, _d3Format.formatPrefix)('.' + String(pp), resolution);
  var formattedResolution = f(resolution);

  return formattedResolution;
}

/**
 * Get a text description of a resolution based on a zoom level
 * and a list of resolutions
 *
 * @param {list} resolutions: A list of resolutions (e.g. [1000,2000,3000])
 * @param {int} zoomLevel: The current zoom level (e.g. 4)
 *
 * @returns {string} A formatted string representation of the zoom level
 *   (e.g. "30K")
 */


// Configs
function getResolutionBasedResolutionText(resolutions, zoomLevel) {
  var sortedResolutions = resolutions.map(function (x) {
    return +x;
  }).sort(function (a, b) {
    return b - a;
  });
  var resolution = sortedResolutions[zoomLevel];
  var maxResolutionSize = sortedResolutions[sortedResolutions.length - 1];

  return formatResolutionText(resolution, maxResolutionSize);
}

/**
 * Get a text description of the resolution based on the zoom level
 * max width of the dataset, the bins per dimension and the maximum
 * zoom.
 *
 * @param {int} zoomLevel The current zoomLevel (e.g. 0)
 * @param {int} max_width The max width
 *   (e.g. 2 ** maxZoom * highestResolution * binsPerDimension)
 * @param {int} bins_per_dimension The number of bins per tile dimension
 *   (e.g. 256)
 * @param {int} maxZoom The maximum zoom level for this tileset
 *
 * @returns {string} A formatted string representation of the zoom level
 *   (e.g. "30K")
 */
function getWidthBasedResolutionText(zoomLevel, maxWidth, binsPerDimension, maxZoom) {
  var resolution = maxWidth / (Math.pow(2, zoomLevel) * binsPerDimension);

  // we can't display a NaN resolution
  if (!(0, _isNan2['default'])(resolution)) {
    // what is the maximum possible resolution?
    // this will determine how we format the lower resolutions
    var maxResolutionSize = maxWidth / (Math.pow(2, maxZoom) * binsPerDimension);

    var pp = (0, _d3Format.precisionPrefix)(maxResolutionSize, resolution);
    var f = (0, _d3Format.formatPrefix)('.' + String(pp), resolution);
    var formattedResolution = f(resolution);

    return formattedResolution;
  }
  console.warn('NaN resolution, screen is probably too small.');

  return '';
}

var PixiTrack = function (_Track) {
  (0, _inherits3['default'])(PixiTrack, _Track);

  /**
   * @param scene: A PIXI.js scene to draw everything to.
   * @param options: A set of options that describe how this track is rendered.
    this.pMain.position.x = this.position[0];
   *          - labelPosition: If the label is to be drawn, where should it be drawn?
   *          - labelText: What should be drawn in the label. If either labelPosition
   *                  or labelText are false, no label will be drawn.
   */
  function PixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, PixiTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (PixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(PixiTrack)).call(this, context, options));

    var scene = context.scene;

    // the PIXI drawing areas
    // pMain will have transforms applied to it as users scroll to and fro

    _this.scene = scene;

    // this option is used to temporarily prevent drawing so that
    // updates can be batched (e.g. zoomed and options changed)
    _this.delayDrawing = false;

    _this.pBase = new _configs.GLOBALS.PIXI.Graphics();

    _this.pMasked = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMask = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMain = new _configs.GLOBALS.PIXI.Graphics();

    // for drawing the track label (often its name)
    _this.pBorder = new _configs.GLOBALS.PIXI.Graphics();
    _this.pBackground = new _configs.GLOBALS.PIXI.Graphics();
    _this.pForeground = new _configs.GLOBALS.PIXI.Graphics();
    _this.pLabel = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMobile = new _configs.GLOBALS.PIXI.Graphics();
    _this.pAxis = new _configs.GLOBALS.PIXI.Graphics();

    // for drawing information on mouseover events
    _this.pMouseOver = new _configs.GLOBALS.PIXI.Graphics();

    _this.scene.addChild(_this.pBase);

    _this.pBase.addChild(_this.pMasked);

    _this.pMasked.addChild(_this.pBackground);
    _this.pMasked.addChild(_this.pMain);
    _this.pMasked.addChild(_this.pMask);
    _this.pMasked.addChild(_this.pMobile);
    _this.pMasked.addChild(_this.pBorder);
    _this.pMasked.addChild(_this.pLabel);
    _this.pMasked.addChild(_this.pForeground);
    _this.pMasked.addChild(_this.pMouseOver);
    _this.pBase.addChild(_this.pAxis);

    _this.pMasked.mask = _this.pMask;

    _this.prevOptions = '';

    // pMobile will be a graphics object that is moved around
    // tracks that wish to use it will replace this.pMain with it

    _this.options = (0, _assign2['default'])(_this.options, options);

    var labelTextText = _this.getName();

    _this.labelTextFontFamily = 'Arial';
    _this.labelTextFontSize = 12;
    // Used to avoid label/colormap clashes
    _this.labelXOffset = 0;

    _this.labelText = new _configs.GLOBALS.PIXI.Text(labelTextText, {
      fontSize: String(_this.labelTextFontSize) + 'px',
      fontFamily: _this.labelTextFontFamily,
      fill: 'black'
    });
    _this.pLabel.addChild(_this.labelText);

    _this.errorText = new _configs.GLOBALS.PIXI.Text('', {
      fontSize: '12px',
      fontFamily: 'Arial',
      fill: 'red'
    });
    _this.errorText.anchor.x = 0.5;
    _this.errorText.anchor.y = 0.5;
    _this.pLabel.addChild(_this.errorText);
    return _this;
  }

  (0, _createClass3['default'])(PixiTrack, [{
    key: 'setLabelText',
    value: function () {
      function setLabelText() {
        // will be drawn in draw() anyway
      }

      return setLabelText;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        this.position = newPosition;

        this.drawBorder();
        this.drawLabel();
        this.drawBackground();
        this.setMask(this.position, this.dimensions);
        this.setForeground();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(PixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(PixiTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        this.drawBorder();
        this.drawLabel();
        this.drawBackground();
        this.setMask(this.position, this.dimensions);
        this.setForeground();
      }

      return setDimensions;
    }()
  }, {
    key: 'setMask',
    value: function () {
      function setMask(position, dimensions) {
        this.pMask.clear();
        this.pMask.beginFill();

        this.pMask.drawRect(position[0], position[1], dimensions[0], dimensions[1]);
        this.pMask.endFill();
      }

      return setMask;
    }()
  }, {
    key: 'setForeground',
    value: function () {
      function setForeground() {
        this.pForeground.position.y = this.position[1];
        this.pForeground.position.x = this.position[0];
      }

      return setForeground;
    }()

    /**
     * We're going to destroy this object, so we need to detach its
     * graphics from the scene
     */

  }, {
    key: 'remove',
    value: function () {
      function remove() {
        // the entire PIXI stage was probably removed
        this.pBase.clear();
        this.scene.removeChild(this.pBase);
      }

      return remove;
    }()

    /**
     * Draw a border around each track.
     */

  }, {
    key: 'drawBorder',
    value: function () {
      function drawBorder() {
        var graphics = this.pBorder;

        graphics.clear();

        // don't display the track label
        if (!this.options || !this.options.trackBorderWidth) return;

        var stroke = (0, _utils.colorToHex)(this.options.trackBorderColor ? this.options.trackBorderColor : 'white');

        graphics.lineStyle(this.options.trackBorderWidth, stroke);

        graphics.drawRect(this.position[0], this.position[1], this.dimensions[0], this.dimensions[1]);
      }

      return drawBorder;
    }()
  }, {
    key: 'drawError',
    value: function () {
      function drawError() {
        this.errorText.x = this.position[0] + this.dimensions[0] / 2;
        this.errorText.y = this.position[1] + this.dimensions[1] / 2;

        this.errorText.text = this.errorTextText;

        if (this.errorTextText && this.errorTextText.length) {
          // draw a red border around the track to bring attention to its
          // error
          var graphics = this.pBorder;
          graphics.clear();
          graphics.lineStyle(1, (0, _utils.colorToHex)('red'));

          graphics.drawRect(this.position[0], this.position[1], this.dimensions[0], this.dimensions[1]);
        }
      }

      return drawError;
    }()
  }, {
    key: 'drawBackground',
    value: function () {
      function drawBackground() {
        var graphics = this.pBackground;

        graphics.clear();

        if (!this.options || !this.options.backgroundColor) {
          return;
        }

        var opacity = 1;
        var color = this.options.backgroundColor;

        if (this.options.backgroundColor === 'transparent') {
          opacity = 0;
          color = 'white';
        }

        var hexColor = (0, _utils.colorToHex)(color);
        graphics.beginFill(hexColor, opacity);

        graphics.drawRect(this.position[0], this.position[1], this.dimensions[0], this.dimensions[1]);
      }

      return drawBackground;
    }()

    /**
     * Determine the label color based on the number of options.
     *
     * @return {string} The color to use for the label.
     */

  }, {
    key: 'getLabelColor',
    value: function () {
      function getLabelColor() {
        if (this.options.labelColor && this.options.labelColor !== '[glyph-color]') {
          return this.options.labelColor;
        }

        return this.options.lineStrokeColor || this.options.barFillColor || 'black';
      }

      return getLabelColor;
    }()
  }, {
    key: 'getName',
    value: function () {
      function getName() {
        return this.options.name ? this.options.name : this.tilesetInfo && this.tilesetInfo.name || '';
      }

      return getName;
    }()
  }, {
    key: 'drawLabel',
    value: function () {
      function drawLabel() {
        if (!this.labelText) return;

        var graphics = this.pLabel;

        graphics.clear();

        if (!this.options || !this.options.labelPosition || this.options.labelPosition === 'hidden') {
          // don't display the track label
          this.labelText.alpha = 0;
          return;
        }

        graphics.beginFill((0, _utils.colorToHex)(this.options.labelBackgroundColor || 'white'), +this.options.labelBackgroundOpacity >= 0 ? +this.options.labelBackgroundOpacity : 0.5);

        var fontColor = (0, _utils.colorToHex)(this.getLabelColor());
        var labelBackgroundMargin = 2;

        // we can't draw a label if there's no space
        if (this.dimensions[0] < 0) {
          return;
        }

        var labelTextText = this.options.labelShowAssembly && this.tilesetInfo && this.tilesetInfo.coordSystem ? String(this.tilesetInfo.coordSystem) + ' | ' : '';

        labelTextText += this.getName();

        if (this.options.labelShowResolution && this.tilesetInfo && this.tilesetInfo.max_width && this.tilesetInfo.bins_per_dimension) {
          var formattedResolution = getWidthBasedResolutionText(this.calculateZoomLevel(), this.tilesetInfo.max_width, this.tilesetInfo.bins_per_dimension, this.tilesetInfo.max_zoom);

          labelTextText += '\n[Current data resolution: ' + String(formattedResolution) + ']';
        } else if (this.options.labelShowResolution && this.tilesetInfo && this.tilesetInfo.resolutions) {
          var _formattedResolution = getResolutionBasedResolutionText(this.tilesetInfo.resolutions, this.calculateZoomLevel());

          labelTextText += '\n[Current data resolution: ' + String(_formattedResolution) + ']';
        }

        if (this.options && this.options.dataTransform) {
          var chosenTransform = null;

          if (this.tilesetInfo && this.tilesetInfo.transforms) {
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
              for (var _iterator = (0, _getIterator3['default'])(this.tilesetInfo.transforms), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var transform = _step.value;

                if (transform.value === this.options.dataTransform) {
                  chosenTransform = transform;
                }
              }
            } catch (err) {
              _didIteratorError = true;
              _iteratorError = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion && _iterator['return']) {
                  _iterator['return']();
                }
              } finally {
                if (_didIteratorError) {
                  throw _iteratorError;
                }
              }
            }
          }

          if (chosenTransform) {
            labelTextText += '\n[Transform: ' + String(chosenTransform.name) + ']';
          } else if (this.options.dataTransform === 'None') {
            labelTextText += '\n[Transform: None ]';
          } else {
            labelTextText += '\n[Transform: Default ]';
          }
        }

        this.labelText.text = labelTextText;
        this.labelText.style = {
          fontSize: String(this.labelTextFontSize) + 'px',
          fontFamily: this.labelTextFontFamily,
          fill: fontColor
        };
        this.labelText.alpha = typeof this.options.labelTextOpacity !== 'undefined' ? this.options.labelTextOpacity : 1;

        this.labelText.visible = true;

        if (this.flipText) {
          this.labelText.scale.x = -1;
        }

        var labelLeftMargin = +this.options.labelLeftMargin || 0;
        var labelRightMargin = +this.options.labelRightMargin || 0;
        var labelTopMargin = +this.options.labelTopMargin || 0;
        var labelBottomMargin = +this.options.labelBottomMargin || 0;

        if (this.options.labelPosition === 'topLeft') {
          this.labelText.x = this.position[0] + labelLeftMargin + this.labelXOffset;
          this.labelText.y = this.position[1] + labelTopMargin;

          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 0;

          this.labelText.x += this.labelText.width / 2;

          graphics.drawRect(this.position[0] + labelLeftMargin + this.labelXOffset, this.position[1] + labelTopMargin, this.labelText.width + labelBackgroundMargin, this.labelText.height + labelBackgroundMargin);
        } else if (this.options.labelPosition === 'bottomLeft' && !this.flipText || this.options.labelPosition === 'topRight' && this.flipText) {
          this.labelText.x = this.position[0] + (labelLeftMargin || labelTopMargin);
          this.labelText.y = this.position[1] + this.dimensions[1] - (labelBottomMargin || labelRightMargin);
          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 1;

          this.labelText.x += this.labelText.width / 2 + this.labelXOffset;
          graphics.drawRect(this.position[0] + (labelLeftMargin || labelTopMargin) + this.labelXOffset, this.position[1] + this.dimensions[1] - this.labelText.height - labelBackgroundMargin - (labelBottomMargin || labelRightMargin), this.labelText.width + labelBackgroundMargin, this.labelText.height + labelBackgroundMargin);
        } else if (this.options.labelPosition === 'topRight' && !this.flipText || this.options.labelPosition === 'bottomLeft' && this.flipText) {
          this.labelText.x = this.position[0] + this.dimensions[0] - (labelRightMargin || labelBottomMargin);
          this.labelText.y = this.position[1] + (labelTopMargin || labelLeftMargin);
          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 0;

          this.labelText.x -= this.labelText.width / 2 + this.labelXOffset;

          graphics.drawRect(this.position[0] + this.dimensions[0] - this.labelText.width - labelBackgroundMargin - (labelRightMargin || labelBottomMargin) - this.labelXOffset, this.position[1] + (labelTopMargin || labelLeftMargin), this.labelText.width + labelBackgroundMargin, this.labelText.height + labelBackgroundMargin);
        } else if (this.options.labelPosition === 'bottomRight') {
          this.labelText.x = this.position[0] + this.dimensions[0] - labelRightMargin;
          this.labelText.y = this.position[1] + this.dimensions[1] - labelBottomMargin;
          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 1;

          // we set the anchor to 0.5 so that we can flip the text if the track
          // is rotated but that means we have to adjust its position
          this.labelText.x -= this.labelText.width / 2 + this.labelXOffset;

          graphics.drawRect(this.position[0] + this.dimensions[0] - this.labelText.width - labelBackgroundMargin - labelRightMargin - this.labelXOffset, this.position[1] + this.dimensions[1] - this.labelText.height - labelBackgroundMargin - labelBottomMargin, this.labelText.width + labelBackgroundMargin, this.labelText.height + labelBackgroundMargin);
        } else if (this.options.labelPosition === 'outerLeft' && !this.flipText || this.options.labelPosition === 'outerTop' && this.flipText) {
          this.labelText.x = this.position[0];
          this.labelText.y = this.position[1] + this.dimensions[1] / 2;

          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 0.5;

          this.labelText.x -= this.labelText.width / 2 + 3;
        } else if (this.options.labelPosition === 'outerTop' && !this.flipText || this.options.labelPosition === 'outerLeft' && this.flipText) {
          this.labelText.x = this.position[0] + this.dimensions[0] / 2;
          this.labelText.y = this.position[1];

          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 0.5;

          this.labelText.y -= this.labelText.height / 2 + 3;
        } else if (this.options.labelPosition === 'outerBottom' && !this.flipText || this.options.labelPosition === 'outerRight' && this.flipText) {
          this.labelText.x = this.position[0] + this.dimensions[0] / 2;
          this.labelText.y = this.position[1] + this.dimensions[1];

          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 0.5;

          this.labelText.y += this.labelText.height / 2 + 3;
        } else if (this.options.labelPosition === 'outerRight' && !this.flipText || this.options.labelPosition === 'outerBottom' && this.flipText) {
          this.labelText.x = this.position[0] + this.dimensions[0];
          this.labelText.y = this.position[1] + this.dimensions[1] / 2;

          this.labelText.anchor.x = 0.5;
          this.labelText.anchor.y = 0.5;

          this.labelText.x += this.labelText.width / 2 + 3;
        } else {
          this.labelText.visible = false;
        }

        if (this.options.labelPosition === 'outerLeft' || this.options.labelPosition === 'outerRight' || this.options.labelPosition === 'outerTop' || this.options.labelPosition === 'outerBottom') {
          this.pLabel.setParent(this.pBase);
        } else {
          this.pLabel.setParent(this.pMasked);
        }
      }

      return drawLabel;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options) {
        this.options = options;

        this.draw();
        this.drawBackground();
        this.drawLabel();
        this.drawError();
        this.drawBorder();
      }

      return rerender;
    }()

    /**
     * Draw all the data associated with this track
     */

  }, {
    key: 'draw',
    value: function () {
      function draw() {
        // this rectangle is cleared by functions that override this draw method
        // this.drawBorder();
        // this.drawLabel();
        this.drawError();
      }

      return draw;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var gBase = document.createElement('g');
        var rectBackground = document.createElement('rect');

        rectBackground.setAttribute('x', '' + String(this.position[0]));
        rectBackground.setAttribute('y', '' + String(this.position[1]));
        rectBackground.setAttribute('width', '' + String(this.dimensions[0]));
        rectBackground.setAttribute('height', '' + String(this.dimensions[1]));

        if (this.options && this.options.backgroundColor) {
          rectBackground.setAttribute('fill', this.options.backgroundColor);
        } else {
          rectBackground.setAttribute('fill-opacity', '0');
        }

        var gClipped = document.createElement('g');
        gClipped.setAttribute('class', 'g-clipped');
        gBase.appendChild(gClipped);
        gClipped.appendChild(rectBackground);

        var gTrack = document.createElement('g');
        gClipped.setAttribute('class', 'g-track');
        gClipped.appendChild(gTrack);

        var gLabels = document.createElement('g');
        gClipped.setAttribute('class', 'g-labels');
        gClipped.appendChild(gLabels); // labels should always appear on top of the track

        // define the clipping area as a polygon defined by the track's
        // dimensions on the canvas
        var clipPath = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath');
        gBase.appendChild(clipPath);

        var clipPolygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
        clipPath.appendChild(clipPolygon);

        clipPolygon.setAttribute('points', String(this.position[0]) + ',' + String(this.position[1]) + ' ' + (String(this.position[0] + this.dimensions[0]) + ',' + String(this.position[1]) + ' ') + (String(this.position[0] + this.dimensions[0]) + ',' + String(this.position[1] + this.dimensions[1]) + ' ') + (String(this.position[0]) + ',' + String(this.position[1] + this.dimensions[1]) + ' '));

        // the clipping area needs to be a clipPath element
        var clipPathId = _slugid2['default'].nice();
        clipPath.setAttribute('id', clipPathId);

        gClipped.setAttribute('style', 'clip-path:url(#' + String(clipPathId) + ');');

        var lineParts = this.labelText.text.split('\n');
        var ddy = 0;

        // SVG text alignment is wonky, just adjust the dy values of the tspans
        // instead

        var paddingBottom = 3;
        var labelTextHeight = (this.labelTextFontSize + 2) * lineParts.length + paddingBottom;

        if (this.labelText.anchor.y === 0.5) {
          ddy = labelTextHeight / 2;
        } else if (this.labelText.anchor.y === 1) {
          ddy = -labelTextHeight;
        }

        for (var i = 0; i < lineParts.length; i++) {
          var text = document.createElement('text');

          text.setAttribute('font-family', this.labelTextFontFamily);
          text.setAttribute('font-size', String(this.labelTextFontSize) + 'px');

          // break up newlines into separate tspan elements because SVG text
          // doesn't support line breaks:
          // http://stackoverflow.com/a/16701952/899470

          text.innerText = lineParts[i];
          if (this.options.labelPosition === 'topLeft' || this.options.labelPosition === 'topRight') {
            var dy = ddy + (i + 1) * (this.labelTextFontSize + 2);
            text.setAttribute('dy', dy);
          } else if (this.options.labelPosition === 'bottomLeft' || this.options.labelPosition === 'bottomRight') {
            text.setAttribute('dy', ddy + i * (this.labelTextFontSize + 2));
          }

          text.setAttribute('fill', this.options.labelColor);

          if (this.labelText.anchor.x === 0.5) {
            text.setAttribute('text-anchor', 'middle');
          } else if (this.labelText.anchor.x === 1) {
            text.setAttribute('text-anchor', 'end');
          }

          gLabels.appendChild(text);
        }

        gLabels.setAttribute('transform', 'translate(' + String(this.labelText.x) + ',' + String(this.labelText.y) + ')scale(' + String(this.labelText.scale.x) + ',1)');

        // return the whole SVG and where the specific track should draw its
        // contents
        return [gBase, gTrack];
      }

      return exportSVG;
    }()
  }]);
  return PixiTrack;
}(_Track3['default']);

exports['default'] = PixiTrack;

/***/ }),
/* 41 */
/***/ (function(module, exports, __nested_webpack_require_252990__) {

var freeGlobal = __nested_webpack_require_252990__(406);

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

module.exports = root;


/***/ }),
/* 42 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE__42__;

/***/ }),
/* 43 */
/***/ (function(module, exports, __nested_webpack_require_253474__) {

var dP = __nested_webpack_require_253474__(32);
var createDesc = __nested_webpack_require_253474__(66);
module.exports = __nested_webpack_require_253474__(36) ? function (object, key, value) {
  return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
  object[key] = value;
  return object;
};


/***/ }),
/* 44 */
/***/ (function(module, exports, __nested_webpack_require_253832__) {

module.exports = { "default": __nested_webpack_require_253832__(222), __esModule: true };

/***/ }),
/* 45 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

module.exports = isObject;


/***/ }),
/* 46 */
/***/ (function(module, exports, __nested_webpack_require_254775__) {

var baseMerge = __nested_webpack_require_254775__(831),
    createAssigner = __nested_webpack_require_254775__(290);

/**
 * This method is like `_.assign` except that it recursively merges own and
 * inherited enumerable string keyed properties of source objects into the
 * destination object. Source properties that resolve to `undefined` are
 * skipped if a destination value exists. Array and plain object properties
 * are merged recursively. Other objects and value types are overridden by
 * assignment. Source objects are applied from left to right. Subsequent
 * sources overwrite property assignments of previous sources.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 0.5.0
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @example
 *
 * var object = {
 *   'a': [{ 'b': 2 }, { 'd': 4 }]
 * };
 *
 * var other = {
 *   'a': [{ 'c': 3 }, { 'e': 5 }]
 * };
 *
 * _.merge(object, other);
 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
 */
var merge = createAssigner(function(object, source, srcIndex) {
  baseMerge(object, source, srcIndex);
});

module.exports = merge;


/***/ }),
/* 47 */
/***/ (function(module, exports) {

var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
  return hasOwnProperty.call(it, key);
};


/***/ }),
/* 48 */
/***/ (function(module, exports, __nested_webpack_require_256247__) {

// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __nested_webpack_require_256247__(105);
var defined = __nested_webpack_require_256247__(87);
module.exports = function (it) {
  return IObject(defined(it));
};


/***/ }),
/* 49 */
/***/ (function(module, exports, __nested_webpack_require_256547__) {

// optional / simple context binding
var aFunction = __nested_webpack_require_256547__(92);
module.exports = function (fn, that, length) {
  aFunction(fn);
  if (that === undefined) return fn;
  switch (length) {
    case 1: return function (a) {
      return fn.call(that, a);
    };
    case 2: return function (a, b) {
      return fn.call(that, a, b);
    };
    case 3: return function (a, b, c) {
      return fn.call(that, a, b, c);
    };
  }
  return function (/* ...args */) {
    return fn.apply(that, arguments);
  };
};


/***/ }),
/* 50 */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return !!exec();
  } catch (e) {
    return true;
  }
};


/***/ }),
/* 51 */
/***/ (function(module, exports) {

module.exports = {};


/***/ }),
/* 52 */
/***/ (function(module, exports, __nested_webpack_require_257383__) {

"use strict";


var keys = __nested_webpack_require_257383__(295);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';

var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;

var isFunction = function (fn) {
	return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};

var arePropertyDescriptorsSupported = function () {
	var obj = {};
	try {
		origDefineProperty(obj, 'x', { enumerable: false, value: obj });
		// eslint-disable-next-line no-unused-vars, no-restricted-syntax
		for (var _ in obj) { // jscs:ignore disallowUnusedVariables
			return false;
		}
		return obj.x === obj;
	} catch (e) { /* this is IE 8. */
		return false;
	}
};
var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported();

var defineProperty = function (object, name, value, predicate) {
	if (name in object && (!isFunction(predicate) || !predicate())) {
		return;
	}
	if (supportsDescriptors) {
		origDefineProperty(object, name, {
			configurable: true,
			enumerable: false,
			value: value,
			writable: true
		});
	} else {
		object[name] = value;
	}
};

var defineProperties = function (object, map) {
	var predicates = arguments.length > 2 ? arguments[2] : {};
	var props = keys(map);
	if (hasSymbols) {
		props = concat.call(props, Object.getOwnPropertySymbols(map));
	}
	for (var i = 0; i < props.length; i += 1) {
		defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
	}
};

defineProperties.supportsDescriptors = !!supportsDescriptors;

module.exports = defineProperties;


/***/ }),
/* 53 */
/***/ (function(module, exports, __nested_webpack_require_259072__) {

"use strict";


var implementation = __nested_webpack_require_259072__(954);

module.exports = Function.prototype.bind || implementation;


/***/ }),
/* 54 */
/***/ (function(module, exports, __nested_webpack_require_259274__) {

// 7.1.13 ToObject(argument)
var defined = __nested_webpack_require_259274__(87);
module.exports = function (it) {
  return Object(defined(it));
};


/***/ }),
/* 55 */
/***/ (function(module, exports, __nested_webpack_require_259486__) {

module.exports = { "default": __nested_webpack_require_259486__(241), __esModule: true };

/***/ }),
/* 56 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

module.exports = isObjectLike;


/***/ }),
/* 57 */
/***/ (function(module, exports, __nested_webpack_require_260310__) {

"use strict";


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

var _each = __nested_webpack_require_260310__(841);

var _each2 = _interopRequireDefault(_each);

var _tinycolor = __nested_webpack_require_260310__(842);

var _tinycolor2 = _interopRequireDefault(_tinycolor);

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

exports.default = {
  simpleCheckForValidColor: function simpleCheckForValidColor(data) {
    var keysToCheck = ['r', 'g', 'b', 'a', 'h', 's', 'l', 'v'];
    var checked = 0;
    var passed = 0;
    (0, _each2.default)(keysToCheck, function (letter) {
      if (data[letter]) {
        checked += 1;
        if (!isNaN(data[letter])) {
          passed += 1;
        }
        if (letter === 's' || letter === 'l') {
          var percentPatt = /^\d+%$/;
          if (percentPatt.test(data[letter])) {
            passed += 1;
          }
        }
      }
    });
    return checked === passed ? data : false;
  },
  toState: function toState(data, oldHue) {
    var color = data.hex ? (0, _tinycolor2.default)(data.hex) : (0, _tinycolor2.default)(data);
    var hsl = color.toHsl();
    var hsv = color.toHsv();
    var rgb = color.toRgb();
    var hex = color.toHex();
    if (hsl.s === 0) {
      hsl.h = oldHue || 0;
      hsv.h = oldHue || 0;
    }
    var transparent = hex === '000000' && rgb.a === 0;

    return {
      hsl: hsl,
      hex: transparent ? 'transparent' : '#' + hex,
      rgb: rgb,
      hsv: hsv,
      oldHue: data.h || oldHue || hsl.h,
      source: data.source
    };
  },
  isValidHex: function isValidHex(hex) {
    // disable hex4 and hex8
    var lh = String(hex).charAt(0) === '#' ? 1 : 0;
    return hex.length !== 4 + lh && hex.length < 7 + lh && (0, _tinycolor2.default)(hex).isValid();
  },
  getContrastingColor: function getContrastingColor(data) {
    if (!data) {
      return '#fff';
    }
    var col = this.toState(data);
    if (col.hex === 'transparent') {
      return 'rgba(0,0,0,0.4)';
    }
    var yiq = (col.rgb.r * 299 + col.rgb.g * 587 + col.rgb.b * 114) / 1000;
    return yiq >= 128 ? '#000' : '#fff';
  }
};
var red = exports.red = {
  hsl: { a: 1, h: 0, l: 0.5, s: 1 },
  hex: '#ff0000',
  rgb: { r: 255, g: 0, b: 0, a: 1 },
  hsv: { h: 0, s: 1, v: 1, a: 1 }
};

/***/ }),
/* 58 */
/***/ (function(module, exports) {

if (typeof Object.create === 'function') {
  // implementation from standard node.js 'util' module
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  // old school shim for old browsers
  module.exports = function inherits(ctor, superCtor) {
    ctor.super_ = superCtor
    var TempCtor = function () {}
    TempCtor.prototype = superCtor.prototype
    ctor.prototype = new TempCtor()
    ctor.prototype.constructor = ctor
  }
}


/***/ }),
/* 59 */
/***/ (function(module, exports, __nested_webpack_require_263426__) {

"use strict";


var bind = __nested_webpack_require_263426__(53);

module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);


/***/ }),
/* 60 */
/***/ (function(module, exports, __nested_webpack_require_263633__) {

// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __nested_webpack_require_263633__(158);
var enumBugKeys = __nested_webpack_require_263633__(107);

module.exports = Object.keys || function keys(O) {
  return $keys(O, enumBugKeys);
};


/***/ }),
/* 61 */
/***/ (function(module, exports, __nested_webpack_require_263920__) {

"use strict";

var $at = __nested_webpack_require_263920__(215)(true);

// 21.1.3.27 String.prototype[@@iterator]()
__nested_webpack_require_263920__(109)(String, 'String', function (iterated) {
  this._t = String(iterated); // target
  this._i = 0;                // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var index = this._i;
  var point;
  if (index >= O.length) return { value: undefined, done: true };
  point = $at(O, index);
  this._i += point.length;
  return { value: point, done: false };
});


/***/ }),
/* 62 */
/***/ (function(module, exports, __nested_webpack_require_264530__) {

module.exports = { "default": __nested_webpack_require_264530__(522), __esModule: true };

/***/ }),
/* 63 */
/***/ (function(module, exports, __nested_webpack_require_264683__) {

module.exports = { "default": __nested_webpack_require_264683__(239), __esModule: true };

/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var NS = exports.NAMESPACES = {
    HTML: 'http://www.w3.org/1999/xhtml',
    MATHML: 'http://www.w3.org/1998/Math/MathML',
    SVG: 'http://www.w3.org/2000/svg',
    XLINK: 'http://www.w3.org/1999/xlink',
    XML: 'http://www.w3.org/XML/1998/namespace',
    XMLNS: 'http://www.w3.org/2000/xmlns/'
};

exports.ATTRS = {
    TYPE: 'type',
    ACTION: 'action',
    ENCODING: 'encoding',
    PROMPT: 'prompt',
    NAME: 'name',
    COLOR: 'color',
    FACE: 'face',
    SIZE: 'size'
};

exports.DOCUMENT_MODE = {
    NO_QUIRKS: 'no-quirks',
    QUIRKS: 'quirks',
    LIMITED_QUIRKS: 'limited-quirks'
};

var $ = exports.TAG_NAMES = {
    A: 'a',
    ADDRESS: 'address',
    ANNOTATION_XML: 'annotation-xml',
    APPLET: 'applet',
    AREA: 'area',
    ARTICLE: 'article',
    ASIDE: 'aside',

    B: 'b',
    BASE: 'base',
    BASEFONT: 'basefont',
    BGSOUND: 'bgsound',
    BIG: 'big',
    BLOCKQUOTE: 'blockquote',
    BODY: 'body',
    BR: 'br',
    BUTTON: 'button',

    CAPTION: 'caption',
    CENTER: 'center',
    CODE: 'code',
    COL: 'col',
    COLGROUP: 'colgroup',

    DD: 'dd',
    DESC: 'desc',
    DETAILS: 'details',
    DIALOG: 'dialog',
    DIR: 'dir',
    DIV: 'div',
    DL: 'dl',
    DT: 'dt',

    EM: 'em',
    EMBED: 'embed',

    FIELDSET: 'fieldset',
    FIGCAPTION: 'figcaption',
    FIGURE: 'figure',
    FONT: 'font',
    FOOTER: 'footer',
    FOREIGN_OBJECT: 'foreignObject',
    FORM: 'form',
    FRAME: 'frame',
    FRAMESET: 'frameset',

    H1: 'h1',
    H2: 'h2',
    H3: 'h3',
    H4: 'h4',
    H5: 'h5',
    H6: 'h6',
    HEAD: 'head',
    HEADER: 'header',
    HGROUP: 'hgroup',
    HR: 'hr',
    HTML: 'html',

    I: 'i',
    IMG: 'img',
    IMAGE: 'image',
    INPUT: 'input',
    IFRAME: 'iframe',

    KEYGEN: 'keygen',

    LABEL: 'label',
    LI: 'li',
    LINK: 'link',
    LISTING: 'listing',

    MAIN: 'main',
    MALIGNMARK: 'malignmark',
    MARQUEE: 'marquee',
    MATH: 'math',
    MENU: 'menu',
    MENUITEM: 'menuitem',
    META: 'meta',
    MGLYPH: 'mglyph',
    MI: 'mi',
    MO: 'mo',
    MN: 'mn',
    MS: 'ms',
    MTEXT: 'mtext',

    NAV: 'nav',
    NOBR: 'nobr',
    NOFRAMES: 'noframes',
    NOEMBED: 'noembed',
    NOSCRIPT: 'noscript',

    OBJECT: 'object',
    OL: 'ol',
    OPTGROUP: 'optgroup',
    OPTION: 'option',

    P: 'p',
    PARAM: 'param',
    PLAINTEXT: 'plaintext',
    PRE: 'pre',

    RB: 'rb',
    RP: 'rp',
    RT: 'rt',
    RTC: 'rtc',
    RUBY: 'ruby',

    S: 's',
    SCRIPT: 'script',
    SECTION: 'section',
    SELECT: 'select',
    SOURCE: 'source',
    SMALL: 'small',
    SPAN: 'span',
    STRIKE: 'strike',
    STRONG: 'strong',
    STYLE: 'style',
    SUB: 'sub',
    SUMMARY: 'summary',
    SUP: 'sup',

    TABLE: 'table',
    TBODY: 'tbody',
    TEMPLATE: 'template',
    TEXTAREA: 'textarea',
    TFOOT: 'tfoot',
    TD: 'td',
    TH: 'th',
    THEAD: 'thead',
    TITLE: 'title',
    TR: 'tr',
    TRACK: 'track',
    TT: 'tt',

    U: 'u',
    UL: 'ul',

    SVG: 'svg',

    VAR: 'var',

    WBR: 'wbr',

    XMP: 'xmp'
};

var SPECIAL_ELEMENTS = exports.SPECIAL_ELEMENTS = Object.create(null);

SPECIAL_ELEMENTS[NS.HTML] = Object.create(null);
SPECIAL_ELEMENTS[NS.HTML][$.ADDRESS] = true;
SPECIAL_ELEMENTS[NS.HTML][$.APPLET] = true;
SPECIAL_ELEMENTS[NS.HTML][$.AREA] = true;
SPECIAL_ELEMENTS[NS.HTML][$.ARTICLE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.ASIDE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BASE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BASEFONT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BGSOUND] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BLOCKQUOTE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BODY] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BR] = true;
SPECIAL_ELEMENTS[NS.HTML][$.BUTTON] = true;
SPECIAL_ELEMENTS[NS.HTML][$.CAPTION] = true;
SPECIAL_ELEMENTS[NS.HTML][$.CENTER] = true;
SPECIAL_ELEMENTS[NS.HTML][$.COL] = true;
SPECIAL_ELEMENTS[NS.HTML][$.COLGROUP] = true;
SPECIAL_ELEMENTS[NS.HTML][$.DD] = true;
SPECIAL_ELEMENTS[NS.HTML][$.DETAILS] = true;
SPECIAL_ELEMENTS[NS.HTML][$.DIR] = true;
SPECIAL_ELEMENTS[NS.HTML][$.DIV] = true;
SPECIAL_ELEMENTS[NS.HTML][$.DL] = true;
SPECIAL_ELEMENTS[NS.HTML][$.DT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.EMBED] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FIELDSET] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FIGCAPTION] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FIGURE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FOOTER] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FORM] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FRAME] = true;
SPECIAL_ELEMENTS[NS.HTML][$.FRAMESET] = true;
SPECIAL_ELEMENTS[NS.HTML][$.H1] = true;
SPECIAL_ELEMENTS[NS.HTML][$.H2] = true;
SPECIAL_ELEMENTS[NS.HTML][$.H3] = true;
SPECIAL_ELEMENTS[NS.HTML][$.H4] = true;
SPECIAL_ELEMENTS[NS.HTML][$.H5] = true;
SPECIAL_ELEMENTS[NS.HTML][$.H6] = true;
SPECIAL_ELEMENTS[NS.HTML][$.HEAD] = true;
SPECIAL_ELEMENTS[NS.HTML][$.HEADER] = true;
SPECIAL_ELEMENTS[NS.HTML][$.HGROUP] = true;
SPECIAL_ELEMENTS[NS.HTML][$.HR] = true;
SPECIAL_ELEMENTS[NS.HTML][$.HTML] = true;
SPECIAL_ELEMENTS[NS.HTML][$.IFRAME] = true;
SPECIAL_ELEMENTS[NS.HTML][$.IMG] = true;
SPECIAL_ELEMENTS[NS.HTML][$.INPUT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.LI] = true;
SPECIAL_ELEMENTS[NS.HTML][$.LINK] = true;
SPECIAL_ELEMENTS[NS.HTML][$.LISTING] = true;
SPECIAL_ELEMENTS[NS.HTML][$.MAIN] = true;
SPECIAL_ELEMENTS[NS.HTML][$.MARQUEE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.MENU] = true;
SPECIAL_ELEMENTS[NS.HTML][$.META] = true;
SPECIAL_ELEMENTS[NS.HTML][$.NAV] = true;
SPECIAL_ELEMENTS[NS.HTML][$.NOEMBED] = true;
SPECIAL_ELEMENTS[NS.HTML][$.NOFRAMES] = true;
SPECIAL_ELEMENTS[NS.HTML][$.NOSCRIPT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.OBJECT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.OL] = true;
SPECIAL_ELEMENTS[NS.HTML][$.P] = true;
SPECIAL_ELEMENTS[NS.HTML][$.PARAM] = true;
SPECIAL_ELEMENTS[NS.HTML][$.PLAINTEXT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.PRE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.SCRIPT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.SECTION] = true;
SPECIAL_ELEMENTS[NS.HTML][$.SELECT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.SOURCE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.STYLE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.SUMMARY] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TABLE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TBODY] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TD] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TEMPLATE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TEXTAREA] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TFOOT] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TH] = true;
SPECIAL_ELEMENTS[NS.HTML][$.THEAD] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TITLE] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TR] = true;
SPECIAL_ELEMENTS[NS.HTML][$.TRACK] = true;
SPECIAL_ELEMENTS[NS.HTML][$.UL] = true;
SPECIAL_ELEMENTS[NS.HTML][$.WBR] = true;
SPECIAL_ELEMENTS[NS.HTML][$.XMP] = true;

SPECIAL_ELEMENTS[NS.MATHML] = Object.create(null);
SPECIAL_ELEMENTS[NS.MATHML][$.MI] = true;
SPECIAL_ELEMENTS[NS.MATHML][$.MO] = true;
SPECIAL_ELEMENTS[NS.MATHML][$.MN] = true;
SPECIAL_ELEMENTS[NS.MATHML][$.MS] = true;
SPECIAL_ELEMENTS[NS.MATHML][$.MTEXT] = true;
SPECIAL_ELEMENTS[NS.MATHML][$.ANNOTATION_XML] = true;

SPECIAL_ELEMENTS[NS.SVG] = Object.create(null);
SPECIAL_ELEMENTS[NS.SVG][$.TITLE] = true;
SPECIAL_ELEMENTS[NS.SVG][$.FOREIGN_OBJECT] = true;
SPECIAL_ELEMENTS[NS.SVG][$.DESC] = true;


/***/ }),
/* 65 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_272068__) {

"use strict";

// CONCATENATED MODULE: ../node_modules/d3-dispatch/src/dispatch.js
var noop = {value: function() {}};

function dispatch() {
  for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
    if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t);
    _[t] = [];
  }
  return new Dispatch(_);
}

function Dispatch(_) {
  this._ = _;
}

function parseTypenames(typenames, types) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
    return {type: t, name: name};
  });
}

Dispatch.prototype = dispatch.prototype = {
  constructor: Dispatch,
  on: function(typename, callback) {
    var _ = this._,
        T = parseTypenames(typename + "", _),
        t,
        i = -1,
        n = T.length;

    // If no callback was specified, return the callback of the given type and name.
    if (arguments.length < 2) {
      while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
      return;
    }

    // If a type was specified, set the callback for the given type and name.
    // Otherwise, if a null callback was specified, remove callbacks of the given name.
    if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
    while (++i < n) {
      if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
      else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
    }

    return this;
  },
  copy: function() {
    var copy = {}, _ = this._;
    for (var t in _) copy[t] = _[t].slice();
    return new Dispatch(copy);
  },
  call: function(type, that) {
    if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  },
  apply: function(type, that, args) {
    if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
    for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  }
};

function get(type, name) {
  for (var i = 0, n = type.length, c; i < n; ++i) {
    if ((c = type[i]).name === name) {
      return c.value;
    }
  }
}

function set(type, name, callback) {
  for (var i = 0, n = type.length; i < n; ++i) {
    if (type[i].name === name) {
      type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
      break;
    }
  }
  if (callback != null) type.push({name: name, value: callback});
  return type;
}

/* harmony default export */ var src_dispatch = (dispatch);

// CONCATENATED MODULE: ../node_modules/d3-dispatch/src/index.js
/* concated harmony reexport dispatch */__nested_webpack_require_272068__.d(__webpack_exports__, "a", function() { return src_dispatch; });



/***/ }),
/* 66 */
/***/ (function(module, exports) {

module.exports = function (bitmap, value) {
  return {
    enumerable: !(bitmap & 1),
    configurable: !(bitmap & 2),
    writable: !(bitmap & 4),
    value: value
  };
};


/***/ }),
/* 67 */
/***/ (function(module, exports, __nested_webpack_require_275416__) {

"use strict";


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

var _propTypes = __nested_webpack_require_275416__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_275416__(1);

var _react2 = _interopRequireDefault(_react);

__nested_webpack_require_275416__(68);

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

var ContextMenuItem = function ContextMenuItem(props) {
  return _react2['default'].createElement(
    'div',
    {
      'data-menu-item-for': typeof props.children === 'string' ? props.children : null,
      onClick: function () {
        function onClick(e) {
          return props.onClick(e);
        }

        return onClick;
      }(),
      onMouseEnter: function () {
        function onMouseEnter(e) {
          return props.onMouseEnter(e);
        }

        return onMouseEnter;
      }(),
      onMouseLeave: function () {
        function onMouseLeave(e) {
          return props.onMouseLeave(e);
        }

        return onMouseLeave;
      }(),
      role: 'button',
      className: 'ContextMenu-module_context-menu-item-1HeVv',
      tabIndex: 0
    },
    _react2['default'].createElement(
      'span',
      { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
      props.children
    )
  );
};

// Styles


ContextMenuItem.defaultProps = {
  onMouseEnter: function () {
    function onMouseEnter() {
      return undefined;
    }

    return onMouseEnter;
  }(),
  onMouseLeave: function () {
    function onMouseLeave() {
      return undefined;
    }

    return onMouseLeave;
  }()
};

ContextMenuItem.propTypes = {
  children: _propTypes2['default'].node.isRequired,
  onClick: _propTypes2['default'].func.isRequired,
  onMouseEnter: _propTypes2['default'].func,
  onMouseLeave: _propTypes2['default'].func
};

exports['default'] = ContextMenuItem;

/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"context-menu":"ContextMenu-module_context-menu-2OwvL","context-menu-dark":"ContextMenu-module_context-menu-dark-2PO31","context-menu-icon":"ContextMenu-module_context-menu-icon-I4kiw","context-menu-item":"ContextMenu-module_context-menu-item-1HeVv","context-menu-hr":"ContextMenu-module_context-menu-hr-3yapb","play-icon":"ContextMenu-module_play-icon-R4pIO","context-menu-span":"ContextMenu-module_context-menu-span-8EUfZ","context-menu-thumbnail":"ContextMenu-module_context-menu-thumbnail-2vHLD","context-menu-thumbnail-inline":"ContextMenu-module_context-menu-thumbnail-inline-1iOcg"};

/***/ }),
/* 69 */
/***/ (function(module, exports, __nested_webpack_require_278095__) {

"use strict";


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

var _extends2 = __nested_webpack_require_278095__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _react = __nested_webpack_require_278095__(1);

var _react2 = _interopRequireDefault(_react);

var _toVoid = __nested_webpack_require_278095__(171);

var _toVoid2 = _interopRequireDefault(_toVoid);

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

var fake = {
  __fake__: true,
  publish: _toVoid2['default'],
  subscribe: _toVoid2['default'],
  unsubscribe: _toVoid2['default']
};

var _React$createContext = _react2['default'].createContext(fake),
    Provider = _React$createContext.Provider,
    Consumer = _React$createContext.Consumer;

// Higher order component


var withPubSub = function withPubSub(Component) {
  return _react2['default'].forwardRef(function (props, ref) {
    return _react2['default'].createElement(
      Consumer,
      null,
      function (pubSub) {
        return _react2['default'].createElement(Component, (0, _extends3['default'])({ ref: ref }, props, { pubSub: pubSub }));
      }
    );
  });
};

exports['default'] = withPubSub;
exports.fake = fake;
exports.Provider = Provider;

/***/ }),
/* 70 */
/***/ (function(module, exports, __nested_webpack_require_279439__) {

var arrayMap = __nested_webpack_require_279439__(413),
    baseIteratee = __nested_webpack_require_279439__(144),
    baseMap = __nested_webpack_require_279439__(797),
    isArray = __nested_webpack_require_279439__(31);

/**
 * Creates an array of values by running each element in `collection` thru
 * `iteratee`. The iteratee is invoked with three arguments:
 * (value, index|key, collection).
 *
 * Many lodash methods are guarded to work as iteratees for methods like
 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
 *
 * The guarded methods are:
 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 * @example
 *
 * function square(n) {
 *   return n * n;
 * }
 *
 * _.map([4, 8], square);
 * // => [16, 64]
 *
 * _.map({ 'a': 4, 'b': 8 }, square);
 * // => [16, 64] (iteration order is not guaranteed)
 *
 * var users = [
 *   { 'user': 'barney' },
 *   { 'user': 'fred' }
 * ];
 *
 * // The `_.property` iteratee shorthand.
 * _.map(users, 'user');
 * // => ['barney', 'fred']
 */
function map(collection, iteratee) {
  var func = isArray(collection) ? arrayMap : baseMap;
  return func(collection, baseIteratee(iteratee, 3));
}

module.exports = map;


/***/ }),
/* 71 */
/***/ (function(module, exports, __nested_webpack_require_281144__) {

/* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  function getOwnPropertyDescriptors(obj) {
    var keys = Object.keys(obj);
    var descriptors = {};
    for (var i = 0; i < keys.length; i++) {
      descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
    }
    return descriptors;
  };

var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
  if (!isString(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect(arguments[i]));
    }
    return objects.join(' ');
  }

  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') return '%';
    if (i >= len) return x;
    switch (x) {
      case '%s': return String(args[i++]);
      case '%d': return Number(args[i++]);
      case '%j':
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return '[Circular]';
        }
      default:
        return x;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject(x)) {
      str += ' ' + x;
    } else {
      str += ' ' + inspect(x);
    }
  }
  return str;
};


// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
  if (typeof process !== 'undefined' && process.noDeprecation === true) {
    return fn;
  }

  // Allow for deprecating things in the process of starting up.
  if (typeof process === 'undefined') {
    return function() {
      return exports.deprecate(fn, msg).apply(this, arguments);
    };
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (process.throwDeprecation) {
        throw new Error(msg);
      } else if (process.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
};


var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
  if (isUndefined(debugEnviron))
    debugEnviron = Object({"NODE_ENV":"production"}).NODE_DEBUG || '';
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};


/**
 * Echos the value of a value. Trys to print the value out
 * in the best way possible given the different types.
 *
 * @param {Object} obj The object to print out.
 * @param {Object} opts Optional options object that alters the output.
 */
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
  // default options
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  // legacy...
  if (arguments.length >= 3) ctx.depth = arguments[2];
  if (arguments.length >= 4) ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    // legacy...
    ctx.showHidden = opts;
  } else if (opts) {
    // got an "options" object
    exports._extend(ctx, opts);
  }
  // set default options
  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  if (isUndefined(ctx.depth)) ctx.depth = 2;
  if (isUndefined(ctx.colors)) ctx.colors = false;
  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  if (ctx.colors) ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;


// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
  'bold' : [1, 22],
  'italic' : [3, 23],
  'underline' : [4, 24],
  'inverse' : [7, 27],
  'white' : [37, 39],
  'grey' : [90, 39],
  'black' : [30, 39],
  'blue' : [34, 39],
  'cyan' : [36, 39],
  'green' : [32, 39],
  'magenta' : [35, 39],
  'red' : [31, 39],
  'yellow' : [33, 39]
};

// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
  'special': 'cyan',
  'number': 'yellow',
  'boolean': 'yellow',
  'undefined': 'grey',
  'null': 'bold',
  'string': 'green',
  'date': 'magenta',
  // "name": intentionally not styling
  'regexp': 'red'
};


function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];

  if (style) {
    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
           '\u001b[' + inspect.colors[style][1] + 'm';
  } else {
    return str;
  }
}


function stylizeNoColor(str, styleType) {
  return str;
}


function arrayToHash(array) {
  var hash = {};

  array.forEach(function(val, idx) {
    hash[val] = true;
  });

  return hash;
}


function formatValue(ctx, value, recurseTimes) {
  // Provide a hook for user-specified inspect functions.
  // Check that value is an object with an inspect function on it
  if (ctx.customInspect &&
      value &&
      isFunction(value.inspect) &&
      // Filter out the util module, it's inspect function is special
      value.inspect !== exports.inspect &&
      // Also filter out any prototype objects using the circular check.
      !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }

  // Primitive types cannot have properties
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }

  // Look up the keys of the object.
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);

  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }

  // IE doesn't make error fields non-enumerable
  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  if (isError(value)
      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
    return formatError(value);
  }

  // Some type of object without properties can be shortcutted.
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ': ' + value.name : '';
      return ctx.stylize('[Function' + name + ']', 'special');
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), 'date');
    }
    if (isError(value)) {
      return formatError(value);
    }
  }

  var base = '', array = false, braces = ['{', '}'];

  // Make Array say that they are Array
  if (isArray(value)) {
    array = true;
    braces = ['[', ']'];
  }

  // Make functions say that they are functions
  if (isFunction(value)) {
    var n = value.name ? ': ' + value.name : '';
    base = ' [Function' + n + ']';
  }

  // Make RegExps say that they are RegExps
  if (isRegExp(value)) {
    base = ' ' + RegExp.prototype.toString.call(value);
  }

  // Make dates with properties first say the date
  if (isDate(value)) {
    base = ' ' + Date.prototype.toUTCString.call(value);
  }

  // Make error with message first say the error
  if (isError(value)) {
    base = ' ' + formatError(value);
  }

  if (keys.length === 0 && (!array || value.length == 0)) {
    return braces[0] + base + braces[1];
  }

  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
    } else {
      return ctx.stylize('[Object]', 'special');
    }
  }

  ctx.seen.push(value);

  var output;
  if (array) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  }

  ctx.seen.pop();

  return reduceToSingleString(output, base, braces);
}


function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize('undefined', 'undefined');
  if (isString(value)) {
    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
                                             .replace(/'/g, "\\'")
                                             .replace(/\\"/g, '"') + '\'';
    return ctx.stylize(simple, 'string');
  }
  if (isNumber(value))
    return ctx.stylize('' + value, 'number');
  if (isBoolean(value))
    return ctx.stylize('' + value, 'boolean');
  // For some reason typeof null is "object", so special case here.
  if (isNull(value))
    return ctx.stylize('null', 'null');
}


function formatError(value) {
  return '[' + Error.prototype.toString.call(value) + ']';
}


function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty(value, String(i))) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          String(i), true));
    } else {
      output.push('');
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
          key, true));
    }
  });
  return output;
}


function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str = ctx.stylize('[Getter/Setter]', 'special');
    } else {
      str = ctx.stylize('[Getter]', 'special');
    }
  } else {
    if (desc.set) {
      str = ctx.stylize('[Setter]', 'special');
    }
  }
  if (!hasOwnProperty(visibleKeys, key)) {
    name = '[' + key + ']';
  }
  if (!str) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str = formatValue(ctx, desc.value, null);
      } else {
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str.indexOf('\n') > -1) {
        if (array) {
          str = str.split('\n').map(function(line) {
            return '  ' + line;
          }).join('\n').substr(2);
        } else {
          str = '\n' + str.split('\n').map(function(line) {
            return '   ' + line;
          }).join('\n');
        }
      }
    } else {
      str = ctx.stylize('[Circular]', 'special');
    }
  }
  if (isUndefined(name)) {
    if (array && key.match(/^\d+$/)) {
      return str;
    }
    name = JSON.stringify('' + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, 'name');
    } else {
      name = name.replace(/'/g, "\\'")
                 .replace(/\\"/g, '"')
                 .replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, 'string');
    }
  }

  return name + ': ' + str;
}


function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}


// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = __nested_webpack_require_281144__(978);

function objectToString(o) {
  return Object.prototype.toString.call(o);
}


function pad(n) {
  return n < 10 ? '0' + n.toString(10) : n.toString(10);
}


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

// 26 Feb 16:19:34
function timestamp() {
  var d = new Date();
  var time = [pad(d.getHours()),
              pad(d.getMinutes()),
              pad(d.getSeconds())].join(':');
  return [d.getDate(), months[d.getMonth()], time].join(' ');
}


// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};


/**
 * Inherit the prototype methods from one constructor into another.
 *
 * The Function.prototype.inherits from lang.js rewritten as a standalone
 * function (not on Function.prototype). NOTE: If this file is to be loaded
 * during bootstrapping this function needs to be rewritten using some native
 * functions as prototype setup using normal JavaScript does not work as
 * expected during bootstrapping (see mirror.js in r114903).
 *
 * @param {function} ctor Constructor function which needs to inherit the
 *     prototype.
 * @param {function} superCtor Constructor function to inherit prototype from.
 */
exports.inherits = __nested_webpack_require_281144__(58);

exports._extend = function(origin, add) {
  // Don't do anything if add isn't an object
  if (!add || !isObject(add)) return origin;

  var keys = Object.keys(add);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add[keys[i]];
  }
  return origin;
};

function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;

exports.promisify = function promisify(original) {
  if (typeof original !== 'function')
    throw new TypeError('The "original" argument must be of type Function');

  if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
    var fn = original[kCustomPromisifiedSymbol];
    if (typeof fn !== 'function') {
      throw new TypeError('The "util.promisify.custom" argument must be of type Function');
    }
    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
      value: fn, enumerable: false, writable: false, configurable: true
    });
    return fn;
  }

  function fn() {
    var promiseResolve, promiseReject;
    var promise = new Promise(function (resolve, reject) {
      promiseResolve = resolve;
      promiseReject = reject;
    });

    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }
    args.push(function (err, value) {
      if (err) {
        promiseReject(err);
      } else {
        promiseResolve(value);
      }
    });

    try {
      original.apply(this, args);
    } catch (err) {
      promiseReject(err);
    }

    return promise;
  }

  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));

  if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
    value: fn, enumerable: false, writable: false, configurable: true
  });
  return Object.defineProperties(
    fn,
    getOwnPropertyDescriptors(original)
  );
}

exports.promisify.custom = kCustomPromisifiedSymbol

function callbackifyOnRejected(reason, cb) {
  // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  // Because `null` is a special error value in callbacks which means "no error
  // occurred", we error-wrap so the callback consumer can distinguish between
  // "the promise rejected with null" or "the promise fulfilled with undefined".
  if (!reason) {
    var newReason = new Error('Promise was rejected with a falsy value');
    newReason.reason = reason;
    reason = newReason;
  }
  return cb(reason);
}

function callbackify(original) {
  if (typeof original !== 'function') {
    throw new TypeError('The "original" argument must be of type Function');
  }

  // We DO NOT return the promise as it gives the user a false sense that
  // the promise is actually somehow related to the callback's execution
  // and that the callback throwing will reject the promise.
  function callbackified() {
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }

    var maybeCb = args.pop();
    if (typeof maybeCb !== 'function') {
      throw new TypeError('The last argument must be of type Function');
    }
    var self = this;
    var cb = function() {
      return maybeCb.apply(self, arguments);
    };
    // In true node style we process the callback on `nextTick` with all the
    // implications (stack, `uncaughtException`, `async_hooks`)
    original.apply(this, args)
      .then(function(ret) { process.nextTick(cb, null, ret) },
            function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });
  }

  Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  Object.defineProperties(callbackified,
                          getOwnPropertyDescriptors(original));
  return callbackified;
}
exports.callbackify = callbackify;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_281144__(150)))

/***/ }),
/* 72 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_300752__) {

"use strict";

// CONCATENATED MODULE: ../node_modules/d3-collection/src/map.js
var prefix = "$";

function Map() {}

Map.prototype = map.prototype = {
  constructor: Map,
  has: function(key) {
    return (prefix + key) in this;
  },
  get: function(key) {
    return this[prefix + key];
  },
  set: function(key, value) {
    this[prefix + key] = value;
    return this;
  },
  remove: function(key) {
    var property = prefix + key;
    return property in this && delete this[property];
  },
  clear: function() {
    for (var property in this) if (property[0] === prefix) delete this[property];
  },
  keys: function() {
    var keys = [];
    for (var property in this) if (property[0] === prefix) keys.push(property.slice(1));
    return keys;
  },
  values: function() {
    var values = [];
    for (var property in this) if (property[0] === prefix) values.push(this[property]);
    return values;
  },
  entries: function() {
    var entries = [];
    for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]});
    return entries;
  },
  size: function() {
    var size = 0;
    for (var property in this) if (property[0] === prefix) ++size;
    return size;
  },
  empty: function() {
    for (var property in this) if (property[0] === prefix) return false;
    return true;
  },
  each: function(f) {
    for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this);
  }
};

function map(object, f) {
  var map = new Map;

  // Copy constructor.
  if (object instanceof Map) object.each(function(value, key) { map.set(key, value); });

  // Index array by numeric index or specified key function.
  else if (Array.isArray(object)) {
    var i = -1,
        n = object.length,
        o;

    if (f == null) while (++i < n) map.set(i, object[i]);
    else while (++i < n) map.set(f(o = object[i], i, object), o);
  }

  // Convert object to map.
  else if (object) for (var key in object) map.set(key, object[key]);

  return map;
}

/* harmony default export */ var src_map = (map);

// CONCATENATED MODULE: ../node_modules/d3-collection/src/nest.js


/* harmony default export */ var src_nest = (function() {
  var keys = [],
      sortKeys = [],
      sortValues,
      rollup,
      nest;

  function apply(array, depth, createResult, setResult) {
    if (depth >= keys.length) {
      if (sortValues != null) array.sort(sortValues);
      return rollup != null ? rollup(array) : array;
    }

    var i = -1,
        n = array.length,
        key = keys[depth++],
        keyValue,
        value,
        valuesByKey = src_map(),
        values,
        result = createResult();

    while (++i < n) {
      if (values = valuesByKey.get(keyValue = key(value = array[i]) + "")) {
        values.push(value);
      } else {
        valuesByKey.set(keyValue, [value]);
      }
    }

    valuesByKey.each(function(values, key) {
      setResult(result, key, apply(values, depth, createResult, setResult));
    });

    return result;
  }

  function entries(map, depth) {
    if (++depth > keys.length) return map;
    var array, sortKey = sortKeys[depth - 1];
    if (rollup != null && depth >= keys.length) array = map.entries();
    else array = [], map.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); });
    return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array;
  }

  return nest = {
    object: function(array) { return apply(array, 0, createObject, setObject); },
    map: function(array) { return apply(array, 0, createMap, setMap); },
    entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); },
    key: function(d) { keys.push(d); return nest; },
    sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; },
    sortValues: function(order) { sortValues = order; return nest; },
    rollup: function(f) { rollup = f; return nest; }
  };
});

function createObject() {
  return {};
}

function setObject(object, key, value) {
  object[key] = value;
}

function createMap() {
  return src_map();
}

function setMap(map, key, value) {
  map.set(key, value);
}

// CONCATENATED MODULE: ../node_modules/d3-collection/src/set.js


function Set() {}

var proto = src_map.prototype;

Set.prototype = set.prototype = {
  constructor: Set,
  has: proto.has,
  add: function(value) {
    value += "";
    this[prefix + value] = value;
    return this;
  },
  remove: proto.remove,
  clear: proto.clear,
  values: proto.keys,
  size: proto.size,
  empty: proto.empty,
  each: proto.each
};

function set(object, f) {
  var set = new Set;

  // Copy constructor.
  if (object instanceof Set) object.each(function(value) { set.add(value); });

  // Otherwise, assume it’s an array.
  else if (object) {
    var i = -1, n = object.length;
    if (f == null) while (++i < n) set.add(object[i]);
    else while (++i < n) set.add(f(object[i], i, object));
  }

  return set;
}

/* harmony default export */ var src_set = (set);

// CONCATENATED MODULE: ../node_modules/d3-collection/src/keys.js
/* harmony default export */ var src_keys = (function(map) {
  var keys = [];
  for (var key in map) keys.push(key);
  return keys;
});

// CONCATENATED MODULE: ../node_modules/d3-collection/src/values.js
/* harmony default export */ var src_values = (function(map) {
  var values = [];
  for (var key in map) values.push(map[key]);
  return values;
});

// CONCATENATED MODULE: ../node_modules/d3-collection/src/entries.js
/* harmony default export */ var src_entries = (function(map) {
  var entries = [];
  for (var key in map) entries.push({key: key, value: map[key]});
  return entries;
});

// CONCATENATED MODULE: ../node_modules/d3-collection/src/index.js
/* unused concated harmony import nest */
/* unused concated harmony import set */
/* concated harmony reexport map */__nested_webpack_require_300752__.d(__webpack_exports__, "a", function() { return src_map; });
/* unused concated harmony import keys */
/* unused concated harmony import values */
/* unused concated harmony import entries */








/***/ }),
/* 73 */
/***/ (function(module, exports, __nested_webpack_require_306941__) {

"use strict";


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

var _keys = __nested_webpack_require_306941__(18);

var _keys2 = _interopRequireDefault(_keys);

var _slicedToArray2 = __nested_webpack_require_306941__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _d3Dsv = __nested_webpack_require_306941__(104);

var _services = __nested_webpack_require_306941__(24);

var _utils = __nested_webpack_require_306941__(10);

var _withPubSub = __nested_webpack_require_306941__(69);

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

function ChromosomeInfo(filepath, success) {
  var pubSub = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _withPubSub.fake;

  var ret = {};

  ret.absToChr = function (absPos) {
    return ret.chrPositions ? (0, _utils.absToChr)(absPos, ret) : null;
  };

  ret.chrToAbs = function () {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [],
        _ref2 = (0, _slicedToArray3['default'])(_ref, 2),
        chrName = _ref2[0],
        chrPos = _ref2[1];

    return ret.chrPositions ? (0, _utils.chrToAbs)(chrName, chrPos, ret) : null;
  };

  return _services.tileProxy.text(filepath, function (error, chrInfoText) {
    if (error) {
      // console.warn('Chromosome info not found at:', filepath);
      if (success) success(null);
    } else {
      var data = (0, _d3Dsv.tsvParseRows)(chrInfoText);
      var chromInfo = (0, _utils.parseChromsizesRows)(data);

      (0, _keys2['default'])(chromInfo).forEach(function (key) {
        ret[key] = chromInfo[key];
      });
      if (success) success(ret);
    }
  }, pubSub).then(function () {
    return ret;
  });
}

exports['default'] = ChromosomeInfo;

/***/ }),
/* 74 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = function (it) {
  return toString.call(it).slice(8, -1);
};


/***/ }),
/* 75 */
/***/ (function(module, exports) {

module.exports = true;


/***/ }),
/* 76 */
/***/ (function(module, exports, __nested_webpack_require_308967__) {

__nested_webpack_require_308967__(212);
var global = __nested_webpack_require_308967__(23);
var hide = __nested_webpack_require_308967__(43);
var Iterators = __nested_webpack_require_308967__(51);
var TO_STRING_TAG = __nested_webpack_require_308967__(21)('toStringTag');

var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
  'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
  'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
  'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
  'TextTrackList,TouchList').split(',');

for (var i = 0; i < DOMIterables.length; i++) {
  var NAME = DOMIterables[i];
  var Collection = global[NAME];
  var proto = Collection && Collection.prototype;
  if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
  Iterators[NAME] = Iterators.Array;
}


/***/ }),
/* 77 */
/***/ (function(module, exports, __nested_webpack_require_310021__) {

var def = __nested_webpack_require_310021__(32).f;
var has = __nested_webpack_require_310021__(47);
var TAG = __nested_webpack_require_310021__(21)('toStringTag');

module.exports = function (it, tag, stat) {
  if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};


/***/ }),
/* 78 */
/***/ (function(module, exports, __nested_webpack_require_310373__) {

"use strict";


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

var _extends2 = __nested_webpack_require_310373__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _react = __nested_webpack_require_310373__(1);

var _react2 = _interopRequireDefault(_react);

var _toVoid = __nested_webpack_require_310373__(171);

var _toVoid2 = _interopRequireDefault(_toVoid);

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

var _React$createContext = _react2['default'].createContext({
  close: _toVoid2['default'],
  open: _toVoid2['default']
}),
    Provider = _React$createContext.Provider,
    Consumer = _React$createContext.Consumer;

// Higher order component


var withTheme = function withTheme(Component) {
  return _react2['default'].forwardRef(function (props, ref) {
    return _react2['default'].createElement(
      Consumer,
      null,
      function (theme) {
        return _react2['default'].createElement(Component, (0, _extends3['default'])({ ref: ref }, props, { theme: theme }));
      }
    );
  });
};

exports['default'] = withTheme;
exports.Provider = Provider;

/***/ }),
/* 79 */
/***/ (function(module, exports, __nested_webpack_require_311596__) {

"use strict";


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

var _minSafeInteger = __nested_webpack_require_311596__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

var _maxSafeInteger = __nested_webpack_require_311596__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _from = __nested_webpack_require_311596__(95);

var _from2 = _interopRequireDefault(_from);

var _values = __nested_webpack_require_311596__(37);

var _values2 = _interopRequireDefault(_values);

var _slicedToArray2 = __nested_webpack_require_311596__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _extends2 = __nested_webpack_require_311596__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _stringify = __nested_webpack_require_311596__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getIterator2 = __nested_webpack_require_311596__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _toConsumableArray2 = __nested_webpack_require_311596__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _keys = __nested_webpack_require_311596__(18);

var _keys2 = _interopRequireDefault(_keys);

var _isNan = __nested_webpack_require_311596__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _set = __nested_webpack_require_311596__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_311596__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_311596__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_311596__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_311596__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_311596__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_311596__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

exports.getValueScale = getValueScale;

var _d3Scale = __nested_webpack_require_311596__(28);

var _d3Array = __nested_webpack_require_311596__(8);

var _slugid = __nested_webpack_require_311596__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _DataFetcher = __nested_webpack_require_311596__(245);

var _DataFetcher2 = _interopRequireDefault(_DataFetcher);

var _PixiTrack2 = __nested_webpack_require_311596__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _utils = __nested_webpack_require_311596__(10);

var _backgroundTaskScheduler = __nested_webpack_require_311596__(619);

var _backgroundTaskScheduler2 = _interopRequireDefault(_backgroundTaskScheduler);

var _configs = __nested_webpack_require_311596__(11);

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

/**
 * Get a valueScale for a heatmap.
 *
 * If the scalingType isn't specified, then default to the defaultScaling.
 *
 * @param {string} scalingType: The type of the (e.g. 'linear', or 'log')
 * @param {number} minValue: The minimum data value to which this scale will apply
 * @param {number} pseudocount: A value to add to all numbers to prevent taking the log of 0
 * @param {number} maxValue: The maximum data value to which this scale will apply
 * @param {string} defaultScaling: The default scaling type to use in case
 * 'scalingType' is null (e.g. 'linear' or 'log')
 *
 * @returns {array} An array of [string, scale] containin the scale type
 *  and a scale with an appropriately set domain and range
 */
function getValueScale(scalingType, minValue, pseudocountIn, maxValue, defaultScaling) {
  var scalingTypeToUse = scalingType || defaultScaling;

  // purposely set to not equal pseudocountIn for now
  // eventually this will be an option
  var pseudocount = 0;

  if (scalingTypeToUse === 'log' && minValue > 0) {
    return ['log', (0, _d3Scale.scaleLog)().range([254, 0]).domain([minValue + pseudocount, maxValue + pseudocount])];
  }

  if (scalingTypeToUse === 'log') {
    // warn the users that their desired scaling type couldn't be used
    // console.warn('Negative values present in data. Defaulting to linear scale: ', minValue);
  }

  return ['linear', (0, _d3Scale.scaleLinear)().range([254, 0]).domain([minValue, maxValue])];
}

// Configs


// Utils

var TiledPixiTrack = function (_PixiTrack) {
  (0, _inherits3['default'])(TiledPixiTrack, _PixiTrack);

  /**
   * A track that must pull remote tiles
   *
   * @param (PIXI.scene) scene A PIXI.js scene to draw everything to.
   * @param (Object) dataConfig: A data source. Usually a
   *  ``{{server: 'x/api/v1/', tilesetUuid: 'y'}}`` Object.
   * @param {Object} handleTilesetInfoReceived: A callback to do something once once the tileset
   *  info is received. Usually it registers some information about the tileset with its
   * definition
   * @param {Object} options The track's options
   * @param {function} animate A function to redraw this track. Typically called when an
   *  asynchronous event occurs (i.e. tiles loaded)
   * @param {function} onValueScaleChanged The range of values has changed so we need to inform
   *  the higher ups that the value scale has changed. Only occurs on tracks with ``dense`` data.
   */
  function TiledPixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, TiledPixiTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (TiledPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(TiledPixiTrack)).call(this, context, options));

    var pubSub = context.pubSub,
        dataConfig = context.dataConfig,
        handleTilesetInfoReceived = context.handleTilesetInfoReceived,
        animate = context.animate,
        onValueScaleChanged = context.onValueScaleChanged;

    // keep track of which render we're on so that we save ourselves
    // rerendering all rendering in the same version will have the same
    // scaling so tiles rendered in the same version will have the same
    // output. Mostly useful for heatmap tiles.

    _this.renderVersion = 1;

    // the tiles which should be visible (although they're not necessarily fetched)
    _this.visibleTiles = new _set2['default']();
    _this.visibleTileIds = new _set2['default']();

    // keep track of tiles that are currently being rendered
    _this.renderingTiles = new _set2['default']();

    // the tiles we already have requests out for
    _this.fetching = new _set2['default']();
    _this.scale = {};

    // tiles we have fetched and ready to be rendered
    _this.fetchedTiles = {};

    // the graphics that have already been drawn for this track
    _this.tileGraphics = {};

    _this.maxZoom = 0;
    _this.medianVisibleValue = null;

    _this.backgroundTaskScheduler = _backgroundTaskScheduler2['default'];

    // If the browser supports requestIdleCallback we use continuous
    // instead of tile based scaling
    _this.continuousScaling = 'requestIdleCallback' in window;

    _this.valueScaleMin = null;
    _this.fixedValueScaleMin = null;
    _this.valueScaleMax = null;
    _this.fixedValueScaleMax = null;

    _this.listeners = {};

    _this.pubSub = pubSub;
    _this.animate = animate;
    _this.onValueScaleChanged = onValueScaleChanged;

    // store the server and tileset uid so they can be used in draw()
    // if the tileset info is not found
    _this.prevValueScale = null;

    if (!context.dataFetcher) {
      _this.dataFetcher = new _DataFetcher2['default'](dataConfig, _this.pubSub);
    } else {
      _this.dataFetcher = context.dataFetcher;
    }

    // To indicate that this track is requiring a tileset info
    _this.tilesetInfo = null;
    _this.uuid = _slugid2['default'].nice();

    // this needs to be above the tilesetInfo() call because if that
    // executes first, the call to draw() will complain that this text
    // doesn't exist
    _this.trackNotFoundText = new _configs.GLOBALS.PIXI.Text('', {
      fontSize: '12px',
      fontFamily: 'Arial',
      fill: 'black'
    });

    _this.pLabel.addChild(_this.trackNotFoundText);

    _this.refreshTilesDebounced = (0, _utils.throttleAndDebounce)(_this.refreshTiles.bind(_this), _configs.ZOOM_DEBOUNCE, _configs.ZOOM_DEBOUNCE);

    _this.dataFetcher.tilesetInfo(function (tilesetInfo, tilesetUid) {
      _this.tilesetInfo = tilesetInfo;
      // If the dataConfig contained a fileUrl, then
      // we need to update the tilesetUid based
      // on the registration of the fileUrl.
      if (!_this.dataFetcher.dataConfig.tilesetUid) {
        _this.dataFetcher.dataConfig.tilesetUid = tilesetUid;
      }

      _this.tilesetUid = _this.dataFetcher.dataConfig.tilesetUid;
      _this.server = _this.dataFetcher.dataConfig.server || 'unknown';

      if (_this.tilesetInfo.chromsizes) {
        _this.chromInfo = (0, _utils.parseChromsizesRows)(_this.tilesetInfo.chromsizes);
      }

      if ('error' in _this.tilesetInfo) {
        // no tileset info for this track
        console.warn('Error retrieving tilesetInfo:', dataConfig, _this.tilesetInfo.error);

        // Fritz: Not sure why it's reset
        // this.trackNotFoundText = '';
        _this.tilesetInfo = null;

        _this.setError(_this.tilesetInfo.error);
        return;
      }

      if (_this.tilesetInfo.resolutions) {
        _this.maxZoom = _this.tilesetInfo.resolutions.length;
      } else {
        _this.maxZoom = +_this.tilesetInfo.max_zoom;
      }

      if (_this.options && _this.options.maxZoom) {
        if (_this.options.maxZoom >= 0) {
          _this.maxZoom = Math.min(_this.options.maxZoom, _this.maxZoom);
        } else {
          console.error('Invalid maxZoom on track:', _this);
        }
      }

      _this.refreshTiles();

      if (handleTilesetInfoReceived) handleTilesetInfoReceived(tilesetInfo);

      if (!_this.options) _this.options = {};

      _this.options.name = _this.options.name || tilesetInfo.name;

      _this.checkValueScaleLimits();

      _this.draw();
      _this.drawLabel(); // draw the label so that the current resolution is displayed
      _this.animate();
    });
    return _this;
  }

  (0, _createClass3['default'])(TiledPixiTrack, [{
    key: 'setError',
    value: function () {
      function setError(error) {
        this.errorTextText = error;
        this.draw();
        this.animate();
      }

      return setError;
    }()
  }, {
    key: 'setFixedValueScaleMin',
    value: function () {
      function setFixedValueScaleMin(value) {
        if (!(0, _isNan2['default'])(+value)) this.fixedValueScaleMin = +value;else this.fixedValueScaleMin = null;
      }

      return setFixedValueScaleMin;
    }()
  }, {
    key: 'setFixedValueScaleMax',
    value: function () {
      function setFixedValueScaleMax(value) {
        if (!(0, _isNan2['default'])(+value)) this.fixedValueScaleMax = +value;else this.fixedValueScaleMax = null;
      }

      return setFixedValueScaleMax;
    }()
  }, {
    key: 'checkValueScaleLimits',
    value: function () {
      function checkValueScaleLimits() {
        this.valueScaleMin = typeof this.options.valueScaleMin !== 'undefined' ? +this.options.valueScaleMin : null;

        if (this.fixedValueScaleMin !== null) {
          this.valueScaleMin = this.fixedValueScaleMin;
        }

        this.valueScaleMax = typeof this.options.valueScaleMax !== 'undefined' ? +this.options.valueScaleMax : null;

        if (this.fixedValueScaleMax !== null) {
          this.valueScaleMax = this.fixedValueScaleMax;
        }
      }

      return checkValueScaleLimits;
    }()

    /**
     * Register an event listener for track events. Currently, the only supported
     * event is ``dataChanged``.
     *
     * @param {string} event The event to listen for
     * @param {function} callback The callback to call when the event occurs. The
     *  parameters for the event depend on the event called.
     *
     * @example
     *
     *  trackObj.on('dataChanged', (newData) => {
     *   console.log('newData:', newData)
     *  });
     */

  }, {
    key: 'on',
    value: function () {
      function on(event, callback) {
        if (!this.listeners[event]) {
          this.listeners[event] = [];
        }

        this.listeners[event].push(callback);
      }

      return on;
    }()
  }, {
    key: 'off',
    value: function () {
      function off(event, callback) {
        var id = this.listeners[event].indexOf(callback);
        if (id === -1 || id >= this.listeners[event].length) return;

        this.listeners[event].splice(id, 1);
      }

      return off;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options) {
        (0, _get3['default'])(TiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(TiledPixiTrack.prototype), 'rerender', this).call(this, options);

        this.renderVersion += 1;

        if (!this.tilesetInfo) {
          return;
        }

        this.checkValueScaleLimits();

        if (this.tilesetInfo.resolutions) {
          this.maxZoom = this.tilesetInfo.resolutions.length;
        } else {
          this.maxZoom = +this.tilesetInfo.max_zoom;
        }

        if (this.options && this.options.maxZoom) {
          if (this.options.maxZoom >= 0) {
            this.maxZoom = Math.min(this.options.maxZoom, this.maxZoom);
          } else {
            console.error('Invalid maxZoom on track:', this);
          }
        }
      }

      return rerender;
    }()

    /**
     * Return the set of ids of all tiles which are both visible and fetched.
     */

  }, {
    key: 'visibleAndFetchedIds',
    value: function () {
      function visibleAndFetchedIds() {
        var _this2 = this;

        return (0, _keys2['default'])(this.fetchedTiles).filter(function (x) {
          return _this2.visibleTileIds.has(x);
        });
      }

      return visibleAndFetchedIds;
    }()
  }, {
    key: 'visibleAndFetchedTiles',
    value: function () {
      function visibleAndFetchedTiles() {
        var _this3 = this;

        return this.visibleAndFetchedIds().map(function (x) {
          return _this3.fetchedTiles[x];
        });
      }

      return visibleAndFetchedTiles;
    }()

    /**
     * Set which tiles are visible right now.
     *
     * @param tiles: A set of tiles which will be considered the currently visible
     * tile positions.
     */

  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this4 = this;

        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this4.tileToLocalId(x),
            remoteId: _this4.tileToRemoteId(x),
            mirrored: x.mirrored
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.tileId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'removeOldTiles',
    value: function () {
      function removeOldTiles() {
        var _this5 = this;

        this.calculateVisibleTiles();

        // tiles that are fetched
        var fetchedTileIDs = new _set2['default']((0, _keys2['default'])(this.fetchedTiles));
        //
        // calculate which tiles are obsolete and remove them
        // fetchedTileID are remote ids
        var toRemove = [].concat((0, _toConsumableArray3['default'])(fetchedTileIDs)).filter(function (x) {
          return !_this5.visibleTileIds.has(x);
        });

        this.removeTiles(toRemove);
      }

      return removeOldTiles;
    }()
  }, {
    key: 'refreshTiles',
    value: function () {
      function refreshTiles() {
        var _this6 = this;

        if (!this.tilesetInfo) {
          return;
        }

        this.calculateVisibleTiles();

        // tiles that are fetched
        var fetchedTileIDs = new _set2['default']((0, _keys2['default'])(this.fetchedTiles));

        // fetch the tiles that should be visible but haven't been fetched
        // and aren't in the process of being fetched
        var toFetch = [].concat((0, _toConsumableArray3['default'])(this.visibleTiles)).filter(function (x) {
          return !_this6.fetching.has(x.remoteId) && !fetchedTileIDs.has(x.tileId);
        });

        for (var i = 0; i < toFetch.length; i++) {
          this.fetching.add(toFetch[i].remoteId);
        }

        this.removeOldTiles();
        this.fetchNewTiles(toFetch);
      }

      return refreshTiles;
    }()
  }, {
    key: 'parentInFetched',
    value: function () {
      function parentInFetched(tile) {
        var uid = tile.tileData.tilesetUid;
        var zl = tile.tileData.zoomLevel;
        var pos = tile.tileData.tilePos;

        while (zl > 0) {
          zl -= 1;
          pos = pos.map(function (x) {
            return Math.floor(x / 2);
          });

          var parentId = String(uid) + '.' + String(zl) + '.' + String(pos.join('.'));
          if (parentId in this.fetchedTiles) {
            return true;
          }
        }

        return false;
      }

      return parentInFetched;
    }()
  }, {
    key: 'parentTileId',
    value: function () {
      function parentTileId(tile) {
        var parentZoomLevel = tile.tileData.zoomLevel - 1;
        var parentPos = tile.tileData.tilePos.map(function (x) {
          return Math.floor(x / 2);
        });
        var parentUid = tile.tileData.tilesetUid;

        return String(parentUid) + '.' + parentZoomLevel + '.' + String(parentPos.join('.'));
      }

      return parentTileId;
    }()

    /**
     * Remove obsolete tiles
     *
     * @param toRemoveIds: An array of tile ids to remove from the list of fetched tiles.
     */

  }, {
    key: 'removeTiles',
    value: function () {
      function removeTiles(toRemoveIds) {
        var _this7 = this;

        // if there's nothing to remove, don't bother doing anything
        if (!toRemoveIds.length || !this.areAllVisibleTilesLoaded() || this.renderingTiles.size) {
          return;
        }

        toRemoveIds.forEach(function (x) {
          var tileIdStr = x;
          _this7.destroyTile(_this7.fetchedTiles[tileIdStr]);

          if (tileIdStr in _this7.tileGraphics) {
            _this7.pMain.removeChild(_this7.tileGraphics[tileIdStr]);
            delete _this7.tileGraphics[tileIdStr];
          }

          delete _this7.fetchedTiles[tileIdStr];
        });

        this.synchronizeTilesAndGraphics();
        this.draw();
      }

      return removeTiles;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        var k = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
        var tx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
        var ty = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;

        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTilesDebounced();

        this.pMobile.position.x = tx;
        this.pMobile.position.y = this.position[1];

        this.pMobile.scale.x = k;
        this.pMobile.scale.y = 1;
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(TiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(TiledPixiTrack.prototype), 'setPosition', this).call(this, newPosition);

        // this.draw();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(TiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(TiledPixiTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        // this.draw();
      }

      return setDimensions;
    }()

    /**
     * Check to see if all the visible tiles are loaded.
     *
     * If they are, remove all other tiles.
     */

  }, {
    key: 'areAllVisibleTilesLoaded',
    value: function () {
      function areAllVisibleTilesLoaded() {
        // tiles that are fetched
        var fetchedTileIDs = new _set2['default']((0, _keys2['default'])(this.fetchedTiles));

        var visibleTileIdsList = [].concat((0, _toConsumableArray3['default'])(this.visibleTileIds));

        for (var i = 0; i < visibleTileIdsList.length; i++) {
          if (!fetchedTileIDs.has(visibleTileIdsList[i])) {
            return false;
          }
        }

        return true;
      }

      return areAllVisibleTilesLoaded;
    }()

    /**
     * Function is called when all tiles that should be visible have
     * been received.
     */

  }, {
    key: 'allTilesLoaded',
    value: function () {
      function allTilesLoaded() {}

      return allTilesLoaded;
    }()
  }, {
    key: 'minValue',
    value: function () {
      function minValue(_) {
        if (_) {
          this.scale.minValue = _;
          return this;
        }
        return this.valueScaleMin !== null ? this.valueScaleMin : this.scale.minValue;
      }

      return minValue;
    }()
  }, {
    key: 'maxValue',
    value: function () {
      function maxValue(_) {
        if (_) {
          this.scale.maxValue = _;
          return this;
        }
        return this.valueScaleMax !== null ? this.valueScaleMax : this.scale.maxValue;
      }

      return maxValue;
    }()
  }, {
    key: 'minRawValue',
    value: function () {
      function minRawValue() {
        // this is the minimum value from all the tiles that
        // hasn't been externally modified by locked scales
        return this.scale.minRawValue;
      }

      return minRawValue;
    }()
  }, {
    key: 'maxRawValue',
    value: function () {
      function maxRawValue() {
        // this is the maximum value from all the tiles that
        // hasn't been externally modified by locked scales
        return this.scale.maxRawValue;
      }

      return maxRawValue;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile() /* tile */{
        // create the tile
        // should be overwritten by child classes
        this.scale.minRawValue = this.continuousScaling ? this.minVisibleValue() : this.minVisibleValueInTiles();
        this.scale.maxRawValue = this.continuousScaling ? this.maxVisibleValue() : this.maxVisibleValueInTiles();

        this.scale.minValue = this.scale.minRawValue;
        this.scale.maxValue = this.scale.maxRawValue;
      }

      return initTile;
    }()
  }, {
    key: 'updateTile',
    value: function () {
      function updateTile() /* tile */{}

      return updateTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile() /* tile */{
        // remove all data structures needed to draw this tile
      }

      return destroyTile;
    }()
  }, {
    key: 'addMissingGraphics',
    value: function () {
      function addMissingGraphics() {
        /**
         * Add graphics for tiles that have no graphics
         */
        var fetchedTileIDs = (0, _keys2['default'])(this.fetchedTiles);
        this.renderVersion += 1;

        for (var i = 0; i < fetchedTileIDs.length; i++) {
          if (!(fetchedTileIDs[i] in this.tileGraphics)) {
            // console.trace('adding:', fetchedTileIDs[i]);

            var newGraphics = new _configs.GLOBALS.PIXI.Graphics();
            this.pMain.addChild(newGraphics);

            this.fetchedTiles[fetchedTileIDs[i]].graphics = newGraphics;
            this.initTile(this.fetchedTiles[fetchedTileIDs[i]]);

            this.tileGraphics[fetchedTileIDs[i]] = newGraphics;
          }
        }

        /*
            if (added)
                this.draw();
            */
      }

      return addMissingGraphics;
    }()

    /**
     * Change the graphics for existing tiles
     */

  }, {
    key: 'updateExistingGraphics',
    value: function () {
      function updateExistingGraphics() {
        var fetchedTileIDs = (0, _keys2['default'])(this.fetchedTiles);

        for (var i = 0; i < fetchedTileIDs.length; i++) {
          var tile = this.fetchedTiles[fetchedTileIDs[i]];

          this.updateTile(tile);
        }
      }

      return updateExistingGraphics;
    }()
  }, {
    key: 'synchronizeTilesAndGraphics',
    value: function () {
      function synchronizeTilesAndGraphics() {
        /**
         * Make sure that we have a one to one mapping between tiles
         * and graphics objects
         *
         */

        // keep track of which tiles are visible at the moment
        this.addMissingGraphics();
        this.removeOldTiles();
        this.updateExistingGraphics();

        if (this.listeners.dataChanged) {
          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = undefined;

          try {
            for (var _iterator = (0, _getIterator3['default'])(this.listeners.dataChanged), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              var callback = _step.value;

              callback(this.visibleAndFetchedTiles().map(function (x) {
                return x.tileData;
              }));
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator['return']) {
                _iterator['return']();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }
        }
      }

      return synchronizeTilesAndGraphics;
    }()
  }, {
    key: 'loadTileData',
    value: function () {
      function loadTileData(tile, dataLoader) {
        /**
         * Extract drawable data from a tile loaded by a generic tile loader
         *
         * @param tile: A tile returned by a TiledArea.
         * @param dataLoader: A function for extracting drawable data from a tile. This
         *                    usually means differentiating the between dense and sparse
         *                    tiles and putting the data into an array.
         */

        // see if the data is already cached
        var loadedTileData = this.lruCache.get(tile.tileId);

        // if not, load it and put it in the cache
        if (!loadedTileData) {
          loadedTileData = dataLoader(tile.data, tile.type);
          this.lruCache.put(tile.tileId, loadedTileData);
        }

        return loadedTileData;
      }

      return loadTileData;
    }()
  }, {
    key: 'fetchNewTiles',
    value: function () {
      function fetchNewTiles(toFetch) {
        if (toFetch.length > 0) {
          var toFetchList = [].concat((0, _toConsumableArray3['default'])(new _set2['default'](toFetch.map(function (x) {
            return x.remoteId;
          }))));

          this.dataFetcher.fetchTilesDebounced(this.receivedTiles.bind(this), toFetchList);
        }
      }

      return fetchNewTiles;
    }()

    /**
     * We've gotten a bunch of tiles from the server in
     * response to a request from fetchTiles.
     */

  }, {
    key: 'receivedTiles',
    value: function () {
      function receivedTiles(loadedTiles) {
        var _this8 = this;

        var _loop = function () {
          function _loop(i) {
            var tileId = _this8.visibleTiles[i].tileId;


            if (!loadedTiles[_this8.visibleTiles[i].remoteId]) return 'continue';

            if (_this8.visibleTiles[i].remoteId in loadedTiles) {
              if (!(tileId in _this8.fetchedTiles)) {
                // this tile may have graphics associated with it
                _this8.fetchedTiles[tileId] = _this8.visibleTiles[i];
              }

              // Fritz: Store a shallow copy. If necessary we perform a deep copy of
              // the dense data in `tile-proxy.js :: tileDataToPixData()`
              // Somehow 2d rectangular domain tiles do not come in the flavor of an
              // object but an object array...
              if (Array.isArray(loadedTiles[_this8.visibleTiles[i].remoteId])) {
                var tileData = loadedTiles[_this8.visibleTiles[i].remoteId];
                _this8.fetchedTiles[tileId].tileData = [].concat((0, _toConsumableArray3['default'])(tileData));
                // Fritz: this is sooo hacky... we should really not use object arrays
                (0, _keys2['default'])(tileData).filter(function (key) {
                  return (0, _isNan2['default'])(+key);
                }).forEach(function (key) {
                  _this8.fetchedTiles[tileId].tileData[key] = tileData[key];
                });
              } else {
                _this8.fetchedTiles[tileId].tileData = (0, _extends3['default'])({}, loadedTiles[_this8.visibleTiles[i].remoteId]);
              }

              if (_this8.fetchedTiles[tileId].tileData.error) {
                console.warn('Error in loaded tile', tileId, _this8.fetchedTiles[tileId].tileData);
              }
            }
          }

          return _loop;
        }();

        for (var i = 0; i < this.visibleTiles.length; i++) {
          var _ret = _loop(i);

          if (_ret === 'continue') continue;
        }

        // const fetchedTileIDs = new Set(Object.keys(this.fetchedTiles));

        for (var key in loadedTiles) {
          if (loadedTiles[key]) {
            var _tileId = loadedTiles[key].tilePositionId;

            if (this.fetching.has(_tileId)) {
              this.fetching['delete'](_tileId);
            }
          }
        }

        /*
         * Mainly called to remove old unnecessary tiles
         */
        this.synchronizeTilesAndGraphics();

        // we need to draw when we receive new data
        this.draw();
        this.drawLabel(); // update the current zoom level

        // Let HiGlass know we need to re-render
        // check if the value scale has changed
        if (this.valueScale) {
          if (!this.prevValueScale || (0, _stringify2['default'])(this.valueScale.domain()) !== (0, _stringify2['default'])(this.prevValueScale.domain())) {
            this.prevValueScale = this.valueScale.copy();

            if (this.onValueScaleChanged) {
              // this is used to synchronize tracks with locked value scales
              this.onValueScaleChanged();
            }
          }
        }

        this.animate();

        // 1. Check if all visible tiles are loaded
        // 2. If `true` then send out event
        if (this.areAllVisibleTilesLoaded()) {
          if (this.pubSub) {
            this.pubSub.publish('TiledPixiTrack.tilesLoaded', { uuid: this.uuid });
          }
        }
      }

      return receivedTiles;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var _this9 = this;

        if (this.delayDrawing) return;

        if (!this.tilesetInfo) {
          if (this.dataFetcher.tilesetInfoLoading) {
            this.trackNotFoundText.text = 'Loading...';
          } else {
            this.trackNotFoundText.text = 'Tileset info not found. Server: [' + String(this.server) + '] tilesetUid: [' + String(this.tilesetUid) + ']';
          }

          var _position = (0, _slicedToArray3['default'])(this.position, 2);

          this.trackNotFoundText.x = _position[0];
          this.trackNotFoundText.y = _position[1];


          if (this.flipText) {
            this.trackNotFoundText.anchor.x = 1;
            this.trackNotFoundText.scale.x = -1;
          }

          this.trackNotFoundText.visible = true;
        } else {
          this.trackNotFoundText.visible = false;
        }

        if (this.pubSub) {
          this.pubSub.publish('TiledPixiTrack.tilesDrawnStart', {
            uuid: this.uuid
          });
        }
        var errors = (0, _values2['default'])(this.fetchedTiles).map(function (x) {
          return x.tileData && x.tileData.error && String(x.tileId) + ': ' + String(x.tileData.error);
        }).filter(function (x) {
          return x;
        });

        if (errors.length) {
          this.errorTextText = errors.join('\n');
        } else {
          this.errorTextText = '';
        }

        (0, _get3['default'])(TiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(TiledPixiTrack.prototype), 'draw', this).call(this);

        (0, _keys2['default'])(this.fetchedTiles).forEach(function (tilesetUid) {
          _this9.drawTile(_this9.fetchedTiles[tilesetUid]);
        });
        // console.log('errors:', errors);

        if (this.pubSub) {
          this.pubSub.publish('TiledPixiTrack.tilesDrawnEnd', { uuid: this.uuid });
        }
      }

      return draw;
    }()

    /**
     * Draw a tile on some graphics
     */

  }, {
    key: 'drawTile',
    value: function () {
      function drawTile() /* tileData, graphics */{}

      return drawTile;
    }()
  }, {
    key: 'calculateMedianVisibleValue',
    value: function () {
      function calculateMedianVisibleValue() {
        var _ref,
            _this10 = this;

        if (this.areAllVisibleTilesLoaded()) {
          this.allTilesLoaded();
        }

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var values = (_ref = []).concat.apply(_ref, (0, _toConsumableArray3['default'])(visibleAndFetchedIds.filter(function (x) {
          return _this10.fetchedTiles[x].tileData.dense;
        }).map(function (x) {
          return (0, _from2['default'])(_this10.fetchedTiles[x].tileData.dense);
        }))).filter(function (x) {
          return x > 0;
        });

        this.medianVisibleValue = (0, _d3Array.median)(values);
        return this.medianVisibleValue;
      }

      return calculateMedianVisibleValue;
    }()
  }, {
    key: 'allVisibleValues',
    value: function () {
      function allVisibleValues() {
        var _ref2,
            _this11 = this;

        return (_ref2 = []).concat.apply(_ref2, (0, _toConsumableArray3['default'])(this.visibleAndFetchedIds().map(function (x) {
          return (0, _from2['default'])(_this11.fetchedTiles[x].tileData.dense);
        })));
      }

      return allVisibleValues;
    }()

    // Should be overwriten by child clases to get the true minimal
    // visible value in the currently viewed area

  }, {
    key: 'minVisibleValue',
    value: function () {
      function minVisibleValue() {
        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        return this.minVisibleValueInTiles(ignoreFixedScale);
      }

      return minVisibleValue;
    }()
  }, {
    key: 'minVisibleValueInTiles',
    value: function () {
      function minVisibleValueInTiles() {
        var _this12 = this;

        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        // Get minimum in currently visible tiles
        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var min = Math.min.apply(Math, (0, _toConsumableArray3['default'])(visibleAndFetchedIds.map(function (x) {
          return _this12.fetchedTiles[x].tileData.minNonZero;
        })));

        // if there's no data, use null
        if (min === _maxSafeInteger2['default']) {
          min = null;
        }

        if (ignoreFixedScale) return min;

        return this.valueScaleMin !== null ? this.valueScaleMin : min;
      }

      return minVisibleValueInTiles;
    }()

    // Should be overwriten by child clases to get the true maximal
    // visible value in the currently viewed area

  }, {
    key: 'maxVisibleValue',
    value: function () {
      function maxVisibleValue() {
        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        return this.maxVisibleValueInTiles(ignoreFixedScale);
      }

      return maxVisibleValue;
    }()
  }, {
    key: 'maxVisibleValueInTiles',
    value: function () {
      function maxVisibleValueInTiles() {
        var _this13 = this;

        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        // Get maximum in currently visible tiles
        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var max = Math.max.apply(Math, (0, _toConsumableArray3['default'])(visibleAndFetchedIds.map(function (x) {
          return _this13.fetchedTiles[x].tileData.maxNonZero;
        })));

        // if there's no data, use null
        if (max === _minSafeInteger2['default']) {
          max = null;
        }

        if (ignoreFixedScale) return max;

        return this.valueScaleMax !== null ? this.valueScaleMax : max;
      }

      return maxVisibleValueInTiles;
    }()
  }, {
    key: 'makeValueScale',
    value: function () {
      function makeValueScale(minValue, medianValue, maxValue, inMargin) {
        /*
         * Create a value scale that will be used to position values
         * along the y axis.
         *
         * Parameters
         * ----------
         *  minValue: number
         *    The minimum value of the data
         *  medianValue: number
         *    The median value of the data. Potentially used for adding
         *    a pseudocount
         *  maxValue: number
         *    The maximum value of the data
         *  margin: number
         *    A number of pixels to be left free on the top and bottom
         *    of the track. For example if the glyphs have a certain
         *    width and we want all of them to fit into the space.
         *
         * Returns
         * -------
         *  valueScale: d3.scale
         *      A d3 value scale
         */
        var valueScale = null;
        var offsetValue = 0;

        var margin = inMargin;

        if (margin === null || typeof margin === 'undefined') {
          margin = 6; // set a default value
        }

        var minDimension = Math.min(this.dimensions[1] - margin, margin);
        var maxDimension = Math.max(this.dimensions[1] - margin, margin);

        if (this.dimensions[1] - margin < margin) {
          // if the track becomes smaller than the margins, then just draw a flat
          // line in the center
          minDimension = this.dimensions[1] / 2;
          maxDimension = this.dimensions[1] / 2;
        }

        if (this.options.valueScaling === 'log') {
          offsetValue = medianValue;

          if (!offsetValue) {
            offsetValue = minValue;
          }

          valueScale = (0, _d3Scale.scaleLog)()
          // .base(Math.E)
          .domain([offsetValue, maxValue + offsetValue])
          // .domain([offsetValue, this.maxValue()])
          .range([minDimension, maxDimension]);

          // pseudocount = offsetValue;
        } else if (this.options.valueScaling === 'quantile') {
          var start = this.dimensions[1] - margin;
          var end = margin;
          var quantScale = (0, _d3Scale.scaleQuantile)().domain(this.allVisibleValues()).range((0, _d3Array.range)(start, end, (end - start) / 256));
          quantScale.ticks = function (n) {
            return (0, _d3Array.ticks)(start, end, n);
          };

          return [quantScale, 0];
        } else if (this.options.valueScaling === 'setquantile') {
          var _start = this.dimensions[1] - margin;
          var _end = margin;
          var s = new _set2['default'](this.allVisibleValues());
          var _quantScale = (0, _d3Scale.scaleQuantile)().domain([].concat((0, _toConsumableArray3['default'])(s))).range((0, _d3Array.range)(_start, _end, (_end - _start) / 256));
          _quantScale.ticks = function (n) {
            return (0, _d3Array.ticks)(_start, _end, n);
          };

          return [_quantScale, 0];
        } else {
          // linear scale
          valueScale = (0, _d3Scale.scaleLinear)().domain([minValue, maxValue]).range([maxDimension, minDimension]);
        }

        return [valueScale, offsetValue];
      }

      return makeValueScale;
    }()
  }]);
  return TiledPixiTrack;
}(_PixiTrack3['default']);

exports['default'] = TiledPixiTrack;

/***/ }),
/* 80 */
/***/ (function(module, exports, __nested_webpack_require_352025__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_352025__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_352025__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_352025__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_352025__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_352025__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Selection = __nested_webpack_require_352025__(0);

var _slugid = __nested_webpack_require_352025__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _Track2 = __nested_webpack_require_352025__(177);

var _Track3 = _interopRequireDefault(_Track2);

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

var SVGTrack = function (_Track) {
  (0, _inherits3['default'])(SVGTrack, _Track);

  function SVGTrack(context, options) {
    (0, _classCallCheck3['default'])(this, SVGTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (SVGTrack.__proto__ || (0, _getPrototypeOf2['default'])(SVGTrack)).call(this, context, options));

    var svgElement = context.svgElement;
    /**
     * Create a new SVG track. It will contain a g element
     * that maintains all of its element.
     */

    _this.gMain = (0, _d3Selection.select)(svgElement).append('g');
    _this.clipUid = _slugid2['default'].nice();

    _this.clipRect = _this.gMain.append('clipPath').attr('id', 'track-bounds-' + String(_this.clipUid)).append('rect');

    _this.gMain.attr('clip-path', 'url(#track-bounds-' + String(_this.clipUid) + ')');
    return _this;
  }

  (0, _createClass3['default'])(SVGTrack, [{
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        this.position = newPosition;

        this.gMain.attr('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');
        this.draw();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        this.dimensions = newDimensions;

        this._xScale.range([0, this.dimensions[0]]);
        this._yScale.range([0, this.dimensions[1]]);

        if (newDimensions[0] >= 0 && newDimensions[1] >= 0) {
          this.clipRect.attr('width', newDimensions[0]);
          this.clipRect.attr('height', newDimensions[1]);
        } else {
          this.clipRect.attr('width', 0);
          this.clipRect.attr('height', 0);
        }

        this.draw();
      }

      return setDimensions;
    }()
  }, {
    key: 'remove',
    value: function () {
      function remove() {
        this.gMain.remove();
        this.gMain = null;
      }

      return remove;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        return this;
      }

      return draw;
    }()
  }]);
  return SVGTrack;
}(_Track3['default']);

exports['default'] = SVGTrack;

/***/ }),
/* 81 */
/***/ (function(module, exports, __nested_webpack_require_355277__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.mix = exports.Mixin = exports.BareMixin = exports.HasInstance = exports.DeDupe = exports.Cached = exports.wrap = exports.hasMixin = exports.isApplicationOf = exports.apply = exports.unwrap = undefined;

var _classCallCheck2 = __nested_webpack_require_355277__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_355277__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _defineProperty = __nested_webpack_require_355277__(131);

var _defineProperty2 = _interopRequireDefault(_defineProperty);

var _hasInstance = __nested_webpack_require_355277__(636);

var _hasInstance2 = _interopRequireDefault(_hasInstance);

var _symbol = __nested_webpack_require_355277__(225);

var _symbol2 = _interopRequireDefault(_symbol);

var _map = __nested_webpack_require_355277__(639);

var _map2 = _interopRequireDefault(_map);

var _setPrototypeOf = __nested_webpack_require_355277__(331);

var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);

var _getPrototypeOf = __nested_webpack_require_355277__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

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

// used by apply() and isApplicationOf()
var _appliedMixin = '__mixwith_appliedMixin';
// used by wrap() and unwrap()
var _wrappedMixin = '__mixwith_wrappedMixin';

/**
 * A function that returns a subclass of its argument.
 *
 * @example
 * const M = (superclass) => class extends superclass {
 *   getMessage() {
 *     return "Hello";
 *   }
 * }
 *
 * @typedef {Function} MixinFunction
 * @param {Function} superclass
 * @return {Function} A subclass of `superclass`
 */

/**
 * Unwraps the function `wrapper` to return the original function wrapped by
 * one or more calls to `wrap`. Returns `wrapper` if it's not a wrapped
 * function.
 *
 * @function
 * @param {MixinFunction} wrapper A wrapped mixin produced by {@link wrap}
 * @return {MixinFunction} The originally wrapped mixin
 */
var unwrap = exports.unwrap = function unwrap(wrapper) {
  return wrapper[_wrappedMixin] || wrapper;
};

/**
 * Applies `mixin` to `superclass`.
 *
 * `apply` stores a reference from the mixin application to the unwrapped mixin
 * to make `isApplicationOf` and `hasMixin` work.
 *
 * This function is usefull for mixin wrappers that want to automatically enable
 * {@link hasMixin} support.
 *
 * @example
 * const Applier = (mixin) => wrap(mixin, (superclass) => apply(superclass, mixin));
 *
 * // M now works with `hasMixin` and `isApplicationOf`
 * const M = Applier((superclass) => class extends superclass {});
 *
 * class C extends M(Object) {}
 * let i = new C();
 * hasMixin(i, M); // true
 *
 * @function
 * @param {Function} superclass A class or constructor function
 * @param {MixinFunction} mixin The mixin to apply
 * @return {Function} A subclass of `superclass` produced by `mixin`
 */
var apply = exports.apply = function apply(superclass, mixin) {
  var application = mixin(superclass);
  application.prototype[_appliedMixin] = unwrap(mixin);
  return application;
};

/**
 * Returns `true` iff `proto` is a prototype created by the application of
 * `mixin` to a superclass.
 *
 * `isApplicationOf` works by checking that `proto` has a reference to `mixin`
 * as created by `apply`.
 *
 * @function
 * @param {Object} proto A prototype object created by {@link apply}.
 * @param {MixinFunction} mixin A mixin function used with {@link apply}.
 * @return {boolean} whether `proto` is a prototype created by the application of
 * `mixin` to a superclass
 */
var isApplicationOf = exports.isApplicationOf = function isApplicationOf(proto, mixin) {
  return proto.hasOwnProperty(_appliedMixin) && proto[_appliedMixin] === unwrap(mixin);
};

/**
 * Returns `true` iff `o` has an application of `mixin` on its prototype
 * chain.
 *
 * @function
 * @param {Object} o An object
 * @param {MixinFunction} mixin A mixin applied with {@link apply}
 * @return {boolean} whether `o` has an application of `mixin` on its prototype
 * chain
 */
var hasMixin = exports.hasMixin = function hasMixin(o, mixin) {
  while (o !== null) {
    if (isApplicationOf(o, mixin)) return true;
    o = (0, _getPrototypeOf2['default'])(o);
  }
  return false;
};

/**
 * Sets up the function `mixin` to be wrapped by the function `wrapper`, while
 * allowing properties on `mixin` to be available via `wrapper`, and allowing
 * `wrapper` to be unwrapped to get to the original function.
 *
 * `wrap` does two things:
 *   1. Sets the prototype of `mixin` to `wrapper` so that properties set on
 *      `mixin` inherited by `wrapper`.
 *   2. Sets a special property on `mixin` that points back to `mixin` so that
 *      it can be retreived from `wrapper`
 *
 * @function
 * @param {MixinFunction} mixin A mixin function
 * @param {MixinFunction} wrapper A function that wraps {@link mixin}
 * @return {MixinFunction} `wrapper`
 */
var wrap = exports.wrap = function wrap(mixin, wrapper) {
  (0, _setPrototypeOf2['default'])(wrapper, mixin);
  if (!mixin[_wrappedMixin]) {
    mixin[_wrappedMixin] = mixin;
  }
  return wrapper;
};

var _cachedApplications = '__mixwith_cachedApplications';

/**
 * Decorates `mixin` so that it caches its applications. When applied multiple
 * times to the same superclass, `mixin` will only create one subclass, memoize
 * it and return it for each application.
 *
 * Note: If `mixin` somehow stores properties its classes constructor (static
 * properties), or on its classes prototype, it will be shared across all
 * applications of `mixin` to a super class. It's reccomended that `mixin` only
 * access instance state.
 *
 * @function
 * @param {MixinFunction} mixin The mixin to wrap with caching behavior
 * @return {MixinFunction} a new mixin function
 */
var Cached = exports.Cached = function Cached(mixin) {
  return wrap(mixin, function (superclass) {
    // Get or create a symbol used to look up a previous application of mixin
    // to the class. This symbol is unique per mixin definition, so a class will have N
    // applicationRefs if it has had N mixins applied to it. A mixin will have
    // exactly one _cachedApplicationRef used to store its applications.

    var cachedApplications = superclass[_cachedApplications];
    if (!cachedApplications) {
      superclass[_cachedApplications] = new _map2['default']();
      cachedApplications = superclass[_cachedApplications];
    }

    var application = cachedApplications.get(mixin);
    if (!application) {
      application = mixin(superclass);
      cachedApplications.set(mixin, application);
    }

    return application;
  });
};

/**
 * Decorates `mixin` so that it only applies if it's not already on the
 * prototype chain.
 *
 * @function
 * @param {MixinFunction} mixin The mixin to wrap with deduplication behavior
 * @return {MixinFunction} a new mixin function
 */
var DeDupe = exports.DeDupe = function DeDupe(mixin) {
  return wrap(mixin, function (superclass) {
    return hasMixin(superclass.prototype, mixin) ? superclass : mixin(superclass);
  });
};

/**
 * Adds [Symbol.hasInstance] (ES2015 custom instanceof support) to `mixin`.
 *
 * @function
 * @param {MixinFunction} mixin The mixin to add [Symbol.hasInstance] to
 * @return {MixinFunction} the given mixin function
 */
var HasInstance = exports.HasInstance = function HasInstance(mixin) {
  if (_symbol2['default'] && _hasInstance2['default'] && !mixin[_hasInstance2['default']]) {
    (0, _defineProperty2['default'])(mixin, _hasInstance2['default'], {
      value: function () {
        function value(o) {
          return hasMixin(o, mixin);
        }

        return value;
      }()
    });
  }
  return mixin;
};

/**
 * A basic mixin decorator that applies the mixin with {@link apply} so that it
 * can be used with {@link isApplicationOf}, {@link hasMixin} and the other
 * mixin decorator functions.
 *
 * @function
 * @param {MixinFunction} mixin The mixin to wrap
 * @return {MixinFunction} a new mixin function
 */
var BareMixin = exports.BareMixin = function BareMixin(mixin) {
  return wrap(mixin, function (s) {
    return apply(s, mixin);
  });
};

/**
 * Decorates a mixin function to add deduplication, application caching and
 * instanceof support.
 *
 * @function
 * @param {MixinFunction} mixin The mixin to wrap
 * @return {MixinFunction} a new mixin function
 */
var Mixin = exports.Mixin = function Mixin(mixin) {
  return DeDupe(Cached(BareMixin(mixin)));
};

var MixinBuilder = function () {
  function MixinBuilder(superclass) {
    (0, _classCallCheck3['default'])(this, MixinBuilder);

    this.superclass = superclass || function () {
      function _class() {
        (0, _classCallCheck3['default'])(this, _class);
      }

      return _class;
    }();
  }

  /**
   * Applies `mixins` in order to the superclass given to `mix()`.
   *
   * @param {Array.<Mixin>} mixins
   * @return {Function} a subclass of `superclass` with `mixins` applied
   */


  (0, _createClass3['default'])(MixinBuilder, [{
    key: 'with',
    value: function () {
      function _with() {
        for (var _len = arguments.length, mixins = Array(_len), _key = 0; _key < _len; _key++) {
          mixins[_key] = arguments[_key];
        }

        return mixins.reduce(function (c, m) {
          return m(c);
        }, this.superclass);
      }

      return _with;
    }()
  }]);
  return MixinBuilder;
}();

/**
 * A fluent interface to apply a list of mixins to a superclass.
 *
 * ```javascript
 * class X extends mix(Object).with(A, B, C) {}
 * ```
 *
 * The mixins are applied in order to the superclass, so the prototype chain
 * will be: X->C'->B'->A'->Object.
 *
 * This is purely a convenience function. The above example is equivalent to:
 *
 * ```javascript
 * class X extends C(B(A(Object))) {}
 * ```
 *
 * @function
 * @param {Function} [superclass=Object]
 * @return {MixinBuilder}
 */


var mix = exports.mix = function mix(superclass) {
  return new MixinBuilder(superclass);
};

/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";



var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
                (typeof Uint16Array !== 'undefined') &&
                (typeof Int32Array !== 'undefined');

function _has(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}

exports.assign = function (obj /*from1, from2, from3, ...*/) {
  var sources = Array.prototype.slice.call(arguments, 1);
  while (sources.length) {
    var source = sources.shift();
    if (!source) { continue; }

    if (typeof source !== 'object') {
      throw new TypeError(source + 'must be non-object');
    }

    for (var p in source) {
      if (_has(source, p)) {
        obj[p] = source[p];
      }
    }
  }

  return obj;
};


// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
  if (buf.length === size) { return buf; }
  if (buf.subarray) { return buf.subarray(0, size); }
  buf.length = size;
  return buf;
};


var fnTyped = {
  arraySet: function (dest, src, src_offs, len, dest_offs) {
    if (src.subarray && dest.subarray) {
      dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
      return;
    }
    // Fallback to ordinary array
    for (var i = 0; i < len; i++) {
      dest[dest_offs + i] = src[src_offs + i];
    }
  },
  // Join array of chunks to single array.
  flattenChunks: function (chunks) {
    var i, l, len, pos, chunk, result;

    // calculate data length
    len = 0;
    for (i = 0, l = chunks.length; i < l; i++) {
      len += chunks[i].length;
    }

    // join chunks
    result = new Uint8Array(len);
    pos = 0;
    for (i = 0, l = chunks.length; i < l; i++) {
      chunk = chunks[i];
      result.set(chunk, pos);
      pos += chunk.length;
    }

    return result;
  }
};

var fnUntyped = {
  arraySet: function (dest, src, src_offs, len, dest_offs) {
    for (var i = 0; i < len; i++) {
      dest[dest_offs + i] = src[src_offs + i];
    }
  },
  // Join array of chunks to single array.
  flattenChunks: function (chunks) {
    return [].concat.apply([], chunks);
  }
};


// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
  if (on) {
    exports.Buf8  = Uint8Array;
    exports.Buf16 = Uint16Array;
    exports.Buf32 = Int32Array;
    exports.assign(exports, fnTyped);
  } else {
    exports.Buf8  = Array;
    exports.Buf16 = Array;
    exports.Buf32 = Array;
    exports.assign(exports, fnUntyped);
  }
};

exports.setTyped(TYPED_OK);


/***/ }),
/* 83 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_367900__) {

"use strict";
__nested_webpack_require_367900__.r(__webpack_exports__);

// EXTERNAL MODULE: ../node_modules/d3-dispatch/src/index.js + 1 modules
var src = __nested_webpack_require_367900__(65);

// EXTERNAL MODULE: ../node_modules/d3-drag/src/index.js + 5 modules
var d3_drag_src = __nested_webpack_require_367900__(84);

// EXTERNAL MODULE: ../node_modules/d3-interpolate/src/index.js + 24 modules
var d3_interpolate_src = __nested_webpack_require_367900__(15);

// EXTERNAL MODULE: ../node_modules/d3-selection/src/index.js + 50 modules
var d3_selection_src = __nested_webpack_require_367900__(0);

// EXTERNAL MODULE: ../node_modules/d3-transition/src/index.js + 41 modules
var d3_transition_src = __nested_webpack_require_367900__(85);

// CONCATENATED MODULE: ../node_modules/d3-brush/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-brush/src/event.js
/* harmony default export */ var src_event = (function(target, type, selection) {
  this.target = target;
  this.type = type;
  this.selection = selection;
});

// CONCATENATED MODULE: ../node_modules/d3-brush/src/noevent.js


function nopropagation() {
  d3_selection_src["event"].stopImmediatePropagation();
}

/* harmony default export */ var noevent = (function() {
  d3_selection_src["event"].preventDefault();
  d3_selection_src["event"].stopImmediatePropagation();
});

// CONCATENATED MODULE: ../node_modules/d3-brush/src/brush.js









var MODE_DRAG = {name: "drag"},
    MODE_SPACE = {name: "space"},
    MODE_HANDLE = {name: "handle"},
    MODE_CENTER = {name: "center"};

var X = {
  name: "x",
  handles: ["e", "w"].map(brush_type),
  input: function(x, e) { return x && [[x[0], e[0][1]], [x[1], e[1][1]]]; },
  output: function(xy) { return xy && [xy[0][0], xy[1][0]]; }
};

var Y = {
  name: "y",
  handles: ["n", "s"].map(brush_type),
  input: function(y, e) { return y && [[e[0][0], y[0]], [e[1][0], y[1]]]; },
  output: function(xy) { return xy && [xy[0][1], xy[1][1]]; }
};

var XY = {
  name: "xy",
  handles: ["n", "e", "s", "w", "nw", "ne", "se", "sw"].map(brush_type),
  input: function(xy) { return xy; },
  output: function(xy) { return xy; }
};

var cursors = {
  overlay: "crosshair",
  selection: "move",
  n: "ns-resize",
  e: "ew-resize",
  s: "ns-resize",
  w: "ew-resize",
  nw: "nwse-resize",
  ne: "nesw-resize",
  se: "nwse-resize",
  sw: "nesw-resize"
};

var flipX = {
  e: "w",
  w: "e",
  nw: "ne",
  ne: "nw",
  se: "sw",
  sw: "se"
};

var flipY = {
  n: "s",
  s: "n",
  nw: "sw",
  ne: "se",
  se: "ne",
  sw: "nw"
};

var signsX = {
  overlay: +1,
  selection: +1,
  n: null,
  e: +1,
  s: null,
  w: -1,
  nw: -1,
  ne: +1,
  se: +1,
  sw: -1
};

var signsY = {
  overlay: +1,
  selection: +1,
  n: -1,
  e: null,
  s: +1,
  w: null,
  nw: -1,
  ne: -1,
  se: +1,
  sw: +1
};

function brush_type(t) {
  return {type: t};
}

// Ignore right-click, since that should open the context menu.
function defaultFilter() {
  return !d3_selection_src["event"].button;
}

function defaultExtent() {
  var svg = this.ownerSVGElement || this;
  return [[0, 0], [svg.width.baseVal.value, svg.height.baseVal.value]];
}

// Like d3.local, but with the name “__brush” rather than auto-generated.
function local(node) {
  while (!node.__brush) if (!(node = node.parentNode)) return;
  return node.__brush;
}

function empty(extent) {
  return extent[0][0] === extent[1][0]
      || extent[0][1] === extent[1][1];
}

function brushSelection(node) {
  var state = node.__brush;
  return state ? state.dim.output(state.selection) : null;
}

function brushX(noKeyModifiers, noNew, noEventBlocking) {
  return brush_brush(X, noKeyModifiers, noNew, noEventBlocking);
}

function brushY(noKeyModifiers, noNew, noEventBlocking) {
  return brush_brush(Y, noKeyModifiers, noNew, noEventBlocking);
}

/* harmony default export */ var src_brush = (function(noKeyModifiers, noNew, noEventBlocking) {
  return brush_brush(XY, noKeyModifiers, noNew, noEventBlocking);
});

function brush_brush(dim, noKeyModifiers, noNew, noEventBlocking) {
  var extent = defaultExtent,
      filter = defaultFilter,
      listeners = Object(src["a" /* dispatch */])(brush, "start", "brush", "end"),
      handleSize = 6,
      touchending;

  function brush(group) {
    var overlay = group
        .property("__brush", initialize)
      .selectAll(".overlay")
      .data([brush_type("overlay")]);

    overlay.enter().append("rect")
        .attr("class", "overlay")
        .attr("pointer-events", noEventBlocking ? "auto" : "all")
        .attr("cursor", noNew ? 'default' : cursors.overlay)
      .merge(overlay)
        .each(function() {
          var extent = local(this).extent;
          Object(d3_selection_src["select"])(this)
              .attr("x", extent[0][0])
              .attr("y", extent[0][1])
              .attr("width", extent[1][0] - extent[0][0])
              .attr("height", extent[1][1] - extent[0][1]);
        });

    group.selectAll(".selection")
      .data([brush_type("selection")])
      .enter()
      .append("rect")
        .attr("class", "selection")
        .attr("cursor", cursors.selection)
        .attr("fill", "#777")
        .attr("fill-opacity", 0.3)
        .attr("stroke", "#fff")
        .attr("shape-rendering", "crispEdges");

    var handle = group.selectAll(".handle")
      .data(dim.handles, function(d) { return d.type; });

    handle.exit().remove();

    handle.enter().append("rect")
        .attr("class", function(d) { return "handle handle--" + d.type; })
        .attr("cursor", function(d) { return cursors[d.type]; });

    group
        .each(redraw)
        .attr("fill", "none")
        .attr("pointer-events", noEventBlocking ? "auto" : "all")
        .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");

    if (noNew) {
      group.on("mousedown.brush touchstart.brush", function() {
        d3_selection_src["event"].target.__data__.type !== 'overlay' && started.apply(this, arguments);
      });
    } else {
      group.on("mousedown.brush touchstart.brush", started);
    }
  }

  brush.move = function(group, selection) {
    if (group.selection) {
      group
          .on("start.brush", function() { emitter(this, arguments).beforestart().start(); })
          .on("interrupt.brush end.brush", function() { emitter(this, arguments).end(); })
          .tween("brush", function() {
            var that = this,
                state = that.__brush,
                emit = emitter(that, arguments),
                selection0 = state.selection,
                selection1 = dim.input(typeof selection === "function" ? selection.apply(this, arguments) : selection, state.extent),
                i = Object(d3_interpolate_src["a" /* interpolate */])(selection0, selection1);

            function tween(t) {
              state.selection = t === 1 && empty(selection1) ? null : i(t);
              redraw.call(that);
              emit.brush();
            }

            return selection0 && selection1 ? tween : tween(1);
          });
    } else {
      group
          .each(function() {
            var that = this,
                args = arguments,
                state = that.__brush,
                selection1 = dim.input(typeof selection === "function" ? selection.apply(that, args) : selection, state.extent),
                emit = emitter(that, args).beforestart();

            Object(d3_transition_src["interrupt"])(that);
            state.selection = selection1 == null || empty(selection1) ? null : selection1;
            redraw.call(that);
            emit.start().brush().end();
          });
    }
  };

  function redraw() {
    var group = Object(d3_selection_src["select"])(this),
        selection = local(this).selection;

    if (selection) {
      group.selectAll(".selection")
          .style("display", null)
          .attr("x", selection[0][0])
          .attr("y", selection[0][1])
          .attr("width", selection[1][0] - selection[0][0])
          .attr("height", selection[1][1] - selection[0][1]);

      group.selectAll(".handle")
          .style("display", null)
          .attr("x", function(d) { return d.type[d.type.length - 1] === "e" ? selection[1][0] - handleSize / 2 : selection[0][0] - handleSize / 2; })
          .attr("y", function(d) { return d.type[0] === "s" ? selection[1][1] - handleSize / 2 : selection[0][1] - handleSize / 2; })
          .attr("width", function(d) { return d.type === "n" || d.type === "s" ? selection[1][0] - selection[0][0] + handleSize : handleSize; })
          .attr("height", function(d) { return d.type === "e" || d.type === "w" ? selection[1][1] - selection[0][1] + handleSize : handleSize; });
    }

    else {
      group.selectAll(".selection,.handle")
          .style("display", "none")
          .attr("x", null)
          .attr("y", null)
          .attr("width", null)
          .attr("height", null);
    }
  }

  function emitter(that, args) {
    return that.__brush.emitter || new Emitter(that, args);
  }

  function Emitter(that, args) {
    this.that = that;
    this.args = args;
    this.state = that.__brush;
    this.active = 0;
  }

  Emitter.prototype = {
    beforestart: function() {
      if (++this.active === 1) this.state.emitter = this, this.starting = true;
      return this;
    },
    start: function() {
      if (this.starting) this.starting = false, this.emit("start");
      return this;
    },
    brush: function() {
      this.emit("brush");
      return this;
    },
    end: function() {
      if (--this.active === 0) delete this.state.emitter, this.emit("end");
      return this;
    },
    emit: function(type) {
      Object(d3_selection_src["customEvent"])(new src_event(brush, type, dim.output(this.state.selection)), listeners.apply, listeners, [type, this.that, this.args]);
    }
  };

  function started() {
    if (d3_selection_src["event"].touches) { if (d3_selection_src["event"].changedTouches.length < d3_selection_src["event"].touches.length) return noevent(); }
    else if (touchending) return;
    if (!filter.apply(this, arguments)) return;

    var that = this,
        type = d3_selection_src["event"].target.__data__.type,
        mode = (d3_selection_src["event"].metaKey && !noKeyModifiers ? type = "overlay" : type) === "selection" ? MODE_DRAG : (d3_selection_src["event"].altKey && !noKeyModifiers ? MODE_CENTER : MODE_HANDLE),
        signX = dim === Y ? null : signsX[type],
        signY = dim === X ? null : signsY[type],
        state = local(that),
        extent = state.extent,
        selection = state.selection,
        W = extent[0][0], w0, w1,
        N = extent[0][1], n0, n1,
        E = extent[1][0], e0, e1,
        S = extent[1][1], s0, s1,
        dx,
        dy,
        moving,
        shifting = signX && signY && d3_selection_src["event"].shiftKey,
        lockX,
        lockY,
        point0 = Object(d3_selection_src["mouse"])(that),
        point = point0,
        emit = emitter(that, arguments).beforestart();

    if (type === "overlay") {
      state.selection = selection = [
        [w0 = dim === Y ? W : point0[0], n0 = dim === X ? N : point0[1]],
        [e0 = dim === Y ? E : w0, s0 = dim === X ? S : n0]
      ];
    } else {
      w0 = selection[0][0];
      n0 = selection[0][1];
      e0 = selection[1][0];
      s0 = selection[1][1];
    }

    w1 = w0;
    n1 = n0;
    e1 = e0;
    s1 = s0;

    var group = Object(d3_selection_src["select"])(that)
        .attr("pointer-events", "none");

    var overlay = group.selectAll(".overlay")
        .attr("cursor", cursors[type]);

    if (d3_selection_src["event"].touches) {
      group
          .on("touchmove.brush", moved, true)
          .on("touchend.brush touchcancel.brush", ended, true);
    } else {
      var view = Object(d3_selection_src["select"])(d3_selection_src["event"].view)
          .on("mousemove.brush", moved, true)
          .on("mouseup.brush", ended, true);

      if (!noKeyModifiers) {
        view.on("keydown.brush", keydowned, true)
            .on("keyup.brush", keyupped, true);
      }

      Object(d3_drag_src["dragDisable"])(d3_selection_src["event"].view);
    }

    nopropagation();
    Object(d3_transition_src["interrupt"])(that);
    redraw.call(that);
    emit.start();

    function moved() {
      var point1 = Object(d3_selection_src["mouse"])(that);
      if (shifting && !lockX && !lockY) {
        if (Math.abs(point1[0] - point[0]) > Math.abs(point1[1] - point[1])) lockY = true;
        else lockX = true;
      }
      point = point1;
      moving = true;
      noevent();
      move();
    }

    function move() {
      var t;

      dx = point[0] - point0[0];
      dy = point[1] - point0[1];

      switch (mode) {
        case MODE_SPACE:
        case MODE_DRAG: {
          if (signX) dx = Math.max(W - w0, Math.min(E - e0, dx)), w1 = w0 + dx, e1 = e0 + dx;
          if (signY) dy = Math.max(N - n0, Math.min(S - s0, dy)), n1 = n0 + dy, s1 = s0 + dy;
          break;
        }
        case MODE_HANDLE: {
          if (signX < 0) dx = Math.max(W - w0, Math.min(E - w0, dx)), w1 = w0 + dx, e1 = e0;
          else if (signX > 0) dx = Math.max(W - e0, Math.min(E - e0, dx)), w1 = w0, e1 = e0 + dx;
          if (signY < 0) dy = Math.max(N - n0, Math.min(S - n0, dy)), n1 = n0 + dy, s1 = s0;
          else if (signY > 0) dy = Math.max(N - s0, Math.min(S - s0, dy)), n1 = n0, s1 = s0 + dy;
          break;
        }
        case MODE_CENTER: {
          if (signX) w1 = Math.max(W, Math.min(E, w0 - dx * signX)), e1 = Math.max(W, Math.min(E, e0 + dx * signX));
          if (signY) n1 = Math.max(N, Math.min(S, n0 - dy * signY)), s1 = Math.max(N, Math.min(S, s0 + dy * signY));
          break;
        }
      }

      if (e1 < w1) {
        signX *= -1;
        t = w0, w0 = e0, e0 = t;
        t = w1, w1 = e1, e1 = t;
        if (type in flipX) overlay.attr("cursor", cursors[type = flipX[type]]);
      }

      if (s1 < n1) {
        signY *= -1;
        t = n0, n0 = s0, s0 = t;
        t = n1, n1 = s1, s1 = t;
        if (type in flipY) overlay.attr("cursor", cursors[type = flipY[type]]);
      }

      if (state.selection) selection = state.selection; // May be set by brush.move!
      if (lockX) w1 = selection[0][0], e1 = selection[1][0];
      if (lockY) n1 = selection[0][1], s1 = selection[1][1];

      if (selection[0][0] !== w1
          || selection[0][1] !== n1
          || selection[1][0] !== e1
          || selection[1][1] !== s1) {
        state.selection = [[w1, n1], [e1, s1]];
        redraw.call(that);
        emit.brush();
      }
    }

    function ended() {
      nopropagation();
      if (d3_selection_src["event"].touches) {
        if (d3_selection_src["event"].touches.length) return;
        if (touchending) clearTimeout(touchending);
        touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
        group.on("touchmove.brush touchend.brush touchcancel.brush", null);
      } else {
        Object(d3_drag_src["dragEnable"])(d3_selection_src["event"].view, moving);
        view.on("keydown.brush keyup.brush mousemove.brush mouseup.brush", null);
      }
      group.attr("pointer-events", "all");
      overlay.attr("cursor", cursors.overlay);
      if (state.selection) selection = state.selection; // May be set by brush.move (on start)!
      if (empty(selection)) state.selection = null, redraw.call(that);
      emit.end();
    }

    function keydowned() {
      switch (d3_selection_src["event"].keyCode) {
        case 16: { // SHIFT
          shifting = signX && signY;
          break;
        }
        case 18: { // ALT
          if (mode === MODE_HANDLE) {
            if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;
            if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;
            mode = MODE_CENTER;
            move();
          }
          break;
        }
        case 32: { // SPACE; takes priority over ALT
          if (mode === MODE_HANDLE || mode === MODE_CENTER) {
            if (signX < 0) e0 = e1 - dx; else if (signX > 0) w0 = w1 - dx;
            if (signY < 0) s0 = s1 - dy; else if (signY > 0) n0 = n1 - dy;
            mode = MODE_SPACE;
            overlay.attr("cursor", cursors.selection);
            move();
          }
          break;
        }
        default: return;
      }
      noevent();
    }

    function keyupped() {
      switch (d3_selection_src["event"].keyCode) {
        case 16: { // SHIFT
          if (shifting) {
            lockX = lockY = shifting = false;
            move();
          }
          break;
        }
        case 18: { // ALT
          if (mode === MODE_CENTER) {
            if (signX < 0) e0 = e1; else if (signX > 0) w0 = w1;
            if (signY < 0) s0 = s1; else if (signY > 0) n0 = n1;
            mode = MODE_HANDLE;
            move();
          }
          break;
        }
        case 32: { // SPACE
          if (mode === MODE_SPACE) {
            if (d3_selection_src["event"].altKey) {
              if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;
              if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;
              mode = MODE_CENTER;
            } else {
              if (signX < 0) e0 = e1; else if (signX > 0) w0 = w1;
              if (signY < 0) s0 = s1; else if (signY > 0) n0 = n1;
              mode = MODE_HANDLE;
            }
            overlay.attr("cursor", cursors[type]);
            move();
          }
          break;
        }
        default: return;
      }
      noevent();
    }
  }

  function initialize() {
    var state = this.__brush || {selection: null};
    state.extent = extent.apply(this, arguments);
    state.dim = dim;
    return state;
  }

  brush.extent = function(_) {
    return arguments.length ? (extent = typeof _ === "function" ? _ : constant([[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]]), brush) : extent;
  };

  brush.filter = function(_) {
    return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), brush) : filter;
  };

  brush.handleSize = function(_) {
    return arguments.length ? (handleSize = +_, brush) : handleSize;
  };

  brush.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? brush : value;
  };

  return brush;
}

// CONCATENATED MODULE: ../node_modules/d3-brush/index.js
/* concated harmony reexport brush */__nested_webpack_require_367900__.d(__webpack_exports__, "brush", function() { return src_brush; });
/* concated harmony reexport brushX */__nested_webpack_require_367900__.d(__webpack_exports__, "brushX", function() { return brushX; });
/* concated harmony reexport brushY */__nested_webpack_require_367900__.d(__webpack_exports__, "brushY", function() { return brushY; });
/* concated harmony reexport brushSelection */__nested_webpack_require_367900__.d(__webpack_exports__, "brushSelection", function() { return brushSelection; });



/***/ }),
/* 84 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_386850__) {

"use strict";
__nested_webpack_require_386850__.r(__webpack_exports__);

// EXTERNAL MODULE: ../node_modules/d3-dispatch/src/index.js + 1 modules
var src = __nested_webpack_require_386850__(65);

// EXTERNAL MODULE: ../node_modules/d3-selection/src/index.js + 50 modules
var d3_selection_src = __nested_webpack_require_386850__(0);

// CONCATENATED MODULE: ../node_modules/d3-drag/src/noevent.js


function nopropagation() {
  d3_selection_src["event"].stopImmediatePropagation();
}

/* harmony default export */ var noevent = (function() {
  d3_selection_src["event"].preventDefault();
  d3_selection_src["event"].stopImmediatePropagation();
});

// CONCATENATED MODULE: ../node_modules/d3-drag/src/nodrag.js



/* harmony default export */ var nodrag = (function(view) {
  var root = view.document.documentElement,
      selection = Object(d3_selection_src["select"])(view).on("dragstart.drag", noevent, true);
  if ("onselectstart" in root) {
    selection.on("selectstart.drag", noevent, true);
  } else {
    root.__noselect = root.style.MozUserSelect;
    root.style.MozUserSelect = "none";
  }
});

function yesdrag(view, noclick) {
  var root = view.document.documentElement,
      selection = Object(d3_selection_src["select"])(view).on("dragstart.drag", null);
  if (noclick) {
    selection.on("click.drag", noevent, true);
    setTimeout(function() { selection.on("click.drag", null); }, 0);
  }
  if ("onselectstart" in root) {
    selection.on("selectstart.drag", null);
  } else {
    root.style.MozUserSelect = root.__noselect;
    delete root.__noselect;
  }
}

// CONCATENATED MODULE: ../node_modules/d3-drag/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-drag/src/event.js
function DragEvent(target, type, subject, id, active, x, y, dx, dy, dispatch) {
  this.target = target;
  this.type = type;
  this.subject = subject;
  this.identifier = id;
  this.active = active;
  this.x = x;
  this.y = y;
  this.dx = dx;
  this.dy = dy;
  this._ = dispatch;
}

DragEvent.prototype.on = function() {
  var value = this._.on.apply(this._, arguments);
  return value === this._ ? this : value;
};

// CONCATENATED MODULE: ../node_modules/d3-drag/src/drag.js







// Ignore right-click, since that should open the context menu.
function defaultFilter() {
  return !d3_selection_src["event"].button;
}

function defaultContainer() {
  return this.parentNode;
}

function defaultSubject(d) {
  return d == null ? {x: d3_selection_src["event"].x, y: d3_selection_src["event"].y} : d;
}

function defaultTouchable() {
  return "ontouchstart" in this;
}

/* harmony default export */ var src_drag = (function() {
  var filter = defaultFilter,
      container = defaultContainer,
      subject = defaultSubject,
      touchable = defaultTouchable,
      gestures = {},
      listeners = Object(src["a" /* dispatch */])("start", "drag", "end"),
      active = 0,
      mousedownx,
      mousedowny,
      mousemoving,
      touchending,
      clickDistance2 = 0;

  function drag(selection) {
    selection
        .on("mousedown.drag", mousedowned)
      .filter(touchable)
        .on("touchstart.drag", touchstarted)
        .on("touchmove.drag", touchmoved)
        .on("touchend.drag touchcancel.drag", touchended)
        .style("touch-action", "none")
        .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }

  function mousedowned() {
    if (touchending || !filter.apply(this, arguments)) return;
    var gesture = beforestart("mouse", container.apply(this, arguments), d3_selection_src["mouse"], this, arguments);
    if (!gesture) return;
    Object(d3_selection_src["select"])(d3_selection_src["event"].view).on("mousemove.drag", mousemoved, true).on("mouseup.drag", mouseupped, true);
    nodrag(d3_selection_src["event"].view);
    nopropagation();
    mousemoving = false;
    mousedownx = d3_selection_src["event"].clientX;
    mousedowny = d3_selection_src["event"].clientY;
    gesture("start");
  }

  function mousemoved() {
    noevent();
    if (!mousemoving) {
      var dx = d3_selection_src["event"].clientX - mousedownx, dy = d3_selection_src["event"].clientY - mousedowny;
      mousemoving = dx * dx + dy * dy > clickDistance2;
    }
    gestures.mouse("drag");
  }

  function mouseupped() {
    Object(d3_selection_src["select"])(d3_selection_src["event"].view).on("mousemove.drag mouseup.drag", null);
    yesdrag(d3_selection_src["event"].view, mousemoving);
    noevent();
    gestures.mouse("end");
  }

  function touchstarted() {
    if (!filter.apply(this, arguments)) return;
    var touches = d3_selection_src["event"].changedTouches,
        c = container.apply(this, arguments),
        n = touches.length, i, gesture;

    for (i = 0; i < n; ++i) {
      if (gesture = beforestart(touches[i].identifier, c, d3_selection_src["touch"], this, arguments)) {
        nopropagation();
        gesture("start");
      }
    }
  }

  function touchmoved() {
    var touches = d3_selection_src["event"].changedTouches,
        n = touches.length, i, gesture;

    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        noevent();
        gesture("drag");
      }
    }
  }

  function touchended() {
    var touches = d3_selection_src["event"].changedTouches,
        n = touches.length, i, gesture;

    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
    for (i = 0; i < n; ++i) {
      if (gesture = gestures[touches[i].identifier]) {
        nopropagation();
        gesture("end");
      }
    }
  }

  function beforestart(id, container, point, that, args) {
    var p = point(container, id), s, dx, dy,
        sublisteners = listeners.copy();

    if (!Object(d3_selection_src["customEvent"])(new DragEvent(drag, "beforestart", s, id, active, p[0], p[1], 0, 0, sublisteners), function() {
      if ((d3_selection_src["event"].subject = s = subject.apply(that, args)) == null) return false;
      dx = s.x - p[0] || 0;
      dy = s.y - p[1] || 0;
      return true;
    })) return;

    return function gesture(type) {
      var p0 = p, n;
      switch (type) {
        case "start": gestures[id] = gesture, n = active++; break;
        case "end": delete gestures[id], --active; // nobreak
        case "drag": p = point(container, id), n = active; break;
      }
      Object(d3_selection_src["customEvent"])(new DragEvent(drag, type, s, id, n, p[0] + dx, p[1] + dy, p[0] - p0[0], p[1] - p0[1], sublisteners), sublisteners.apply, sublisteners, [type, that, args]);
    };
  }

  drag.filter = function(_) {
    return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), drag) : filter;
  };

  drag.container = function(_) {
    return arguments.length ? (container = typeof _ === "function" ? _ : constant(_), drag) : container;
  };

  drag.subject = function(_) {
    return arguments.length ? (subject = typeof _ === "function" ? _ : constant(_), drag) : subject;
  };

  drag.touchable = function(_) {
    return arguments.length ? (touchable = typeof _ === "function" ? _ : constant(!!_), drag) : touchable;
  };

  drag.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? drag : value;
  };

  drag.clickDistance = function(_) {
    return arguments.length ? (clickDistance2 = (_ = +_) * _, drag) : Math.sqrt(clickDistance2);
  };

  return drag;
});

// CONCATENATED MODULE: ../node_modules/d3-drag/src/index.js
/* concated harmony reexport drag */__nested_webpack_require_386850__.d(__webpack_exports__, "drag", function() { return src_drag; });
/* concated harmony reexport dragDisable */__nested_webpack_require_386850__.d(__webpack_exports__, "dragDisable", function() { return nodrag; });
/* concated harmony reexport dragEnable */__nested_webpack_require_386850__.d(__webpack_exports__, "dragEnable", function() { return yesdrag; });




/***/ }),
/* 85 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_394890__) {

"use strict";
__nested_webpack_require_394890__.r(__webpack_exports__);

// EXTERNAL MODULE: ../node_modules/d3-selection/src/index.js + 50 modules
var src = __nested_webpack_require_394890__(0);

// EXTERNAL MODULE: ../node_modules/d3-dispatch/src/index.js + 1 modules
var d3_dispatch_src = __nested_webpack_require_394890__(65);

// CONCATENATED MODULE: ../node_modules/d3-timer/src/timer.js
var timer_frame = 0, // is an animation frame pending?
    timeout = 0, // is a timeout pending?
    interval = 0, // are any timers active?
    pokeDelay = 1000, // how frequently we check for clock skew
    taskHead,
    taskTail,
    clockLast = 0,
    clockNow = 0,
    clockSkew = 0,
    clock = typeof performance === "object" && performance.now ? performance : Date,
    setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };

function now() {
  return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}

function clearNow() {
  clockNow = 0;
}

function Timer() {
  this._call =
  this._time =
  this._next = null;
}

Timer.prototype = timer.prototype = {
  constructor: Timer,
  restart: function(callback, delay, time) {
    if (typeof callback !== "function") throw new TypeError("callback is not a function");
    time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
    if (!this._next && taskTail !== this) {
      if (taskTail) taskTail._next = this;
      else taskHead = this;
      taskTail = this;
    }
    this._call = callback;
    this._time = time;
    sleep();
  },
  stop: function() {
    if (this._call) {
      this._call = null;
      this._time = Infinity;
      sleep();
    }
  }
};

function timer(callback, delay, time) {
  var t = new Timer;
  t.restart(callback, delay, time);
  return t;
}

function timerFlush() {
  now(); // Get the current time, if not already set.
  ++timer_frame; // Pretend we’ve set an alarm, if we haven’t already.
  var t = taskHead, e;
  while (t) {
    if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
    t = t._next;
  }
  --timer_frame;
}

function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  timer_frame = timeout = 0;
  try {
    timerFlush();
  } finally {
    timer_frame = 0;
    nap();
    clockNow = 0;
  }
}

function poke() {
  var now = clock.now(), delay = now - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
}

function nap() {
  var t0, t1 = taskHead, t2, time = Infinity;
  while (t1) {
    if (t1._call) {
      if (time > t1._time) time = t1._time;
      t0 = t1, t1 = t1._next;
    } else {
      t2 = t1._next, t1._next = null;
      t1 = t0 ? t0._next = t2 : taskHead = t2;
    }
  }
  taskTail = t0;
  sleep(time);
}

function sleep(time) {
  if (timer_frame) return; // Soonest alarm already set, or will be.
  if (timeout) timeout = clearTimeout(timeout);
  var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
  if (delay > 24) {
    if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
    if (interval) interval = clearInterval(interval);
  } else {
    if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);
    timer_frame = 1, setFrame(wake);
  }
}

// CONCATENATED MODULE: ../node_modules/d3-timer/src/timeout.js


/* harmony default export */ var src_timeout = (function(callback, delay, time) {
  var t = new Timer;
  delay = delay == null ? 0 : +delay;
  t.restart(function(elapsed) {
    t.stop();
    callback(elapsed + delay);
  }, delay, time);
  return t;
});

// CONCATENATED MODULE: ../node_modules/d3-timer/src/interval.js


/* harmony default export */ var src_interval = (function(callback, delay, time) {
  var t = new Timer, total = delay;
  if (delay == null) return t.restart(callback, delay, time), t;
  delay = +delay, time = time == null ? now() : +time;
  t.restart(function tick(elapsed) {
    elapsed += total;
    t.restart(tick, total += delay, time);
    callback(elapsed);
  }, delay, time);
  return t;
});

// CONCATENATED MODULE: ../node_modules/d3-timer/src/index.js






// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/schedule.js



var emptyOn = Object(d3_dispatch_src["a" /* dispatch */])("start", "end", "cancel", "interrupt");
var emptyTween = [];

var CREATED = 0;
var SCHEDULED = 1;
var STARTING = 2;
var STARTED = 3;
var RUNNING = 4;
var ENDING = 5;
var ENDED = 6;

/* harmony default export */ var transition_schedule = (function(node, name, id, index, group, timing) {
  var schedules = node.__transition;
  if (!schedules) node.__transition = {};
  else if (id in schedules) return;
  create(node, id, {
    name: name,
    index: index, // For context during callback.
    group: group, // For context during callback.
    on: emptyOn,
    tween: emptyTween,
    time: timing.time,
    delay: timing.delay,
    duration: timing.duration,
    ease: timing.ease,
    timer: null,
    state: CREATED
  });
});

function init(node, id) {
  var schedule = get(node, id);
  if (schedule.state > CREATED) throw new Error("too late; already scheduled");
  return schedule;
}

function set(node, id) {
  var schedule = get(node, id);
  if (schedule.state > STARTED) throw new Error("too late; already running");
  return schedule;
}

function get(node, id) {
  var schedule = node.__transition;
  if (!schedule || !(schedule = schedule[id])) throw new Error("transition not found");
  return schedule;
}

function create(node, id, self) {
  var schedules = node.__transition,
      tween;

  // Initialize the self timer when the transition is created.
  // Note the actual delay is not known until the first callback!
  schedules[id] = self;
  self.timer = timer(schedule, 0, self.time);

  function schedule(elapsed) {
    self.state = SCHEDULED;
    self.timer.restart(start, self.delay, self.time);

    // If the elapsed delay is less than our first sleep, start immediately.
    if (self.delay <= elapsed) start(elapsed - self.delay);
  }

  function start(elapsed) {
    var i, j, n, o;

    // If the state is not SCHEDULED, then we previously errored on start.
    if (self.state !== SCHEDULED) return stop();

    for (i in schedules) {
      o = schedules[i];
      if (o.name !== self.name) continue;

      // While this element already has a starting transition during this frame,
      // defer starting an interrupting transition until that transition has a
      // chance to tick (and possibly end); see d3/d3-transition#54!
      if (o.state === STARTED) return src_timeout(start);

      // Interrupt the active transition, if any.
      if (o.state === RUNNING) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("interrupt", node, node.__data__, o.index, o.group);
        delete schedules[i];
      }

      // Cancel any pre-empted transitions.
      else if (+i < id) {
        o.state = ENDED;
        o.timer.stop();
        o.on.call("cancel", node, node.__data__, o.index, o.group);
        delete schedules[i];
      }
    }

    // Defer the first tick to end of the current frame; see d3/d3#1576.
    // Note the transition may be canceled after start and before the first tick!
    // Note this must be scheduled before the start event; see d3/d3-transition#16!
    // Assuming this is successful, subsequent callbacks go straight to tick.
    src_timeout(function() {
      if (self.state === STARTED) {
        self.state = RUNNING;
        self.timer.restart(tick, self.delay, self.time);
        tick(elapsed);
      }
    });

    // Dispatch the start event.
    // Note this must be done before the tween are initialized.
    self.state = STARTING;
    self.on.call("start", node, node.__data__, self.index, self.group);
    if (self.state !== STARTING) return; // interrupted
    self.state = STARTED;

    // Initialize the tween, deleting null tween.
    tween = new Array(n = self.tween.length);
    for (i = 0, j = -1; i < n; ++i) {
      if (o = self.tween[i].value.call(node, node.__data__, self.index, self.group)) {
        tween[++j] = o;
      }
    }
    tween.length = j + 1;
  }

  function tick(elapsed) {
    var t = elapsed < self.duration ? self.ease.call(null, elapsed / self.duration) : (self.timer.restart(stop), self.state = ENDING, 1),
        i = -1,
        n = tween.length;

    while (++i < n) {
      tween[i].call(node, t);
    }

    // Dispatch the end event.
    if (self.state === ENDING) {
      self.on.call("end", node, node.__data__, self.index, self.group);
      stop();
    }
  }

  function stop() {
    self.state = ENDED;
    self.timer.stop();
    delete schedules[id];
    for (var i in schedules) return; // eslint-disable-line no-unused-vars
    delete node.__transition;
  }
}

// CONCATENATED MODULE: ../node_modules/d3-transition/src/interrupt.js


/* harmony default export */ var interrupt = (function(node, name) {
  var schedules = node.__transition,
      schedule,
      active,
      empty = true,
      i;

  if (!schedules) return;

  name = name == null ? null : name + "";

  for (i in schedules) {
    if ((schedule = schedules[i]).name !== name) { empty = false; continue; }
    active = schedule.state > STARTING && schedule.state < ENDING;
    schedule.state = ENDED;
    schedule.timer.stop();
    schedule.on.call(active ? "interrupt" : "cancel", node, node.__data__, schedule.index, schedule.group);
    delete schedules[i];
  }

  if (empty) delete node.__transition;
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/selection/interrupt.js


/* harmony default export */ var selection_interrupt = (function(name) {
  return this.each(function() {
    interrupt(this, name);
  });
});

// EXTERNAL MODULE: ../node_modules/d3-interpolate/src/index.js + 24 modules
var d3_interpolate_src = __nested_webpack_require_394890__(15);

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/tween.js


function tweenRemove(id, name) {
  var tween0, tween1;
  return function() {
    var schedule = set(this, id),
        tween = schedule.tween;

    // If this node shared tween with the previous node,
    // just assign the updated shared tween and we’re done!
    // Otherwise, copy-on-write.
    if (tween !== tween0) {
      tween1 = tween0 = tween;
      for (var i = 0, n = tween1.length; i < n; ++i) {
        if (tween1[i].name === name) {
          tween1 = tween1.slice();
          tween1.splice(i, 1);
          break;
        }
      }
    }

    schedule.tween = tween1;
  };
}

function tweenFunction(id, name, value) {
  var tween0, tween1;
  if (typeof value !== "function") throw new Error;
  return function() {
    var schedule = set(this, id),
        tween = schedule.tween;

    // If this node shared tween with the previous node,
    // just assign the updated shared tween and we’re done!
    // Otherwise, copy-on-write.
    if (tween !== tween0) {
      tween1 = (tween0 = tween).slice();
      for (var t = {name: name, value: value}, i = 0, n = tween1.length; i < n; ++i) {
        if (tween1[i].name === name) {
          tween1[i] = t;
          break;
        }
      }
      if (i === n) tween1.push(t);
    }

    schedule.tween = tween1;
  };
}

/* harmony default export */ var transition_tween = (function(name, value) {
  var id = this._id;

  name += "";

  if (arguments.length < 2) {
    var tween = get(this.node(), id).tween;
    for (var i = 0, n = tween.length, t; i < n; ++i) {
      if ((t = tween[i]).name === name) {
        return t.value;
      }
    }
    return null;
  }

  return this.each((value == null ? tweenRemove : tweenFunction)(id, name, value));
});

function tweenValue(transition, name, value) {
  var id = transition._id;

  transition.each(function() {
    var schedule = set(this, id);
    (schedule.value || (schedule.value = {}))[name] = value.apply(this, arguments);
  });

  return function(node) {
    return get(node, id).value[name];
  };
}

// EXTERNAL MODULE: ../node_modules/d3-color/src/index.js + 5 modules
var d3_color_src = __nested_webpack_require_394890__(9);

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/interpolate.js



/* harmony default export */ var transition_interpolate = (function(a, b) {
  var c;
  return (typeof b === "number" ? d3_interpolate_src["c" /* interpolateNumber */]
      : b instanceof d3_color_src["color"] ? d3_interpolate_src["d" /* interpolateRgb */]
      : (c = Object(d3_color_src["color"])(b)) ? (b = c, d3_interpolate_src["d" /* interpolateRgb */])
      : d3_interpolate_src["f" /* interpolateString */])(a, b);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/attr.js





function attrRemove(name) {
  return function() {
    this.removeAttribute(name);
  };
}

function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}

function attrConstant(name, interpolate, value1) {
  var string00,
      string1 = value1 + "",
      interpolate0;
  return function() {
    var string0 = this.getAttribute(name);
    return string0 === string1 ? null
        : string0 === string00 ? interpolate0
        : interpolate0 = interpolate(string00 = string0, value1);
  };
}

function attrConstantNS(fullname, interpolate, value1) {
  var string00,
      string1 = value1 + "",
      interpolate0;
  return function() {
    var string0 = this.getAttributeNS(fullname.space, fullname.local);
    return string0 === string1 ? null
        : string0 === string00 ? interpolate0
        : interpolate0 = interpolate(string00 = string0, value1);
  };
}

function attrFunction(name, interpolate, value) {
  var string00,
      string10,
      interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null) return void this.removeAttribute(name);
    string0 = this.getAttribute(name);
    string1 = value1 + "";
    return string0 === string1 ? null
        : string0 === string00 && string1 === string10 ? interpolate0
        : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
  };
}

function attrFunctionNS(fullname, interpolate, value) {
  var string00,
      string10,
      interpolate0;
  return function() {
    var string0, value1 = value(this), string1;
    if (value1 == null) return void this.removeAttributeNS(fullname.space, fullname.local);
    string0 = this.getAttributeNS(fullname.space, fullname.local);
    string1 = value1 + "";
    return string0 === string1 ? null
        : string0 === string00 && string1 === string10 ? interpolate0
        : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
  };
}

/* harmony default export */ var attr = (function(name, value) {
  var fullname = Object(src["namespace"])(name), i = fullname === "transform" ? d3_interpolate_src["h" /* interpolateTransformSvg */] : transition_interpolate;
  return this.attrTween(name, typeof value === "function"
      ? (fullname.local ? attrFunctionNS : attrFunction)(fullname, i, tweenValue(this, "attr." + name, value))
      : value == null ? (fullname.local ? attrRemoveNS : attrRemove)(fullname)
      : (fullname.local ? attrConstantNS : attrConstant)(fullname, i, value));
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/attrTween.js


function attrInterpolate(name, i) {
  return function(t) {
    this.setAttribute(name, i(t));
  };
}

function attrInterpolateNS(fullname, i) {
  return function(t) {
    this.setAttributeNS(fullname.space, fullname.local, i(t));
  };
}

function attrTweenNS(fullname, value) {
  var t0, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t0 = (i0 = i) && attrInterpolateNS(fullname, i);
    return t0;
  }
  tween._value = value;
  return tween;
}

function attrTween(name, value) {
  var t0, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t0 = (i0 = i) && attrInterpolate(name, i);
    return t0;
  }
  tween._value = value;
  return tween;
}

/* harmony default export */ var transition_attrTween = (function(name, value) {
  var key = "attr." + name;
  if (arguments.length < 2) return (key = this.tween(key)) && key._value;
  if (value == null) return this.tween(key, null);
  if (typeof value !== "function") throw new Error;
  var fullname = Object(src["namespace"])(name);
  return this.tween(key, (fullname.local ? attrTweenNS : attrTween)(fullname, value));
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/delay.js


function delayFunction(id, value) {
  return function() {
    init(this, id).delay = +value.apply(this, arguments);
  };
}

function delayConstant(id, value) {
  return value = +value, function() {
    init(this, id).delay = value;
  };
}

/* harmony default export */ var transition_delay = (function(value) {
  var id = this._id;

  return arguments.length
      ? this.each((typeof value === "function"
          ? delayFunction
          : delayConstant)(id, value))
      : get(this.node(), id).delay;
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/duration.js


function durationFunction(id, value) {
  return function() {
    set(this, id).duration = +value.apply(this, arguments);
  };
}

function durationConstant(id, value) {
  return value = +value, function() {
    set(this, id).duration = value;
  };
}

/* harmony default export */ var duration = (function(value) {
  var id = this._id;

  return arguments.length
      ? this.each((typeof value === "function"
          ? durationFunction
          : durationConstant)(id, value))
      : get(this.node(), id).duration;
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/ease.js


function easeConstant(id, value) {
  if (typeof value !== "function") throw new Error;
  return function() {
    set(this, id).ease = value;
  };
}

/* harmony default export */ var ease = (function(value) {
  var id = this._id;

  return arguments.length
      ? this.each(easeConstant(id, value))
      : get(this.node(), id).ease;
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/filter.js



/* harmony default export */ var filter = (function(match) {
  if (typeof match !== "function") match = Object(src["matcher"])(match);

  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
      if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
        subgroup.push(node);
      }
    }
  }

  return new Transition(subgroups, this._parents, this._name, this._id);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/merge.js


/* harmony default export */ var transition_merge = (function(transition) {
  if (transition._id !== this._id) throw new Error;

  for (var groups0 = this._groups, groups1 = transition._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge[i] = node;
      }
    }
  }

  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }

  return new Transition(merges, this._parents, this._name, this._id);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/on.js


function on_start(name) {
  return (name + "").trim().split(/^|\s+/).every(function(t) {
    var i = t.indexOf(".");
    if (i >= 0) t = t.slice(0, i);
    return !t || t === "start";
  });
}

function onFunction(id, name, listener) {
  var on0, on1, sit = on_start(name) ? init : set;
  return function() {
    var schedule = sit(this, id),
        on = schedule.on;

    // If this node shared a dispatch with the previous node,
    // just assign the updated shared dispatch and we’re done!
    // Otherwise, copy-on-write.
    if (on !== on0) (on1 = (on0 = on).copy()).on(name, listener);

    schedule.on = on1;
  };
}

/* harmony default export */ var transition_on = (function(name, listener) {
  var id = this._id;

  return arguments.length < 2
      ? get(this.node(), id).on.on(name)
      : this.each(onFunction(id, name, listener));
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/remove.js
function removeFunction(id) {
  return function() {
    var parent = this.parentNode;
    for (var i in this.__transition) if (+i !== id) return;
    if (parent) parent.removeChild(this);
  };
}

/* harmony default export */ var transition_remove = (function() {
  return this.on("end.remove", removeFunction(this._id));
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/select.js




/* harmony default export */ var transition_select = (function(select) {
  var name = this._name,
      id = this._id;

  if (typeof select !== "function") select = Object(src["selector"])(select);

  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
      if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
        transition_schedule(subgroup[i], name, id, i, subgroup, get(node, id));
      }
    }
  }

  return new Transition(subgroups, this._parents, name, id);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/selectAll.js




/* harmony default export */ var selectAll = (function(select) {
  var name = this._name,
      id = this._id;

  if (typeof select !== "function") select = Object(src["selectorAll"])(select);

  for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        for (var children = select.call(node, node.__data__, i, group), child, inherit = get(node, id), k = 0, l = children.length; k < l; ++k) {
          if (child = children[k]) {
            transition_schedule(child, name, id, k, children, inherit);
          }
        }
        subgroups.push(children);
        parents.push(node);
      }
    }
  }

  return new Transition(subgroups, parents, name, id);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/selection.js


var Selection = src["selection"].prototype.constructor;

/* harmony default export */ var selection = (function() {
  return new Selection(this._groups, this._parents);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/style.js






function styleNull(name, interpolate) {
  var string00,
      string10,
      interpolate0;
  return function() {
    var string0 = Object(src["style"])(this, name),
        string1 = (this.style.removeProperty(name), Object(src["style"])(this, name));
    return string0 === string1 ? null
        : string0 === string00 && string1 === string10 ? interpolate0
        : interpolate0 = interpolate(string00 = string0, string10 = string1);
  };
}

function styleRemove(name) {
  return function() {
    this.style.removeProperty(name);
  };
}

function styleConstant(name, interpolate, value1) {
  var string00,
      string1 = value1 + "",
      interpolate0;
  return function() {
    var string0 = Object(src["style"])(this, name);
    return string0 === string1 ? null
        : string0 === string00 ? interpolate0
        : interpolate0 = interpolate(string00 = string0, value1);
  };
}

function styleFunction(name, interpolate, value) {
  var string00,
      string10,
      interpolate0;
  return function() {
    var string0 = Object(src["style"])(this, name),
        value1 = value(this),
        string1 = value1 + "";
    if (value1 == null) string1 = value1 = (this.style.removeProperty(name), Object(src["style"])(this, name));
    return string0 === string1 ? null
        : string0 === string00 && string1 === string10 ? interpolate0
        : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
  };
}

function styleMaybeRemove(id, name) {
  var on0, on1, listener0, key = "style." + name, event = "end." + key, remove;
  return function() {
    var schedule = set(this, id),
        on = schedule.on,
        listener = schedule.value[key] == null ? remove || (remove = styleRemove(name)) : undefined;

    // If this node shared a dispatch with the previous node,
    // just assign the updated shared dispatch and we’re done!
    // Otherwise, copy-on-write.
    if (on !== on0 || listener0 !== listener) (on1 = (on0 = on).copy()).on(event, listener0 = listener);

    schedule.on = on1;
  };
}

/* harmony default export */ var style = (function(name, value, priority) {
  var i = (name += "") === "transform" ? d3_interpolate_src["g" /* interpolateTransformCss */] : transition_interpolate;
  return value == null ? this
      .styleTween(name, styleNull(name, i))
      .on("end.style." + name, styleRemove(name))
    : typeof value === "function" ? this
      .styleTween(name, styleFunction(name, i, tweenValue(this, "style." + name, value)))
      .each(styleMaybeRemove(this._id, name))
    : this
      .styleTween(name, styleConstant(name, i, value), priority)
      .on("end.style." + name, null);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/styleTween.js
function styleInterpolate(name, i, priority) {
  return function(t) {
    this.style.setProperty(name, i(t), priority);
  };
}

function styleTween(name, value, priority) {
  var t, i0;
  function tween() {
    var i = value.apply(this, arguments);
    if (i !== i0) t = (i0 = i) && styleInterpolate(name, i, priority);
    return t;
  }
  tween._value = value;
  return tween;
}

/* harmony default export */ var transition_styleTween = (function(name, value, priority) {
  var key = "style." + (name += "");
  if (arguments.length < 2) return (key = this.tween(key)) && key._value;
  if (value == null) return this.tween(key, null);
  if (typeof value !== "function") throw new Error;
  return this.tween(key, styleTween(name, value, priority == null ? "" : priority));
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/text.js


function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}

function textFunction(value) {
  return function() {
    var value1 = value(this);
    this.textContent = value1 == null ? "" : value1;
  };
}

/* harmony default export */ var transition_text = (function(value) {
  return this.tween("text", typeof value === "function"
      ? textFunction(tweenValue(this, "text", value))
      : textConstant(value == null ? "" : value + ""));
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/transition.js



/* harmony default export */ var transition_transition = (function() {
  var name = this._name,
      id0 = this._id,
      id1 = newId();

  for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        var inherit = get(node, id0);
        transition_schedule(node, name, id1, i, group, {
          time: inherit.time + inherit.delay + inherit.duration,
          delay: 0,
          duration: inherit.duration,
          ease: inherit.ease
        });
      }
    }
  }

  return new Transition(groups, this._parents, name, id1);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/end.js


/* harmony default export */ var transition_end = (function() {
  var on0, on1, that = this, id = that._id, size = that.size();
  return new Promise(function(resolve, reject) {
    var cancel = {value: reject},
        end = {value: function() { if (--size === 0) resolve(); }};

    that.each(function() {
      var schedule = set(this, id),
          on = schedule.on;

      // If this node shared a dispatch with the previous node,
      // just assign the updated shared dispatch and we’re done!
      // Otherwise, copy-on-write.
      if (on !== on0) {
        on1 = (on0 = on).copy();
        on1._.cancel.push(cancel);
        on1._.interrupt.push(cancel);
        on1._.end.push(end);
      }

      schedule.on = on1;
    });
  });
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/transition/index.js




















var transition_id = 0;

function Transition(groups, parents, name, id) {
  this._groups = groups;
  this._parents = parents;
  this._name = name;
  this._id = id;
}

function src_transition_transition(name) {
  return Object(src["selection"])().transition(name);
}

function newId() {
  return ++transition_id;
}

var selection_prototype = src["selection"].prototype;

Transition.prototype = src_transition_transition.prototype = {
  constructor: Transition,
  select: transition_select,
  selectAll: selectAll,
  filter: filter,
  merge: transition_merge,
  selection: selection,
  transition: transition_transition,
  call: selection_prototype.call,
  nodes: selection_prototype.nodes,
  node: selection_prototype.node,
  size: selection_prototype.size,
  empty: selection_prototype.empty,
  each: selection_prototype.each,
  on: transition_on,
  attr: attr,
  attrTween: transition_attrTween,
  style: style,
  styleTween: transition_styleTween,
  text: transition_text,
  remove: transition_remove,
  tween: transition_tween,
  delay: transition_delay,
  duration: duration,
  ease: ease,
  end: transition_end
};

// CONCATENATED MODULE: ../node_modules/d3-ease/src/linear.js
function linear(t) {
  return +t;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/quad.js
function quadIn(t) {
  return t * t;
}

function quadOut(t) {
  return t * (2 - t);
}

function quadInOut(t) {
  return ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/cubic.js
function cubicIn(t) {
  return t * t * t;
}

function cubicOut(t) {
  return --t * t * t + 1;
}

function cubicInOut(t) {
  return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/poly.js
var exponent = 3;

var polyIn = (function custom(e) {
  e = +e;

  function polyIn(t) {
    return Math.pow(t, e);
  }

  polyIn.exponent = custom;

  return polyIn;
})(exponent);

var polyOut = (function custom(e) {
  e = +e;

  function polyOut(t) {
    return 1 - Math.pow(1 - t, e);
  }

  polyOut.exponent = custom;

  return polyOut;
})(exponent);

var polyInOut = (function custom(e) {
  e = +e;

  function polyInOut(t) {
    return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2;
  }

  polyInOut.exponent = custom;

  return polyInOut;
})(exponent);

// CONCATENATED MODULE: ../node_modules/d3-ease/src/sin.js
var pi = Math.PI,
    halfPi = pi / 2;

function sinIn(t) {
  return 1 - Math.cos(t * halfPi);
}

function sinOut(t) {
  return Math.sin(t * halfPi);
}

function sinInOut(t) {
  return (1 - Math.cos(pi * t)) / 2;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/exp.js
function expIn(t) {
  return Math.pow(2, 10 * t - 10);
}

function expOut(t) {
  return 1 - Math.pow(2, -10 * t);
}

function expInOut(t) {
  return ((t *= 2) <= 1 ? Math.pow(2, 10 * t - 10) : 2 - Math.pow(2, 10 - 10 * t)) / 2;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/circle.js
function circleIn(t) {
  return 1 - Math.sqrt(1 - t * t);
}

function circleOut(t) {
  return Math.sqrt(1 - --t * t);
}

function circleInOut(t) {
  return ((t *= 2) <= 1 ? 1 - Math.sqrt(1 - t * t) : Math.sqrt(1 - (t -= 2) * t) + 1) / 2;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/bounce.js
var b1 = 4 / 11,
    b2 = 6 / 11,
    b3 = 8 / 11,
    b4 = 3 / 4,
    b5 = 9 / 11,
    b6 = 10 / 11,
    b7 = 15 / 16,
    b8 = 21 / 22,
    b9 = 63 / 64,
    b0 = 1 / b1 / b1;

function bounceIn(t) {
  return 1 - bounceOut(1 - t);
}

function bounceOut(t) {
  return (t = +t) < b1 ? b0 * t * t : t < b3 ? b0 * (t -= b2) * t + b4 : t < b6 ? b0 * (t -= b5) * t + b7 : b0 * (t -= b8) * t + b9;
}

function bounceInOut(t) {
  return ((t *= 2) <= 1 ? 1 - bounceOut(1 - t) : bounceOut(t - 1) + 1) / 2;
}

// CONCATENATED MODULE: ../node_modules/d3-ease/src/back.js
var overshoot = 1.70158;

var backIn = (function custom(s) {
  s = +s;

  function backIn(t) {
    return t * t * ((s + 1) * t - s);
  }

  backIn.overshoot = custom;

  return backIn;
})(overshoot);

var backOut = (function custom(s) {
  s = +s;

  function backOut(t) {
    return --t * t * ((s + 1) * t + s) + 1;
  }

  backOut.overshoot = custom;

  return backOut;
})(overshoot);

var backInOut = (function custom(s) {
  s = +s;

  function backInOut(t) {
    return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;
  }

  backInOut.overshoot = custom;

  return backInOut;
})(overshoot);

// CONCATENATED MODULE: ../node_modules/d3-ease/src/elastic.js
var tau = 2 * Math.PI,
    amplitude = 1,
    period = 0.3;

var elasticIn = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);

  function elasticIn(t) {
    return a * Math.pow(2, 10 * --t) * Math.sin((s - t) / p);
  }

  elasticIn.amplitude = function(a) { return custom(a, p * tau); };
  elasticIn.period = function(p) { return custom(a, p); };

  return elasticIn;
})(amplitude, period);

var elasticOut = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);

  function elasticOut(t) {
    return 1 - a * Math.pow(2, -10 * (t = +t)) * Math.sin((t + s) / p);
  }

  elasticOut.amplitude = function(a) { return custom(a, p * tau); };
  elasticOut.period = function(p) { return custom(a, p); };

  return elasticOut;
})(amplitude, period);

var elasticInOut = (function custom(a, p) {
  var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);

  function elasticInOut(t) {
    return ((t = t * 2 - 1) < 0
        ? a * Math.pow(2, 10 * t) * Math.sin((s - t) / p)
        : 2 - a * Math.pow(2, -10 * t) * Math.sin((s + t) / p)) / 2;
  }

  elasticInOut.amplitude = function(a) { return custom(a, p * tau); };
  elasticInOut.period = function(p) { return custom(a, p); };

  return elasticInOut;
})(amplitude, period);

// CONCATENATED MODULE: ../node_modules/d3-ease/src/index.js




















// CONCATENATED MODULE: ../node_modules/d3-transition/src/selection/transition.js





var defaultTiming = {
  time: null, // Set on use.
  delay: 0,
  duration: 250,
  ease: cubicInOut
};

function transition_inherit(node, id) {
  var timing;
  while (!(timing = node.__transition) || !(timing = timing[id])) {
    if (!(node = node.parentNode)) {
      return defaultTiming.time = now(), defaultTiming;
    }
  }
  return timing;
}

/* harmony default export */ var selection_transition = (function(name) {
  var id,
      timing;

  if (name instanceof Transition) {
    id = name._id, name = name._name;
  } else {
    id = newId(), (timing = defaultTiming).time = now(), name = name == null ? null : name + "";
  }

  for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {
    for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
      if (node = group[i]) {
        transition_schedule(node, name, id, i, group, timing || transition_inherit(node, id));
      }
    }
  }

  return new Transition(groups, this._parents, name, id);
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/selection/index.js




src["selection"].prototype.interrupt = selection_interrupt;
src["selection"].prototype.transition = selection_transition;

// CONCATENATED MODULE: ../node_modules/d3-transition/src/active.js



var root = [null];

/* harmony default export */ var src_active = (function(node, name) {
  var schedules = node.__transition,
      schedule,
      i;

  if (schedules) {
    name = name == null ? null : name + "";
    for (i in schedules) {
      if ((schedule = schedules[i]).state > SCHEDULED && schedule.name === name) {
        return new Transition([[node]], root, name, +i);
      }
    }
  }

  return null;
});

// CONCATENATED MODULE: ../node_modules/d3-transition/src/index.js
/* concated harmony reexport transition */__nested_webpack_require_394890__.d(__webpack_exports__, "transition", function() { return src_transition_transition; });
/* concated harmony reexport active */__nested_webpack_require_394890__.d(__webpack_exports__, "active", function() { return src_active; });
/* concated harmony reexport interrupt */__nested_webpack_require_394890__.d(__webpack_exports__, "interrupt", function() { return interrupt; });






/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



/**
 * Use invariant() to assert state which your program assumes to be true.
 *
 * Provide sprintf-style format (only %s is supported) and arguments
 * to provide information about what broke and what you were
 * expecting.
 *
 * The invariant message will be stripped in production, but the invariant
 * will remain to ensure logic does not differ in production.
 */

var invariant = function(condition, format, a, b, c, d, e, f) {
  if (false) {}

  if (!condition) {
    var error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
        'for the full error message and additional helpful warnings.'
      );
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() { return args[argIndex++]; })
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
};

module.exports = invariant;


/***/ }),
/* 87 */
/***/ (function(module, exports) {

// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
  if (it == undefined) throw TypeError("Can't call method on  " + it);
  return it;
};


/***/ }),
/* 88 */
/***/ (function(module, exports, __nested_webpack_require_433264__) {

// 7.1.15 ToLength
var toInteger = __nested_webpack_require_433264__(89);
var min = Math.min;
module.exports = function (it) {
  return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};


/***/ }),
/* 89 */
/***/ (function(module, exports) {

// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};


/***/ }),
/* 90 */
/***/ (function(module, exports, __nested_webpack_require_433774__) {

var shared = __nested_webpack_require_433774__(106)('keys');
var uid = __nested_webpack_require_433774__(91);
module.exports = function (key) {
  return shared[key] || (shared[key] = uid(key));
};


/***/ }),
/* 91 */
/***/ (function(module, exports) {

var id = 0;
var px = Math.random();
module.exports = function (key) {
  return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};


/***/ }),
/* 92 */
/***/ (function(module, exports) {

module.exports = function (it) {
  if (typeof it != 'function') throw TypeError(it + ' is not a function!');
  return it;
};


/***/ }),
/* 93 */
/***/ (function(module, exports) {

exports.f = {}.propertyIsEnumerable;


/***/ }),
/* 94 */
/***/ (function(module, exports, __nested_webpack_require_434516__) {

"use strict";


exports.__esModule = true;

var _iterator = __nested_webpack_require_434516__(562);

var _iterator2 = _interopRequireDefault(_iterator);

var _symbol = __nested_webpack_require_434516__(225);

var _symbol2 = _interopRequireDefault(_symbol);

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

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

exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
  return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
  return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};

/***/ }),
/* 95 */
/***/ (function(module, exports, __nested_webpack_require_435647__) {

module.exports = { "default": __nested_webpack_require_435647__(235), __esModule: true };

/***/ }),
/* 96 */
/***/ (function(module, exports, __nested_webpack_require_435800__) {

"use strict";


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

var _assign = __nested_webpack_require_435800__(44);

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = __nested_webpack_require_435800__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_435800__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_435800__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_435800__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_435800__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_435800__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_435800__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_435800__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_435800__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _configs = __nested_webpack_require_435800__(11);

__nested_webpack_require_435800__(68);

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

// the size of the track controls
// taken from ../styles/TrackControl.module.css
var _styleModuleImportMap = {
  '../styles/ContextMenu.module.scss': {
    'context-menu': 'ContextMenu-module_context-menu-2OwvL',
    'context-menu-dark': 'ContextMenu-module_context-menu-dark-2PO31',
    'context-menu-icon': 'ContextMenu-module_context-menu-icon-I4kiw',
    'context-menu-item': 'ContextMenu-module_context-menu-item-1HeVv',
    'context-menu-hr': 'ContextMenu-module_context-menu-hr-3yapb',
    'play-icon': 'ContextMenu-module_play-icon-R4pIO',
    'context-menu-span': 'ContextMenu-module_context-menu-span-8EUfZ',
    'context-menu-thumbnail': 'ContextMenu-module_context-menu-thumbnail-2vHLD',
    'context-menu-thumbnail-inline': 'ContextMenu-module_context-menu-thumbnail-inline-1iOcg'
  }
};

// Styles

var TRACK_CONTROL_HEIGHT = 20;

var ContextMenuContainer = function (_React$Component) {
  (0, _inherits3['default'])(ContextMenuContainer, _React$Component);

  function ContextMenuContainer(props) {
    (0, _classCallCheck3['default'])(this, ContextMenuContainer);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ContextMenuContainer.__proto__ || (0, _getPrototypeOf2['default'])(ContextMenuContainer)).call(this, props));
    /**
     * A window that is opened when a user clicks on the track configuration icon.
     */


    _this.adjusted = false;

    _this.state = {
      orientation: _this.props.orientation ? _this.props.orientation : 'right',
      left: _this.props.position.left,
      top: _this.props.position.top,
      submenuShown: null
    };
    return _this;
  }

  /* -------------------------- Life Cycle Methods -------------------------- */

  (0, _createClass3['default'])(ContextMenuContainer, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        this.updateOrientation();
      }

      return componentDidMount;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(newProps) {
        this.adjusted = false;

        this.setState({
          left: newProps.position.left,
          top: newProps.position.top
        });
      }

      return UNSAFE_componentWillReceiveProps;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate() {
        this.updateOrientation();
      }

      return componentDidUpdate;
    }()

    /* ---------------------------- Custom Methods ---------------------------- */

  }, {
    key: 'handleItemMouseEnterWithRect',
    value: function () {
      function handleItemMouseEnterWithRect(clientRect, series) {
        this.setState({
          submenuShown: series,
          submenuSourceBbox: clientRect
        });
      }

      return handleItemMouseEnterWithRect;
    }()
  }, {
    key: 'handleItemMouseEnter',
    value: function () {
      function handleItemMouseEnter(evt, series) {
        this.handleItemMouseEnterWithRect(evt.currentTarget.getBoundingClientRect(), series);
      }

      return handleItemMouseEnter;
    }()
  }, {
    key: 'handleMouseLeave',
    value: function () {
      function handleMouseLeave() {}

      return handleMouseLeave;
    }()
  }, {
    key: 'handleOtherMouseEnter',
    value: function () {
      function handleOtherMouseEnter() {
        this.setState({
          submenuShown: null
        });
      }

      return handleOtherMouseEnter;
    }()

    /*
    handleSeriesMouseEnter(evt, uid) {
      let domNode = evt.currentTarget;
       this.setState({
        submenuShown: uid,
        submenuSourceBbox: domNode.getBoundingClientRect()
      });
    }
     handleMouseLeave(evt) {
      return;
    }
     handleOtherMouseEnter(evt) {
      this.setState({
        submenuShown: null
      });
    }
    */

  }, {
    key: 'updateOrientation',
    value: function () {
      function updateOrientation() {
        if (this.adjusted) return;

        this.adjusted = true;
        this.divDom = _reactDom2['default'].findDOMNode(this.div);
        var bbox = this.divDom.getBoundingClientRect();

        var parentBbox = this.props.parentBbox ? this.props.parentBbox : {
          top: this.props.position.top,
          left: this.props.position.left,
          width: 0,
          height: 0
        };

        var orientation = this.state.orientation;

        var topPosition = parentBbox.top;

        if (parentBbox.top + bbox.height > window.innerHeight) {
          // goes off the bottom
          if (parentBbox.top - bbox.height > 0) {
            // will fit on top
            topPosition = parentBbox.top - bbox.height + TRACK_CONTROL_HEIGHT;
          } else {
            // align along the bottom
            topPosition = parentBbox.top - bbox.height + TRACK_CONTROL_HEIGHT;
            topPosition -= topPosition + bbox.height - window.innerHeight;
          }
        }

        if (this.state.orientation === 'left') {
          var leftPosition = parentBbox.left - bbox.width;

          if (leftPosition < 0) {
            if (parentBbox.left + parentBbox.width + bbox.width > window.innerWidth) {
              leftPosition = 0; // goes off the side either way
            } else {
              // switch to the right
              leftPosition = parentBbox.left + parentBbox.width;
              orientation = 'right';
            }
          }

          // we're fine keeping it left oriented
          this.setState({
            left: leftPosition,
            top: topPosition,
            orientation: orientation
          });
        } else {
          var _leftPosition = parentBbox.left + parentBbox.width;

          if (parentBbox.left + parentBbox.width + bbox.width > window.innerWidth) {
            if (parentBbox.left - bbox.width < 0) {
              // goes off both sides
              _leftPosition = 0;
              orientation = 'right';
            } else {
              _leftPosition = parentBbox.left - bbox.width;
              orientation = 'left';
            }
          }

          this.setState({
            left: _leftPosition,
            top: topPosition,
            orientation: orientation
          });
        }
      }

      return updateOrientation;
    }()

    /* ------------------------------ Rendering ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var stylePosition = this.state.left ? {
          left: this.state.left
        } : {
          right: this.state.right
        };

        var otherStyle = {
          top: this.state.top
        };

        var wholeStyle = (0, _assign2['default'])(stylePosition, otherStyle);

        var stylenames = 'context-menu';

        if (this.props.theme === _configs.THEME_DARK) stylenames += ' context-menu-dark';

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this2.div = c;
              }

              return ref;
            }(),

            style: wholeStyle,
            className: 'context-menu-item ' + (0, _getClassName3['default'])(stylenames, _styleModuleImportMap)
          },
          this.props.children
        );
      }

      return render;
    }()
  }]);
  return ContextMenuContainer;
}(_react2['default'].Component);

ContextMenuContainer.propTypes = {
  children: _propTypes2['default'].node,
  orientation: _propTypes2['default'].string,
  parentBbox: _propTypes2['default'].object,
  position: _propTypes2['default'].object,
  theme: _propTypes2['default'].symbol.isRequired
};

exports['default'] = ContextMenuContainer;

/***/ }),
/* 97 */
/***/ (function(module, exports, __nested_webpack_require_444950__) {

var Symbol = __nested_webpack_require_444950__(118),
    getRawTag = __nested_webpack_require_444950__(735),
    objectToString = __nested_webpack_require_444950__(736);

/** `Object#toString` result references. */
var nullTag = '[object Null]',
    undefinedTag = '[object Undefined]';

/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }
  return (symToStringTag && symToStringTag in Object(value))
    ? getRawTag(value)
    : objectToString(value);
}

module.exports = baseGetTag;


/***/ }),
/* 98 */
/***/ (function(module, exports, __nested_webpack_require_445821__) {

var isFunction = __nested_webpack_require_445821__(277),
    isLength = __nested_webpack_require_445821__(274);

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

module.exports = isArrayLike;


/***/ }),
/* 99 */
/***/ (function(module, exports, __nested_webpack_require_446733__) {

var baseIsNative = __nested_webpack_require_446733__(756),
    getValue = __nested_webpack_require_446733__(759);

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}

module.exports = getNative;


/***/ }),
/* 100 */
/***/ (function(module, exports, __nested_webpack_require_447295__) {

var assignValue = __nested_webpack_require_447295__(195),
    baseAssignValue = __nested_webpack_require_447295__(287);

/**
 * Copies properties of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy properties from.
 * @param {Array} props The property identifiers to copy.
 * @param {Object} [object={}] The object to copy properties to.
 * @param {Function} [customizer] The function to customize copied values.
 * @returns {Object} Returns `object`.
 */
function copyObject(source, props, object, customizer) {
  var isNew = !object;
  object || (object = {});

  var index = -1,
      length = props.length;

  while (++index < length) {
    var key = props[index];

    var newValue = customizer
      ? customizer(object[key], source[key], key, object, source)
      : undefined;

    if (newValue === undefined) {
      newValue = source[key];
    }
    if (isNew) {
      baseAssignValue(object, key, newValue);
    } else {
      assignValue(object, key, newValue);
    }
  }
  return object;
}

module.exports = copyObject;


/***/ }),
/* 101 */
/***/ (function(module, exports, __nested_webpack_require_448412__) {

var DomUtils = module.exports;

[
	__nested_webpack_require_448412__(959),
	__nested_webpack_require_448412__(963),
	__nested_webpack_require_448412__(964),
	__nested_webpack_require_448412__(965),
	__nested_webpack_require_448412__(966),
	__nested_webpack_require_448412__(967)
].forEach(function(ext){
	Object.keys(ext).forEach(function(key){
		DomUtils[key] = ext[key].bind(DomUtils);
	});
});


/***/ }),
/* 102 */
/***/ (function(module, exports, __nested_webpack_require_448804__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.



/*<replacement>*/

var pna = __nested_webpack_require_448804__(203);
/*</replacement>*/

/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) {
    keys.push(key);
  }return keys;
};
/*</replacement>*/

module.exports = Duplex;

/*<replacement>*/
var util = __nested_webpack_require_448804__(151);
util.inherits = __nested_webpack_require_448804__(58);
/*</replacement>*/

var Readable = __nested_webpack_require_448804__(468);
var Writable = __nested_webpack_require_448804__(305);

util.inherits(Duplex, Readable);

{
  // avoid scope creep, the keys array can then be collected
  var keys = objectKeys(Writable.prototype);
  for (var v = 0; v < keys.length; v++) {
    var method = keys[v];
    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  }
}

function Duplex(options) {
  if (!(this instanceof Duplex)) return new Duplex(options);

  Readable.call(this, options);
  Writable.call(this, options);

  if (options && options.readable === false) this.readable = false;

  if (options && options.writable === false) this.writable = false;

  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;

  this.once('end', onend);
}

Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._writableState.highWaterMark;
  }
});

// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended) return;

  // no more data can be written.
  // But allow more writes to happen in this tick.
  pna.nextTick(onEndNT, this);
}

function onEndNT(self) {
  self.end();
}

Object.defineProperty(Duplex.prototype, 'destroyed', {
  get: function () {
    if (this._readableState === undefined || this._writableState === undefined) {
      return false;
    }
    return this._readableState.destroyed && this._writableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (this._readableState === undefined || this._writableState === undefined) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
    this._writableState.destroyed = value;
  }
});

Duplex.prototype._destroy = function (err, cb) {
  this.push(null);
  this.end();

  pna.nextTick(cb, err);
};

/***/ }),
/* 103 */
/***/ (function(module, exports, __nested_webpack_require_452872__) {

"use strict";


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

var _validateAdapter = __nested_webpack_require_452872__(511);

var _validateAdapter2 = _interopRequireDefault(_validateAdapter);

var _configuration = __nested_webpack_require_452872__(315);

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

function getAdapter() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  if (options.adapter) {
    (0, _validateAdapter2['default'])(options.adapter);
    return options.adapter;
  }

  var _get = (0, _configuration.get)(),
      adapter = _get.adapter;

  (0, _validateAdapter2['default'])(adapter);
  return adapter;
}

/***/ }),
/* 104 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_453705__) {

"use strict";
__nested_webpack_require_453705__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-dsv/src/dsv.js
var EOL = {},
    EOF = {},
    QUOTE = 34,
    NEWLINE = 10,
    RETURN = 13;

function objectConverter(columns) {
  return new Function("d", "return {" + columns.map(function(name, i) {
    return JSON.stringify(name) + ": d[" + i + "]";
  }).join(",") + "}");
}

function customConverter(columns, f) {
  var object = objectConverter(columns);
  return function(row, i) {
    return f(object(row), i, columns);
  };
}

// Compute unique columns in order of discovery.
function inferColumns(rows) {
  var columnSet = Object.create(null),
      columns = [];

  rows.forEach(function(row) {
    for (var column in row) {
      if (!(column in columnSet)) {
        columns.push(columnSet[column] = column);
      }
    }
  });

  return columns;
}

function pad(value, width) {
  var s = value + "", length = s.length;
  return length < width ? new Array(width - length + 1).join(0) + s : s;
}

function formatYear(year) {
  return year < 0 ? "-" + pad(-year, 6)
    : year > 9999 ? "+" + pad(year, 6)
    : pad(year, 4);
}

function formatDate(date) {
  var hours = date.getUTCHours(),
      minutes = date.getUTCMinutes(),
      seconds = date.getUTCSeconds(),
      milliseconds = date.getUTCMilliseconds();
  return isNaN(date) ? "Invalid Date"
      : formatYear(date.getUTCFullYear(), 4) + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2)
      + (milliseconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "." + pad(milliseconds, 3) + "Z"
      : seconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "Z"
      : minutes || hours ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + "Z"
      : "");
}

/* harmony default export */ var dsv = (function(delimiter) {
  var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
      DELIMITER = delimiter.charCodeAt(0);

  function parse(text, f) {
    var convert, columns, rows = parseRows(text, function(row, i) {
      if (convert) return convert(row, i - 1);
      columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
    });
    rows.columns = columns || [];
    return rows;
  }

  function parseRows(text, f) {
    var rows = [], // output rows
        N = text.length,
        I = 0, // current character index
        n = 0, // current line number
        t, // current token
        eof = N <= 0, // current token followed by EOF?
        eol = false; // current token followed by EOL?

    // Strip the trailing newline.
    if (text.charCodeAt(N - 1) === NEWLINE) --N;
    if (text.charCodeAt(N - 1) === RETURN) --N;

    function token() {
      if (eof) return EOF;
      if (eol) return eol = false, EOL;

      // Unescape quotes.
      var i, j = I, c;
      if (text.charCodeAt(j) === QUOTE) {
        while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);
        if ((i = I) >= N) eof = true;
        else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;
        else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
        return text.slice(j + 1, i - 1).replace(/""/g, "\"");
      }

      // Find next delimiter or newline.
      while (I < N) {
        if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
        else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
        else if (c !== DELIMITER) continue;
        return text.slice(j, i);
      }

      // Return last token before EOF.
      return eof = true, text.slice(j, N);
    }

    while ((t = token()) !== EOF) {
      var row = [];
      while (t !== EOL && t !== EOF) row.push(t), t = token();
      if (f && (row = f(row, n++)) == null) continue;
      rows.push(row);
    }

    return rows;
  }

  function preformatBody(rows, columns) {
    return rows.map(function(row) {
      return columns.map(function(column) {
        return formatValue(row[column]);
      }).join(delimiter);
    });
  }

  function format(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");
  }

  function formatBody(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return preformatBody(rows, columns).join("\n");
  }

  function formatRows(rows) {
    return rows.map(formatRow).join("\n");
  }

  function formatRow(row) {
    return row.map(formatValue).join(delimiter);
  }

  function formatValue(value) {
    return value == null ? ""
        : value instanceof Date ? formatDate(value)
        : reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\""
        : value;
  }

  return {
    parse: parse,
    parseRows: parseRows,
    format: format,
    formatBody: formatBody,
    formatRows: formatRows
  };
});

// CONCATENATED MODULE: ../node_modules/d3-dsv/src/csv.js


var csv = dsv(",");

var csvParse = csv.parse;
var csvParseRows = csv.parseRows;
var csvFormat = csv.format;
var csvFormatBody = csv.formatBody;
var csvFormatRows = csv.formatRows;

// CONCATENATED MODULE: ../node_modules/d3-dsv/src/tsv.js


var tsv = dsv("\t");

var tsvParse = tsv.parse;
var tsvParseRows = tsv.parseRows;
var tsvFormat = tsv.format;
var tsvFormatBody = tsv.formatBody;
var tsvFormatRows = tsv.formatRows;

// CONCATENATED MODULE: ../node_modules/d3-dsv/src/autoType.js
function autoType(object) {
  for (var key in object) {
    var value = object[key].trim(), number;
    if (!value) value = null;
    else if (value === "true") value = true;
    else if (value === "false") value = false;
    else if (value === "NaN") value = NaN;
    else if (!isNaN(number = +value)) value = number;
    else if (/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/.test(value)) value = new Date(value);
    else continue;
    object[key] = value;
  }
  return object;
}

// CONCATENATED MODULE: ../node_modules/d3-dsv/src/index.js
/* concated harmony reexport dsvFormat */__nested_webpack_require_453705__.d(__webpack_exports__, "dsvFormat", function() { return dsv; });
/* concated harmony reexport csvParse */__nested_webpack_require_453705__.d(__webpack_exports__, "csvParse", function() { return csvParse; });
/* concated harmony reexport csvParseRows */__nested_webpack_require_453705__.d(__webpack_exports__, "csvParseRows", function() { return csvParseRows; });
/* concated harmony reexport csvFormat */__nested_webpack_require_453705__.d(__webpack_exports__, "csvFormat", function() { return csvFormat; });
/* concated harmony reexport csvFormatBody */__nested_webpack_require_453705__.d(__webpack_exports__, "csvFormatBody", function() { return csvFormatBody; });
/* concated harmony reexport csvFormatRows */__nested_webpack_require_453705__.d(__webpack_exports__, "csvFormatRows", function() { return csvFormatRows; });
/* concated harmony reexport tsvParse */__nested_webpack_require_453705__.d(__webpack_exports__, "tsvParse", function() { return tsvParse; });
/* concated harmony reexport tsvParseRows */__nested_webpack_require_453705__.d(__webpack_exports__, "tsvParseRows", function() { return tsvParseRows; });
/* concated harmony reexport tsvFormat */__nested_webpack_require_453705__.d(__webpack_exports__, "tsvFormat", function() { return tsvFormat; });
/* concated harmony reexport tsvFormatBody */__nested_webpack_require_453705__.d(__webpack_exports__, "tsvFormatBody", function() { return tsvFormatBody; });
/* concated harmony reexport tsvFormatRows */__nested_webpack_require_453705__.d(__webpack_exports__, "tsvFormatRows", function() { return tsvFormatRows; });
/* concated harmony reexport autoType */__nested_webpack_require_453705__.d(__webpack_exports__, "autoType", function() { return autoType; });






/***/ }),
/* 105 */
/***/ (function(module, exports, __nested_webpack_require_461482__) {

// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __nested_webpack_require_461482__(74);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
  return cof(it) == 'String' ? it.split('') : Object(it);
};


/***/ }),
/* 106 */
/***/ (function(module, exports, __nested_webpack_require_461856__) {

var core = __nested_webpack_require_461856__(12);
var global = __nested_webpack_require_461856__(23);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});

(module.exports = function (key, value) {
  return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
  version: core.version,
  mode: __nested_webpack_require_461856__(75) ? 'pure' : 'global',
  copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});


/***/ }),
/* 107 */
/***/ (function(module, exports) {

// IE 8- don't enum bug keys
module.exports = (
  'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');


/***/ }),
/* 108 */
/***/ (function(module, exports, __nested_webpack_require_462590__) {

var isObject = __nested_webpack_require_462590__(33);
var document = __nested_webpack_require_462590__(23).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
  return is ? document.createElement(it) : {};
};


/***/ }),
/* 109 */
/***/ (function(module, exports, __nested_webpack_require_462961__) {

"use strict";

var LIBRARY = __nested_webpack_require_462961__(75);
var $export = __nested_webpack_require_462961__(16);
var redefine = __nested_webpack_require_462961__(161);
var hide = __nested_webpack_require_462961__(43);
var Iterators = __nested_webpack_require_462961__(51);
var $iterCreate = __nested_webpack_require_462961__(214);
var setToStringTag = __nested_webpack_require_462961__(77);
var getPrototypeOf = __nested_webpack_require_462961__(128);
var ITERATOR = __nested_webpack_require_462961__(21)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';

var returnThis = function () { return this; };

module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
  $iterCreate(Constructor, NAME, next);
  var getMethod = function (kind) {
    if (!BUGGY && kind in proto) return proto[kind];
    switch (kind) {
      case KEYS: return function keys() { return new Constructor(this, kind); };
      case VALUES: return function values() { return new Constructor(this, kind); };
    } return function entries() { return new Constructor(this, kind); };
  };
  var TAG = NAME + ' Iterator';
  var DEF_VALUES = DEFAULT == VALUES;
  var VALUES_BUG = false;
  var proto = Base.prototype;
  var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
  var $default = $native || getMethod(DEFAULT);
  var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
  var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
  var methods, key, IteratorPrototype;
  // Fix native
  if ($anyNative) {
    IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
    if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
      // Set @@toStringTag to native iterators
      setToStringTag(IteratorPrototype, TAG, true);
      // fix for some old engines
      if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
    }
  }
  // fix Array#{values, @@iterator}.name in V8 / FF
  if (DEF_VALUES && $native && $native.name !== VALUES) {
    VALUES_BUG = true;
    $default = function values() { return $native.call(this); };
  }
  // Define iterator
  if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
    hide(proto, ITERATOR, $default);
  }
  // Plug for library
  Iterators[NAME] = $default;
  Iterators[TAG] = returnThis;
  if (DEFAULT) {
    methods = {
      values: DEF_VALUES ? $default : getMethod(VALUES),
      keys: IS_SET ? $default : getMethod(KEYS),
      entries: $entries
    };
    if (FORCED) for (key in methods) {
      if (!(key in proto)) redefine(proto, key, methods[key]);
    } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
  }
  return methods;
};


/***/ }),
/* 110 */
/***/ (function(module, exports, __nested_webpack_require_465829__) {

// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __nested_webpack_require_465829__(39);
var dPs = __nested_webpack_require_465829__(162);
var enumBugKeys = __nested_webpack_require_465829__(107);
var IE_PROTO = __nested_webpack_require_465829__(90)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';

// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
  // Thrash, waste and sodomy: IE GC bug
  var iframe = __nested_webpack_require_465829__(108)('iframe');
  var i = enumBugKeys.length;
  var lt = '<';
  var gt = '>';
  var iframeDocument;
  iframe.style.display = 'none';
  __nested_webpack_require_465829__(163).appendChild(iframe);
  iframe.src = 'javascript:'; // eslint-disable-line no-script-url
  // createDict = iframe.contentWindow.Object;
  // html.removeChild(iframe);
  iframeDocument = iframe.contentWindow.document;
  iframeDocument.open();
  iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
  iframeDocument.close();
  createDict = iframeDocument.F;
  while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
  return createDict();
};

module.exports = Object.create || function create(O, Properties) {
  var result;
  if (O !== null) {
    Empty[PROTOTYPE] = anObject(O);
    result = new Empty();
    Empty[PROTOTYPE] = null;
    // add "__proto__" for Object.getPrototypeOf polyfill
    result[IE_PROTO] = O;
  } else result = createDict();
  return Properties === undefined ? result : dPs(result, Properties);
};


/***/ }),
/* 111 */
/***/ (function(module, exports, __nested_webpack_require_467415__) {

// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __nested_webpack_require_467415__(74);
var TAG = __nested_webpack_require_467415__(21)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';

// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
  try {
    return it[key];
  } catch (e) { /* empty */ }
};

module.exports = function (it) {
  var O, T, B;
  return it === undefined ? 'Undefined' : it === null ? 'Null'
    // @@toStringTag case
    : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
    // builtinTag case
    : ARG ? cof(O)
    // ES3 arguments fallback
    : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};


/***/ }),
/* 112 */
/***/ (function(module, exports, __nested_webpack_require_468224__) {

var classof = __nested_webpack_require_468224__(111);
var ITERATOR = __nested_webpack_require_468224__(21)('iterator');
var Iterators = __nested_webpack_require_468224__(51);
module.exports = __nested_webpack_require_468224__(12).getIteratorMethod = function (it) {
  if (it != undefined) return it[ITERATOR]
    || it['@@iterator']
    || Iterators[classof(it)];
};


/***/ }),
/* 113 */
/***/ (function(module, exports, __nested_webpack_require_468614__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



var base64 = __nested_webpack_require_468614__(590)
var ieee754 = __nested_webpack_require_468614__(591)
var isArray = __nested_webpack_require_468614__(338)

exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50

/**
 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 *   === true    Use Uint8Array implementation (fastest)
 *   === false   Use Object implementation (most compatible, even IE6)
 *
 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 * Opera 11.6+, iOS 4.2+.
 *
 * Due to various browser bugs, sometimes the Object implementation will be used even
 * when the browser supports typed arrays.
 *
 * Note:
 *
 *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
 *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
 *
 *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
 *
 *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
 *     incorrect length in some situations.

 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
 * get the Object implementation, which is slower but behaves correctly.
 */
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  ? global.TYPED_ARRAY_SUPPORT
  : typedArraySupport()

/*
 * Export kMaxLength after typed array support is determined.
 */
exports.kMaxLength = kMaxLength()

function typedArraySupport () {
  try {
    var arr = new Uint8Array(1)
    arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
    return arr.foo() === 42 && // typed array instances can be augmented
        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
        arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  } catch (e) {
    return false
  }
}

function kMaxLength () {
  return Buffer.TYPED_ARRAY_SUPPORT
    ? 0x7fffffff
    : 0x3fffffff
}

function createBuffer (that, length) {
  if (kMaxLength() < length) {
    throw new RangeError('Invalid typed array length')
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = new Uint8Array(length)
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    if (that === null) {
      that = new Buffer(length)
    }
    that.length = length
  }

  return that
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
    return new Buffer(arg, encodingOrOffset, length)
  }

  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new Error(
        'If encoding is specified then the first argument must be a string'
      )
    }
    return allocUnsafe(this, arg)
  }
  return from(this, arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192 // not used by this implementation

// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
  arr.__proto__ = Buffer.prototype
  return arr
}

function from (that, value, encodingOrOffset, length) {
  if (typeof value === 'number') {
    throw new TypeError('"value" argument must not be a number')
  }

  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length)
  }

  if (typeof value === 'string') {
    return fromString(that, value, encodingOrOffset)
  }

  return fromObject(that, value)
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(null, value, encodingOrOffset, length)
}

if (Buffer.TYPED_ARRAY_SUPPORT) {
  Buffer.prototype.__proto__ = Uint8Array.prototype
  Buffer.__proto__ = Uint8Array
  if (typeof Symbol !== 'undefined' && Symbol.species &&
      Buffer[Symbol.species] === Buffer) {
    // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
    Object.defineProperty(Buffer, Symbol.species, {
      value: null,
      configurable: true
    })
  }
}

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be a number')
  } else if (size < 0) {
    throw new RangeError('"size" argument must not be negative')
  }
}

function alloc (that, size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(that, size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(that, size).fill(fill, encoding)
      : createBuffer(that, size).fill(fill)
  }
  return createBuffer(that, size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(null, size, fill, encoding)
}

function allocUnsafe (that, size) {
  assertSize(size)
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0
    }
  }
  return that
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(null, size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(null, size)
}

function fromString (that, string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding')
  }

  var length = byteLength(string, encoding) | 0
  that = createBuffer(that, length)

  var actual = that.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    that = that.slice(0, actual)
  }

  return that
}

function fromArrayLike (that, array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  that = createBuffer(that, length)
  for (var i = 0; i < length; i += 1) {
    that[i] = array[i] & 255
  }
  return that
}

function fromArrayBuffer (that, array, byteOffset, length) {
  array.byteLength // this throws if `array` is not a valid ArrayBuffer

  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('\'offset\' is out of bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('\'length\' is out of bounds')
  }

  if (byteOffset === undefined && length === undefined) {
    array = new Uint8Array(array)
  } else if (length === undefined) {
    array = new Uint8Array(array, byteOffset)
  } else {
    array = new Uint8Array(array, byteOffset, length)
  }

  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = array
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    that = fromArrayLike(that, array)
  }
  return that
}

function fromObject (that, obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    that = createBuffer(that, len)

    if (that.length === 0) {
      return that
    }

    obj.copy(that, 0, 0, len)
    return that
  }

  if (obj) {
    if ((typeof ArrayBuffer !== 'undefined' &&
        obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
      if (typeof obj.length !== 'number' || isnan(obj.length)) {
        return createBuffer(that, 0)
      }
      return fromArrayLike(that, obj)
    }

    if (obj.type === 'Buffer' && isArray(obj.data)) {
      return fromArrayLike(that, obj.data)
    }
  }

  throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}

function checked (length) {
  // Note: cannot use `length < kMaxLength()` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= kMaxLength()) {
    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
                         'size: 0x' + kMaxLength().toString(16) + ' bytes')
  }
  return length | 0
}

function SlowBuffer (length) {
  if (+length != length) { // eslint-disable-line eqeqeq
    length = 0
  }
  return Buffer.alloc(+length)
}

Buffer.isBuffer = function isBuffer (b) {
  return !!(b != null && b._isBuffer)
}

Buffer.compare = function compare (a, b) {
  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
    throw new TypeError('Arguments must be Buffers')
  }

  if (a === b) return 0

  var x = a.length
  var y = b.length

  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
      (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    string = '' + string
  }

  var len = string.length
  if (len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
      case undefined:
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 1
      case 'base64':
        return base64ToBytes(string).length
      default:
        if (loweredCase) return utf8ToBytes(string).length // assume utf8
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}
Buffer.byteLength = byteLength

function slowToString (encoding, start, end) {
  var loweredCase = false

  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  // property of a typed array.

  // This behaves neither like String nor Uint8Array in that we set start/end
  // to their upper/lower bounds if the value passed is out of range.
  // undefined is handled specially as per ECMA-262 6th Edition,
  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  if (start === undefined || start < 0) {
    start = 0
  }
  // Return early if start > this.length. Done here to prevent potential uint32
  // coercion fail below.
  if (start > this.length) {
    return ''
  }

  if (end === undefined || end > this.length) {
    end = this.length
  }

  if (end <= 0) {
    return ''
  }

  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  end >>>= 0
  start >>>= 0

  if (end <= start) {
    return ''
  }

  if (!encoding) encoding = 'utf8'

  while (true) {
    switch (encoding) {
      case 'hex':
        return hexSlice(this, start, end)

      case 'utf8':
      case 'utf-8':
        return utf8Slice(this, start, end)

      case 'ascii':
        return asciiSlice(this, start, end)

      case 'latin1':
      case 'binary':
        return latin1Slice(this, start, end)

      case 'base64':
        return base64Slice(this, start, end)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return utf16leSlice(this, start, end)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = (encoding + '').toLowerCase()
        loweredCase = true
    }
  }
}

// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true

function swap (b, n, m) {
  var i = b[n]
  b[n] = b[m]
  b[m] = i
}

Buffer.prototype.swap16 = function swap16 () {
  var len = this.length
  if (len % 2 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 16-bits')
  }
  for (var i = 0; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length | 0
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  if (this.length > 0) {
    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
    if (this.length > max) str += ' ... '
  }
  return '<Buffer ' + str + '>'
}

Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  if (!Buffer.isBuffer(target)) {
    throw new TypeError('Argument must be a Buffer')
  }

  if (start === undefined) {
    start = 0
  }
  if (end === undefined) {
    end = target ? target.length : 0
  }
  if (thisStart === undefined) {
    thisStart = 0
  }
  if (thisEnd === undefined) {
    thisEnd = this.length
  }

  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError('out of range index')
  }

  if (thisStart >= thisEnd && start >= end) {
    return 0
  }
  if (thisStart >= thisEnd) {
    return -1
  }
  if (start >= end) {
    return 1
  }

  start >>>= 0
  end >>>= 0
  thisStart >>>= 0
  thisEnd >>>= 0

  if (this === target) return 0

  var x = thisEnd - thisStart
  var y = end - start
  var len = Math.min(x, y)

  var thisCopy = this.slice(thisStart, thisEnd)
  var targetCopy = target.slice(start, end)

  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  // Empty buffer means no match
  if (buffer.length === 0) return -1

  // Normalize byteOffset
  if (typeof byteOffset === 'string') {
    encoding = byteOffset
    byteOffset = 0
  } else if (byteOffset > 0x7fffffff) {
    byteOffset = 0x7fffffff
  } else if (byteOffset < -0x80000000) {
    byteOffset = -0x80000000
  }
  byteOffset = +byteOffset  // Coerce to Number.
  if (isNaN(byteOffset)) {
    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
    byteOffset = dir ? 0 : (buffer.length - 1)
  }

  // Normalize byteOffset: negative offsets start from the end of the buffer
  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  if (byteOffset >= buffer.length) {
    if (dir) return -1
    else byteOffset = buffer.length - 1
  } else if (byteOffset < 0) {
    if (dir) byteOffset = 0
    else return -1
  }

  // Normalize val
  if (typeof val === 'string') {
    val = Buffer.from(val, encoding)
  }

  // Finally, search either indexOf (if dir is true) or lastIndexOf
  if (Buffer.isBuffer(val)) {
    // Special case: looking for empty string/buffer always fails
    if (val.length === 0) {
      return -1
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  } else if (typeof val === 'number') {
    val = val & 0xFF // Search for a byte value [0-255]
    if (Buffer.TYPED_ARRAY_SUPPORT &&
        typeof Uint8Array.prototype.indexOf === 'function') {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
      }
    }
    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  }

  throw new TypeError('val must be string, number or Buffer')
}

function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  var indexSize = 1
  var arrLength = arr.length
  var valLength = val.length

  if (encoding !== undefined) {
    encoding = String(encoding).toLowerCase()
    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
        encoding === 'utf16le' || encoding === 'utf-16le') {
      if (arr.length < 2 || val.length < 2) {
        return -1
      }
      indexSize = 2
      arrLength /= 2
      valLength /= 2
      byteOffset /= 2
    }
  }

  function read (buf, i) {
    if (indexSize === 1) {
      return buf[i]
    } else {
      return buf.readUInt16BE(i * indexSize)
    }
  }

  var i
  if (dir) {
    var foundIndex = -1
    for (i = byteOffset; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      length = remaining
    }
  }

  // must be an even number of digits
  var strLen = string.length
  if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')

  if (length > strLen / 2) {
    length = strLen / 2
  }
  for (var i = 0; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (isNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset | 0
    if (isFinite(length)) {
      length = length | 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  // legacy write(string, encoding, offset, length) - remove in v0.13
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) length = remaining

  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
    throw new RangeError('Attempt to write outside buffer bounds')
  }

  if (!encoding) encoding = 'utf8'

  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'hex':
        return hexWrite(this, string, offset, length)

      case 'utf8':
      case 'utf-8':
        return utf8Write(this, string, offset, length)

      case 'ascii':
        return asciiWrite(this, string, offset, length)

      case 'latin1':
      case 'binary':
        return latin1Write(this, string, offset, length)

      case 'base64':
        // Warning: maxLength not taken into account in base64Write
        return base64Write(this, string, offset, length)

      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return ucs2Write(this, string, offset, length)

      default:
        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
        encoding = ('' + encoding).toLowerCase()
        loweredCase = true
    }
  }
}

Buffer.prototype.toJSON = function toJSON () {
  return {
    type: 'Buffer',
    data: Array.prototype.slice.call(this._arr || this, 0)
  }
}

function base64Slice (buf, start, end) {
  if (start === 0 && end === buf.length) {
    return base64.fromByteArray(buf)
  } else {
    return base64.fromByteArray(buf.slice(start, end))
  }
}

function utf8Slice (buf, start, end) {
  end = Math.min(buf.length, end)
  var res = []

  var i = start
  while (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 4
      : (firstByte > 0xDF) ? 3
      : (firstByte > 0xBF) ? 2
      : 1

    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint

      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 0x80) {
            codePoint = firstByte
          }
          break
        case 2:
          secondByte = buf[i + 1]
          if ((secondByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
            if (tempCodePoint > 0x7F) {
              codePoint = tempCodePoint
            }
          }
          break
        case 3:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
              codePoint = tempCodePoint
            }
          }
          break
        case 4:
          secondByte = buf[i + 1]
          thirdByte = buf[i + 2]
          fourthByte = buf[i + 3]
          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
              codePoint = tempCodePoint
            }
          }
      }
    }

    if (codePoint === null) {
      // we did not generate a valid codePoint so insert a
      // replacement char (U+FFFD) and advance only 1 byte
      codePoint = 0xFFFD
      bytesPerSequence = 1
    } else if (codePoint > 0xFFFF) {
      // encode to utf16 (surrogate pair dance)
      codePoint -= 0x10000
      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
      codePoint = 0xDC00 | codePoint & 0x3FF
    }

    res.push(codePoint)
    i += bytesPerSequence
  }

  return decodeCodePointsArray(res)
}

// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000

function decodeCodePointsArray (codePoints) {
  var len = codePoints.length
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  }

  // Decode in chunks to avoid "call stack size exceeded".
  var res = ''
  var i = 0
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end)
    newBuf.__proto__ = Buffer.prototype
  } else {
    var sliceLen = end - start
    newBuf = new Buffer(sliceLen, undefined)
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start]
    }
  }

  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}

Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (mul *= 0x100)) {
    val += this[offset + --byteLength] * mul
  }

  return val
}

Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 1, this.length)
  return this[offset]
}

Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  return this[offset] | (this[offset + 1] << 8)
}

Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  return (this[offset] << 8) | this[offset + 1]
}

Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return ((this[offset]) |
      (this[offset + 1] << 8) |
      (this[offset + 2] << 16)) +
      (this[offset + 3] * 0x1000000)
}

Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] * 0x1000000) +
    ((this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    this[offset + 3])
}

Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var val = this[offset]
  var mul = 1
  var i = 0
  while (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) checkOffset(offset, byteLength, this.length)

  var i = byteLength
  var mul = 1
  var val = this[offset + --i]
  while (i > 0 && (mul *= 0x100)) {
    val += this[offset + --i] * mul
  }
  mul *= 0x80

  if (val >= mul) val -= Math.pow(2, 8 * byteLength)

  return val
}

Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 1, this.length)
  if (!(this[offset] & 0x80)) return (this[offset])
  return ((0xff - this[offset] + 1) * -1)
}

Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset] | (this[offset + 1] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 2, this.length)
  var val = this[offset + 1] | (this[offset] << 8)
  return (val & 0x8000) ? val | 0xFFFF0000 : val
}

Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset]) |
    (this[offset + 1] << 8) |
    (this[offset + 2] << 16) |
    (this[offset + 3] << 24)
}

Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)

  return (this[offset] << 24) |
    (this[offset + 1] << 16) |
    (this[offset + 2] << 8) |
    (this[offset + 3])
}

Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, true, 23, 4)
}

Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 4, this.length)
  return ieee754.read(this, offset, false, 23, 4)
}

Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, true, 52, 8)
}

Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  if (!noAssert) checkOffset(offset, 8, this.length)
  return ieee754.read(this, offset, false, 52, 8)
}

function checkInt (buf, value, offset, ext, max, min) {
  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
}

Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var mul = 1
  var i = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength) - 1
    checkInt(this, value, offset, byteLength, maxBytes, 0)
  }

  var i = byteLength - 1
  var mul = 1
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  this[offset] = (value & 0xff)
  return offset + 1
}

function objectWriteUInt16 (buf, value, offset, littleEndian) {
  if (value < 0) value = 0xffff + value + 1
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
      (littleEndian ? i : 1 - i) * 8
  }
}

Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
  } else {
    objectWriteUInt16(this, value, offset, true)
  }
  return offset + 2
}

Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
  } else {
    objectWriteUInt16(this, value, offset, false)
  }
  return offset + 2
}

function objectWriteUInt32 (buf, value, offset, littleEndian) {
  if (value < 0) value = 0xffffffff + value + 1
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  }
}

Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset + 3] = (value >>> 24)
    this[offset + 2] = (value >>> 16)
    this[offset + 1] = (value >>> 8)
    this[offset] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, true)
  }
  return offset + 4
}

Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, false)
  }
  return offset + 4
}

Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = 0
  var mul = 1
  var sub = 0
  this[offset] = value & 0xFF
  while (++i < byteLength && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength - 1)

    checkInt(this, value, offset, byteLength, limit - 1, -limit)
  }

  var i = byteLength - 1
  var mul = 1
  var sub = 0
  this[offset + i] = value & 0xFF
  while (--i >= 0 && (mul *= 0x100)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1
    }
    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  if (value < 0) value = 0xff + value + 1
  this[offset] = (value & 0xff)
  return offset + 1
}

Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
  } else {
    objectWriteUInt16(this, value, offset, true)
  }
  return offset + 2
}

Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 8)
    this[offset + 1] = (value & 0xff)
  } else {
    objectWriteUInt16(this, value, offset, false)
  }
  return offset + 2
}

Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value & 0xff)
    this[offset + 1] = (value >>> 8)
    this[offset + 2] = (value >>> 16)
    this[offset + 3] = (value >>> 24)
  } else {
    objectWriteUInt32(this, value, offset, true)
  }
  return offset + 4
}

Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  value = +value
  offset = offset | 0
  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  if (value < 0) value = 0xffffffff + value + 1
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    this[offset] = (value >>> 24)
    this[offset + 1] = (value >>> 16)
    this[offset + 2] = (value >>> 8)
    this[offset + 3] = (value & 0xff)
  } else {
    objectWriteUInt32(this, value, offset, false)
  }
  return offset + 4
}

function checkIEEE754 (buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
  if (offset < 0) throw new RangeError('Index out of range')
}

function writeFloat (buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  }
  ieee754.write(buf, value, offset, littleEndian, 23, 4)
  return offset + 4
}

Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert)
}

Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert)
}

function writeDouble (buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  }
  ieee754.write(buf, value, offset, littleEndian, 52, 8)
  return offset + 8
}

Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert)
}

Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert)
}

// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  if (!start) start = 0
  if (!end && end !== 0) end = this.length
  if (targetStart >= target.length) targetStart = target.length
  if (!targetStart) targetStart = 0
  if (end > 0 && end < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  if (end < 0) throw new RangeError('sourceEnd out of bounds')

  // Are we oob?
  if (end > this.length) end = this.length
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start
  var i

  if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
    // ascending copy from start
    for (i = 0; i < len; ++i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, start + len),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if (code < 256) {
        val = code
      }
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : utf8ToBytes(new Buffer(val, encoding).toString())
    var len = bytes.length
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function stringtrim (str) {
  if (str.trim) return str.trim()
  return str.replace(/^\s+|\s+$/g, '')
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && codePoint < 0xE000) {
      // last char was a lead
      if (!leadSurrogate) {
        // no lead yet
        if (codePoint > 0xDBFF) {
          // unexpected trail
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        } else if (i + 1 === length) {
          // unpaired lead
          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
          continue
        }

        // valid lead
        leadSurrogate = codePoint

        continue
      }

      // 2 leads in a row
      if (codePoint < 0xDC00) {
        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
        leadSurrogate = codePoint
        continue
      }

      // valid surrogate pair
      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
    } else if (leadSurrogate) {
      // valid bmp char, but last char was a lead
      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
    }

    leadSurrogate = null

    // encode utf8
    if (codePoint < 0x80) {
      if ((units -= 1) < 0) break
      bytes.push(codePoint)
    } else if (codePoint < 0x800) {
      if ((units -= 2) < 0) break
      bytes.push(
        codePoint >> 0x6 | 0xC0,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x10000) {
      if ((units -= 3) < 0) break
      bytes.push(
        codePoint >> 0xC | 0xE0,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else if (codePoint < 0x110000) {
      if ((units -= 4) < 0) break
      bytes.push(
        codePoint >> 0x12 | 0xF0,
        codePoint >> 0xC & 0x3F | 0x80,
        codePoint >> 0x6 & 0x3F | 0x80,
        codePoint & 0x3F | 0x80
      )
    } else {
      throw new Error('Invalid code point')
    }
  }

  return bytes
}

function asciiToBytes (str) {
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 8
    lo = c % 256
    byteArray.push(lo)
    byteArray.push(hi)
  }

  return byteArray
}

function base64ToBytes (str) {
  return base64.toByteArray(base64clean(str))
}

function blitBuffer (src, dst, offset, length) {
  for (var i = 0; i < length; ++i) {
    if ((i + offset >= dst.length) || (i >= src.length)) break
    dst[i + offset] = src[i]
  }
  return i
}

function isnan (val) {
  return val !== val // eslint-disable-line no-self-compare
}

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_468614__(27)))

/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
// Number of subset (in one direction) that is used to precompute extrema
// in the case of continuous scaling
var NUM_PRECOMP_SUBSETS_PER_1D_TTILE = exports.NUM_PRECOMP_SUBSETS_PER_1D_TTILE = 8;

// Number of subset (in one direction) that is used to precompute extrema
// in the case of continuous scaling
var NUM_PRECOMP_SUBSETS_PER_2D_TTILE = exports.NUM_PRECOMP_SUBSETS_PER_2D_TTILE = 8;

/***/ }),
/* 115 */
/***/ (function(module, exports, __nested_webpack_require_517985__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_517985__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _stringify = __nested_webpack_require_517985__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = __nested_webpack_require_517985__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_517985__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_517985__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_517985__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_517985__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_517985__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _Tiled1DPixiTrack2 = __nested_webpack_require_517985__(255);

var _Tiled1DPixiTrack3 = _interopRequireDefault(_Tiled1DPixiTrack2);

var _AxisPixi = __nested_webpack_require_517985__(179);

var _AxisPixi2 = _interopRequireDefault(_AxisPixi);

var _services = __nested_webpack_require_517985__(24);

var _utils = __nested_webpack_require_517985__(10);

var _configs = __nested_webpack_require_517985__(11);

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

var HorizontalTiled1DPixiTrack = function (_Tiled1DPixiTrack) {
  (0, _inherits3['default'])(HorizontalTiled1DPixiTrack, _Tiled1DPixiTrack);

  function HorizontalTiled1DPixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, HorizontalTiled1DPixiTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HorizontalTiled1DPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTiled1DPixiTrack)).call(this, context, options));

    var animate = context.animate,
        isShowGlobalMousePosition = context.isShowGlobalMousePosition;


    _this.constIndicator = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMain.addChild(_this.constIndicator);

    _this.axis = new _AxisPixi2['default'](_this);
    _this.pBase.addChild(_this.axis.pAxis);

    _this.animate = animate;
    _this.options = options;
    _this.isShowGlobalMousePosition = isShowGlobalMousePosition;

    _this.pubSubs = [];

    if (_this.options.showMousePosition && !_this.hideMousePosition) {
      _this.hideMousePosition = (0, _utils.showMousePosition)(_this, _this.is2d, _this.isShowGlobalMousePosition());
    }
    return _this;
  }

  (0, _createClass3['default'])(HorizontalTiled1DPixiTrack, [{
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        var strOptions = (0, _stringify2['default'])(options);

        if (!force && strOptions === this.prevOptions) return;

        (0, _get3['default'])(HorizontalTiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTiled1DPixiTrack.prototype), 'rerender', this).call(this, options, force);

        this.prevOptions = strOptions;
        this.options = options;

        if (this.options.showMousePosition && !this.hideMousePosition) {
          this.hideMousePosition = (0, _utils.showMousePosition)(this, this.is2d, this.isShowGlobalMousePosition());
        }

        if (!this.options.showMousePosition && this.hideMousePosition) {
          this.hideMousePosition();
          this.hideMousePosition = undefined;
        }
      }

      return rerender;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        // offset by 2 because 1D tiles are more dense than 2D tiles
        // 1024 points per tile vs 256 for 2D tiles
        if (this.tilesetInfo.resolutions) {
          var zoomIndexX = _services.tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0] - 2);

          return zoomIndexX;
        }

        // the tileProxy calculateZoomLevel function only cares about the
        // difference between the minimum and maximum position
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.bins_per_dimension || this.tilesetInfo.tile_size);

        var zoomLevel = Math.min(xZoomLevel, this.maxZoom);
        zoomLevel = Math.max(zoomLevel, 0);

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()

    /**
     * Which scale should we use for calculating tile positions?
     *
     * Horizontal tracks should use the xScale and vertical tracks
     * should use the yScale
     *
     * This function should be overwritten by HorizontalTiled1DPixiTrack.js
     * and VerticalTiled1DPixiTrack.js
     */

  }, {
    key: 'relevantScale',
    value: function () {
      function relevantScale() {
        return this._xScale;
      }

      return relevantScale;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        (0, _get3['default'])(HorizontalTiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTiled1DPixiTrack.prototype), 'draw', this).call(this);
        this.drawConstIndicator();
      }

      return draw;
    }()
  }, {
    key: 'drawAxis',
    value: function () {
      function drawAxis(valueScale) {
        // either no axis position is specified
        if (!this.options.axisPositionVertical && !this.options.axisPositionHorizontal) {
          this.axis.clearAxis();
          return;
        }

        if (this.options.axisPositionVertical && this.options.axisPositionVertical === 'hidden') {
          this.axis.clearAxis();
          return;
        }

        if (this.options.axisPositionHorizontal && this.options.axisPositionHorizontal === 'hidden') {
          this.axis.clearAxis();
          return;
        }

        var margin = this.options.axisMargin || 0;

        if (this.options.axisPositionHorizontal === 'left' || this.options.axisPositionVertical === 'top') {
          // left axis are shown at the beginning of the plot
          this.axis.pAxis.position.x = this.position[0] + margin;
          this.axis.pAxis.position.y = this.position[1];

          this.axis.drawAxisRight(valueScale, this.dimensions[1]);
        } else if (this.options.axisPositionHorizontal === 'outsideLeft' || this.options.axisPositionVertical === 'outsideTop') {
          // left axis are shown at the beginning of the plot
          this.axis.pAxis.position.x = this.position[0] + margin;
          this.axis.pAxis.position.y = this.position[1];

          this.axis.drawAxisLeft(valueScale, this.dimensions[1]);
        } else if (this.options.axisPositionHorizontal === 'right' || this.options.axisPositionVertical === 'bottom') {
          this.axis.pAxis.position.x = this.position[0] + this.dimensions[0] - margin;
          this.axis.pAxis.position.y = this.position[1];
          this.axis.drawAxisLeft(valueScale, this.dimensions[1]);
        } else if (this.options.axisPositionHorizontal === 'outsideRight' || this.options.axisPositionVertical === 'outsideBottom') {
          this.axis.pAxis.position.x = this.position[0] + this.dimensions[0] - margin;
          this.axis.pAxis.position.y = this.position[1];
          this.axis.drawAxisRight(valueScale, this.dimensions[1]);
        }
      }

      return drawAxis;
    }()
  }, {
    key: 'mouseMoveZoomHandler',
    value: function () {
      function mouseMoveZoomHandler() {
        var absX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.mouseX;
        var absY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.mouseY;

        if (typeof absX === 'undefined' || !this.areAllVisibleTilesLoaded() || !this.tilesetInfo) return;

        var dataPosX = 0;
        var dataPosY = 0;
        var orientation = '1d-horizontal';

        if (this.isLeftModified) {
          dataPosX = absY - this.position[1];
          dataPosY = absX - this.position[0];
          orientation = '1d-vertical';
        } else {
          dataPosX = absX - this.position[0];
          dataPosY = absY - this.position[1];
        }

        var relX = absX - this.position[0];
        var relY = absY - this.position[1];
        var dataX = this._xScale.invert(dataPosX);
        var dataY = this._yScale.invert(dataPosY);

        var data = this.getDataAtPos(dataPosX);
        if (!data) return;

        this.onMouseMoveZoom({
          trackId: this.id,
          data: data,
          absX: absX,
          absY: absY,
          relX: relX,
          relY: relY,
          dataX: dataX,
          dataY: dataY,
          orientation: orientation
        });
      }

      return mouseMoveZoomHandler;
    }()
  }, {
    key: 'drawConstIndicator',
    value: function () {
      function drawConstIndicator() {
        var _this2 = this;

        if (!this.constIndicator) {
          // this can happen if we receive a tilesetInfo in the TiledPixiTrack
          // constructor before we get a chance to initialize this object
          return;
        }

        this.constIndicator.clear();
        while (this.constIndicator.children[0]) {
          this.constIndicator.removeChild(this.constIndicator.children[0]);
        }

        if (!this.options.constIndicators || !this.valueScale) return;

        this.options.constIndicators.forEach(function () {
          var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
              _ref$color = _ref.color,
              color = _ref$color === undefined ? 'black' : _ref$color,
              _ref$opacity = _ref.opacity,
              opacity = _ref$opacity === undefined ? 1.0 : _ref$opacity,
              _ref$label = _ref.label,
              label = _ref$label === undefined ? null : _ref$label,
              _ref$labelColor = _ref.labelColor,
              labelColor = _ref$labelColor === undefined ? 'black' : _ref$labelColor,
              _ref$labelOpacity = _ref.labelOpacity,
              labelOpacity = _ref$labelOpacity === undefined ? 1.0 : _ref$labelOpacity,
              _ref$labelPosition = _ref.labelPosition,
              labelPosition = _ref$labelPosition === undefined ? 'leftTop' : _ref$labelPosition,
              _ref$labelSize = _ref.labelSize,
              labelSize = _ref$labelSize === undefined ? 12 : _ref$labelSize,
              _ref$value = _ref.value,
              value = _ref$value === undefined ? 0 : _ref$value;

          var colorHex = (0, _utils.colorToHex)(color);
          var labelColorHex = (0, _utils.colorToHex)(labelColor);

          _this2.constIndicator.beginFill(colorHex, opacity);

          var y = _this2.valueScale(value);
          var xOffset = 0;
          var widthOffset = 0;

          if (label) {
            var labelG = new _configs.GLOBALS.PIXI.Text(label, {
              fontFamily: 'Arial',
              fontSize: labelSize,
              fill: labelColorHex
            });
            labelG.alpha = labelOpacity;

            switch (labelPosition) {
              case 'right':
                labelG.anchor.x = 1;
                labelG.anchor.y = 0.5;
                labelG.x = _this2.position[0] + _this2.dimensions[0] - 6;
                labelG.y = y;
                widthOffset = labelG.width + 8;
                break;

              case 'rightBottom':
                labelG.anchor.x = 1;
                labelG.anchor.y = 0;
                labelG.x = _this2.position[0] + _this2.dimensions[0] - 6;
                labelG.y = y;
                break;

              case 'rightTop':
                labelG.anchor.x = 1;
                labelG.anchor.y = 1;
                labelG.x = _this2.position[0] + _this2.dimensions[0] - 6;
                labelG.y = y;
                break;

              case 'left':
                labelG.anchor.x = 0;
                labelG.anchor.y = 0.5;
                labelG.x = _this2.position[0] + 2;
                labelG.y = y;
                xOffset = labelG.width + 4;
                break;

              case 'leftBottom':
                labelG.anchor.x = 0;
                labelG.anchor.y = 0;
                labelG.x = _this2.position[0] + 2;
                labelG.y = y;
                break;

              case 'leftTop':
              default:
                labelG.anchor.x = 0;
                labelG.anchor.y = 1;
                labelG.x = _this2.position[0] + 2;
                labelG.y = y;
                break;
            }
            _this2.constIndicator.addChild(labelG);
          }

          _this2.constIndicator.drawRect(_this2.position[0] + xOffset, y, _this2.dimensions[0] - widthOffset, 1);
        });
      }

      return drawConstIndicator;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var _this3 = this;

        var track = null;
        var base = null;

        if ((0, _get3['default'])(HorizontalTiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTiled1DPixiTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(HorizontalTiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTiled1DPixiTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }

        base.setAttribute('class', 'horizontal-tiled-1d-track');
        var output = document.createElement('g');

        track.appendChild(output);

        if (this.options.constIndicators) {
          this.options.constIndicators.forEach(function () {
            var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
                _ref2$color = _ref2.color,
                color = _ref2$color === undefined ? 'black' : _ref2$color,
                _ref2$opacity = _ref2.opacity,
                opacity = _ref2$opacity === undefined ? 1.0 : _ref2$opacity,
                _ref2$label = _ref2.label,
                label = _ref2$label === undefined ? null : _ref2$label,
                _ref2$labelColor = _ref2.labelColor,
                labelColor = _ref2$labelColor === undefined ? 'black' : _ref2$labelColor,
                _ref2$labelOpacity = _ref2.labelOpacity,
                labelOpacity = _ref2$labelOpacity === undefined ? 1.0 : _ref2$labelOpacity,
                _ref2$labelPosition = _ref2.labelPosition,
                labelPosition = _ref2$labelPosition === undefined ? 'leftTop' : _ref2$labelPosition,
                _ref2$labelSize = _ref2.labelSize,
                labelSize = _ref2$labelSize === undefined ? 12 : _ref2$labelSize,
                _ref2$value = _ref2.value,
                value = _ref2$value === undefined ? 0 : _ref2$value;

            var y = _this3.valueScale(value);

            if (label) {
              var labelEl = document.createElement('text');
              labelEl.textContent = label;

              labelEl.setAttribute('x', _this3.position[0]);
              labelEl.setAttribute('y', y);
              labelEl.setAttribute('style', 'font-family: \'Arial\'; font-size: ' + String(labelSize) + 'px; fill: ' + String(labelColor) + '; fill-opacity: ' + String(labelOpacity) + ';');

              switch (labelPosition) {
                case 'rightBottom':
                  labelEl.setAttribute('x', _this3.position[0] + _this3.dimensions[0] - 6);
                  labelEl.setAttribute('y', y + labelSize + 2);
                  labelEl.setAttribute('text-anchor', 'end');
                  break;

                case 'right':
                case 'rightTop':
                  labelEl.setAttribute('x', _this3.position[0] + _this3.dimensions[0] - 6);
                  labelEl.setAttribute('y', y - 2);
                  labelEl.setAttribute('text-anchor', 'end');
                  break;

                case 'leftBottom':
                  labelEl.setAttribute('x', _this3.position[0] + 2);
                  labelEl.setAttribute('y', y + labelSize + 2);
                  break;

                case 'left':
                case 'leftTop':
                default:
                  labelEl.setAttribute('x', _this3.position[0] + 2);
                  labelEl.setAttribute('y', y - 2);
                  break;
              }

              output.appendChild(labelEl);
            }

            var line = document.createElement('line');
            line.setAttribute('x1', _this3.position[0]);
            line.setAttribute('y1', y);
            line.setAttribute('x2', _this3.dimensions[0]);
            line.setAttribute('y2', y);
            line.setAttribute('stroke', color);
            line.setAttribute('stroke-opacity', opacity);

            output.appendChild(line);
          });
        }

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return HorizontalTiled1DPixiTrack;
}(_Tiled1DPixiTrack3['default']);

// Configs


exports['default'] = HorizontalTiled1DPixiTrack;

/***/ }),
/* 116 */
/***/ (function(module, exports, __nested_webpack_require_535313__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_535313__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _isNan = __nested_webpack_require_535313__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _slicedToArray2 = __nested_webpack_require_535313__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_535313__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_535313__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_535313__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_535313__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_535313__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_535313__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Format = __nested_webpack_require_535313__(20);

var _d3Scale = __nested_webpack_require_535313__(28);

var _HorizontalTiled1DPixiTrack = __nested_webpack_require_535313__(115);

var _HorizontalTiled1DPixiTrack2 = _interopRequireDefault(_HorizontalTiled1DPixiTrack);

var _utils = __nested_webpack_require_535313__(10);

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

var HorizontalLine1DPixiTrack = function (_HorizontalTiled1DPix) {
  (0, _inherits3['default'])(HorizontalLine1DPixiTrack, _HorizontalTiled1DPix);

  function HorizontalLine1DPixiTrack() {
    (0, _classCallCheck3['default'])(this, HorizontalLine1DPixiTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (HorizontalLine1DPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(HorizontalLine1DPixiTrack, [{
    key: 'stopHover',
    value: function () {
      function stopHover() {
        this.pMouseOver.clear();
        this.animate();
      }

      return stopHover;
    }()
  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX) {
        // if we're not supposed to show the tooltip, don't show it
        // we return here so that the mark isn't drawn in the code
        // below
        if (!this.tilesetInfo || !this.options.showTooltip || !this.valueScale) return '';

        var value = this.getDataAtPos(trackX);
        var textValue = '';

        if (value) textValue = (0, _d3Format.format)('.3f')(value);

        var graphics = this.pMouseOver;
        var colorHex = 0;
        var yPos = this.valueScale(value);

        graphics.clear();
        graphics.beginFill(colorHex, 0.5);
        graphics.lineStyle(1, colorHex, 1);
        var markerWidth = 4;

        graphics.drawRect(trackX - markerWidth / 2, yPos - markerWidth / 2, markerWidth, markerWidth);

        this.animate();

        return '' + String(textValue);
      }

      return getMouseOverHtml;
    }()

    /**
     * Create whatever is needed to draw this tile.
     */

  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'initTile', this).call(this, tile);

        if (!tile.tileData || !tile.tileData.dense) {
          console.warn('emptyTile:', tile);
          return;
        }

        tile.xValues = new Array(tile.tileData.dense.length);
        tile.yValues = new Array(tile.tileData.dense.length);

        if (this.isValueScaleLocked()) {
          // If valueScales are locked get min and max values of the locked group
          // for initialization. This prevents a flickering that is caused by
          // rendering the track multiple times with possibly different valueScales
          var glge = this.getLockGroupExtrema();
          if (glge !== null) {
            this.minValue(glge[0]);
            this.maxValue(glge[1]);
          }
        }

        this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        var _this2 = this;

        (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'rerender', this).call(this, options, force);

        this.options = options;

        (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'draw', this).call(this);

        this.visibleAndFetchedTiles().forEach(function (tile) {
          _this2.renderTile(tile);
        });
      }

      return rerender;
    }()
  }, {
    key: 'renderTile',
    value: function () {
      function renderTile(tile) {
        // this function is just so that we follow the same pattern as
        // HeatmapTiledPixiTrack.js
        this.drawTile(tile);
        this.drawAxis(this.valueScale);
      }

      return renderTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'drawTile', this).call(this, tile);

        if (!tile.graphics) {
          return;
        }

        if (!tile.tileData || !tile.tileData.dense) {
          return;
        }

        var graphics = tile.graphics;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileValues = tile.tileData.dense;

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

        var _makeValueScale = this.makeValueScale(this.minValue(), this.medianVisibleValue, this.maxValue()),
            _makeValueScale2 = (0, _slicedToArray3['default'])(_makeValueScale, 2),
            vs = _makeValueScale2[0],
            offsetValue = _makeValueScale2[1];

        this.valueScale = vs;

        graphics.clear();

        this.drawAxis(this.valueScale);

        if (this.options.valueScaling === 'log' && this.valueScale.domain()[1] < 0) {
          console.warn('Negative values present when using a log scale', this.valueScale.domain());
          return;
        }

        var stroke = (0, _utils.colorToHex)(this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue');
        // this scale should go from an index in the data array to
        // a position in the genome coordinates
        if (!this.tilesetInfo.tile_size && !this.tilesetInfo.bins_per_dimension) {
          console.warn('No tileset_info.tile_size or tileset_info.bins_per_dimension', this.tilesetInfo);
        }

        var tileSize = this.tilesetInfo.tile_size || this.tilesetInfo.bins_per_dimension;

        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, tileSize]).range([tileX, tileX + tileWidth]);

        var strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1;
        graphics.lineStyle(strokeWidth, stroke, 1);

        tile.segments = [];
        var currentSegment = [];

        for (var i = 0; i < tileValues.length; i++) {
          var xPos = this._xScale(tileXScale(i));
          var yPos = this.valueScale(tileValues[i] + offsetValue);

          if (this.options.valueScaling === 'log' && tileValues[i] === 0 || (0, _isNan2['default'])(yPos)) {
            if (currentSegment.length > 1) {
              tile.segments.push(currentSegment);
            }
            // Just ignore 1-element segments.
            currentSegment = [];
            continue;
          }

          if (tileXScale(i) > this.tilesetInfo.max_pos[0]) {
            // Data is in the last tile and extends beyond the coordinate system.
            break;
          }

          currentSegment.push([xPos, yPos]);
        }
        if (currentSegment.length > 1) {
          tile.segments.push(currentSegment);
        }

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(tile.segments), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var segment = _step.value;

            var first = segment[0];
            var rest = segment.slice(1);
            graphics.moveTo(first[0], first[1]);
            var _iteratorNormalCompletion2 = true;
            var _didIteratorError2 = false;
            var _iteratorError2 = undefined;

            try {
              for (var _iterator2 = (0, _getIterator3['default'])(rest), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                var point = _step2.value;

                graphics.lineTo(point[0], point[1]);
              }
            } catch (err) {
              _didIteratorError2 = true;
              _iteratorError2 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion2 && _iterator2['return']) {
                  _iterator2['return']();
                }
              } finally {
                if (_didIteratorError2) {
                  throw _iteratorError2;
                }
              }
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return drawTile;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];

        this.pMouseOver.position.y = this.position[1];
        this.pMouseOver.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTiles();

        this.draw();

        var isValueScaleLocked = this.isValueScaleLocked();

        if (this.continuousScaling && this.minValue() !== undefined && this.maxValue() !== undefined) {
          if (this.valueScaleMin === null && this.valueScaleMax === null && !isValueScaleLocked) {
            var newMin = this.minVisibleValue();
            var newMax = this.maxVisibleValue();

            var epsilon = 1e-6;

            if (newMin !== null && newMax !== null && (Math.abs(this.minValue() - newMin) > epsilon || Math.abs(this.maxValue() - newMax) > epsilon)) {
              this.minValue(newMin);
              this.maxValue(newMax);

              this.scheduleRerender();
            }
          }

          if (isValueScaleLocked) {
            this.onValueScaleChanged();
          }
        }
      }

      return zoomed;
    }()
  }, {
    key: 'superSVG',
    value: function () {
      function superSVG() {
        /*
         * Bypass this track's exportSVG and call its parent's directly.
         */
        return (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'exportSVG', this).call(this);
      }

      return superSVG;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(HorizontalLine1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalLine1DPixiTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }

        base.setAttribute('class', 'exported-line-track');
        var output = document.createElement('g');

        track.appendChild(output);
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        var stroke = this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue';

        this.visibleAndFetchedTiles().forEach(function (tile) {
          var g = document.createElement('path');
          g.setAttribute('fill', 'transparent');
          g.setAttribute('stroke', stroke);
          var d = '';

          var _iteratorNormalCompletion3 = true;
          var _didIteratorError3 = false;
          var _iteratorError3 = undefined;

          try {
            for (var _iterator3 = (0, _getIterator3['default'])(tile.segments), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
              var segment = _step3.value;

              var first = segment[0];
              var rest = segment.slice(1);
              d += 'M' + String(first[0]) + ' ' + String(first[1]);
              var _iteratorNormalCompletion4 = true;
              var _didIteratorError4 = false;
              var _iteratorError4 = undefined;

              try {
                for (var _iterator4 = (0, _getIterator3['default'])(rest), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                  var point = _step4.value;

                  d += 'L' + String(point[0]) + ' ' + String(point[1]);
                }
              } catch (err) {
                _didIteratorError4 = true;
                _iteratorError4 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion4 && _iterator4['return']) {
                    _iterator4['return']();
                  }
                } finally {
                  if (_didIteratorError4) {
                    throw _iteratorError4;
                  }
                }
              }
            }
          } catch (err) {
            _didIteratorError3 = true;
            _iteratorError3 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion3 && _iterator3['return']) {
                _iterator3['return']();
              }
            } finally {
              if (_didIteratorError3) {
                throw _iteratorError3;
              }
            }
          }

          g.setAttribute('d', d);
          output.appendChild(g);
        });

        var gAxis = document.createElement('g');
        gAxis.setAttribute('id', 'axis');

        // append the axis to base so that it's not clipped
        base.appendChild(gAxis);
        gAxis.setAttribute('transform', 'translate(' + String(this.axis.pAxis.position.x) + ', ' + String(this.axis.pAxis.position.y) + ')');

        // add the axis to the export
        if (this.options.axisPositionHorizontal === 'left' || this.options.axisPositionVertical === 'top') {
          // left axis are shown at the beginning of the plot
          var gDrawnAxis = this.axis.exportAxisLeftSVG(this.valueScale, this.dimensions[1]);
          gAxis.appendChild(gDrawnAxis);
        } else if (this.options.axisPositionHorizontal === 'right' || this.options.axisPositionVertical === 'bottom') {
          var _gDrawnAxis = this.axis.exportAxisRightSVG(this.valueScale, this.dimensions[1]);
          gAxis.appendChild(_gDrawnAxis);
        }

        return [base, track];
      }

      return exportSVG;
    }()
  }, {
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        if (this.options.aggregationMode && this.options.aggregationMode !== 'mean') {
          return String(tile.join('.')) + '.' + String(this.options.aggregationMode);
        }
        return '' + String(tile.join('.'));
      }

      return tileToLocalId;
    }()
  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        return this.tileToLocalId(tile);
      }

      return tileToRemoteId;
    }()
  }]);
  return HorizontalLine1DPixiTrack;
}(_HorizontalTiled1DPixiTrack2['default']);

exports['default'] = HorizontalLine1DPixiTrack;

/***/ }),
/* 117 */
/***/ (function(module, exports, __nested_webpack_require_552764__) {

"use strict";



module.exports = {
  copy: copy,
  checkDataType: checkDataType,
  checkDataTypes: checkDataTypes,
  coerceToTypes: coerceToTypes,
  toHash: toHash,
  getProperty: getProperty,
  escapeQuotes: escapeQuotes,
  equal: __nested_webpack_require_552764__(269),
  ucs2length: __nested_webpack_require_552764__(694),
  varOccurences: varOccurences,
  varReplace: varReplace,
  cleanUpCode: cleanUpCode,
  finalCleanUpCode: finalCleanUpCode,
  schemaHasRules: schemaHasRules,
  schemaHasRulesExcept: schemaHasRulesExcept,
  schemaUnknownRules: schemaUnknownRules,
  toQuotedString: toQuotedString,
  getPathExpr: getPathExpr,
  getPath: getPath,
  getData: getData,
  unescapeFragment: unescapeFragment,
  unescapeJsonPointer: unescapeJsonPointer,
  escapeFragment: escapeFragment,
  escapeJsonPointer: escapeJsonPointer
};


function copy(o, to) {
  to = to || {};
  for (var key in o) to[key] = o[key];
  return to;
}


function checkDataType(dataType, data, negate) {
  var EQUAL = negate ? ' !== ' : ' === '
    , AND = negate ? ' || ' : ' && '
    , OK = negate ? '!' : ''
    , NOT = negate ? '' : '!';
  switch (dataType) {
    case 'null': return data + EQUAL + 'null';
    case 'array': return OK + 'Array.isArray(' + data + ')';
    case 'object': return '(' + OK + data + AND +
                          'typeof ' + data + EQUAL + '"object"' + AND +
                          NOT + 'Array.isArray(' + data + '))';
    case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
                           NOT + '(' + data + ' % 1)' +
                           AND + data + EQUAL + data + ')';
    default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  }
}


function checkDataTypes(dataTypes, data) {
  switch (dataTypes.length) {
    case 1: return checkDataType(dataTypes[0], data, true);
    default:
      var code = '';
      var types = toHash(dataTypes);
      if (types.array && types.object) {
        code = types.null ? '(': '(!' + data + ' || ';
        code += 'typeof ' + data + ' !== "object")';
        delete types.null;
        delete types.array;
        delete types.object;
      }
      if (types.number) delete types.integer;
      for (var t in types)
        code += (code ? ' && ' : '' ) + checkDataType(t, data, true);

      return code;
  }
}


var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
  if (Array.isArray(dataTypes)) {
    var types = [];
    for (var i=0; i<dataTypes.length; i++) {
      var t = dataTypes[i];
      if (COERCE_TO_TYPES[t]) types[types.length] = t;
      else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
    }
    if (types.length) return types;
  } else if (COERCE_TO_TYPES[dataTypes]) {
    return [dataTypes];
  } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
    return ['array'];
  }
}


function toHash(arr) {
  var hash = {};
  for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  return hash;
}


var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
  return typeof key == 'number'
          ? '[' + key + ']'
          : IDENTIFIER.test(key)
            ? '.' + key
            : "['" + escapeQuotes(key) + "']";
}


function escapeQuotes(str) {
  return str.replace(SINGLE_QUOTE, '\\$&')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\f/g, '\\f')
            .replace(/\t/g, '\\t');
}


function varOccurences(str, dataVar) {
  dataVar += '[^0-9]';
  var matches = str.match(new RegExp(dataVar, 'g'));
  return matches ? matches.length : 0;
}


function varReplace(str, dataVar, expr) {
  dataVar += '([^0-9])';
  expr = expr.replace(/\$/g, '$$$$');
  return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}


var EMPTY_ELSE = /else\s*{\s*}/g
  , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
  , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
function cleanUpCode(out) {
  return out.replace(EMPTY_ELSE, '')
            .replace(EMPTY_IF_NO_ELSE, '')
            .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
}


var ERRORS_REGEXP = /[^v.]errors/g
  , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
  , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
  , RETURN_VALID = 'return errors === 0;'
  , RETURN_TRUE = 'validate.errors = null; return true;'
  , RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/
  , RETURN_DATA_ASYNC = 'return data;'
  , ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g
  , REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;

function finalCleanUpCode(out, async) {
  var matches = out.match(ERRORS_REGEXP);
  if (matches && matches.length == 2) {
    out = async
          ? out.replace(REMOVE_ERRORS_ASYNC, '')
               .replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
          : out.replace(REMOVE_ERRORS, '')
               .replace(RETURN_VALID, RETURN_TRUE);
  }

  matches = out.match(ROOTDATA_REGEXP);
  if (!matches || matches.length !== 3) return out;
  return out.replace(REMOVE_ROOTDATA, '');
}


function schemaHasRules(schema, rules) {
  if (typeof schema == 'boolean') return !schema;
  for (var key in schema) if (rules[key]) return true;
}


function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
  for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}


function schemaUnknownRules(schema, rules) {
  if (typeof schema == 'boolean') return;
  for (var key in schema) if (!rules[key]) return key;
}


function toQuotedString(str) {
  return '\'' + escapeQuotes(str) + '\'';
}


function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  var path = jsonPointers // false by default
              ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
              : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  return joinPaths(currentPath, path);
}


function getPath(currentPath, prop, jsonPointers) {
  var path = jsonPointers // false by default
              ? toQuotedString('/' + escapeJsonPointer(prop))
              : toQuotedString(getProperty(prop));
  return joinPaths(currentPath, path);
}


var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
  var up, jsonPointer, data, matches;
  if ($data === '') return 'rootData';
  if ($data[0] == '/') {
    if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
    jsonPointer = $data;
    data = 'rootData';
  } else {
    matches = $data.match(RELATIVE_JSON_POINTER);
    if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
    up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer == '#') {
      if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
      return paths[lvl - up];
    }

    if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
    data = 'data' + ((lvl - up) || '');
    if (!jsonPointer) return data;
  }

  var expr = data;
  var segments = jsonPointer.split('/');
  for (var i=0; i<segments.length; i++) {
    var segment = segments[i];
    if (segment) {
      data += getProperty(unescapeJsonPointer(segment));
      expr += ' && ' + data;
    }
  }
  return expr;
}


function joinPaths (a, b) {
  if (a == '""') return b;
  return (a + ' + ' + b).replace(/' \+ '/g, '');
}


function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}


function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}


function escapeJsonPointer(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


function unescapeJsonPointer(str) {
  return str.replace(/~1/g, '/').replace(/~0/g, '~');
}


/***/ }),
/* 118 */
/***/ (function(module, exports, __nested_webpack_require_560926__) {

var root = __nested_webpack_require_560926__(41);

/** Built-in value references. */
var Symbol = root.Symbol;

module.exports = Symbol;


/***/ }),
/* 119 */
/***/ (function(module, exports, __nested_webpack_require_561128__) {

var arrayLikeKeys = __nested_webpack_require_561128__(409),
    baseKeys = __nested_webpack_require_561128__(742),
    isArrayLike = __nested_webpack_require_561128__(98);

/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}

module.exports = keys;


/***/ }),
/* 120 */
/***/ (function(module, exports) {

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}

module.exports = eq;


/***/ }),
/* 121 */
/***/ (function(module, exports, __nested_webpack_require_562946__) {

var arrayLikeKeys = __nested_webpack_require_562946__(409),
    baseKeysIn = __nested_webpack_require_562946__(804),
    isArrayLike = __nested_webpack_require_562946__(98);

/**
 * Creates an array of the own and inherited enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keysIn(new Foo);
 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
 */
function keysIn(object) {
  return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}

module.exports = keysIn;


/***/ }),
/* 122 */
/***/ (function(module, exports, __nested_webpack_require_563799__) {

"use strict";


var defineProperties = __nested_webpack_require_563799__(52);

var implementation = __nested_webpack_require_563799__(451);
var getPolyfill = __nested_webpack_require_563799__(453);
var shim = __nested_webpack_require_563799__(955);

var polyfill = getPolyfill();

defineProperties(polyfill, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = polyfill;


/***/ }),
/* 123 */
/***/ (function(module, exports) {

//Types of elements found in the DOM
module.exports = {
	Text: "text", //Text
	Directive: "directive", //<? ... ?>
	Comment: "comment", //<!-- ... -->
	Script: "script", //<script> tags
	Style: "style", //<style> tags
	Tag: "tag", //Any tag
	CDATA: "cdata", //<![CDATA[ ... ]]>
	Doctype: "doctype",

	isTag: function(elem){
		return elem.type === "tag" || elem.type === "script" || elem.type === "style";
	}
};


/***/ }),
/* 124 */
/***/ (function(module, exports, __nested_webpack_require_564705__) {

"use strict";


var Preprocessor = __nested_webpack_require_564705__(973),
    UNICODE = __nested_webpack_require_564705__(149),
    neTree = __nested_webpack_require_564705__(974);

//Aliases
var $ = UNICODE.CODE_POINTS,
    $$ = UNICODE.CODE_POINT_SEQUENCES;

//Replacement code points for numeric entities
var NUMERIC_ENTITY_REPLACEMENTS = {
    0x00: 0xFFFD, 0x0D: 0x000D, 0x80: 0x20AC, 0x81: 0x0081, 0x82: 0x201A, 0x83: 0x0192, 0x84: 0x201E,
    0x85: 0x2026, 0x86: 0x2020, 0x87: 0x2021, 0x88: 0x02C6, 0x89: 0x2030, 0x8A: 0x0160, 0x8B: 0x2039,
    0x8C: 0x0152, 0x8D: 0x008D, 0x8E: 0x017D, 0x8F: 0x008F, 0x90: 0x0090, 0x91: 0x2018, 0x92: 0x2019,
    0x93: 0x201C, 0x94: 0x201D, 0x95: 0x2022, 0x96: 0x2013, 0x97: 0x2014, 0x98: 0x02DC, 0x99: 0x2122,
    0x9A: 0x0161, 0x9B: 0x203A, 0x9C: 0x0153, 0x9D: 0x009D, 0x9E: 0x017E, 0x9F: 0x0178
};

// Named entity tree flags
var HAS_DATA_FLAG = 1 << 0;
var DATA_DUPLET_FLAG = 1 << 1;
var HAS_BRANCHES_FLAG = 1 << 2;
var MAX_BRANCH_MARKER_VALUE = HAS_DATA_FLAG | DATA_DUPLET_FLAG | HAS_BRANCHES_FLAG;


//States
var DATA_STATE = 'DATA_STATE',
    CHARACTER_REFERENCE_IN_DATA_STATE = 'CHARACTER_REFERENCE_IN_DATA_STATE',
    RCDATA_STATE = 'RCDATA_STATE',
    CHARACTER_REFERENCE_IN_RCDATA_STATE = 'CHARACTER_REFERENCE_IN_RCDATA_STATE',
    RAWTEXT_STATE = 'RAWTEXT_STATE',
    SCRIPT_DATA_STATE = 'SCRIPT_DATA_STATE',
    PLAINTEXT_STATE = 'PLAINTEXT_STATE',
    TAG_OPEN_STATE = 'TAG_OPEN_STATE',
    END_TAG_OPEN_STATE = 'END_TAG_OPEN_STATE',
    TAG_NAME_STATE = 'TAG_NAME_STATE',
    RCDATA_LESS_THAN_SIGN_STATE = 'RCDATA_LESS_THAN_SIGN_STATE',
    RCDATA_END_TAG_OPEN_STATE = 'RCDATA_END_TAG_OPEN_STATE',
    RCDATA_END_TAG_NAME_STATE = 'RCDATA_END_TAG_NAME_STATE',
    RAWTEXT_LESS_THAN_SIGN_STATE = 'RAWTEXT_LESS_THAN_SIGN_STATE',
    RAWTEXT_END_TAG_OPEN_STATE = 'RAWTEXT_END_TAG_OPEN_STATE',
    RAWTEXT_END_TAG_NAME_STATE = 'RAWTEXT_END_TAG_NAME_STATE',
    SCRIPT_DATA_LESS_THAN_SIGN_STATE = 'SCRIPT_DATA_LESS_THAN_SIGN_STATE',
    SCRIPT_DATA_END_TAG_OPEN_STATE = 'SCRIPT_DATA_END_TAG_OPEN_STATE',
    SCRIPT_DATA_END_TAG_NAME_STATE = 'SCRIPT_DATA_END_TAG_NAME_STATE',
    SCRIPT_DATA_ESCAPE_START_STATE = 'SCRIPT_DATA_ESCAPE_START_STATE',
    SCRIPT_DATA_ESCAPE_START_DASH_STATE = 'SCRIPT_DATA_ESCAPE_START_DASH_STATE',
    SCRIPT_DATA_ESCAPED_STATE = 'SCRIPT_DATA_ESCAPED_STATE',
    SCRIPT_DATA_ESCAPED_DASH_STATE = 'SCRIPT_DATA_ESCAPED_DASH_STATE',
    SCRIPT_DATA_ESCAPED_DASH_DASH_STATE = 'SCRIPT_DATA_ESCAPED_DASH_DASH_STATE',
    SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE = 'SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE',
    SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE = 'SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE',
    SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE = 'SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE',
    SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE',
    SCRIPT_DATA_DOUBLE_ESCAPED_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_STATE',
    SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE',
    SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE',
    SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE',
    SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE = 'SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE',
    BEFORE_ATTRIBUTE_NAME_STATE = 'BEFORE_ATTRIBUTE_NAME_STATE',
    ATTRIBUTE_NAME_STATE = 'ATTRIBUTE_NAME_STATE',
    AFTER_ATTRIBUTE_NAME_STATE = 'AFTER_ATTRIBUTE_NAME_STATE',
    BEFORE_ATTRIBUTE_VALUE_STATE = 'BEFORE_ATTRIBUTE_VALUE_STATE',
    ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE = 'ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE',
    ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE = 'ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE',
    ATTRIBUTE_VALUE_UNQUOTED_STATE = 'ATTRIBUTE_VALUE_UNQUOTED_STATE',
    CHARACTER_REFERENCE_IN_ATTRIBUTE_VALUE_STATE = 'CHARACTER_REFERENCE_IN_ATTRIBUTE_VALUE_STATE',
    AFTER_ATTRIBUTE_VALUE_QUOTED_STATE = 'AFTER_ATTRIBUTE_VALUE_QUOTED_STATE',
    SELF_CLOSING_START_TAG_STATE = 'SELF_CLOSING_START_TAG_STATE',
    BOGUS_COMMENT_STATE = 'BOGUS_COMMENT_STATE',
    BOGUS_COMMENT_STATE_CONTINUATION = 'BOGUS_COMMENT_STATE_CONTINUATION',
    MARKUP_DECLARATION_OPEN_STATE = 'MARKUP_DECLARATION_OPEN_STATE',
    COMMENT_START_STATE = 'COMMENT_START_STATE',
    COMMENT_START_DASH_STATE = 'COMMENT_START_DASH_STATE',
    COMMENT_STATE = 'COMMENT_STATE',
    COMMENT_END_DASH_STATE = 'COMMENT_END_DASH_STATE',
    COMMENT_END_STATE = 'COMMENT_END_STATE',
    COMMENT_END_BANG_STATE = 'COMMENT_END_BANG_STATE',
    DOCTYPE_STATE = 'DOCTYPE_STATE',
    DOCTYPE_NAME_STATE = 'DOCTYPE_NAME_STATE',
    AFTER_DOCTYPE_NAME_STATE = 'AFTER_DOCTYPE_NAME_STATE',
    BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE = 'BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE',
    DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE = 'DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE',
    DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE = 'DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE',
    BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE = 'BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE',
    BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE = 'BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE',
    DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE = 'DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE',
    DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE = 'DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE',
    AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE = 'AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE',
    BOGUS_DOCTYPE_STATE = 'BOGUS_DOCTYPE_STATE',
    CDATA_SECTION_STATE = 'CDATA_SECTION_STATE';

//Utils

//OPTIMIZATION: these utility functions should not be moved out of this module. V8 Crankshaft will not inline
//this functions if they will be situated in another module due to context switch.
//Always perform inlining check before modifying this functions ('node --trace-inlining').
function isWhitespace(cp) {
    return cp === $.SPACE || cp === $.LINE_FEED || cp === $.TABULATION || cp === $.FORM_FEED;
}

function isAsciiDigit(cp) {
    return cp >= $.DIGIT_0 && cp <= $.DIGIT_9;
}

function isAsciiUpper(cp) {
    return cp >= $.LATIN_CAPITAL_A && cp <= $.LATIN_CAPITAL_Z;
}

function isAsciiLower(cp) {
    return cp >= $.LATIN_SMALL_A && cp <= $.LATIN_SMALL_Z;
}

function isAsciiLetter(cp) {
    return isAsciiLower(cp) || isAsciiUpper(cp);
}

function isAsciiAlphaNumeric(cp) {
    return isAsciiLetter(cp) || isAsciiDigit(cp);
}

function isDigit(cp, isHex) {
    return isAsciiDigit(cp) || isHex && (cp >= $.LATIN_CAPITAL_A && cp <= $.LATIN_CAPITAL_F ||
                                         cp >= $.LATIN_SMALL_A && cp <= $.LATIN_SMALL_F);
}

function isReservedCodePoint(cp) {
    return cp >= 0xD800 && cp <= 0xDFFF || cp > 0x10FFFF;
}

function toAsciiLowerCodePoint(cp) {
    return cp + 0x0020;
}

//NOTE: String.fromCharCode() function can handle only characters from BMP subset.
//So, we need to workaround this manually.
//(see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode#Getting_it_to_work_with_higher_values)
function toChar(cp) {
    if (cp <= 0xFFFF)
        return String.fromCharCode(cp);

    cp -= 0x10000;
    return String.fromCharCode(cp >>> 10 & 0x3FF | 0xD800) + String.fromCharCode(0xDC00 | cp & 0x3FF);
}

function toAsciiLowerChar(cp) {
    return String.fromCharCode(toAsciiLowerCodePoint(cp));
}

function findNamedEntityTreeBranch(nodeIx, cp) {
    var branchCount = neTree[++nodeIx],
        lo = ++nodeIx,
        hi = lo + branchCount - 1;

    while (lo <= hi) {
        var mid = lo + hi >>> 1,
            midCp = neTree[mid];

        if (midCp < cp)
            lo = mid + 1;

        else if (midCp > cp)
            hi = mid - 1;

        else
            return neTree[mid + branchCount];
    }

    return -1;
}


//Tokenizer
var Tokenizer = module.exports = function () {
    this.preprocessor = new Preprocessor();

    this.tokenQueue = [];

    this.allowCDATA = false;

    this.state = DATA_STATE;
    this.returnState = '';

    this.tempBuff = [];
    this.additionalAllowedCp = void 0;
    this.lastStartTagName = '';

    this.consumedAfterSnapshot = -1;
    this.active = false;

    this.currentCharacterToken = null;
    this.currentToken = null;
    this.currentAttr = null;
};

//Token types
Tokenizer.CHARACTER_TOKEN = 'CHARACTER_TOKEN';
Tokenizer.NULL_CHARACTER_TOKEN = 'NULL_CHARACTER_TOKEN';
Tokenizer.WHITESPACE_CHARACTER_TOKEN = 'WHITESPACE_CHARACTER_TOKEN';
Tokenizer.START_TAG_TOKEN = 'START_TAG_TOKEN';
Tokenizer.END_TAG_TOKEN = 'END_TAG_TOKEN';
Tokenizer.COMMENT_TOKEN = 'COMMENT_TOKEN';
Tokenizer.DOCTYPE_TOKEN = 'DOCTYPE_TOKEN';
Tokenizer.EOF_TOKEN = 'EOF_TOKEN';
Tokenizer.HIBERNATION_TOKEN = 'HIBERNATION_TOKEN';

//Tokenizer initial states for different modes
Tokenizer.MODE = {
    DATA: DATA_STATE,
    RCDATA: RCDATA_STATE,
    RAWTEXT: RAWTEXT_STATE,
    SCRIPT_DATA: SCRIPT_DATA_STATE,
    PLAINTEXT: PLAINTEXT_STATE
};

//Static
Tokenizer.getTokenAttr = function (token, attrName) {
    for (var i = token.attrs.length - 1; i >= 0; i--) {
        if (token.attrs[i].name === attrName)
            return token.attrs[i].value;
    }

    return null;
};

//API
Tokenizer.prototype.getNextToken = function () {
    while (!this.tokenQueue.length && this.active) {
        this._hibernationSnapshot();

        var cp = this._consume();

        if (!this._ensureHibernation())
            this[this.state](cp);
    }

    return this.tokenQueue.shift();
};

Tokenizer.prototype.write = function (chunk, isLastChunk) {
    this.active = true;
    this.preprocessor.write(chunk, isLastChunk);
};

Tokenizer.prototype.insertHtmlAtCurrentPos = function (chunk) {
    this.active = true;
    this.preprocessor.insertHtmlAtCurrentPos(chunk);
};

//Hibernation
Tokenizer.prototype._hibernationSnapshot = function () {
    this.consumedAfterSnapshot = 0;
};

Tokenizer.prototype._ensureHibernation = function () {
    if (this.preprocessor.endOfChunkHit) {
        for (; this.consumedAfterSnapshot > 0; this.consumedAfterSnapshot--)
            this.preprocessor.retreat();

        this.active = false;
        this.tokenQueue.push({type: Tokenizer.HIBERNATION_TOKEN});

        return true;
    }

    return false;
};


//Consumption
Tokenizer.prototype._consume = function () {
    this.consumedAfterSnapshot++;
    return this.preprocessor.advance();
};

Tokenizer.prototype._unconsume = function () {
    this.consumedAfterSnapshot--;
    this.preprocessor.retreat();
};

Tokenizer.prototype._unconsumeSeveral = function (count) {
    while (count--)
        this._unconsume();
};

Tokenizer.prototype._reconsumeInState = function (state) {
    this.state = state;
    this._unconsume();
};

Tokenizer.prototype._consumeSubsequentIfMatch = function (pattern, startCp, caseSensitive) {
    var consumedCount = 0,
        isMatch = true,
        patternLength = pattern.length,
        patternPos = 0,
        cp = startCp,
        patternCp = void 0;

    for (; patternPos < patternLength; patternPos++) {
        if (patternPos > 0) {
            cp = this._consume();
            consumedCount++;
        }

        if (cp === $.EOF) {
            isMatch = false;
            break;
        }

        patternCp = pattern[patternPos];

        if (cp !== patternCp && (caseSensitive || cp !== toAsciiLowerCodePoint(patternCp))) {
            isMatch = false;
            break;
        }
    }

    if (!isMatch)
        this._unconsumeSeveral(consumedCount);

    return isMatch;
};

//Lookahead
Tokenizer.prototype._lookahead = function () {
    var cp = this._consume();

    this._unconsume();

    return cp;
};

//Temp buffer
Tokenizer.prototype.isTempBufferEqualToScriptString = function () {
    if (this.tempBuff.length !== $$.SCRIPT_STRING.length)
        return false;

    for (var i = 0; i < this.tempBuff.length; i++) {
        if (this.tempBuff[i] !== $$.SCRIPT_STRING[i])
            return false;
    }

    return true;
};

//Token creation
Tokenizer.prototype._createStartTagToken = function () {
    this.currentToken = {
        type: Tokenizer.START_TAG_TOKEN,
        tagName: '',
        selfClosing: false,
        attrs: []
    };
};

Tokenizer.prototype._createEndTagToken = function () {
    this.currentToken = {
        type: Tokenizer.END_TAG_TOKEN,
        tagName: '',
        attrs: []
    };
};

Tokenizer.prototype._createCommentToken = function () {
    this.currentToken = {
        type: Tokenizer.COMMENT_TOKEN,
        data: ''
    };
};

Tokenizer.prototype._createDoctypeToken = function (initialName) {
    this.currentToken = {
        type: Tokenizer.DOCTYPE_TOKEN,
        name: initialName,
        forceQuirks: false,
        publicId: null,
        systemId: null
    };
};

Tokenizer.prototype._createCharacterToken = function (type, ch) {
    this.currentCharacterToken = {
        type: type,
        chars: ch
    };
};

//Tag attributes
Tokenizer.prototype._createAttr = function (attrNameFirstCh) {
    this.currentAttr = {
        name: attrNameFirstCh,
        value: ''
    };
};

Tokenizer.prototype._isDuplicateAttr = function () {
    return Tokenizer.getTokenAttr(this.currentToken, this.currentAttr.name) !== null;
};

Tokenizer.prototype._leaveAttrName = function (toState) {
    this.state = toState;

    if (!this._isDuplicateAttr())
        this.currentToken.attrs.push(this.currentAttr);
};

Tokenizer.prototype._leaveAttrValue = function (toState) {
    this.state = toState;
};

//Appropriate end tag token
//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#appropriate-end-tag-token)
Tokenizer.prototype._isAppropriateEndTagToken = function () {
    return this.lastStartTagName === this.currentToken.tagName;
};

//Token emission
Tokenizer.prototype._emitCurrentToken = function () {
    this._emitCurrentCharacterToken();

    //NOTE: store emited start tag's tagName to determine is the following end tag token is appropriate.
    if (this.currentToken.type === Tokenizer.START_TAG_TOKEN)
        this.lastStartTagName = this.currentToken.tagName;

    this.tokenQueue.push(this.currentToken);
    this.currentToken = null;
};

Tokenizer.prototype._emitCurrentCharacterToken = function () {
    if (this.currentCharacterToken) {
        this.tokenQueue.push(this.currentCharacterToken);
        this.currentCharacterToken = null;
    }
};

Tokenizer.prototype._emitEOFToken = function () {
    this._emitCurrentCharacterToken();
    this.tokenQueue.push({type: Tokenizer.EOF_TOKEN});
};

//Characters emission

//OPTIMIZATION: specification uses only one type of character tokens (one token per character).
//This causes a huge memory overhead and a lot of unnecessary parser loops. parse5 uses 3 groups of characters.
//If we have a sequence of characters that belong to the same group, parser can process it
//as a single solid character token.
//So, there are 3 types of character tokens in parse5:
//1)NULL_CHARACTER_TOKEN - \u0000-character sequences (e.g. '\u0000\u0000\u0000')
//2)WHITESPACE_CHARACTER_TOKEN - any whitespace/new-line character sequences (e.g. '\n  \r\t   \f')
//3)CHARACTER_TOKEN - any character sequence which don't belong to groups 1 and 2 (e.g. 'abcdef1234@@#$%^')
Tokenizer.prototype._appendCharToCurrentCharacterToken = function (type, ch) {
    if (this.currentCharacterToken && this.currentCharacterToken.type !== type)
        this._emitCurrentCharacterToken();

    if (this.currentCharacterToken)
        this.currentCharacterToken.chars += ch;

    else
        this._createCharacterToken(type, ch);
};

Tokenizer.prototype._emitCodePoint = function (cp) {
    var type = Tokenizer.CHARACTER_TOKEN;

    if (isWhitespace(cp))
        type = Tokenizer.WHITESPACE_CHARACTER_TOKEN;

    else if (cp === $.NULL)
        type = Tokenizer.NULL_CHARACTER_TOKEN;

    this._appendCharToCurrentCharacterToken(type, toChar(cp));
};

Tokenizer.prototype._emitSeveralCodePoints = function (codePoints) {
    for (var i = 0; i < codePoints.length; i++)
        this._emitCodePoint(codePoints[i]);
};

//NOTE: used then we emit character explicitly. This is always a non-whitespace and a non-null character.
//So we can avoid additional checks here.
Tokenizer.prototype._emitChar = function (ch) {
    this._appendCharToCurrentCharacterToken(Tokenizer.CHARACTER_TOKEN, ch);
};

//Character reference tokenization
Tokenizer.prototype._consumeNumericEntity = function (isHex) {
    var digits = '',
        nextCp = void 0;

    do {
        digits += toChar(this._consume());
        nextCp = this._lookahead();
    } while (nextCp !== $.EOF && isDigit(nextCp, isHex));

    if (this._lookahead() === $.SEMICOLON)
        this._consume();

    var referencedCp = parseInt(digits, isHex ? 16 : 10),
        replacement = NUMERIC_ENTITY_REPLACEMENTS[referencedCp];

    if (replacement)
        return replacement;

    if (isReservedCodePoint(referencedCp))
        return $.REPLACEMENT_CHARACTER;

    return referencedCp;
};

// NOTE: for the details on this algorithm see
// https://github.com/inikulin/parse5/tree/master/scripts/generate_named_entity_data/README.md
Tokenizer.prototype._consumeNamedEntity = function (inAttr) {
    var referencedCodePoints = null,
        referenceSize = 0,
        cp = null,
        consumedCount = 0,
        semicolonTerminated = false;

    for (var i = 0; i > -1;) {
        var current = neTree[i],
            inNode = current < MAX_BRANCH_MARKER_VALUE,
            nodeWithData = inNode && current & HAS_DATA_FLAG;

        if (nodeWithData) {
            referencedCodePoints = current & DATA_DUPLET_FLAG ? [neTree[++i], neTree[++i]] : [neTree[++i]];
            referenceSize = consumedCount;

            if (cp === $.SEMICOLON) {
                semicolonTerminated = true;
                break;
            }
        }

        cp = this._consume();
        consumedCount++;

        if (cp === $.EOF)
            break;

        if (inNode)
            i = current & HAS_BRANCHES_FLAG ? findNamedEntityTreeBranch(i, cp) : -1;

        else
            i = cp === current ? ++i : -1;
    }


    if (referencedCodePoints) {
        if (!semicolonTerminated) {
            //NOTE: unconsume excess (e.g. 'it' in '&notit')
            this._unconsumeSeveral(consumedCount - referenceSize);

            //NOTE: If the character reference is being consumed as part of an attribute and the next character
            //is either a U+003D EQUALS SIGN character (=) or an alphanumeric ASCII character, then, for historical
            //reasons, all the characters that were matched after the U+0026 AMPERSAND character (&) must be
            //unconsumed, and nothing is returned.
            //However, if this next character is in fact a U+003D EQUALS SIGN character (=), then this is a
            //parse error, because some legacy user agents will misinterpret the markup in those cases.
            //(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#tokenizing-character-references)
            if (inAttr) {
                var nextCp = this._lookahead();

                if (nextCp === $.EQUALS_SIGN || isAsciiAlphaNumeric(nextCp)) {
                    this._unconsumeSeveral(referenceSize);
                    return null;
                }
            }
        }

        return referencedCodePoints;
    }

    this._unconsumeSeveral(consumedCount);

    return null;
};

Tokenizer.prototype._consumeCharacterReference = function (startCp, inAttr) {
    if (isWhitespace(startCp) || startCp === $.GREATER_THAN_SIGN ||
        startCp === $.AMPERSAND || startCp === this.additionalAllowedCp || startCp === $.EOF) {
        //NOTE: not a character reference. No characters are consumed, and nothing is returned.
        this._unconsume();
        return null;
    }

    if (startCp === $.NUMBER_SIGN) {
        //NOTE: we have a numeric entity candidate, now we should determine if it's hex or decimal
        var isHex = false,
            nextCp = this._lookahead();

        if (nextCp === $.LATIN_SMALL_X || nextCp === $.LATIN_CAPITAL_X) {
            this._consume();
            isHex = true;
        }

        nextCp = this._lookahead();

        //NOTE: if we have at least one digit this is a numeric entity for sure, so we consume it
        if (nextCp !== $.EOF && isDigit(nextCp, isHex))
            return [this._consumeNumericEntity(isHex)];

        //NOTE: otherwise this is a bogus number entity and a parse error. Unconsume the number sign
        //and the 'x'-character if appropriate.
        this._unconsumeSeveral(isHex ? 2 : 1);
        return null;
    }

    this._unconsume();

    return this._consumeNamedEntity(inAttr);
};

//State machine
var _ = Tokenizer.prototype;

//12.2.4.1 Data state
//------------------------------------------------------------------
_[DATA_STATE] = function dataState(cp) {
    this.preprocessor.dropParsedChunk();

    if (cp === $.AMPERSAND)
        this.state = CHARACTER_REFERENCE_IN_DATA_STATE;

    else if (cp === $.LESS_THAN_SIGN)
        this.state = TAG_OPEN_STATE;

    else if (cp === $.NULL)
        this._emitCodePoint(cp);

    else if (cp === $.EOF)
        this._emitEOFToken();

    else
        this._emitCodePoint(cp);
};


//12.2.4.2 Character reference in data state
//------------------------------------------------------------------
_[CHARACTER_REFERENCE_IN_DATA_STATE] = function characterReferenceInDataState(cp) {
    this.additionalAllowedCp = void 0;

    var referencedCodePoints = this._consumeCharacterReference(cp, false);

    if (!this._ensureHibernation()) {
        if (referencedCodePoints)
            this._emitSeveralCodePoints(referencedCodePoints);

        else
            this._emitChar('&');

        this.state = DATA_STATE;
    }
};


//12.2.4.3 RCDATA state
//------------------------------------------------------------------
_[RCDATA_STATE] = function rcdataState(cp) {
    this.preprocessor.dropParsedChunk();

    if (cp === $.AMPERSAND)
        this.state = CHARACTER_REFERENCE_IN_RCDATA_STATE;

    else if (cp === $.LESS_THAN_SIGN)
        this.state = RCDATA_LESS_THAN_SIGN_STATE;

    else if (cp === $.NULL)
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);

    else if (cp === $.EOF)
        this._emitEOFToken();

    else
        this._emitCodePoint(cp);
};


//12.2.4.4 Character reference in RCDATA state
//------------------------------------------------------------------
_[CHARACTER_REFERENCE_IN_RCDATA_STATE] = function characterReferenceInRcdataState(cp) {
    this.additionalAllowedCp = void 0;

    var referencedCodePoints = this._consumeCharacterReference(cp, false);

    if (!this._ensureHibernation()) {
        if (referencedCodePoints)
            this._emitSeveralCodePoints(referencedCodePoints);

        else
            this._emitChar('&');

        this.state = RCDATA_STATE;
    }
};


//12.2.4.5 RAWTEXT state
//------------------------------------------------------------------
_[RAWTEXT_STATE] = function rawtextState(cp) {
    this.preprocessor.dropParsedChunk();

    if (cp === $.LESS_THAN_SIGN)
        this.state = RAWTEXT_LESS_THAN_SIGN_STATE;

    else if (cp === $.NULL)
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);

    else if (cp === $.EOF)
        this._emitEOFToken();

    else
        this._emitCodePoint(cp);
};


//12.2.4.6 Script data state
//------------------------------------------------------------------
_[SCRIPT_DATA_STATE] = function scriptDataState(cp) {
    this.preprocessor.dropParsedChunk();

    if (cp === $.LESS_THAN_SIGN)
        this.state = SCRIPT_DATA_LESS_THAN_SIGN_STATE;

    else if (cp === $.NULL)
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);

    else if (cp === $.EOF)
        this._emitEOFToken();

    else
        this._emitCodePoint(cp);
};


//12.2.4.7 PLAINTEXT state
//------------------------------------------------------------------
_[PLAINTEXT_STATE] = function plaintextState(cp) {
    this.preprocessor.dropParsedChunk();

    if (cp === $.NULL)
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);

    else if (cp === $.EOF)
        this._emitEOFToken();

    else
        this._emitCodePoint(cp);
};


//12.2.4.8 Tag open state
//------------------------------------------------------------------
_[TAG_OPEN_STATE] = function tagOpenState(cp) {
    if (cp === $.EXCLAMATION_MARK)
        this.state = MARKUP_DECLARATION_OPEN_STATE;

    else if (cp === $.SOLIDUS)
        this.state = END_TAG_OPEN_STATE;

    else if (isAsciiLetter(cp)) {
        this._createStartTagToken();
        this._reconsumeInState(TAG_NAME_STATE);
    }

    else if (cp === $.QUESTION_MARK)
        this._reconsumeInState(BOGUS_COMMENT_STATE);

    else {
        this._emitChar('<');
        this._reconsumeInState(DATA_STATE);
    }
};


//12.2.4.9 End tag open state
//------------------------------------------------------------------
_[END_TAG_OPEN_STATE] = function endTagOpenState(cp) {
    if (isAsciiLetter(cp)) {
        this._createEndTagToken();
        this._reconsumeInState(TAG_NAME_STATE);
    }

    else if (cp === $.GREATER_THAN_SIGN)
        this.state = DATA_STATE;

    else if (cp === $.EOF) {
        this._reconsumeInState(DATA_STATE);
        this._emitChar('<');
        this._emitChar('/');
    }

    else
        this._reconsumeInState(BOGUS_COMMENT_STATE);
};


//12.2.4.10 Tag name state
//------------------------------------------------------------------
_[TAG_NAME_STATE] = function tagNameState(cp) {
    if (isWhitespace(cp))
        this.state = BEFORE_ATTRIBUTE_NAME_STATE;

    else if (cp === $.SOLIDUS)
        this.state = SELF_CLOSING_START_TAG_STATE;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (isAsciiUpper(cp))
        this.currentToken.tagName += toAsciiLowerChar(cp);

    else if (cp === $.NULL)
        this.currentToken.tagName += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this.currentToken.tagName += toChar(cp);
};


//12.2.4.11 RCDATA less-than sign state
//------------------------------------------------------------------
_[RCDATA_LESS_THAN_SIGN_STATE] = function rcdataLessThanSignState(cp) {
    if (cp === $.SOLIDUS) {
        this.tempBuff = [];
        this.state = RCDATA_END_TAG_OPEN_STATE;
    }

    else {
        this._emitChar('<');
        this._reconsumeInState(RCDATA_STATE);
    }
};


//12.2.4.12 RCDATA end tag open state
//------------------------------------------------------------------
_[RCDATA_END_TAG_OPEN_STATE] = function rcdataEndTagOpenState(cp) {
    if (isAsciiLetter(cp)) {
        this._createEndTagToken();
        this._reconsumeInState(RCDATA_END_TAG_NAME_STATE);
    }

    else {
        this._emitChar('<');
        this._emitChar('/');
        this._reconsumeInState(RCDATA_STATE);
    }
};


//12.2.4.13 RCDATA end tag name state
//------------------------------------------------------------------
_[RCDATA_END_TAG_NAME_STATE] = function rcdataEndTagNameState(cp) {
    if (isAsciiUpper(cp)) {
        this.currentToken.tagName += toAsciiLowerChar(cp);
        this.tempBuff.push(cp);
    }

    else if (isAsciiLower(cp)) {
        this.currentToken.tagName += toChar(cp);
        this.tempBuff.push(cp);
    }

    else {
        if (this._isAppropriateEndTagToken()) {
            if (isWhitespace(cp)) {
                this.state = BEFORE_ATTRIBUTE_NAME_STATE;
                return;
            }

            if (cp === $.SOLIDUS) {
                this.state = SELF_CLOSING_START_TAG_STATE;
                return;
            }

            if (cp === $.GREATER_THAN_SIGN) {
                this.state = DATA_STATE;
                this._emitCurrentToken();
                return;
            }
        }

        this._emitChar('<');
        this._emitChar('/');
        this._emitSeveralCodePoints(this.tempBuff);
        this._reconsumeInState(RCDATA_STATE);
    }
};


//12.2.4.14 RAWTEXT less-than sign state
//------------------------------------------------------------------
_[RAWTEXT_LESS_THAN_SIGN_STATE] = function rawtextLessThanSignState(cp) {
    if (cp === $.SOLIDUS) {
        this.tempBuff = [];
        this.state = RAWTEXT_END_TAG_OPEN_STATE;
    }

    else {
        this._emitChar('<');
        this._reconsumeInState(RAWTEXT_STATE);
    }
};


//12.2.4.15 RAWTEXT end tag open state
//------------------------------------------------------------------
_[RAWTEXT_END_TAG_OPEN_STATE] = function rawtextEndTagOpenState(cp) {
    if (isAsciiLetter(cp)) {
        this._createEndTagToken();
        this._reconsumeInState(RAWTEXT_END_TAG_NAME_STATE);
    }

    else {
        this._emitChar('<');
        this._emitChar('/');
        this._reconsumeInState(RAWTEXT_STATE);
    }
};


//12.2.4.16 RAWTEXT end tag name state
//------------------------------------------------------------------
_[RAWTEXT_END_TAG_NAME_STATE] = function rawtextEndTagNameState(cp) {
    if (isAsciiUpper(cp)) {
        this.currentToken.tagName += toAsciiLowerChar(cp);
        this.tempBuff.push(cp);
    }

    else if (isAsciiLower(cp)) {
        this.currentToken.tagName += toChar(cp);
        this.tempBuff.push(cp);
    }

    else {
        if (this._isAppropriateEndTagToken()) {
            if (isWhitespace(cp)) {
                this.state = BEFORE_ATTRIBUTE_NAME_STATE;
                return;
            }

            if (cp === $.SOLIDUS) {
                this.state = SELF_CLOSING_START_TAG_STATE;
                return;
            }

            if (cp === $.GREATER_THAN_SIGN) {
                this._emitCurrentToken();
                this.state = DATA_STATE;
                return;
            }
        }

        this._emitChar('<');
        this._emitChar('/');
        this._emitSeveralCodePoints(this.tempBuff);
        this._reconsumeInState(RAWTEXT_STATE);
    }
};


//12.2.4.17 Script data less-than sign state
//------------------------------------------------------------------
_[SCRIPT_DATA_LESS_THAN_SIGN_STATE] = function scriptDataLessThanSignState(cp) {
    if (cp === $.SOLIDUS) {
        this.tempBuff = [];
        this.state = SCRIPT_DATA_END_TAG_OPEN_STATE;
    }

    else if (cp === $.EXCLAMATION_MARK) {
        this.state = SCRIPT_DATA_ESCAPE_START_STATE;
        this._emitChar('<');
        this._emitChar('!');
    }

    else {
        this._emitChar('<');
        this._reconsumeInState(SCRIPT_DATA_STATE);
    }
};


//12.2.4.18 Script data end tag open state
//------------------------------------------------------------------
_[SCRIPT_DATA_END_TAG_OPEN_STATE] = function scriptDataEndTagOpenState(cp) {
    if (isAsciiLetter(cp)) {
        this._createEndTagToken();
        this._reconsumeInState(SCRIPT_DATA_END_TAG_NAME_STATE);
    }

    else {
        this._emitChar('<');
        this._emitChar('/');
        this._reconsumeInState(SCRIPT_DATA_STATE);
    }
};


//12.2.4.19 Script data end tag name state
//------------------------------------------------------------------
_[SCRIPT_DATA_END_TAG_NAME_STATE] = function scriptDataEndTagNameState(cp) {
    if (isAsciiUpper(cp)) {
        this.currentToken.tagName += toAsciiLowerChar(cp);
        this.tempBuff.push(cp);
    }

    else if (isAsciiLower(cp)) {
        this.currentToken.tagName += toChar(cp);
        this.tempBuff.push(cp);
    }

    else {
        if (this._isAppropriateEndTagToken()) {
            if (isWhitespace(cp)) {
                this.state = BEFORE_ATTRIBUTE_NAME_STATE;
                return;
            }

            else if (cp === $.SOLIDUS) {
                this.state = SELF_CLOSING_START_TAG_STATE;
                return;
            }

            else if (cp === $.GREATER_THAN_SIGN) {
                this._emitCurrentToken();
                this.state = DATA_STATE;
                return;
            }
        }

        this._emitChar('<');
        this._emitChar('/');
        this._emitSeveralCodePoints(this.tempBuff);
        this._reconsumeInState(SCRIPT_DATA_STATE);
    }
};


//12.2.4.20 Script data escape start state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPE_START_STATE] = function scriptDataEscapeStartState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.state = SCRIPT_DATA_ESCAPE_START_DASH_STATE;
        this._emitChar('-');
    }

    else
        this._reconsumeInState(SCRIPT_DATA_STATE);
};


//12.2.4.21 Script data escape start dash state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPE_START_DASH_STATE] = function scriptDataEscapeStartDashState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.state = SCRIPT_DATA_ESCAPED_DASH_DASH_STATE;
        this._emitChar('-');
    }

    else
        this._reconsumeInState(SCRIPT_DATA_STATE);
};


//12.2.4.22 Script data escaped state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPED_STATE] = function scriptDataEscapedState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.state = SCRIPT_DATA_ESCAPED_DASH_STATE;
        this._emitChar('-');
    }

    else if (cp === $.LESS_THAN_SIGN)
        this.state = SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE;

    else if (cp === $.NULL)
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this._emitCodePoint(cp);
};


//12.2.4.23 Script data escaped dash state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPED_DASH_STATE] = function scriptDataEscapedDashState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.state = SCRIPT_DATA_ESCAPED_DASH_DASH_STATE;
        this._emitChar('-');
    }

    else if (cp === $.LESS_THAN_SIGN)
        this.state = SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE;

    else if (cp === $.NULL) {
        this.state = SCRIPT_DATA_ESCAPED_STATE;
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else {
        this.state = SCRIPT_DATA_ESCAPED_STATE;
        this._emitCodePoint(cp);
    }
};


//12.2.4.24 Script data escaped dash dash state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPED_DASH_DASH_STATE] = function scriptDataEscapedDashDashState(cp) {
    if (cp === $.HYPHEN_MINUS)
        this._emitChar('-');

    else if (cp === $.LESS_THAN_SIGN)
        this.state = SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = SCRIPT_DATA_STATE;
        this._emitChar('>');
    }

    else if (cp === $.NULL) {
        this.state = SCRIPT_DATA_ESCAPED_STATE;
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else {
        this.state = SCRIPT_DATA_ESCAPED_STATE;
        this._emitCodePoint(cp);
    }
};


//12.2.4.25 Script data escaped less-than sign state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN_STATE] = function scriptDataEscapedLessThanSignState(cp) {
    if (cp === $.SOLIDUS) {
        this.tempBuff = [];
        this.state = SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE;
    }

    else if (isAsciiLetter(cp)) {
        this.tempBuff = [];
        this._emitChar('<');
        this._reconsumeInState(SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE);
    }

    else {
        this._emitChar('<');
        this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE);
    }
};


//12.2.4.26 Script data escaped end tag open state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPED_END_TAG_OPEN_STATE] = function scriptDataEscapedEndTagOpenState(cp) {
    if (isAsciiLetter(cp)) {
        this._createEndTagToken();
        this._reconsumeInState(SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE);
    }

    else {
        this._emitChar('<');
        this._emitChar('/');
        this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE);
    }
};


//12.2.4.27 Script data escaped end tag name state
//------------------------------------------------------------------
_[SCRIPT_DATA_ESCAPED_END_TAG_NAME_STATE] = function scriptDataEscapedEndTagNameState(cp) {
    if (isAsciiUpper(cp)) {
        this.currentToken.tagName += toAsciiLowerChar(cp);
        this.tempBuff.push(cp);
    }

    else if (isAsciiLower(cp)) {
        this.currentToken.tagName += toChar(cp);
        this.tempBuff.push(cp);
    }

    else {
        if (this._isAppropriateEndTagToken()) {
            if (isWhitespace(cp)) {
                this.state = BEFORE_ATTRIBUTE_NAME_STATE;
                return;
            }

            if (cp === $.SOLIDUS) {
                this.state = SELF_CLOSING_START_TAG_STATE;
                return;
            }

            if (cp === $.GREATER_THAN_SIGN) {
                this._emitCurrentToken();
                this.state = DATA_STATE;
                return;
            }
        }

        this._emitChar('<');
        this._emitChar('/');
        this._emitSeveralCodePoints(this.tempBuff);
        this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE);
    }
};


//12.2.4.28 Script data double escape start state
//------------------------------------------------------------------
_[SCRIPT_DATA_DOUBLE_ESCAPE_START_STATE] = function scriptDataDoubleEscapeStartState(cp) {
    if (isWhitespace(cp) || cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN) {
        this.state = this.isTempBufferEqualToScriptString() ? SCRIPT_DATA_DOUBLE_ESCAPED_STATE : SCRIPT_DATA_ESCAPED_STATE;
        this._emitCodePoint(cp);
    }

    else if (isAsciiUpper(cp)) {
        this.tempBuff.push(toAsciiLowerCodePoint(cp));
        this._emitCodePoint(cp);
    }

    else if (isAsciiLower(cp)) {
        this.tempBuff.push(cp);
        this._emitCodePoint(cp);
    }

    else
        this._reconsumeInState(SCRIPT_DATA_ESCAPED_STATE);
};


//12.2.4.29 Script data double escaped state
//------------------------------------------------------------------
_[SCRIPT_DATA_DOUBLE_ESCAPED_STATE] = function scriptDataDoubleEscapedState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE;
        this._emitChar('-');
    }

    else if (cp === $.LESS_THAN_SIGN) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE;
        this._emitChar('<');
    }

    else if (cp === $.NULL)
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this._emitCodePoint(cp);
};


//12.2.4.30 Script data double escaped dash state
//------------------------------------------------------------------
_[SCRIPT_DATA_DOUBLE_ESCAPED_DASH_STATE] = function scriptDataDoubleEscapedDashState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE;
        this._emitChar('-');
    }

    else if (cp === $.LESS_THAN_SIGN) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE;
        this._emitChar('<');
    }

    else if (cp === $.NULL) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE;
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE;
        this._emitCodePoint(cp);
    }
};


//12.2.4.31 Script data double escaped dash dash state
//------------------------------------------------------------------
_[SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH_STATE] = function scriptDataDoubleEscapedDashDashState(cp) {
    if (cp === $.HYPHEN_MINUS)
        this._emitChar('-');

    else if (cp === $.LESS_THAN_SIGN) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE;
        this._emitChar('<');
    }

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = SCRIPT_DATA_STATE;
        this._emitChar('>');
    }

    else if (cp === $.NULL) {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE;
        this._emitChar(UNICODE.REPLACEMENT_CHARACTER);
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else {
        this.state = SCRIPT_DATA_DOUBLE_ESCAPED_STATE;
        this._emitCodePoint(cp);
    }
};


//12.2.4.32 Script data double escaped less-than sign state
//------------------------------------------------------------------
_[SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN_STATE] = function scriptDataDoubleEscapedLessThanSignState(cp) {
    if (cp === $.SOLIDUS) {
        this.tempBuff = [];
        this.state = SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE;
        this._emitChar('/');
    }

    else
        this._reconsumeInState(SCRIPT_DATA_DOUBLE_ESCAPED_STATE);
};


//12.2.4.33 Script data double escape end state
//------------------------------------------------------------------
_[SCRIPT_DATA_DOUBLE_ESCAPE_END_STATE] = function scriptDataDoubleEscapeEndState(cp) {
    if (isWhitespace(cp) || cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN) {
        this.state = this.isTempBufferEqualToScriptString() ? SCRIPT_DATA_ESCAPED_STATE : SCRIPT_DATA_DOUBLE_ESCAPED_STATE;

        this._emitCodePoint(cp);
    }

    else if (isAsciiUpper(cp)) {
        this.tempBuff.push(toAsciiLowerCodePoint(cp));
        this._emitCodePoint(cp);
    }

    else if (isAsciiLower(cp)) {
        this.tempBuff.push(cp);
        this._emitCodePoint(cp);
    }

    else
        this._reconsumeInState(SCRIPT_DATA_DOUBLE_ESCAPED_STATE);
};


//12.2.4.34 Before attribute name state
//------------------------------------------------------------------
_[BEFORE_ATTRIBUTE_NAME_STATE] = function beforeAttributeNameState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN || cp === $.EOF)
        this._reconsumeInState(AFTER_ATTRIBUTE_NAME_STATE);

    else if (cp === $.EQUALS_SIGN) {
        this._createAttr('=');
        this.state = ATTRIBUTE_NAME_STATE;
    }

    else {
        this._createAttr('');
        this._reconsumeInState(ATTRIBUTE_NAME_STATE);
    }
};


//12.2.4.35 Attribute name state
//------------------------------------------------------------------
_[ATTRIBUTE_NAME_STATE] = function attributeNameState(cp) {
    if (isWhitespace(cp) || cp === $.SOLIDUS || cp === $.GREATER_THAN_SIGN || cp === $.EOF) {
        this._leaveAttrName(AFTER_ATTRIBUTE_NAME_STATE);
        this._unconsume();
    }

    else if (cp === $.EQUALS_SIGN)
        this._leaveAttrName(BEFORE_ATTRIBUTE_VALUE_STATE);

    else if (isAsciiUpper(cp))
        this.currentAttr.name += toAsciiLowerChar(cp);

    else if (cp === $.QUOTATION_MARK || cp === $.APOSTROPHE || cp === $.LESS_THAN_SIGN)
        this.currentAttr.name += toChar(cp);

    else if (cp === $.NULL)
        this.currentAttr.name += UNICODE.REPLACEMENT_CHARACTER;

    else
        this.currentAttr.name += toChar(cp);
};


//12.2.4.36 After attribute name state
//------------------------------------------------------------------
_[AFTER_ATTRIBUTE_NAME_STATE] = function afterAttributeNameState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.SOLIDUS)
        this.state = SELF_CLOSING_START_TAG_STATE;

    else if (cp === $.EQUALS_SIGN)
        this.state = BEFORE_ATTRIBUTE_VALUE_STATE;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else {
        this._createAttr('');
        this._reconsumeInState(ATTRIBUTE_NAME_STATE);
    }
};


//12.2.4.37 Before attribute value state
//------------------------------------------------------------------
_[BEFORE_ATTRIBUTE_VALUE_STATE] = function beforeAttributeValueState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.QUOTATION_MARK)
        this.state = ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE;

    else if (cp === $.APOSTROPHE)
        this.state = ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE;

    else
        this._reconsumeInState(ATTRIBUTE_VALUE_UNQUOTED_STATE);
};


//12.2.4.38 Attribute value (double-quoted) state
//------------------------------------------------------------------
_[ATTRIBUTE_VALUE_DOUBLE_QUOTED_STATE] = function attributeValueDoubleQuotedState(cp) {
    if (cp === $.QUOTATION_MARK)
        this.state = AFTER_ATTRIBUTE_VALUE_QUOTED_STATE;

    else if (cp === $.AMPERSAND) {
        this.additionalAllowedCp = $.QUOTATION_MARK;
        this.returnState = this.state;
        this.state = CHARACTER_REFERENCE_IN_ATTRIBUTE_VALUE_STATE;
    }

    else if (cp === $.NULL)
        this.currentAttr.value += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this.currentAttr.value += toChar(cp);
};


//12.2.4.39 Attribute value (single-quoted) state
//------------------------------------------------------------------
_[ATTRIBUTE_VALUE_SINGLE_QUOTED_STATE] = function attributeValueSingleQuotedState(cp) {
    if (cp === $.APOSTROPHE)
        this.state = AFTER_ATTRIBUTE_VALUE_QUOTED_STATE;

    else if (cp === $.AMPERSAND) {
        this.additionalAllowedCp = $.APOSTROPHE;
        this.returnState = this.state;
        this.state = CHARACTER_REFERENCE_IN_ATTRIBUTE_VALUE_STATE;
    }

    else if (cp === $.NULL)
        this.currentAttr.value += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this.currentAttr.value += toChar(cp);
};


//12.2.4.40 Attribute value (unquoted) state
//------------------------------------------------------------------
_[ATTRIBUTE_VALUE_UNQUOTED_STATE] = function attributeValueUnquotedState(cp) {
    if (isWhitespace(cp))
        this._leaveAttrValue(BEFORE_ATTRIBUTE_NAME_STATE);

    else if (cp === $.AMPERSAND) {
        this.additionalAllowedCp = $.GREATER_THAN_SIGN;
        this.returnState = this.state;
        this.state = CHARACTER_REFERENCE_IN_ATTRIBUTE_VALUE_STATE;
    }

    else if (cp === $.GREATER_THAN_SIGN) {
        this._leaveAttrValue(DATA_STATE);
        this._emitCurrentToken();
    }

    else if (cp === $.NULL)
        this.currentAttr.value += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.QUOTATION_MARK || cp === $.APOSTROPHE || cp === $.LESS_THAN_SIGN ||
             cp === $.EQUALS_SIGN || cp === $.GRAVE_ACCENT)
        this.currentAttr.value += toChar(cp);

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this.currentAttr.value += toChar(cp);
};


//12.2.4.41 Character reference in attribute value state
//------------------------------------------------------------------
_[CHARACTER_REFERENCE_IN_ATTRIBUTE_VALUE_STATE] = function characterReferenceInAttributeValueState(cp) {
    var referencedCodePoints = this._consumeCharacterReference(cp, true);

    if (!this._ensureHibernation()) {
        if (referencedCodePoints) {
            for (var i = 0; i < referencedCodePoints.length; i++)
                this.currentAttr.value += toChar(referencedCodePoints[i]);
        }
        else
            this.currentAttr.value += '&';

        this.state = this.returnState;
    }
};


//12.2.4.42 After attribute value (quoted) state
//------------------------------------------------------------------
_[AFTER_ATTRIBUTE_VALUE_QUOTED_STATE] = function afterAttributeValueQuotedState(cp) {
    if (isWhitespace(cp))
        this._leaveAttrValue(BEFORE_ATTRIBUTE_NAME_STATE);

    else if (cp === $.SOLIDUS)
        this._leaveAttrValue(SELF_CLOSING_START_TAG_STATE);

    else if (cp === $.GREATER_THAN_SIGN) {
        this._leaveAttrValue(DATA_STATE);
        this._emitCurrentToken();
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this._reconsumeInState(BEFORE_ATTRIBUTE_NAME_STATE);
};


//12.2.4.43 Self-closing start tag state
//------------------------------------------------------------------
_[SELF_CLOSING_START_TAG_STATE] = function selfClosingStartTagState(cp) {
    if (cp === $.GREATER_THAN_SIGN) {
        this.currentToken.selfClosing = true;
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (cp === $.EOF)
        this._reconsumeInState(DATA_STATE);

    else
        this._reconsumeInState(BEFORE_ATTRIBUTE_NAME_STATE);
};


//12.2.4.44 Bogus comment state
//------------------------------------------------------------------
_[BOGUS_COMMENT_STATE] = function bogusCommentState() {
    this._createCommentToken();
    this._reconsumeInState(BOGUS_COMMENT_STATE_CONTINUATION);
};

//HACK: to support streaming and make BOGUS_COMMENT_STATE reentrant we've
//introduced BOGUS_COMMENT_STATE_CONTINUATION state which will not produce
//comment token on each call.
_[BOGUS_COMMENT_STATE_CONTINUATION] = function bogusCommentStateContinuation(cp) {
    while (true) {
        if (cp === $.GREATER_THAN_SIGN) {
            this.state = DATA_STATE;
            break;
        }

        else if (cp === $.EOF) {
            this._reconsumeInState(DATA_STATE);
            break;
        }

        else {
            this.currentToken.data += cp === $.NULL ? UNICODE.REPLACEMENT_CHARACTER : toChar(cp);

            this._hibernationSnapshot();
            cp = this._consume();

            if (this._ensureHibernation())
                return;
        }
    }

    this._emitCurrentToken();
};

//12.2.4.45 Markup declaration open state
//------------------------------------------------------------------
_[MARKUP_DECLARATION_OPEN_STATE] = function markupDeclarationOpenState(cp) {
    var dashDashMatch = this._consumeSubsequentIfMatch($$.DASH_DASH_STRING, cp, true),
        doctypeMatch = !dashDashMatch && this._consumeSubsequentIfMatch($$.DOCTYPE_STRING, cp, false),
        cdataMatch = !dashDashMatch && !doctypeMatch &&
                     this.allowCDATA &&
                     this._consumeSubsequentIfMatch($$.CDATA_START_STRING, cp, true);

    if (!this._ensureHibernation()) {
        if (dashDashMatch) {
            this._createCommentToken();
            this.state = COMMENT_START_STATE;
        }

        else if (doctypeMatch)
            this.state = DOCTYPE_STATE;

        else if (cdataMatch)
            this.state = CDATA_SECTION_STATE;

        else
            this._reconsumeInState(BOGUS_COMMENT_STATE);
    }
};


//12.2.4.46 Comment start state
//------------------------------------------------------------------
_[COMMENT_START_STATE] = function commentStartState(cp) {
    if (cp === $.HYPHEN_MINUS)
        this.state = COMMENT_START_DASH_STATE;

    else if (cp === $.NULL) {
        this.currentToken.data += UNICODE.REPLACEMENT_CHARACTER;
        this.state = COMMENT_STATE;
    }

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (cp === $.EOF) {
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else {
        this.currentToken.data += toChar(cp);
        this.state = COMMENT_STATE;
    }
};


//12.2.4.47 Comment start dash state
//------------------------------------------------------------------
_[COMMENT_START_DASH_STATE] = function commentStartDashState(cp) {
    if (cp === $.HYPHEN_MINUS)
        this.state = COMMENT_END_STATE;

    else if (cp === $.NULL) {
        this.currentToken.data += '-';
        this.currentToken.data += UNICODE.REPLACEMENT_CHARACTER;
        this.state = COMMENT_STATE;
    }

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (cp === $.EOF) {
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else {
        this.currentToken.data += '-';
        this.currentToken.data += toChar(cp);
        this.state = COMMENT_STATE;
    }
};


//12.2.4.48 Comment state
//------------------------------------------------------------------
_[COMMENT_STATE] = function commentState(cp) {
    if (cp === $.HYPHEN_MINUS)
        this.state = COMMENT_END_DASH_STATE;

    else if (cp === $.NULL)
        this.currentToken.data += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.EOF) {
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else
        this.currentToken.data += toChar(cp);
};


//12.2.4.49 Comment end dash state
//------------------------------------------------------------------
_[COMMENT_END_DASH_STATE] = function commentEndDashState(cp) {
    if (cp === $.HYPHEN_MINUS)
        this.state = COMMENT_END_STATE;

    else if (cp === $.NULL) {
        this.currentToken.data += '-';
        this.currentToken.data += UNICODE.REPLACEMENT_CHARACTER;
        this.state = COMMENT_STATE;
    }

    else if (cp === $.EOF) {
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else {
        this.currentToken.data += '-';
        this.currentToken.data += toChar(cp);
        this.state = COMMENT_STATE;
    }
};


//12.2.4.50 Comment end state
//------------------------------------------------------------------
_[COMMENT_END_STATE] = function commentEndState(cp) {
    if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (cp === $.EXCLAMATION_MARK)
        this.state = COMMENT_END_BANG_STATE;

    else if (cp === $.HYPHEN_MINUS)
        this.currentToken.data += '-';

    else if (cp === $.NULL) {
        this.currentToken.data += '--';
        this.currentToken.data += UNICODE.REPLACEMENT_CHARACTER;
        this.state = COMMENT_STATE;
    }

    else if (cp === $.EOF) {
        this._reconsumeInState(DATA_STATE);
        this._emitCurrentToken();
    }

    else {
        this.currentToken.data += '--';
        this.currentToken.data += toChar(cp);
        this.state = COMMENT_STATE;
    }
};


//12.2.4.51 Comment end bang state
//------------------------------------------------------------------
_[COMMENT_END_BANG_STATE] = function commentEndBangState(cp) {
    if (cp === $.HYPHEN_MINUS) {
        this.currentToken.data += '--!';
        this.state = COMMENT_END_DASH_STATE;
    }

    else if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else if (cp === $.NULL) {
        this.currentToken.data += '--!';
        this.currentToken.data += UNICODE.REPLACEMENT_CHARACTER;
        this.state = COMMENT_STATE;
    }

    else if (cp === $.EOF) {
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else {
        this.currentToken.data += '--!';
        this.currentToken.data += toChar(cp);
        this.state = COMMENT_STATE;
    }
};


//12.2.4.52 DOCTYPE state
//------------------------------------------------------------------
_[DOCTYPE_STATE] = function doctypeState(cp) {
    if (isWhitespace(cp))
        return;

    else if (cp === $.GREATER_THAN_SIGN) {
        this._createDoctypeToken(null);
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.EOF) {
        this._createDoctypeToken(null);
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }
    else {
        this._createDoctypeToken('');
        this._reconsumeInState(DOCTYPE_NAME_STATE);
    }
};


//12.2.4.54 DOCTYPE name state
//------------------------------------------------------------------
_[DOCTYPE_NAME_STATE] = function doctypeNameState(cp) {
    if (isWhitespace(cp) || cp === $.GREATER_THAN_SIGN || cp === $.EOF)
        this._reconsumeInState(AFTER_DOCTYPE_NAME_STATE);

    else if (isAsciiUpper(cp))
        this.currentToken.name += toAsciiLowerChar(cp);

    else if (cp === $.NULL)
        this.currentToken.name += UNICODE.REPLACEMENT_CHARACTER;

    else
        this.currentToken.name += toChar(cp);
};


//12.2.4.55 After DOCTYPE name state
//------------------------------------------------------------------
_[AFTER_DOCTYPE_NAME_STATE] = function afterDoctypeNameState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.GREATER_THAN_SIGN) {
        this.state = DATA_STATE;
        this._emitCurrentToken();
    }

    else {
        var publicMatch = this._consumeSubsequentIfMatch($$.PUBLIC_STRING, cp, false),
            systemMatch = !publicMatch && this._consumeSubsequentIfMatch($$.SYSTEM_STRING, cp, false);

        if (!this._ensureHibernation()) {
            if (publicMatch)
                this.state = BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE;

            else if (systemMatch)
                this.state = BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE;

            else {
                this.currentToken.forceQuirks = true;
                this.state = BOGUS_DOCTYPE_STATE;
            }
        }
    }
};


//12.2.4.57 Before DOCTYPE public identifier state
//------------------------------------------------------------------
_[BEFORE_DOCTYPE_PUBLIC_IDENTIFIER_STATE] = function beforeDoctypePublicIdentifierState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.QUOTATION_MARK) {
        this.currentToken.publicId = '';
        this.state = DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE;
    }

    else if (cp === $.APOSTROPHE) {
        this.currentToken.publicId = '';
        this.state = DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE;
    }

    else {
        this.currentToken.forceQuirks = true;
        this._reconsumeInState(BOGUS_DOCTYPE_STATE);
    }
};


//12.2.4.58 DOCTYPE public identifier (double-quoted) state
//------------------------------------------------------------------
_[DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED_STATE] = function doctypePublicIdentifierDoubleQuotedState(cp) {
    if (cp === $.QUOTATION_MARK)
        this.state = BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE;

    else if (cp === $.NULL)
        this.currentToken.publicId += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.EOF) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else
        this.currentToken.publicId += toChar(cp);
};


//12.2.4.59 DOCTYPE public identifier (single-quoted) state
//------------------------------------------------------------------
_[DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED_STATE] = function doctypePublicIdentifierSingleQuotedState(cp) {
    if (cp === $.APOSTROPHE)
        this.state = BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE;

    else if (cp === $.NULL)
        this.currentToken.publicId += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.EOF) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else
        this.currentToken.publicId += toChar(cp);
};


//12.2.4.61 Between DOCTYPE public and system identifiers state
//------------------------------------------------------------------
_[BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS_STATE] = function betweenDoctypePublicAndSystemIdentifiersState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.GREATER_THAN_SIGN) {
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.QUOTATION_MARK) {
        this.currentToken.systemId = '';
        this.state = DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE;
    }


    else if (cp === $.APOSTROPHE) {
        this.currentToken.systemId = '';
        this.state = DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE;
    }

    else {
        this.currentToken.forceQuirks = true;
        this._reconsumeInState(BOGUS_DOCTYPE_STATE);
    }
};


//12.2.4.63 Before DOCTYPE system identifier state
//------------------------------------------------------------------
_[BEFORE_DOCTYPE_SYSTEM_IDENTIFIER_STATE] = function beforeDoctypeSystemIdentifierState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.QUOTATION_MARK) {
        this.currentToken.systemId = '';
        this.state = DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE;
    }

    else if (cp === $.APOSTROPHE) {
        this.currentToken.systemId = '';
        this.state = DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE;
    }

    else {
        this.currentToken.forceQuirks = true;
        this._reconsumeInState(BOGUS_DOCTYPE_STATE);
    }
};


//12.2.4.64 DOCTYPE system identifier (double-quoted) state
//------------------------------------------------------------------
_[DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED_STATE] = function doctypeSystemIdentifierDoubleQuotedState(cp) {
    if (cp === $.QUOTATION_MARK)
        this.state = AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.NULL)
        this.currentToken.systemId += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.EOF) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else
        this.currentToken.systemId += toChar(cp);
};


//12.2.4.65 DOCTYPE system identifier (single-quoted) state
//------------------------------------------------------------------
_[DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED_STATE] = function doctypeSystemIdentifierSingleQuotedState(cp) {
    if (cp === $.APOSTROPHE)
        this.state = AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE;

    else if (cp === $.GREATER_THAN_SIGN) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.NULL)
        this.currentToken.systemId += UNICODE.REPLACEMENT_CHARACTER;

    else if (cp === $.EOF) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else
        this.currentToken.systemId += toChar(cp);
};


//12.2.4.66 After DOCTYPE system identifier state
//------------------------------------------------------------------
_[AFTER_DOCTYPE_SYSTEM_IDENTIFIER_STATE] = function afterDoctypeSystemIdentifierState(cp) {
    if (isWhitespace(cp))
        return;

    if (cp === $.GREATER_THAN_SIGN) {
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.EOF) {
        this.currentToken.forceQuirks = true;
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }

    else
        this.state = BOGUS_DOCTYPE_STATE;
};


//12.2.4.67 Bogus DOCTYPE state
//------------------------------------------------------------------
_[BOGUS_DOCTYPE_STATE] = function bogusDoctypeState(cp) {
    if (cp === $.GREATER_THAN_SIGN) {
        this._emitCurrentToken();
        this.state = DATA_STATE;
    }

    else if (cp === $.EOF) {
        this._emitCurrentToken();
        this._reconsumeInState(DATA_STATE);
    }
};


//12.2.4.68 CDATA section state
//------------------------------------------------------------------
_[CDATA_SECTION_STATE] = function cdataSectionState(cp) {
    while (true) {
        if (cp === $.EOF) {
            this._reconsumeInState(DATA_STATE);
            break;
        }

        else {
            var cdataEndMatch = this._consumeSubsequentIfMatch($$.CDATA_END_STRING, cp, true);

            if (this._ensureHibernation())
                break;

            if (cdataEndMatch) {
                this.state = DATA_STATE;
                break;
            }

            this._emitCodePoint(cp);

            this._hibernationSnapshot();
            cp = this._consume();

            if (this._ensureHibernation())
                break;
        }
    }
};


/***/ }),
/* 125 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_628932__) {

"use strict";
__nested_webpack_require_628932__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
  _extends = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends.apply(this, arguments);
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js
function _iterableToArrayLimit(arr, i) {
  var _arr = [];
  var _n = true;
  var _d = false;
  var _e = undefined;

  try {
    for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);

      if (i && _arr.length === i) break;
    }
  } catch (err) {
    _d = true;
    _e = err;
  } finally {
    try {
      if (!_n && _i["return"] != null) _i["return"]();
    } finally {
      if (_d) throw _e;
    }
  }

  return _arr;
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/slicedToArray.js



function _slicedToArray(arr, i) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/defineProperty.js
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/objectSpread.js

function _objectSpread(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};
    var ownKeys = Object.keys(source);

    if (typeof Object.getOwnPropertySymbols === 'function') {
      ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
        return Object.getOwnPropertyDescriptor(source, sym).enumerable;
      }));
    }

    ownKeys.forEach(function (key) {
      _defineProperty(target, key, source[key]);
    });
  }

  return target;
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/classCallCheck.js
function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/createClass.js
function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/typeof.js
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }

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

  return _typeof(obj);
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
function _assertThisInitialized(self) {
  if (self === void 0) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }

  return self;
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js


function _possibleConstructorReturn(self, call) {
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
    return call;
  }

  return _assertThisInitialized(self);
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
function _getPrototypeOf(o) {
  _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
    return o.__proto__ || Object.getPrototypeOf(o);
  };
  return _getPrototypeOf(o);
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
function _setPrototypeOf(o, p) {
  _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
    o.__proto__ = p;
    return o;
  };

  return _setPrototypeOf(o, p);
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/inherits.js

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function");
  }

  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      writable: true,
      configurable: true
    }
  });
  if (superClass) _setPrototypeOf(subClass, superClass);
}
// EXTERNAL MODULE: external {"commonjs":"react","commonjs2":"react","amd":"react","root":"React"}
var external_commonjs_react_commonjs2_react_amd_react_root_React_ = __nested_webpack_require_628932__(1);

// EXTERNAL MODULE: ../node_modules/prop-types/index.js
var prop_types = __nested_webpack_require_628932__(2);
var prop_types_default = /*#__PURE__*/__nested_webpack_require_628932__.n(prop_types);

// EXTERNAL MODULE: external {"commonjs":"react-dom","commonjs2":"react-dom","amd":"react-dom","root":"ReactDOM"}
var external_commonjs_react_dom_commonjs2_react_dom_amd_react_dom_root_ReactDOM_ = __nested_webpack_require_628932__(42);

// EXTERNAL MODULE: ../node_modules/invariant/browser.js
var browser = __nested_webpack_require_628932__(86);
var browser_default = /*#__PURE__*/__nested_webpack_require_628932__.n(browser);

// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }

    return arr2;
  }
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/iterableToArray.js
function _iterableToArray(iter) {
  if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance");
}
// CONCATENATED MODULE: ../node_modules/@babel/runtime/helpers/esm/toConsumableArray.js



function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
// CONCATENATED MODULE: ../node_modules/react-sortable-hoc/dist/react-sortable-hoc.esm.js
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "SortableContainer", function() { return sortableContainer; });
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "sortableContainer", function() { return sortableContainer; });
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "SortableElement", function() { return sortableElement; });
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "sortableElement", function() { return sortableElement; });
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "SortableHandle", function() { return sortableHandle; });
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "sortableHandle", function() { return sortableHandle; });
/* harmony export (binding) */ __nested_webpack_require_628932__.d(__webpack_exports__, "arrayMove", function() { return arrayMove; });
















var react_sortable_hoc_esm_Manager = function () {
  function Manager() {
    _classCallCheck(this, Manager);

    _defineProperty(this, "refs", {});
  }

  _createClass(Manager, [{
    key: "add",
    value: function add(collection, ref) {
      if (!this.refs[collection]) {
        this.refs[collection] = [];
      }

      this.refs[collection].push(ref);
    }
  }, {
    key: "remove",
    value: function remove(collection, ref) {
      var index = this.getIndex(collection, ref);

      if (index !== -1) {
        this.refs[collection].splice(index, 1);
      }
    }
  }, {
    key: "isActive",
    value: function isActive() {
      return this.active;
    }
  }, {
    key: "getActive",
    value: function getActive() {
      var _this = this;

      return this.refs[this.active.collection].find(function (_ref) {
        var node = _ref.node;
        return node.sortableInfo.index == _this.active.index;
      });
    }
  }, {
    key: "getIndex",
    value: function getIndex(collection, ref) {
      return this.refs[collection].indexOf(ref);
    }
  }, {
    key: "getOrderedRefs",
    value: function getOrderedRefs() {
      var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.active.collection;
      return this.refs[collection].sort(sortByIndex);
    }
  }]);

  return Manager;
}();

function sortByIndex(_ref2, _ref3) {
  var index1 = _ref2.node.sortableInfo.index;
  var index2 = _ref3.node.sortableInfo.index;
  return index1 - index2;
}

function arrayMove(array, from, to) {
  if (false) {}

  array = array.slice();
  array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
  return array;
}
function omit(obj, keysToOmit) {
  return Object.keys(obj).reduce(function (acc, key) {
    if (keysToOmit.indexOf(key) === -1) {
      acc[key] = obj[key];
    }

    return acc;
  }, {});
}
var events = {
  end: ['touchend', 'touchcancel', 'mouseup'],
  move: ['touchmove', 'mousemove'],
  start: ['touchstart', 'mousedown']
};
var vendorPrefix = function () {
  if (typeof window === 'undefined' || typeof document === 'undefined') {
    return '';
  }

  var styles = window.getComputedStyle(document.documentElement, '') || ['-moz-hidden-iframe'];
  var pre = (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) || styles.OLink === '' && ['', 'o'])[1];

  switch (pre) {
    case 'ms':
      return 'ms';

    default:
      return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : '';
  }
}();
function setInlineStyles(node, styles) {
  Object.keys(styles).forEach(function (key) {
    node.style[key] = styles[key];
  });
}
function setTranslate3d(node, translate) {
  node.style["".concat(vendorPrefix, "Transform")] = translate == null ? '' : "translate3d(".concat(translate.x, "px,").concat(translate.y, "px,0)");
}
function setTransitionDuration(node, duration) {
  node.style["".concat(vendorPrefix, "TransitionDuration")] = duration == null ? '' : "".concat(duration, "ms");
}
function closest(el, fn) {
  while (el) {
    if (fn(el)) {
      return el;
    }

    el = el.parentNode;
  }

  return null;
}
function limit(min, max, value) {
  return Math.max(min, Math.min(value, max));
}

function getPixelValue(stringValue) {
  if (stringValue.substr(-2) === 'px') {
    return parseFloat(stringValue);
  }

  return 0;
}

function getElementMargin(element) {
  var style = window.getComputedStyle(element);
  return {
    bottom: getPixelValue(style.marginBottom),
    left: getPixelValue(style.marginLeft),
    right: getPixelValue(style.marginRight),
    top: getPixelValue(style.marginTop)
  };
}
function provideDisplayName(prefix, Component$$1) {
  var componentName = Component$$1.displayName || Component$$1.name;
  return componentName ? "".concat(prefix, "(").concat(componentName, ")") : prefix;
}
function getScrollAdjustedBoundingClientRect(node, scrollDelta) {
  var boundingClientRect = node.getBoundingClientRect();
  return {
    top: boundingClientRect.top + scrollDelta.top,
    left: boundingClientRect.left + scrollDelta.left
  };
}
function getPosition(event) {
  if (event.touches && event.touches.length) {
    return {
      x: event.touches[0].pageX,
      y: event.touches[0].pageY
    };
  } else if (event.changedTouches && event.changedTouches.length) {
    return {
      x: event.changedTouches[0].pageX,
      y: event.changedTouches[0].pageY
    };
  } else {
    return {
      x: event.pageX,
      y: event.pageY
    };
  }
}
function isTouchEvent(event) {
  return event.touches && event.touches.length || event.changedTouches && event.changedTouches.length;
}
function getEdgeOffset(node, parent) {
  var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    left: 0,
    top: 0
  };

  if (!node) {
    return undefined;
  }

  var nodeOffset = {
    left: offset.left + node.offsetLeft,
    top: offset.top + node.offsetTop
  };

  if (node.parentNode === parent) {
    return nodeOffset;
  }

  return getEdgeOffset(node.parentNode, parent, nodeOffset);
}
function getTargetIndex(newIndex, prevIndex, oldIndex) {
  if (newIndex < oldIndex && newIndex > prevIndex) {
    return newIndex - 1;
  } else if (newIndex > oldIndex && newIndex < prevIndex) {
    return newIndex + 1;
  } else {
    return newIndex;
  }
}
function getLockPixelOffset(_ref) {
  var lockOffset = _ref.lockOffset,
      width = _ref.width,
      height = _ref.height;
  var offsetX = lockOffset;
  var offsetY = lockOffset;
  var unit = 'px';

  if (typeof lockOffset === 'string') {
    var match = /^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(lockOffset);
    browser_default()(match !== null, 'lockOffset value should be a number or a string of a ' + 'number followed by "px" or "%". Given %s', lockOffset);
    offsetX = parseFloat(lockOffset);
    offsetY = parseFloat(lockOffset);
    unit = match[1];
  }

  browser_default()(isFinite(offsetX) && isFinite(offsetY), 'lockOffset value should be a finite. Given %s', lockOffset);

  if (unit === '%') {
    offsetX = offsetX * width / 100;
    offsetY = offsetY * height / 100;
  }

  return {
    x: offsetX,
    y: offsetY
  };
}
function getLockPixelOffsets(_ref2) {
  var height = _ref2.height,
      width = _ref2.width,
      lockOffset = _ref2.lockOffset;
  var offsets = Array.isArray(lockOffset) ? lockOffset : [lockOffset, lockOffset];
  browser_default()(offsets.length === 2, 'lockOffset prop of SortableContainer should be a single ' + 'value or an array of exactly two values. Given %s', lockOffset);

  var _offsets = _slicedToArray(offsets, 2),
      minLockOffset = _offsets[0],
      maxLockOffset = _offsets[1];

  return [getLockPixelOffset({
    height: height,
    lockOffset: minLockOffset,
    width: width
  }), getLockPixelOffset({
    height: height,
    lockOffset: maxLockOffset,
    width: width
  })];
}

function isScrollable(el) {
  var computedStyle = window.getComputedStyle(el);
  var overflowRegex = /(auto|scroll)/;
  var properties = ['overflow', 'overflowX', 'overflowY'];
  return properties.find(function (property) {
    return overflowRegex.test(computedStyle[property]);
  });
}

function getScrollingParent(el) {
  if (!(el instanceof HTMLElement)) {
    return null;
  } else if (isScrollable(el)) {
    return el;
  } else {
    return getScrollingParent(el.parentNode);
  }
}
var KEYCODE = {
  TAB: 9,
  ESC: 27,
  SPACE: 32,
  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40
};
var NodeType = {
  Anchor: 'A',
  Button: 'BUTTON',
  Canvas: 'CANVAS',
  Input: 'INPUT',
  Option: 'OPTION',
  Textarea: 'TEXTAREA',
  Select: 'SELECT'
};
function cloneNode(node) {
  var selector = 'input, textarea, select, canvas, [contenteditable]';
  var fields = node.querySelectorAll(selector);
  var clonedNode = node.cloneNode(true);

  var clonedFields = _toConsumableArray(clonedNode.querySelectorAll(selector));

  clonedFields.forEach(function (field, i) {
    if (field.type !== 'file') {
      field.value = fields[i].value;
    }

    if (field.type === 'radio' && field.name) {
      field.name = "__sortableClone__".concat(field.name);
    }

    if (field.tagName === NodeType.Canvas && fields[i].width > 0 && fields[i].height > 0) {
      var destCtx = field.getContext('2d');
      destCtx.drawImage(fields[i], 0, 0);
    }
  });
  return clonedNode;
}

function sortableHandle(WrappedComponent) {
  var _class, _temp;

  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    withRef: false
  };
  return _temp = _class = function (_React$Component) {
    _inherits(WithSortableHandle, _React$Component);

    function WithSortableHandle() {
      _classCallCheck(this, WithSortableHandle);

      return _possibleConstructorReturn(this, _getPrototypeOf(WithSortableHandle).apply(this, arguments));
    }

    _createClass(WithSortableHandle, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        var node = Object(external_commonjs_react_dom_commonjs2_react_dom_amd_react_dom_root_ReactDOM_["findDOMNode"])(this);
        node.sortableHandle = true;
      }
    }, {
      key: "getWrappedInstance",
      value: function getWrappedInstance() {
        browser_default()(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call');
        return this.refs.wrappedInstance;
      }
    }, {
      key: "render",
      value: function render() {
        var ref = config.withRef ? 'wrappedInstance' : null;
        return Object(external_commonjs_react_commonjs2_react_amd_react_root_React_["createElement"])(WrappedComponent, _extends({
          ref: ref
        }, this.props));
      }
    }]);

    return WithSortableHandle;
  }(external_commonjs_react_commonjs2_react_amd_react_root_React_["Component"]), _defineProperty(_class, "displayName", provideDisplayName('sortableHandle', WrappedComponent)), _temp;
}
function isSortableHandle(node) {
  return node.sortableHandle != null;
}

var react_sortable_hoc_esm_AutoScroller = function () {
  function AutoScroller(container, onScrollCallback) {
    _classCallCheck(this, AutoScroller);

    this.container = container;
    this.onScrollCallback = onScrollCallback;
  }

  _createClass(AutoScroller, [{
    key: "clear",
    value: function clear() {
      clearInterval(this.interval);
      this.interval = null;
    }
  }, {
    key: "update",
    value: function update(_ref) {
      var _this = this;

      var translate = _ref.translate,
          minTranslate = _ref.minTranslate,
          maxTranslate = _ref.maxTranslate,
          width = _ref.width,
          height = _ref.height;
      var direction = {
        x: 0,
        y: 0
      };
      var speed = {
        x: 1,
        y: 1
      };
      var acceleration = {
        x: 10,
        y: 10
      };
      var _this$container = this.container,
          scrollTop = _this$container.scrollTop,
          scrollLeft = _this$container.scrollLeft,
          scrollHeight = _this$container.scrollHeight,
          scrollWidth = _this$container.scrollWidth,
          clientHeight = _this$container.clientHeight,
          clientWidth = _this$container.clientWidth;
      var isTop = scrollTop === 0;
      var isBottom = scrollHeight - scrollTop - clientHeight === 0;
      var isLeft = scrollLeft === 0;
      var isRight = scrollWidth - scrollLeft - clientWidth === 0;

      if (translate.y >= maxTranslate.y - height / 2 && !isBottom) {
        direction.y = 1;
        speed.y = acceleration.y * Math.abs((maxTranslate.y - height / 2 - translate.y) / height);
      } else if (translate.x >= maxTranslate.x - width / 2 && !isRight) {
        direction.x = 1;
        speed.x = acceleration.x * Math.abs((maxTranslate.x - width / 2 - translate.x) / width);
      } else if (translate.y <= minTranslate.y + height / 2 && !isTop) {
        direction.y = -1;
        speed.y = acceleration.y * Math.abs((translate.y - height / 2 - minTranslate.y) / height);
      } else if (translate.x <= minTranslate.x + width / 2 && !isLeft) {
        direction.x = -1;
        speed.x = acceleration.x * Math.abs((translate.x - width / 2 - minTranslate.x) / width);
      }

      if (this.interval) {
        this.clear();
        this.isAutoScrolling = false;
      }

      if (direction.x !== 0 || direction.y !== 0) {
        this.interval = setInterval(function () {
          _this.isAutoScrolling = true;
          var offset = {
            left: speed.x * direction.x,
            top: speed.y * direction.y
          };
          _this.container.scrollTop += offset.top;
          _this.container.scrollLeft += offset.left;

          _this.onScrollCallback(offset);
        }, 5);
      }
    }
  }]);

  return AutoScroller;
}();

function defaultGetHelperDimensions(_ref) {
  var node = _ref.node;
  return {
    height: node.offsetHeight,
    width: node.offsetWidth
  };
}

function defaultShouldCancelStart(event) {
  var interactiveElements = [NodeType.Input, NodeType.Textarea, NodeType.Select, NodeType.Option, NodeType.Button];

  if (interactiveElements.indexOf(event.target.tagName) !== -1) {
    return true;
  }

  if (closest(event.target, function (el) {
    return el.contentEditable === 'true';
  })) {
    return true;
  }

  return false;
}

var propTypes = {
  axis: prop_types_default.a.oneOf(['x', 'y', 'xy']),
  contentWindow: prop_types_default.a.any,
  disableAutoscroll: prop_types_default.a.bool,
  distance: prop_types_default.a.number,
  getContainer: prop_types_default.a.func,
  getHelperDimensions: prop_types_default.a.func,
  helperClass: prop_types_default.a.string,
  helperContainer: prop_types_default.a.oneOfType([prop_types_default.a.func, typeof HTMLElement === 'undefined' ? prop_types_default.a.any : prop_types_default.a.instanceOf(HTMLElement)]),
  hideSortableGhost: prop_types_default.a.bool,
  keyboardSortingTransitionDuration: prop_types_default.a.number,
  lockAxis: prop_types_default.a.string,
  lockOffset: prop_types_default.a.oneOfType([prop_types_default.a.number, prop_types_default.a.string, prop_types_default.a.arrayOf(prop_types_default.a.oneOfType([prop_types_default.a.number, prop_types_default.a.string]))]),
  lockToContainerEdges: prop_types_default.a.bool,
  onSortEnd: prop_types_default.a.func,
  onSortMove: prop_types_default.a.func,
  onSortOver: prop_types_default.a.func,
  onSortStart: prop_types_default.a.func,
  pressDelay: prop_types_default.a.number,
  pressThreshold: prop_types_default.a.number,
  keyCodes: prop_types_default.a.shape({
    lift: prop_types_default.a.arrayOf(prop_types_default.a.number),
    drop: prop_types_default.a.arrayOf(prop_types_default.a.number),
    cancel: prop_types_default.a.arrayOf(prop_types_default.a.number),
    up: prop_types_default.a.arrayOf(prop_types_default.a.number),
    down: prop_types_default.a.arrayOf(prop_types_default.a.number)
  }),
  shouldCancelStart: prop_types_default.a.func,
  transitionDuration: prop_types_default.a.number,
  updateBeforeSortStart: prop_types_default.a.func,
  useDragHandle: prop_types_default.a.bool,
  useWindowAsScrollContainer: prop_types_default.a.bool
};
var defaultKeyCodes = {
  lift: [KEYCODE.SPACE],
  drop: [KEYCODE.SPACE],
  cancel: [KEYCODE.ESC],
  up: [KEYCODE.UP, KEYCODE.LEFT],
  down: [KEYCODE.DOWN, KEYCODE.RIGHT]
};
var defaultProps = {
  axis: 'y',
  disableAutoscroll: false,
  distance: 0,
  getHelperDimensions: defaultGetHelperDimensions,
  hideSortableGhost: true,
  lockOffset: '50%',
  lockToContainerEdges: false,
  pressDelay: 0,
  pressThreshold: 5,
  keyCodes: defaultKeyCodes,
  shouldCancelStart: defaultShouldCancelStart,
  transitionDuration: 300,
  useWindowAsScrollContainer: false
};
var omittedProps = Object.keys(propTypes);
function validateProps(props) {
  browser_default()(!(props.distance && props.pressDelay), 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.');
}

function _finallyRethrows(body, finalizer) {
  try {
    var result = body();
  } catch (e) {
    return finalizer(true, e);
  }

  if (result && result.then) {
    return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
  }

  return finalizer(false, value);
}
function sortableContainer(WrappedComponent) {
  var _class, _temp;

  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    withRef: false
  };
  return _temp = _class = function (_React$Component) {
    _inherits(WithSortableContainer, _React$Component);

    function WithSortableContainer(props) {
      var _this;

      _classCallCheck(this, WithSortableContainer);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(WithSortableContainer).call(this, props));

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {});

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleStart", function (event) {
        var _this$props = _this.props,
            distance = _this$props.distance,
            shouldCancelStart = _this$props.shouldCancelStart;

        if (event.button === 2 || shouldCancelStart(event)) {
          return;
        }

        _this.touched = true;
        _this.position = getPosition(event);
        var node = closest(event.target, function (el) {
          return el.sortableInfo != null;
        });

        if (node && node.sortableInfo && _this.nodeIsChild(node) && !_this.state.sorting) {
          var useDragHandle = _this.props.useDragHandle;
          var _node$sortableInfo = node.sortableInfo,
              index = _node$sortableInfo.index,
              collection = _node$sortableInfo.collection,
              disabled = _node$sortableInfo.disabled;

          if (disabled) {
            return;
          }

          if (useDragHandle && !closest(event.target, isSortableHandle)) {
            return;
          }

          _this.manager.active = {
            collection: collection,
            index: index
          };

          if (!isTouchEvent(event) && event.target.tagName === NodeType.Anchor) {
            event.preventDefault();
          }

          if (!distance) {
            if (_this.props.pressDelay === 0) {
              _this.handlePress(event);
            } else {
              _this.pressTimer = setTimeout(function () {
                return _this.handlePress(event);
              }, _this.props.pressDelay);
            }
          }
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "nodeIsChild", function (node) {
        return node.sortableInfo.manager === _this.manager;
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleMove", function (event) {
        var _this$props2 = _this.props,
            distance = _this$props2.distance,
            pressThreshold = _this$props2.pressThreshold;

        if (!_this.state.sorting && _this.touched && !_this._awaitingUpdateBeforeSortStart) {
          var position = getPosition(event);
          var delta = {
            x: _this.position.x - position.x,
            y: _this.position.y - position.y
          };
          var combinedDelta = Math.abs(delta.x) + Math.abs(delta.y);
          _this.delta = delta;

          if (!distance && (!pressThreshold || combinedDelta >= pressThreshold)) {
            clearTimeout(_this.cancelTimer);
            _this.cancelTimer = setTimeout(_this.cancel, 0);
          } else if (distance && combinedDelta >= distance && _this.manager.isActive()) {
            _this.handlePress(event);
          }
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleEnd", function () {
        _this.touched = false;

        _this.cancel();
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "cancel", function () {
        var distance = _this.props.distance;
        var sorting = _this.state.sorting;

        if (!sorting) {
          if (!distance) {
            clearTimeout(_this.pressTimer);
          }

          _this.manager.active = null;
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handlePress", function (event) {
        try {
          var active = _this.manager.getActive();

          var _temp6 = function () {
            if (active) {
              var _temp7 = function _temp7() {
                var index = _node.sortableInfo.index;
                var margin = getElementMargin(_node);

                var containerBoundingRect = _this.scrollContainer.getBoundingClientRect();

                var dimensions = _getHelperDimensions({
                  collection: _collection,
                  index: index,
                  node: _node
                });

                _this.node = _node;
                _this.margin = margin;
                _this.width = dimensions.width;
                _this.height = dimensions.height;
                _this.marginOffset = {
                  x: _this.margin.left + _this.margin.right,
                  y: Math.max(_this.margin.top, _this.margin.bottom)
                };
                _this.boundingClientRect = _node.getBoundingClientRect();
                _this.containerBoundingRect = containerBoundingRect;
                _this.index = index;
                _this.newIndex = index;
                _this.axis = {
                  x: _axis.indexOf('x') >= 0,
                  y: _axis.indexOf('y') >= 0
                };
                _this.offsetEdge = getEdgeOffset(_node, _this.container);

                if (_isKeySorting) {
                  _this.initialOffset = getPosition(_objectSpread({}, event, {
                    pageX: _this.boundingClientRect.left,
                    pageY: _this.boundingClientRect.top
                  }));
                } else {
                  _this.initialOffset = getPosition(event);
                }

                _this.initialScroll = {
                  left: _this.scrollContainer.scrollLeft,
                  top: _this.scrollContainer.scrollTop
                };
                _this.initialWindowScroll = {
                  left: window.pageXOffset,
                  top: window.pageYOffset
                };
                _this.helper = _this.helperContainer.appendChild(cloneNode(_node));
                setInlineStyles(_this.helper, {
                  boxSizing: 'border-box',
                  height: "".concat(_this.height, "px"),
                  left: "".concat(_this.boundingClientRect.left - margin.left, "px"),
                  pointerEvents: 'none',
                  position: 'fixed',
                  top: "".concat(_this.boundingClientRect.top - margin.top, "px"),
                  width: "".concat(_this.width, "px")
                });

                if (_isKeySorting) {
                  _this.helper.focus();
                }

                if (_hideSortableGhost) {
                  _this.sortableGhost = _node;
                  setInlineStyles(_node, {
                    opacity: 0,
                    visibility: 'hidden'
                  });
                }

                _this.minTranslate = {};
                _this.maxTranslate = {};

                if (_isKeySorting) {
                  var _ref = _useWindowAsScrollContainer ? {
                    top: 0,
                    left: 0,
                    width: _this.contentWindow.innerWidth,
                    height: _this.contentWindow.innerHeight
                  } : _this.containerBoundingRect,
                      containerTop = _ref.top,
                      containerLeft = _ref.left,
                      containerWidth = _ref.width,
                      containerHeight = _ref.height;

                  var containerBottom = containerTop + containerHeight;
                  var containerRight = containerLeft + containerWidth;

                  if (_this.axis.x) {
                    _this.minTranslate.x = containerLeft - _this.boundingClientRect.left;
                    _this.maxTranslate.x = containerRight - (_this.boundingClientRect.left + _this.width);
                  }

                  if (_this.axis.y) {
                    _this.minTranslate.y = containerTop - _this.boundingClientRect.top;
                    _this.maxTranslate.y = containerBottom - (_this.boundingClientRect.top + _this.height);
                  }
                } else {
                  if (_this.axis.x) {
                    _this.minTranslate.x = (_useWindowAsScrollContainer ? 0 : containerBoundingRect.left) - _this.boundingClientRect.left - _this.width / 2;
                    _this.maxTranslate.x = (_useWindowAsScrollContainer ? _this.contentWindow.innerWidth : containerBoundingRect.left + containerBoundingRect.width) - _this.boundingClientRect.left - _this.width / 2;
                  }

                  if (_this.axis.y) {
                    _this.minTranslate.y = (_useWindowAsScrollContainer ? 0 : containerBoundingRect.top) - _this.boundingClientRect.top - _this.height / 2;
                    _this.maxTranslate.y = (_useWindowAsScrollContainer ? _this.contentWindow.innerHeight : containerBoundingRect.top + containerBoundingRect.height) - _this.boundingClientRect.top - _this.height / 2;
                  }
                }

                if (_helperClass) {
                  _helperClass.split(' ').forEach(function (className) {
                    return _this.helper.classList.add(className);
                  });
                }

                _this.listenerNode = event.touches ? _node : _this.contentWindow;

                if (_isKeySorting) {
                  _this.listenerNode.addEventListener('wheel', _this.handleKeyEnd, true);

                  _this.listenerNode.addEventListener('mousedown', _this.handleKeyEnd, true);

                  _this.listenerNode.addEventListener('keydown', _this.handleKeyDown);
                } else {
                  events.move.forEach(function (eventName) {
                    return _this.listenerNode.addEventListener(eventName, _this.handleSortMove, false);
                  });
                  events.end.forEach(function (eventName) {
                    return _this.listenerNode.addEventListener(eventName, _this.handleSortEnd, false);
                  });
                }

                _this.setState({
                  sorting: true,
                  sortingIndex: index
                });

                if (_onSortStart) {
                  _onSortStart({
                    node: _node,
                    index: index,
                    collection: _collection,
                    isKeySorting: _isKeySorting
                  }, event);
                }

                if (_isKeySorting) {
                  _this.keyMove(0);
                }
              };

              var _this$props3 = _this.props,
                  _axis = _this$props3.axis,
                  _getHelperDimensions = _this$props3.getHelperDimensions,
                  _helperClass = _this$props3.helperClass,
                  _hideSortableGhost = _this$props3.hideSortableGhost,
                  updateBeforeSortStart = _this$props3.updateBeforeSortStart,
                  _onSortStart = _this$props3.onSortStart,
                  _useWindowAsScrollContainer = _this$props3.useWindowAsScrollContainer;
              var _node = active.node,
                  _collection = active.collection;
              var _isKeySorting = _this.manager.isKeySorting;

              var _temp8 = function () {
                if (typeof updateBeforeSortStart === 'function') {
                  _this._awaitingUpdateBeforeSortStart = true;

                  var _temp9 = _finallyRethrows(function () {
                    var index = _node.sortableInfo.index;
                    return Promise.resolve(updateBeforeSortStart({
                      collection: _collection,
                      index: index,
                      node: _node,
                      isKeySorting: _isKeySorting
                    }, event)).then(function () {});
                  }, function (_wasThrown, _result) {
                    _this._awaitingUpdateBeforeSortStart = false;
                    if (_wasThrown) throw _result;
                    return _result;
                  });

                  if (_temp9 && _temp9.then) return _temp9.then(function () {});
                }
              }();

              return _temp8 && _temp8.then ? _temp8.then(_temp7) : _temp7(_temp8);
            }
          }();

          return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0);
        } catch (e) {
          return Promise.reject(e);
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleSortMove", function (event) {
        var onSortMove = _this.props.onSortMove;

        if (typeof event.preventDefault === 'function') {
          event.preventDefault();
        }

        _this.updateHelperPosition(event);

        _this.animateNodes();

        _this.autoscroll();

        if (onSortMove) {
          onSortMove(event);
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleSortEnd", function (event) {
        var _this$props4 = _this.props,
            hideSortableGhost = _this$props4.hideSortableGhost,
            onSortEnd = _this$props4.onSortEnd;
        var _this$manager = _this.manager,
            collection = _this$manager.active.collection,
            isKeySorting = _this$manager.isKeySorting;
        var nodes = _this.manager.refs[collection];

        if (_this.listenerNode) {
          if (isKeySorting) {
            _this.listenerNode.removeEventListener('wheel', _this.handleKeyEnd, true);

            _this.listenerNode.removeEventListener('mousedown', _this.handleKeyEnd, true);

            _this.listenerNode.removeEventListener('keydown', _this.handleKeyDown);
          } else {
            events.move.forEach(function (eventName) {
              return _this.listenerNode.removeEventListener(eventName, _this.handleSortMove);
            });
            events.end.forEach(function (eventName) {
              return _this.listenerNode.removeEventListener(eventName, _this.handleSortEnd);
            });
          }
        }

        _this.helper.parentNode.removeChild(_this.helper);

        if (hideSortableGhost && _this.sortableGhost) {
          setInlineStyles(_this.sortableGhost, {
            opacity: '',
            visibility: ''
          });
        }

        for (var i = 0, len = nodes.length; i < len; i++) {
          var _node2 = nodes[i];
          var el = _node2.node;
          _node2.edgeOffset = null;
          _node2.boundingClientRect = null;
          setTranslate3d(el, null);
          setTransitionDuration(el, null);
          _node2.translate = null;
        }

        _this.autoScroller.clear();

        _this.manager.active = null;
        _this.manager.isKeySorting = false;

        _this.setState({
          sorting: false,
          sortingIndex: null
        });

        if (typeof onSortEnd === 'function') {
          onSortEnd({
            collection: collection,
            newIndex: _this.newIndex,
            oldIndex: _this.index,
            isKeySorting: isKeySorting
          }, event);
        }

        _this.touched = false;
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "autoscroll", function () {
        var disableAutoscroll = _this.props.disableAutoscroll;
        var isKeySorting = _this.manager.isKeySorting;

        if (disableAutoscroll) {
          return;
        }

        if (isKeySorting) {
          var translate = _objectSpread({}, _this.translate);

          var scrollX = 0;
          var scrollY = 0;

          if (_this.axis.x) {
            translate.x = Math.min(_this.maxTranslate.x, Math.max(_this.minTranslate.x, _this.translate.x));
            scrollX = _this.translate.x - translate.x;
          }

          if (_this.axis.y) {
            translate.y = Math.min(_this.maxTranslate.y, Math.max(_this.minTranslate.y, _this.translate.y));
            scrollY = _this.translate.y - translate.y;
          }

          _this.translate = translate;
          setTranslate3d(_this.helper, _this.translate);
          _this.scrollContainer.scrollLeft += scrollX;
          _this.scrollContainer.scrollTop += scrollY;
          return;
        }

        _this.autoScroller.update({
          height: _this.height,
          maxTranslate: _this.maxTranslate,
          minTranslate: _this.minTranslate,
          translate: _this.translate,
          width: _this.width
        });
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onAutoScroll", function (offset) {
        _this.translate.x += offset.left;
        _this.translate.y += offset.top;

        _this.animateNodes();
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleKeyDown", function (event) {
        var keyCode = event.keyCode;
        var _this$props5 = _this.props,
            shouldCancelStart = _this$props5.shouldCancelStart,
            _this$props5$keyCodes = _this$props5.keyCodes,
            customKeyCodes = _this$props5$keyCodes === void 0 ? {} : _this$props5$keyCodes;

        var keyCodes = _objectSpread({}, defaultKeyCodes, customKeyCodes);

        if (_this.manager.active && !_this.manager.isKeySorting || !_this.manager.active && (!keyCodes.lift.includes(keyCode) || shouldCancelStart(event) || !_this.isValidSortingTarget(event))) {
          return;
        }

        event.stopPropagation();
        event.preventDefault();

        if (keyCodes.lift.includes(keyCode) && !_this.manager.active) {
          _this.keyLift(event);
        } else if (keyCodes.drop.includes(keyCode) && _this.manager.active) {
          _this.keyDrop(event);
        } else if (keyCodes.cancel.includes(keyCode)) {
          _this.newIndex = _this.manager.active.index;

          _this.keyDrop(event);
        } else if (keyCodes.up.includes(keyCode)) {
          _this.keyMove(-1);
        } else if (keyCodes.down.includes(keyCode)) {
          _this.keyMove(1);
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "keyLift", function (event) {
        var target = event.target;
        var node = closest(target, function (el) {
          return el.sortableInfo != null;
        });
        var _node$sortableInfo2 = node.sortableInfo,
            index = _node$sortableInfo2.index,
            collection = _node$sortableInfo2.collection;
        _this.initialFocusedNode = target;
        _this.manager.isKeySorting = true;
        _this.manager.active = {
          index: index,
          collection: collection
        };

        _this.handlePress(event);
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "keyMove", function (shift) {
        var nodes = _this.manager.getOrderedRefs();

        var lastIndex = nodes[nodes.length - 1].node.sortableInfo.index;
        var newIndex = _this.newIndex + shift;
        var prevIndex = _this.newIndex;

        if (newIndex < 0 || newIndex > lastIndex) {
          return;
        }

        _this.prevIndex = prevIndex;
        _this.newIndex = newIndex;
        var targetIndex = getTargetIndex(_this.newIndex, _this.prevIndex, _this.index);
        var target = nodes.find(function (_ref2) {
          var node = _ref2.node;
          return node.sortableInfo.index === targetIndex;
        });
        var targetNode = target.node;
        var scrollDelta = _this.containerScrollDelta;
        var targetBoundingClientRect = target.boundingClientRect || getScrollAdjustedBoundingClientRect(targetNode, scrollDelta);
        var targetTranslate = target.translate || {
          x: 0,
          y: 0
        };
        var targetPosition = {
          top: targetBoundingClientRect.top + targetTranslate.y - scrollDelta.top,
          left: targetBoundingClientRect.left + targetTranslate.x - scrollDelta.left
        };
        var shouldAdjustForSize = prevIndex < newIndex;
        var sizeAdjustment = {
          x: shouldAdjustForSize && _this.axis.x ? targetNode.offsetWidth - _this.width : 0,
          y: shouldAdjustForSize && _this.axis.y ? targetNode.offsetHeight - _this.height : 0
        };

        _this.handleSortMove({
          pageX: targetPosition.left + sizeAdjustment.x,
          pageY: targetPosition.top + sizeAdjustment.y,
          ignoreTransition: shift === 0
        });
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "keyDrop", function (event) {
        _this.handleSortEnd(event);

        if (_this.initialFocusedNode) {
          _this.initialFocusedNode.focus();
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleKeyEnd", function (event) {
        if (_this.manager.active) {
          _this.keyDrop(event);
        }
      });

      _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "isValidSortingTarget", function (event) {
        var useDragHandle = _this.props.useDragHandle;
        var target = event.target;
        var node = closest(target, function (el) {
          return el.sortableInfo != null;
        });
        return node && node.sortableInfo && !node.sortableInfo.disabled && (useDragHandle ? isSortableHandle(target) : target.sortableInfo);
      });

      validateProps(props);
      _this.manager = new react_sortable_hoc_esm_Manager();
      _this.events = {
        end: _this.handleEnd,
        move: _this.handleMove,
        start: _this.handleStart
      };
      return _this;
    }

    _createClass(WithSortableContainer, [{
      key: "getChildContext",
      value: function getChildContext() {
        return {
          manager: this.manager
        };
      }
    }, {
      key: "componentDidMount",
      value: function componentDidMount() {
        var _this2 = this;

        var useWindowAsScrollContainer = this.props.useWindowAsScrollContainer;
        var container = this.getContainer();
        Promise.resolve(container).then(function (containerNode) {
          _this2.container = containerNode;
          _this2.document = _this2.container.ownerDocument || document;
          var contentWindow = _this2.props.contentWindow || _this2.document.defaultView || window;
          _this2.contentWindow = typeof contentWindow === 'function' ? contentWindow() : contentWindow;
          _this2.scrollContainer = useWindowAsScrollContainer ? _this2.document.scrollingElement || _this2.document.documentElement : getScrollingParent(_this2.container) || _this2.container;
          _this2.autoScroller = new react_sortable_hoc_esm_AutoScroller(_this2.scrollContainer, _this2.onAutoScroll);
          Object.keys(_this2.events).forEach(function (key) {
            return events[key].forEach(function (eventName) {
              return _this2.container.addEventListener(eventName, _this2.events[key], false);
            });
          });

          _this2.container.addEventListener('keydown', _this2.handleKeyDown);
        });
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        var _this3 = this;

        if (this.helper && this.helper.parentNode) {
          this.helper.parentNode.removeChild(this.helper);
        }

        if (!this.container) {
          return;
        }

        Object.keys(this.events).forEach(function (key) {
          return events[key].forEach(function (eventName) {
            return _this3.container.removeEventListener(eventName, _this3.events[key]);
          });
        });
        this.container.removeEventListener('keydown', this.handleKeyDown);
      }
    }, {
      key: "updateHelperPosition",
      value: function updateHelperPosition(event) {
        var _this$props6 = this.props,
            lockAxis = _this$props6.lockAxis,
            lockOffset = _this$props6.lockOffset,
            lockToContainerEdges = _this$props6.lockToContainerEdges,
            transitionDuration = _this$props6.transitionDuration,
            _this$props6$keyboard = _this$props6.keyboardSortingTransitionDuration,
            keyboardSortingTransitionDuration = _this$props6$keyboard === void 0 ? transitionDuration : _this$props6$keyboard;
        var isKeySorting = this.manager.isKeySorting;
        var ignoreTransition = event.ignoreTransition;
        var offset = getPosition(event);
        var translate = {
          x: offset.x - this.initialOffset.x,
          y: offset.y - this.initialOffset.y
        };
        translate.y -= window.pageYOffset - this.initialWindowScroll.top;
        translate.x -= window.pageXOffset - this.initialWindowScroll.left;
        this.translate = translate;

        if (lockToContainerEdges) {
          var _getLockPixelOffsets = getLockPixelOffsets({
            height: this.height,
            lockOffset: lockOffset,
            width: this.width
          }),
              _getLockPixelOffsets2 = _slicedToArray(_getLockPixelOffsets, 2),
              minLockOffset = _getLockPixelOffsets2[0],
              maxLockOffset = _getLockPixelOffsets2[1];

          var minOffset = {
            x: this.width / 2 - minLockOffset.x,
            y: this.height / 2 - minLockOffset.y
          };
          var maxOffset = {
            x: this.width / 2 - maxLockOffset.x,
            y: this.height / 2 - maxLockOffset.y
          };
          translate.x = limit(this.minTranslate.x + minOffset.x, this.maxTranslate.x - maxOffset.x, translate.x);
          translate.y = limit(this.minTranslate.y + minOffset.y, this.maxTranslate.y - maxOffset.y, translate.y);
        }

        if (lockAxis === 'x') {
          translate.y = 0;
        } else if (lockAxis === 'y') {
          translate.x = 0;
        }

        if (isKeySorting && keyboardSortingTransitionDuration && !ignoreTransition) {
          setTransitionDuration(this.helper, keyboardSortingTransitionDuration);
        }

        setTranslate3d(this.helper, translate);
      }
    }, {
      key: "animateNodes",
      value: function animateNodes() {
        var _this$props7 = this.props,
            transitionDuration = _this$props7.transitionDuration,
            hideSortableGhost = _this$props7.hideSortableGhost,
            onSortOver = _this$props7.onSortOver;
        var containerScrollDelta = this.containerScrollDelta,
            windowScrollDelta = this.windowScrollDelta;
        var nodes = this.manager.getOrderedRefs();
        var sortingOffset = {
          left: this.offsetEdge.left + this.translate.x + containerScrollDelta.left,
          top: this.offsetEdge.top + this.translate.y + containerScrollDelta.top
        };
        var isKeySorting = this.manager.isKeySorting;
        var prevIndex = this.newIndex;
        this.newIndex = null;

        for (var i = 0, len = nodes.length; i < len; i++) {
          var _node3 = nodes[i].node;
          var index = _node3.sortableInfo.index;
          var width = _node3.offsetWidth;
          var height = _node3.offsetHeight;
          var offset = {
            height: this.height > height ? height / 2 : this.height / 2,
            width: this.width > width ? width / 2 : this.width / 2
          };
          var mustShiftBackward = isKeySorting && index > this.index && index <= prevIndex;
          var mustShiftForward = isKeySorting && index < this.index && index >= prevIndex;
          var translate = {
            x: 0,
            y: 0
          };
          var edgeOffset = nodes[i].edgeOffset;

          if (!edgeOffset) {
            edgeOffset = getEdgeOffset(_node3, this.container);
            nodes[i].edgeOffset = edgeOffset;

            if (isKeySorting) {
              nodes[i].boundingClientRect = getScrollAdjustedBoundingClientRect(_node3, containerScrollDelta);
            }
          }

          var nextNode = i < nodes.length - 1 && nodes[i + 1];
          var prevNode = i > 0 && nodes[i - 1];

          if (nextNode && !nextNode.edgeOffset) {
            nextNode.edgeOffset = getEdgeOffset(nextNode.node, this.container);

            if (isKeySorting) {
              nextNode.boundingClientRect = getScrollAdjustedBoundingClientRect(nextNode.node, containerScrollDelta);
            }
          }

          if (index === this.index) {
            if (hideSortableGhost) {
              this.sortableGhost = _node3;
              setInlineStyles(_node3, {
                opacity: 0,
                visibility: 'hidden'
              });
            }

            continue;
          }

          if (transitionDuration) {
            setTransitionDuration(_node3, transitionDuration);
          }

          if (this.axis.x) {
            if (this.axis.y) {
              if (mustShiftForward || index < this.index && (sortingOffset.left + windowScrollDelta.left - offset.width <= edgeOffset.left && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height || sortingOffset.top + windowScrollDelta.top + offset.height <= edgeOffset.top)) {
                translate.x = this.width + this.marginOffset.x;

                if (edgeOffset.left + translate.x > this.containerBoundingRect.width - offset.width) {
                  if (nextNode) {
                    translate.x = nextNode.edgeOffset.left - edgeOffset.left;
                    translate.y = nextNode.edgeOffset.top - edgeOffset.top;
                  }
                }

                if (this.newIndex === null) {
                  this.newIndex = index;
                }
              } else if (mustShiftBackward || index > this.index && (sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top || sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top + height)) {
                translate.x = -(this.width + this.marginOffset.x);

                if (edgeOffset.left + translate.x < this.containerBoundingRect.left + offset.width) {
                  if (prevNode) {
                    translate.x = prevNode.edgeOffset.left - edgeOffset.left;
                    translate.y = prevNode.edgeOffset.top - edgeOffset.top;
                  }
                }

                this.newIndex = index;
              }
            } else {
              if (mustShiftBackward || index > this.index && sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left) {
                translate.x = -(this.width + this.marginOffset.x);
                this.newIndex = index;
              } else if (mustShiftForward || index < this.index && sortingOffset.left + windowScrollDelta.left <= edgeOffset.left + offset.width) {
                translate.x = this.width + this.marginOffset.x;

                if (this.newIndex == null) {
                  this.newIndex = index;
                }
              }
            }
          } else if (this.axis.y) {
            if (mustShiftBackward || index > this.index && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top) {
              translate.y = -(this.height + this.marginOffset.y);
              this.newIndex = index;
            } else if (mustShiftForward || index < this.index && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height) {
              translate.y = this.height + this.marginOffset.y;

              if (this.newIndex == null) {
                this.newIndex = index;
              }
            }
          }

          setTranslate3d(_node3, translate);
          nodes[i].translate = translate;
        }

        if (this.newIndex == null) {
          this.newIndex = this.index;
        }

        if (isKeySorting) {
          this.newIndex = prevIndex;
        }

        var oldIndex = isKeySorting ? this.prevIndex : prevIndex;

        if (onSortOver && this.newIndex !== oldIndex) {
          onSortOver({
            collection: this.manager.active.collection,
            index: this.index,
            newIndex: this.newIndex,
            oldIndex: oldIndex,
            isKeySorting: isKeySorting
          });
        }
      }
    }, {
      key: "getWrappedInstance",
      value: function getWrappedInstance() {
        browser_default()(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call');
        return this.refs.wrappedInstance;
      }
    }, {
      key: "getContainer",
      value: function getContainer() {
        var getContainer = this.props.getContainer;

        if (typeof getContainer !== 'function') {
          return Object(external_commonjs_react_dom_commonjs2_react_dom_amd_react_dom_root_ReactDOM_["findDOMNode"])(this);
        }

        return getContainer(config.withRef ? this.getWrappedInstance() : undefined);
      }
    }, {
      key: "render",
      value: function render() {
        var ref = config.withRef ? 'wrappedInstance' : null;
        return Object(external_commonjs_react_commonjs2_react_amd_react_root_React_["createElement"])(WrappedComponent, _extends({
          ref: ref
        }, omit(this.props, omittedProps)));
      }
    }, {
      key: "helperContainer",
      get: function get() {
        var helperContainer = this.props.helperContainer;

        if (typeof helperContainer === 'function') {
          return helperContainer();
        }

        return this.props.helperContainer || this.document.body;
      }
    }, {
      key: "containerScrollDelta",
      get: function get() {
        var useWindowAsScrollContainer = this.props.useWindowAsScrollContainer;

        if (useWindowAsScrollContainer) {
          return {
            left: 0,
            top: 0
          };
        }

        return {
          left: this.scrollContainer.scrollLeft - this.initialScroll.left,
          top: this.scrollContainer.scrollTop - this.initialScroll.top
        };
      }
    }, {
      key: "windowScrollDelta",
      get: function get() {
        return {
          left: this.contentWindow.pageXOffset - this.initialWindowScroll.left,
          top: this.contentWindow.pageYOffset - this.initialWindowScroll.top
        };
      }
    }]);

    return WithSortableContainer;
  }(external_commonjs_react_commonjs2_react_amd_react_root_React_["Component"]), _defineProperty(_class, "displayName", provideDisplayName('sortableList', WrappedComponent)), _defineProperty(_class, "defaultProps", defaultProps), _defineProperty(_class, "propTypes", propTypes), _defineProperty(_class, "childContextTypes", {
    manager: prop_types_default.a.object.isRequired
  }), _temp;
}

var propTypes$1 = {
  index: prop_types_default.a.number.isRequired,
  collection: prop_types_default.a.oneOfType([prop_types_default.a.number, prop_types_default.a.string]),
  disabled: prop_types_default.a.bool
};
var omittedProps$1 = Object.keys(propTypes$1);
function sortableElement(WrappedComponent) {
  var _class, _temp;

  var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    withRef: false
  };
  return _temp = _class = function (_React$Component) {
    _inherits(WithSortableElement, _React$Component);

    function WithSortableElement() {
      _classCallCheck(this, WithSortableElement);

      return _possibleConstructorReturn(this, _getPrototypeOf(WithSortableElement).apply(this, arguments));
    }

    _createClass(WithSortableElement, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        this.register();
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(prevProps) {
        if (this.node) {
          if (prevProps.index !== this.props.index) {
            this.node.sortableInfo.index = this.props.index;
          }

          if (prevProps.disabled !== this.props.disabled) {
            this.node.sortableInfo.disabled = this.props.disabled;
          }
        }

        if (prevProps.collection !== this.props.collection) {
          this.unregister(prevProps.collection);
          this.register();
        }
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.unregister();
      }
    }, {
      key: "register",
      value: function register() {
        var _this$props = this.props,
            collection = _this$props.collection,
            disabled = _this$props.disabled,
            index = _this$props.index;
        var node = Object(external_commonjs_react_dom_commonjs2_react_dom_amd_react_dom_root_ReactDOM_["findDOMNode"])(this);
        node.sortableInfo = {
          collection: collection,
          disabled: disabled,
          index: index,
          manager: this.context.manager
        };
        this.node = node;
        this.ref = {
          node: node
        };
        this.context.manager.add(collection, this.ref);
      }
    }, {
      key: "unregister",
      value: function unregister() {
        var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.collection;
        this.context.manager.remove(collection, this.ref);
      }
    }, {
      key: "getWrappedInstance",
      value: function getWrappedInstance() {
        browser_default()(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call');
        return this.refs.wrappedInstance;
      }
    }, {
      key: "render",
      value: function render() {
        var ref = config.withRef ? 'wrappedInstance' : null;
        return Object(external_commonjs_react_commonjs2_react_amd_react_root_React_["createElement"])(WrappedComponent, _extends({
          ref: ref
        }, omit(this.props, omittedProps$1)));
      }
    }]);

    return WithSortableElement;
  }(external_commonjs_react_commonjs2_react_amd_react_root_React_["Component"]), _defineProperty(_class, "displayName", provideDisplayName('sortableElement', WrappedComponent)), _defineProperty(_class, "contextTypes", {
    manager: prop_types_default.a.object.isRequired
  }), _defineProperty(_class, "propTypes", propTypes$1), _defineProperty(_class, "defaultProps", {
    collection: 0
  }), _temp;
}




/***/ }),
/* 126 */
/***/ (function(module, exports, __nested_webpack_require_692307__) {

// most Object methods by ES6 should accept primitives
var $export = __nested_webpack_require_692307__(16);
var core = __nested_webpack_require_692307__(12);
var fails = __nested_webpack_require_692307__(50);
module.exports = function (KEY, exec) {
  var fn = (core.Object || {})[KEY] || Object[KEY];
  var exp = {};
  exp[KEY] = exec(fn);
  $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};


/***/ }),
/* 127 */
/***/ (function(module, exports, __nested_webpack_require_692768__) {

// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __nested_webpack_require_692768__(33);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
  if (!isObject(it)) return it;
  var fn, val;
  if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
  if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  throw TypeError("Can't convert object to primitive value");
};


/***/ }),
/* 128 */
/***/ (function(module, exports, __nested_webpack_require_693502__) {

// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __nested_webpack_require_693502__(47);
var toObject = __nested_webpack_require_693502__(54);
var IE_PROTO = __nested_webpack_require_693502__(90)('IE_PROTO');
var ObjectProto = Object.prototype;

module.exports = Object.getPrototypeOf || function (O) {
  O = toObject(O);
  if (has(O, IE_PROTO)) return O[IE_PROTO];
  if (typeof O.constructor == 'function' && O instanceof O.constructor) {
    return O.constructor.prototype;
  } return O instanceof Object ? ObjectProto : null;
};


/***/ }),
/* 129 */
/***/ (function(module, exports, __nested_webpack_require_694079__) {

var ctx = __nested_webpack_require_694079__(49);
var call = __nested_webpack_require_694079__(165);
var isArrayIter = __nested_webpack_require_694079__(166);
var anObject = __nested_webpack_require_694079__(39);
var toLength = __nested_webpack_require_694079__(88);
var getIterFn = __nested_webpack_require_694079__(112);
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
  var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
  var f = ctx(fn, that, entries ? 2 : 1);
  var index = 0;
  var length, step, iterator, result;
  if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
  // fast case for arrays with default iterator
  if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
    result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
    if (result === BREAK || result === RETURN) return result;
  } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
    result = call(iterator, f, step.value, entries);
    if (result === BREAK || result === RETURN) return result;
  }
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;


/***/ }),
/* 130 */
/***/ (function(module, exports) {

exports.f = Object.getOwnPropertySymbols;


/***/ }),
/* 131 */
/***/ (function(module, exports, __nested_webpack_require_695425__) {

module.exports = { "default": __nested_webpack_require_695425__(230), __esModule: true };

/***/ }),
/* 132 */
/***/ (function(module, exports, __nested_webpack_require_695579__) {

"use strict";


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

var _extends2 = __nested_webpack_require_695579__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _react = __nested_webpack_require_695579__(1);

var _react2 = _interopRequireDefault(_react);

var _toVoid = __nested_webpack_require_695579__(171);

var _toVoid2 = _interopRequireDefault(_toVoid);

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

var _React$createContext = _react2['default'].createContext({
  close: _toVoid2['default'],
  open: _toVoid2['default']
}),
    Provider = _React$createContext.Provider,
    Consumer = _React$createContext.Consumer;

// Higher order component


var withModal = function withModal(Component) {
  return _react2['default'].forwardRef(function (props, ref) {
    return _react2['default'].createElement(
      Consumer,
      null,
      function (modal) {
        return _react2['default'].createElement(Component, (0, _extends3['default'])({ ref: ref }, props, { modal: modal }));
      }
    );
  });
};

exports['default'] = withModal;
exports.Provider = Provider;

/***/ }),
/* 133 */
/***/ (function(module, exports, __nested_webpack_require_696803__) {

"use strict";


exports.__esModule = true;
exports.noop = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.bottom = bottom;
exports.cloneLayout = cloneLayout;
exports.cloneLayoutItem = cloneLayoutItem;
exports.childrenEqual = childrenEqual;
exports.collides = collides;
exports.compact = compact;
exports.compactItem = compactItem;
exports.correctBounds = correctBounds;
exports.getLayoutItem = getLayoutItem;
exports.getFirstCollision = getFirstCollision;
exports.getAllCollisions = getAllCollisions;
exports.getStatics = getStatics;
exports.moveElement = moveElement;
exports.moveElementAwayFromCollision = moveElementAwayFromCollision;
exports.perc = perc;
exports.setTransform = setTransform;
exports.setTopLeft = setTopLeft;
exports.sortLayoutItems = sortLayoutItems;
exports.sortLayoutItemsByRowCol = sortLayoutItemsByRowCol;
exports.sortLayoutItemsByColRow = sortLayoutItemsByColRow;
exports.synchronizeLayoutWithChildren = synchronizeLayoutWithChildren;
exports.validateLayout = validateLayout;
exports.autoBindHandlers = autoBindHandlers;

var _lodash = __nested_webpack_require_696803__(172);

var _lodash2 = _interopRequireDefault(_lodash);

var _react = __nested_webpack_require_696803__(1);

var _react2 = _interopRequireDefault(_react);

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

// All callbacks are of the signature (layout, oldItem, newItem, placeholder, e).
var isProduction = "production" === "production";
var DEBUG = false;

/**
 * Return the bottom coordinate of the layout.
 *
 * @param  {Array} layout Layout array.
 * @return {Number}       Bottom coordinate.
 */
function bottom(layout) {
  var max = 0,
      bottomY = void 0;
  for (var _i = 0, len = layout.length; _i < len; _i++) {
    bottomY = layout[_i].y + layout[_i].h;
    if (bottomY > max) max = bottomY;
  }
  return max;
}

function cloneLayout(layout) {
  var newLayout = Array(layout.length);
  for (var _i2 = 0, len = layout.length; _i2 < len; _i2++) {
    newLayout[_i2] = cloneLayoutItem(layout[_i2]);
  }
  return newLayout;
}

// Fast path to cloning, since this is monomorphic
function cloneLayoutItem(layoutItem) {
  return {
    w: layoutItem.w,
    h: layoutItem.h,
    x: layoutItem.x,
    y: layoutItem.y,
    i: layoutItem.i,
    minW: layoutItem.minW,
    maxW: layoutItem.maxW,
    minH: layoutItem.minH,
    maxH: layoutItem.maxH,
    moved: Boolean(layoutItem.moved),
    static: Boolean(layoutItem.static),
    // These can be null
    isDraggable: layoutItem.isDraggable,
    isResizable: layoutItem.isResizable
  };
}

/**
 * Comparing React `children` is a bit difficult. This is a good way to compare them.
 * This will catch differences in keys, order, and length.
 */
function childrenEqual(a, b) {
  return (0, _lodash2.default)(_react2.default.Children.map(a, function (c) {
    return c.key;
  }), _react2.default.Children.map(b, function (c) {
    return c.key;
  }));
}

/**
 * Given two layoutitems, check if they collide.
 */
function collides(l1, l2) {
  if (l1 === l2) return false; // same element
  if (l1.x + l1.w <= l2.x) return false; // l1 is left of l2
  if (l1.x >= l2.x + l2.w) return false; // l1 is right of l2
  if (l1.y + l1.h <= l2.y) return false; // l1 is above l2
  if (l1.y >= l2.y + l2.h) return false; // l1 is below l2
  return true; // boxes overlap
}

/**
 * Given a layout, compact it. This involves going down each y coordinate and removing gaps
 * between items.
 *
 * @param  {Array} layout Layout.
 * @param  {Boolean} verticalCompact Whether or not to compact the layout
 *   vertically.
 * @return {Array}       Compacted Layout.
 */
function compact(layout, compactType, cols) {
  // Statics go in the compareWith array right away so items flow around them.
  var compareWith = getStatics(layout);
  // We go through the items by row and column.
  var sorted = sortLayoutItems(layout, compactType);
  // Holding for new items.
  var out = Array(layout.length);

  for (var _i3 = 0, len = sorted.length; _i3 < len; _i3++) {
    var l = cloneLayoutItem(sorted[_i3]);

    // Don't move static elements
    if (!l.static) {
      l = compactItem(compareWith, l, compactType, cols, sorted);

      // Add to comparison array. We only collide with items before this one.
      // Statics are already in this array.
      compareWith.push(l);
    }

    // Add to output array to make sure they still come out in the right order.
    out[layout.indexOf(sorted[_i3])] = l;

    // Clear moved flag, if it exists.
    l.moved = false;
  }

  return out;
}

var heightWidth = { x: "w", y: "h" };
/**
 * Before moving item down, it will check if the movement will cause collisions and move those items down before.
 */
function resolveCompactionCollision(layout, item, moveToCoord, axis) {
  var sizeProp = heightWidth[axis];
  item[axis] += 1;
  var itemIndex = layout.indexOf(item);

  // Go through each item we collide with.
  for (var _i4 = itemIndex + 1; _i4 < layout.length; _i4++) {
    var otherItem = layout[_i4];
    // Ignore static items
    if (otherItem.static) continue;

    // Optimization: we can break early if we know we're past this el
    // We can do this b/c it's a sorted layout
    if (otherItem.y > item.y + item.h) break;

    if (collides(item, otherItem)) {
      resolveCompactionCollision(layout, otherItem, moveToCoord + item[sizeProp], axis);
    }
  }

  item[axis] = moveToCoord;
}

/**
 * Compact an item in the layout.
 */
function compactItem(compareWith, l, compactType, cols, fullLayout) {
  var compactV = compactType === "vertical";
  var compactH = compactType === "horizontal";
  if (compactV) {
    // Bottom 'y' possible is the bottom of the layout.
    // This allows you to do nice stuff like specify {y: Infinity}
    // This is here because the layout must be sorted in order to get the correct bottom `y`.
    l.y = Math.min(bottom(compareWith), l.y);
    // Move the element up as far as it can go without colliding.
    while (l.y > 0 && !getFirstCollision(compareWith, l)) {
      l.y--;
    }
  } else if (compactH) {
    l.y = Math.min(bottom(compareWith), l.y);
    // Move the element left as far as it can go without colliding.
    while (l.x > 0 && !getFirstCollision(compareWith, l)) {
      l.x--;
    }
  }

  // Move it down, and keep moving it down if it's colliding.
  var collides = void 0;
  while (collides = getFirstCollision(compareWith, l)) {
    if (compactH) {
      resolveCompactionCollision(fullLayout, l, collides.x + collides.w, "x");
    } else {
      resolveCompactionCollision(fullLayout, l, collides.y + collides.h, "y");
    }
    // Since we can't grow without bounds horizontally, if we've overflown, let's move it down and try again.
    if (compactH && l.x + l.w > cols) {
      l.x = cols - l.w;
      l.y++;
    }
  }
  return l;
}

/**
 * Given a layout, make sure all elements fit within its bounds.
 *
 * @param  {Array} layout Layout array.
 * @param  {Number} bounds Number of columns.
 */
function correctBounds(layout, bounds) {
  var collidesWith = getStatics(layout);
  for (var _i5 = 0, len = layout.length; _i5 < len; _i5++) {
    var l = layout[_i5];
    // Overflows right
    if (l.x + l.w > bounds.cols) l.x = bounds.cols - l.w;
    // Overflows left
    if (l.x < 0) {
      l.x = 0;
      l.w = bounds.cols;
    }
    if (!l.static) collidesWith.push(l);else {
      // If this is static and collides with other statics, we must move it down.
      // We have to do something nicer than just letting them overlap.
      while (getFirstCollision(collidesWith, l)) {
        l.y++;
      }
    }
  }
  return layout;
}

/**
 * Get a layout item by ID. Used so we can override later on if necessary.
 *
 * @param  {Array}  layout Layout array.
 * @param  {String} id     ID
 * @return {LayoutItem}    Item at ID.
 */
function getLayoutItem(layout, id) {
  for (var _i6 = 0, len = layout.length; _i6 < len; _i6++) {
    if (layout[_i6].i === id) return layout[_i6];
  }
}

/**
 * Returns the first item this layout collides with.
 * It doesn't appear to matter which order we approach this from, although
 * perhaps that is the wrong thing to do.
 *
 * @param  {Object} layoutItem Layout item.
 * @return {Object|undefined}  A colliding layout item, or undefined.
 */
function getFirstCollision(layout, layoutItem) {
  for (var _i7 = 0, len = layout.length; _i7 < len; _i7++) {
    if (collides(layout[_i7], layoutItem)) return layout[_i7];
  }
}

function getAllCollisions(layout, layoutItem) {
  return layout.filter(function (l) {
    return collides(l, layoutItem);
  });
}

/**
 * Get all static elements.
 * @param  {Array} layout Array of layout objects.
 * @return {Array}        Array of static layout items..
 */
function getStatics(layout) {
  return layout.filter(function (l) {
    return l.static;
  });
}

/**
 * Move an element. Responsible for doing cascading movements of other elements.
 *
 * @param  {Array}      layout            Full layout to modify.
 * @param  {LayoutItem} l                 element to move.
 * @param  {Number}     [x]               X position in grid units.
 * @param  {Number}     [y]               Y position in grid units.
 */
function moveElement(layout, l, x, y, isUserAction, preventCollision, compactType, cols) {
  if (l.static) return layout;

  // Short-circuit if nothing to do.
  if (l.y === y && l.x === x) return layout;

  log("Moving element " + l.i + " to [" + String(x) + "," + String(y) + "] from [" + l.x + "," + l.y + "]");
  var oldX = l.x;
  var oldY = l.y;

  // This is quite a bit faster than extending the object
  if (typeof x === 'number') l.x = x;
  if (typeof y === 'number') l.y = y;
  l.moved = true;

  // If this collides with anything, move it.
  // When doing this comparison, we have to sort the items we compare with
  // to ensure, in the case of multiple collisions, that we're getting the
  // nearest collision.
  var sorted = sortLayoutItems(layout, compactType);
  var movingUp = compactType === "vertical" && typeof y === 'number' ? oldY >= y : compactType === "horizontal" && typeof x === 'number' ? oldX >= x : false;
  if (movingUp) sorted = sorted.reverse();
  var collisions = getAllCollisions(sorted, l);

  // There was a collision; abort
  if (preventCollision && collisions.length) {
    log("Collision prevented on " + l.i + ", reverting.");
    l.x = oldX;
    l.y = oldY;
    l.moved = false;
    return layout;
  }

  // Move each item that collides away from this element.
  for (var _i8 = 0, len = collisions.length; _i8 < len; _i8++) {
    var collision = collisions[_i8];
    log("Resolving collision between " + l.i + " at [" + l.x + "," + l.y + "] and " + collision.i + " at [" + collision.x + "," + collision.y + "]");

    // Short circuit so we can't infinite loop
    if (collision.moved) continue;

    // Don't move static items - we have to move *this* element away
    if (collision.static) {
      layout = moveElementAwayFromCollision(layout, collision, l, isUserAction, compactType, cols);
    } else {
      layout = moveElementAwayFromCollision(layout, l, collision, isUserAction, compactType, cols);
    }
  }

  return layout;
}

/**
 * This is where the magic needs to happen - given a collision, move an element away from the collision.
 * We attempt to move it up if there's room, otherwise it goes below.
 *
 * @param  {Array} layout            Full layout to modify.
 * @param  {LayoutItem} collidesWith Layout item we're colliding with.
 * @param  {LayoutItem} itemToMove   Layout item we're moving.
 */
function moveElementAwayFromCollision(layout, collidesWith, itemToMove, isUserAction, compactType, cols) {
  var compactH = compactType === "horizontal";
  var compactV = compactType === "vertical";
  var preventCollision = false; // we're already colliding

  // If there is enough space above the collision to put this element, move it there.
  // We only do this on the main collision as this can get funky in cascades and cause
  // unwanted swapping behavior.
  if (isUserAction) {
    // Reset isUserAction flag because we're not in the main collision anymore.
    isUserAction = false;

    // Make a mock item so we don't modify the item here, only modify in moveElement.
    var fakeItem = {
      x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,
      y: compactV ? Math.max(collidesWith.y - itemToMove.h, 0) : itemToMove.y,
      w: itemToMove.w,
      h: itemToMove.h,
      i: "-1"
    };

    // No collision? If so, we can go up there; otherwise, we'll end up moving down as normal
    if (!getFirstCollision(layout, fakeItem)) {
      log("Doing reverse collision on " + itemToMove.i + " up to [" + fakeItem.x + "," + fakeItem.y + "].");
      return moveElement(layout, itemToMove, compactH ? fakeItem.x : undefined, compactV ? fakeItem.y : undefined, isUserAction, preventCollision, compactType, cols);
    }
  }

  return moveElement(layout, itemToMove, compactH ? itemToMove.x + 1 : undefined, compactV ? itemToMove.y + 1 : undefined, isUserAction, preventCollision, compactType, cols);
}

/**
 * Helper to convert a number to a percentage string.
 *
 * @param  {Number} num Any number
 * @return {String}     That number as a percentage.
 */
function perc(num) {
  return num * 100 + "%";
}

function setTransform(_ref) {
  var top = _ref.top,
      left = _ref.left,
      width = _ref.width,
      height = _ref.height;

  // Replace unitless items with px
  var translate = "translate(" + left + "px," + top + "px)";
  return {
    transform: translate,
    WebkitTransform: translate,
    MozTransform: translate,
    msTransform: translate,
    OTransform: translate,
    width: width + "px",
    height: height + "px",
    position: "absolute"
  };
}

function setTopLeft(_ref2) {
  var top = _ref2.top,
      left = _ref2.left,
      width = _ref2.width,
      height = _ref2.height;

  return {
    top: top + "px",
    left: left + "px",
    width: width + "px",
    height: height + "px",
    position: "absolute"
  };
}

/**
 * Get layout items sorted from top left to right and down.
 *
 * @return {Array} Array of layout objects.
 * @return {Array}        Layout, sorted static items first.
 */
function sortLayoutItems(layout, compactType) {
  if (compactType === "horizontal") return sortLayoutItemsByColRow(layout);else return sortLayoutItemsByRowCol(layout);
}

function sortLayoutItemsByRowCol(layout) {
  return [].concat(layout).sort(function (a, b) {
    if (a.y > b.y || a.y === b.y && a.x > b.x) {
      return 1;
    } else if (a.y === b.y && a.x === b.x) {
      // Without this, we can get different sort results in IE vs. Chrome/FF
      return 0;
    }
    return -1;
  });
}

function sortLayoutItemsByColRow(layout) {
  return [].concat(layout).sort(function (a, b) {
    if (a.x > b.x || a.x === b.x && a.y > b.y) {
      return 1;
    }
    return -1;
  });
}

/**
 * Generate a layout using the initialLayout and children as a template.
 * Missing entries will be added, extraneous ones will be truncated.
 *
 * @param  {Array}  initialLayout Layout passed in through props.
 * @param  {String} breakpoint    Current responsive breakpoint.
 * @param  {?String} compact      Compaction option.
 * @return {Array}                Working layout.
 */
function synchronizeLayoutWithChildren(initialLayout, children, cols, compactType) {
  initialLayout = initialLayout || [];

  // Generate one layout item per child.
  var layout = [];
  _react2.default.Children.forEach(children, function (child, i) {
    // Don't overwrite if it already exists.
    var exists = getLayoutItem(initialLayout, String(child.key));
    if (exists) {
      layout[i] = cloneLayoutItem(exists);
    } else {
      if (!isProduction && child.props._grid) {
        console.warn("`_grid` properties on children have been deprecated as of React 15.2. " + // eslint-disable-line
        "Please use `data-grid` or add your properties directly to the `layout`.");
      }
      var g = child.props["data-grid"] || child.props._grid;

      // Hey, this item has a data-grid property, use it.
      if (g) {
        if (!isProduction) {
          validateLayout([g], "ReactGridLayout.children");
        }
        layout[i] = cloneLayoutItem(_extends({}, g, { i: child.key }));
      } else {
        // Nothing provided: ensure this is added to the bottom
        layout[i] = cloneLayoutItem({
          w: 1,
          h: 1,
          x: 0,
          y: bottom(layout),
          i: String(child.key)
        });
      }
    }
  });

  // Correct the layout.
  layout = correctBounds(layout, { cols: cols });
  layout = compact(layout, compactType, cols);

  return layout;
}

/**
 * Validate a layout. Throws errors.
 *
 * @param  {Array}  layout        Array of layout items.
 * @param  {String} [contextName] Context name for errors.
 * @throw  {Error}                Validation error.
 */
function validateLayout(layout) {
  var contextName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "Layout";

  var subProps = ["x", "y", "w", "h"];
  if (!Array.isArray(layout)) throw new Error(contextName + " must be an array!");
  for (var _i9 = 0, len = layout.length; _i9 < len; _i9++) {
    var item = layout[_i9];
    for (var j = 0; j < subProps.length; j++) {
      if (typeof item[subProps[j]] !== "number") {
        throw new Error("ReactGridLayout: " + contextName + "[" + _i9 + "]." + subProps[j] + " must be a number!");
      }
    }
    if (item.i && typeof item.i !== "string") {
      throw new Error("ReactGridLayout: " + contextName + "[" + _i9 + "].i must be a string!");
    }
    if (item.static !== undefined && typeof item.static !== "boolean") {
      throw new Error("ReactGridLayout: " + contextName + "[" + _i9 + "].static must be a boolean!");
    }
  }
}

// Flow can't really figure this out, so we just use Object
function autoBindHandlers(el, fns) {
  fns.forEach(function (key) {
    return el[key] = el[key].bind(el);
  });
}

function log() {
  var _console;

  if (!DEBUG) return;
  // eslint-disable-next-line no-console
  (_console = console).log.apply(_console, arguments);
}

var noop = exports.noop = function noop() {};

/***/ }),
/* 134 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_715265__) {

"use strict";
__nested_webpack_require_715265__.r(__webpack_exports__);
/* harmony export (binding) */ __nested_webpack_require_715265__.d(__webpack_exports__, "globalPubSub", function() { return globalPubSub; });
/* harmony export (binding) */ __nested_webpack_require_715265__.d(__webpack_exports__, "createPubSub", function() { return createPubSub; });
/**
 * A new or fake broadcast channel.
 * @type {BroadcastChannel|object}
 */
const bc = (() => {
  const BC = window.BroadcastChannel;
  if (!BC) {
    console.warn("The Broadcast Channel API is not available in your browser.");
    return { postMessage: () => {} };
  }
  return new BC("pub-sub-es");
})();

/**
 * Setup subscriber.
 * @param {object} stack - The bound event stack.
 * @return {function} - Curried function for subscribing to an event on a
 *   specific event stack.
 */
const subscribe = stack =>
  /**
   * Subscribe to an event.
   * @param {string} event - Event name to subscribe to.
   * @param {function} handler - Function to be called when event of type
   *   `event` is published.
   * @param {number} times - Number of times the handler should called for the
   *   given event. The event listener will automatically be unsubscribed once
   *   the number of calls exceeds `times`.
   * @return {object} Object with the event name and the handler. The object
   *   can be used to unsubscribe.
   */
  (event, handler, times = Infinity) => {
    if (!stack[event]) {
      stack[event] = [];
      stack.__times__[event] = [];
    }

    stack[event].push(handler);
    stack.__times__[event].push(+times || Infinity);

    return { event, handler };
  };

/**
 * Setup unsubscriber.
 * @param {object} stack - The bound event stack.
 * @return {function} - Curried function for unsubscribing an event from a
 *   specific event stack.
 */
const unsubscribe = stack =>
  /**
   * Unsubscribe from event.
   * @curried
   * @param {string|object} event - Event from which to unsubscribe or the return
   *   object provided by `subscribe()`.
   * @param {function} handler - Handler function to be unsubscribed. It is
   *   ignored if `id` is provided.
   */
  (event, handler) => {
    if (typeof event === "object") {
      handler = event.handler; // eslint-disable-line no-param-reassign
      event = event.event; // eslint-disable-line no-param-reassign
    }

    if (!stack[event]) return;

    const id = stack[event].indexOf(handler);

    if (id === -1 || id >= stack[event].length) return;

    stack[event].splice(id, 1);
    stack.__times__[event].splice(id, 1);
  };

/**
 * Setup the publisher.
 * @param  {object} stack - The bound event stack.
 * @param  {boolean} isGlobal - If `true` event will be published globally.
 * @return {function} - Curried function for publishing an event on a specific
 *   event stack.
 */
const publish = (stack, isGlobal) =>
  /**
   * Public interface for publishing an event.
   * @curried
   * @param   {string} event - Event type to be published.
   * @param   {any} news - The news to be published.
   * @param   {boolean}  isNoGlobalBroadcast - If `true` event will *not* be
   *   broadcasted gloablly even if `isGlobal` is `true`.
   */
  (event, news, isNoGlobalBroadcast) => {
    if (!stack[event]) return;

    const unsubscriber = unsubscribe(stack);

    stack[event].forEach((listener, i) => {
      listener(news);
      stack.__times__[event][i]--;
      if (stack.__times__[event][i] < 1) unsubscriber(event, listener);
    });

    if (isGlobal && !isNoGlobalBroadcast) {
      try {
        bc.postMessage({ event, news });
      } catch (error) {
        if (error instanceof DOMException) {
          console.warn(
            `Could not broadcast "${event}" globally. Payload is not clonable.`
          );
        } else {
          throw error;
        }
      }
    }
  };

/**
 * Setup event clearer
 * @param {object} stack - The bound event stack.
 * @return {function} - A curried function removing all event listeners on a
 *   specific event stack.
 */
const clear = stack =>
  /**
   * Remove all event listeners and unset listening times
   * @curried
   */
  () => {
    Object.keys(stack)
      .filter(eventName => eventName[0] !== "_")
      .forEach(eventName => {
        stack[eventName] = undefined;
        stack.__times__[eventName] = undefined;
        delete stack[eventName];
        delete stack.__times__[eventName];
      });
  };

/**
 * Create a new empty stack object
 * @return {object} - An empty stack object.
 */
const createEmptyStack = () => ({ __times__: {} });

/**
 * Create a new pub-sub instance
 * @param {object} stack - Object to be used as the event stack.
 * @return {object} - A new pub-sub instance.
 */
const createPubSub = (stack = createEmptyStack()) => {
  if (!stack.__times__) stack.__times__ = {};

  return {
    publish: publish(stack),
    subscribe: subscribe(stack),
    unsubscribe: unsubscribe(stack),
    clear: clear(stack),
    stack
  };
};

/**
 * Global pub-sub stack object
 * @type {object}
 */
const globalPubSubStack = createEmptyStack();
/**
 * Global pub-sub stack instance
 * @type {object}
 */
const globalPubSub = {
  publish: publish(globalPubSubStack, true),
  subscribe: subscribe(globalPubSubStack),
  unsubscribe: unsubscribe(globalPubSubStack),
  stack: globalPubSubStack
};
bc.onmessage = ({ data: { event, news } }) =>
  globalPubSub.publish(event, news, true);



/* harmony default export */ __webpack_exports__["default"] = (createPubSub);


/***/ }),
/* 135 */
/***/ (function(module, exports, __nested_webpack_require_720792__) {

"use strict";


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

var _minSafeInteger = __nested_webpack_require_720792__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

var _maxSafeInteger = __nested_webpack_require_720792__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _getIterator2 = __nested_webpack_require_720792__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _from = __nested_webpack_require_720792__(95);

var _from2 = _interopRequireDefault(_from);

var _isNan = __nested_webpack_require_720792__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _slicedToArray2 = __nested_webpack_require_720792__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _stringify = __nested_webpack_require_720792__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = __nested_webpack_require_720792__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _extends2 = __nested_webpack_require_720792__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _classCallCheck2 = __nested_webpack_require_720792__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_720792__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_720792__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_720792__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_720792__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _ndarray = __nested_webpack_require_720792__(136);

var _ndarray2 = _interopRequireDefault(_ndarray);

var _d3Brush = __nested_webpack_require_720792__(83);

var _d3Format = __nested_webpack_require_720792__(20);

var _d3Scale = __nested_webpack_require_720792__(28);

var _d3Selection = __nested_webpack_require_720792__(0);

var _slugid = __nested_webpack_require_720792__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _utils = __nested_webpack_require_720792__(10);

var _TiledPixiTrack2 = __nested_webpack_require_720792__(79);

var _TiledPixiTrack3 = _interopRequireDefault(_TiledPixiTrack2);

var _AxisPixi = __nested_webpack_require_720792__(179);

var _AxisPixi2 = _interopRequireDefault(_AxisPixi);

var _services = __nested_webpack_require_720792__(24);

var _configs = __nested_webpack_require_720792__(11);

var _denseDataExtremaConfig = __nested_webpack_require_720792__(114);

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

var COLORBAR_MAX_HEIGHT = 200;

// Services

var COLORBAR_WIDTH = 10;
var COLORBAR_LABELS_WIDTH = 40;
var COLORBAR_MARGIN = 10;
var BRUSH_WIDTH = COLORBAR_MARGIN;
var BRUSH_HEIGHT = 4;
var BRUSH_COLORBAR_GAP = 1;
var BRUSH_MARGIN = 4;
var SCALE_LIMIT_PRECISION = 5;
var BINS_PER_TILE = 256;
var COLORBAR_AREA_WIDTH = COLORBAR_WIDTH + COLORBAR_LABELS_WIDTH + COLORBAR_MARGIN + BRUSH_COLORBAR_GAP + BRUSH_WIDTH + BRUSH_MARGIN;

var HeatmapTiledPixiTrack = function (_TiledPixiTrack) {
  (0, _inherits3['default'])(HeatmapTiledPixiTrack, _TiledPixiTrack);

  function HeatmapTiledPixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, HeatmapTiledPixiTrack);

    // Fritz: this smells very hacky!
    var newContext = (0, _extends3['default'])({}, context);
    newContext.onValueScaleChanged = function () {
      context.onValueScaleChanged();
      _this.drawColorbar();
    };

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HeatmapTiledPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack)).call(this, newContext, options));

    var pubSub = context.pubSub,
        animate = context.animate,
        svgElement = context.svgElement,
        onTrackOptionsChanged = context.onTrackOptionsChanged,
        onMouseMoveZoom = context.onMouseMoveZoom,
        isShowGlobalMousePosition = context.isShowGlobalMousePosition,
        isValueScaleLocked = context.isValueScaleLocked;


    _this.pubSub = pubSub;
    _this.is2d = true;
    _this.animate = animate;
    _this.uid = _slugid2['default'].nice();
    _this.scaleBrush = (0, _d3Brush.brushY)();

    _this.onTrackOptionsChanged = onTrackOptionsChanged;
    _this.isShowGlobalMousePosition = isShowGlobalMousePosition;

    _this.isValueScaleLocked = isValueScaleLocked;

    // Graphics for drawing the colorbar
    _this.pColorbarArea = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMasked.addChild(_this.pColorbarArea);

    _this.pColorbar = new _configs.GLOBALS.PIXI.Graphics();
    _this.pColorbarArea.addChild(_this.pColorbar);

    _this.axis = new _AxisPixi2['default'](_this);
    _this.pColorbarArea.addChild(_this.axis.pAxis);

    // [[255,255,255,0], [237,218,10,4] ...
    // a 256 element array mapping the values 0-255 to rgba values
    // not a d3 color scale for speed
    _this.colorScale = _configs.HEATED_OBJECT_MAP;

    if (options && options.colorRange) {
      _this.colorScale = (0, _utils.colorDomainToRgbaArray)(options.colorRange);
    }

    _this.gBase = (0, _d3Selection.select)(svgElement).append('g');
    _this.gMain = _this.gBase.append('g');
    _this.gColorscaleBrush = _this.gMain.append('g');

    _this.brushing = false;
    _this.prevOptions = '';

    // Contains information about which part of the upper left tile is visible
    _this.prevIndUpperLeftTile = '';

    /*
    chromInfoService
      .get(`${dataConfig.server}/chrom-sizes/?id=${dataConfig.tilesetUid}`)
      .then((chromInfo) => { this.chromInfo = chromInfo; });
    */

    _this.onMouseMoveZoom = onMouseMoveZoom;
    _this.setDataLensSize(11);
    _this.dataLens = new Float32Array(Math.pow(_this.dataLensSize, 2));

    _this.mouseMoveHandlerBound = _this.mouseMoveHandler.bind(_this);

    if (_this.onMouseMoveZoom) {
      _this.pubSubs.push(_this.pubSub.subscribe('app.mouseMove', _this.mouseMoveHandlerBound));
    }

    if (_this.options && _this.options.showMousePosition && !_this.hideMousePosition) {
      _this.hideMousePosition = (0, _utils.showMousePosition)(_this, _this.is2d, _this.isShowGlobalMousePosition());
    }

    _this.prevOptions = (0, _stringify2['default'])(options);
    return _this;
  }

  /**
   * Mouse move handler
   *
   * @param  {Object}  e  Event object.
   */


  (0, _createClass3['default'])(HeatmapTiledPixiTrack, [{
    key: 'mouseMoveHandler',
    value: function () {
      function mouseMoveHandler(e) {
        if (!this.isWithin(e.x, e.y)) return;

        this.mouseX = e.x;
        this.mouseY = e.y;

        this.mouseMoveZoomHandler();
      }

      return mouseMoveHandler;
    }()

    /**
     * Mouse move and zoom handler. Is triggered on both events.
     *
     * @param  {Number}  absX  Absolute X coordinate.
     * @param  {Number}  absY  Absolute Y coordinate
     */

  }, {
    key: 'mouseMoveZoomHandler',
    value: function () {
      function mouseMoveZoomHandler() {
        var _this2 = this;

        var absX = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.mouseX;
        var absY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.mouseY;

        if (typeof absX === 'undefined' || typeof absY === 'undefined' || !this.areAllVisibleTilesLoaded()) return;

        if (!this.tilesetInfo) {
          return;
        }

        var relX = absX - this.position[0];
        var relY = absY - this.position[1];

        var data = void 0;
        var dataLens = void 0;
        try {
          dataLens = this.getVisibleRectangleData(relX - this.dataLensPadding, relY - this.dataLensPadding, this.dataLensSize, this.dataLensSize);
          // The center value
          data = dataLens.get(this.dataLensPadding, this.dataLensPadding);
        } catch (e) {
          return;
        }

        var dim = this.dataLensSize;

        var toRgb = void 0;
        try {
          toRgb = (0, _utils.valueToColor)(this.limitedValueScale, this.colorScale, this.valueScale.domain()[0]);
        } catch (err) {
          return;
        }

        if (!toRgb) return;

        var dataX = Math.round(this._xScale.invert(relX));
        var dataY = Math.round(this._yScale.invert(relY));

        var center = [dataX, dataY];
        var xRange = [Math.round(this._xScale.invert(relX - this.dataLensPadding)), Math.round(this._xScale.invert(relX + this.dataLensPadding))];
        var yRange = [Math.round(this._yScale.invert(relY - this.dataLensPadding)), Math.round(this._yScale.invert(relY + this.dataLensPadding))];

        if (this.chromInfo) {
          center = center.map(function (pos) {
            return (0, _utils.absToChr)(pos, _this2.chromInfo).slice(0, 2);
          });
          xRange = xRange.map(function (pos) {
            return (0, _utils.absToChr)(pos, _this2.chromInfo).slice(0, 2);
          });
          yRange = yRange.map(function (pos) {
            return (0, _utils.absToChr)(pos, _this2.chromInfo).slice(0, 2);
          });
        }

        this.onMouseMoveZoom({
          trackId: this.id,
          data: data,
          absX: absX,
          absY: absY,
          relX: relX,
          relY: relY,
          dataX: dataX,
          dataY: dataY,
          orientation: '2d',
          // Specific to 2D matrices
          dataLens: dataLens,
          dim: dim,
          toRgb: toRgb,
          center: center,
          xRange: xRange,
          yRange: yRange,
          isGenomicCoords: !!this.chromInfo
        });
      }

      return mouseMoveZoomHandler;
    }()
  }, {
    key: 'scheduleRerender',
    value: function () {
      function scheduleRerender() {
        this.backgroundTaskScheduler.enqueueTask(this.handleRerender.bind(this), null, this.uuid);
      }

      return scheduleRerender;
    }()
  }, {
    key: 'handleRerender',
    value: function () {
      function handleRerender() {
        this.rerender(this.options, true);
      }

      return handleRerender;
    }()

    /**
     * Get absolute (i.e., display) tile dimension and position.
     *
     * @param {Number}  zoomLevel  Current zoom level.
     * @param {Array}  tilePos  Tile position.
     * @return {Object}  Object holding the absolute x, y, width, and height.
     */

  }, {
    key: 'getAbsTileDim',
    value: function () {
      function getAbsTileDim(zoomLevel, tilePos, mirrored) {
        var _getTilePosAndDimensi = this.getTilePosAndDimensions(zoomLevel, tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileY = _getTilePosAndDimensi.tileY,
            tileWidth = _getTilePosAndDimensi.tileWidth,
            tileHeight = _getTilePosAndDimensi.tileHeight;

        var dim = {};

        dim.width = this._refXScale(tileX + tileWidth) - this._refXScale(tileX);
        dim.height = this._refYScale(tileY + tileHeight) - this._refYScale(tileY);

        if (mirrored) {
          // this is a mirrored tile that represents the other half of a
          // triangular matrix
          dim.x = this._refXScale(tileY);
          dim.y = this._refYScale(tileX);
        } else {
          dim.x = this._refXScale(tileX);
          dim.y = this._refYScale(tileY);
        }

        return dim;
      }

      return getAbsTileDim;
    }()
  }, {
    key: 'updateValueScale',
    value: function () {
      function updateValueScale() {
        var minValue = this.minValue();
        var maxValue = this.maxValue();

        // There might be only one value in the visible area. We extend the
        // valuescale artificially, so that point is still displayed
        var epsilon = 1e-6;
        if (minValue !== undefined && minValue !== null && maxValue !== undefined && maxValue !== null && Math.abs(minValue - maxValue) < epsilon) {
          // don't go to or below 0 in case there is a log scale
          var offset = 1e-3;
          minValue = Math.max(epsilon, minValue - offset);
          maxValue += offset;
        }

        var _getValueScale = (0, _TiledPixiTrack2.getValueScale)(this.options && this.options.heatmapValueScaling || 'log', minValue, this.medianVisibleValue, maxValue, 'log'),
            _getValueScale2 = (0, _slicedToArray3['default'])(_getValueScale, 2),
            scaleType = _getValueScale2[0],
            valueScale = _getValueScale2[1];

        this.valueScale = valueScale;

        this.limitedValueScale = this.valueScale.copy();

        if (this.options && typeof this.options.scaleStartPercent !== 'undefined' && typeof this.options.scaleEndPercent !== 'undefined') {
          this.limitedValueScale.domain([this.valueScale.domain()[0] + (this.valueScale.domain()[1] - this.valueScale.domain()[0]) * this.options.scaleStartPercent, this.valueScale.domain()[0] + (this.valueScale.domain()[1] - this.valueScale.domain()[0]) * this.options.scaleEndPercent]);
        }

        return [scaleType, valueScale];
      }

      return updateValueScale;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        var _this3 = this;

        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'rerender', this).call(this, options, force);

        // We need to update the value scale prior to updating the colorbar
        this.updateValueScale();

        // if force is set, then we force a rerender even if the options
        // haven't changed rerender will force a brush.move
        var strOptions = (0, _stringify2['default'])(options);
        this.drawColorbar();

        if (!force && strOptions === this.prevOptions) return;

        this.prevOptions = strOptions;
        this.options = options;

        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'rerender', this).call(this, options, force);

        // the normalization method may have changed
        this.calculateVisibleTiles();

        if (options && options.colorRange) {
          this.colorScale = (0, _utils.colorDomainToRgbaArray)(options.colorRange);
        }

        this.visibleAndFetchedTiles().forEach(function (tile) {
          return _this3.renderTile(tile);
        });

        // hopefully draw isn't rerendering all the tiles
        // this.drawColorbar();

        if (this.hideMousePosition) {
          this.hideMousePosition();
          this.hideMousePosition = undefined;
        }

        if (this.options && this.options.showMousePosition && !this.hideMousePosition) {
          this.hideMousePosition = (0, _utils.showMousePosition)(this, this.is2d, this.isShowGlobalMousePosition());
        }
      }

      return rerender;
    }()
  }, {
    key: 'drawLabel',
    value: function () {
      function drawLabel() {
        if (this.options.labelPosition === this.options.colorbarPosition) {
          this.labelXOffset = COLORBAR_AREA_WIDTH;
        } else {
          this.labelXOffset = 0;
        }

        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'drawLabel', this).call(this);
      }

      return drawLabel;
    }()
  }, {
    key: 'tileDataToCanvas',
    value: function () {
      function tileDataToCanvas(pixData) {
        var canvas = document.createElement('canvas');

        canvas.width = this.binsPerTile();
        canvas.height = this.binsPerTile();

        var ctx = canvas.getContext('2d');

        ctx.fillStyle = 'transparent';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        var pix = new ImageData(pixData, canvas.width, canvas.height);

        ctx.putImageData(pix, 0, 0);

        return canvas;
      }

      return tileDataToCanvas;
    }()
  }, {
    key: 'exportData',
    value: function () {
      function exportData() {
        if (this.tilesetInfo) {
          // const currentResolution = tileProxy.calculateResolution(this.tilesetInfo,
          //  this.zoomLevel);

          // const pixelsWidth = (this._xScale.domain()[1]  - this._xScale.domain()[0])
          // / currentResolution;
          // const pixelsHeight = (this._yScale.domain()[1]  - this._yScale.domain()[0])
          // / currentResolution;

          var data = this.getVisibleRectangleData(0, 0, this.dimensions[0], this.dimensions[1]);
          var output = {
            bounds: [this._xScale.domain(), this._yScale.domain()],
            dimensions: data.shape,
            data: (0, _utils.ndarrayFlatten)(data)
          };

          (0, _utils.download)('data.json', (0, _stringify2['default'])(output));
        }
      }

      return exportData;
    }()

    /**
     * Position sprite (the rendered tile)
     *
     * @param  {Object}  sprite  PIXI sprite object.
     * @param  {Number}  zoomLevel  Current zoom level.
     * @param  {Array}  tilePos  X,Y position of tile.
     * @param  {Boolean}  mirrored  If `true` tile is mirrored.
     */

  }, {
    key: 'setSpriteProperties',
    value: function () {
      function setSpriteProperties(sprite, zoomLevel, tilePos, mirrored) {
        var dim = this.getAbsTileDim(zoomLevel, tilePos, mirrored);

        sprite.width = dim.width;
        sprite.height = dim.height;
        sprite.x = dim.x;
        sprite.y = dim.y;

        if (mirrored && tilePos[0] !== tilePos[1]) {
          // sprite.pivot = [this._refXScale()[1] / 2, this._refYScale()[1] / 2];

          // I think PIXIv3 used a different method to set the pivot value
          // because the code above no longer works as of v4
          sprite.rotation = -Math.PI / 2;
          sprite.scale.x = Math.abs(sprite.scale.x) * -1;
        }
      }

      return setSpriteProperties;
    }()
  }, {
    key: 'refXScale',
    value: function () {
      function refXScale(_) {
        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'refXScale', this).call(this, _);

        this.draw();
      }

      return refXScale;
    }()
  }, {
    key: 'refYScale',
    value: function () {
      function refYScale(_) {
        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'refYScale', this).call(this, _);

        this.draw();
      }

      return refYScale;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'draw', this).call(this);

        // this.drawColorbar();
      }

      return draw;
    }()
  }, {
    key: 'newBrushOptions',
    value: function () {
      function newBrushOptions(selection) {
        var newOptions = JSON.parse((0, _stringify2['default'])(this.options));

        var axisValueScale = this.valueScale.copy().range([this.colorbarHeight, 0]);

        var endDomain = axisValueScale.invert(selection[0]);
        var startDomain = axisValueScale.invert(selection[1]);

        // Fritz: I am disabling ESLint here twice because moving the slash onto the
        // next line breaks my editors style template somehow.
        var startPercent = (startDomain - axisValueScale.domain()[0]) / ( // eslint-disable-line operator-linebreak
        axisValueScale.domain()[1] - axisValueScale.domain()[0]);
        var endPercent = (endDomain - axisValueScale.domain()[0]) / ( // eslint-disable-line operator-linebreak
        axisValueScale.domain()[1] - axisValueScale.domain()[0]);

        newOptions.scaleStartPercent = startPercent.toFixed(SCALE_LIMIT_PRECISION);
        newOptions.scaleEndPercent = endPercent.toFixed(SCALE_LIMIT_PRECISION);

        return newOptions;
      }

      return newBrushOptions;
    }()
  }, {
    key: 'brushStart',
    value: function () {
      function brushStart() {
        this.brushing = true;
      }

      return brushStart;
    }()
  }, {
    key: 'brushMoved',
    value: function () {
      function brushMoved() {
        if (!_d3Selection.event.selection) {
          return;
        }
        var newOptions = this.newBrushOptions(_d3Selection.event.selection);

        var strOptions = (0, _stringify2['default'])(newOptions);

        this.gColorscaleBrush.selectAll('.handle--custom').attr('y', function (d) {
          return d.type === 'n' ? _d3Selection.event.selection[0] : _d3Selection.event.selection[1] - BRUSH_HEIGHT / 2;
        });

        if (strOptions === this.prevOptions) return;

        this.prevOptions = strOptions;

        // force a rerender because we've already set prevOptions
        // to the new options
        // this is necessary for when value scales are synced between
        // tracks
        this.rerender(newOptions, true);

        this.onTrackOptionsChanged(newOptions);

        if (this.isValueScaleLocked()) {
          this.onValueScaleChanged();
        }
      }

      return brushMoved;
    }()
  }, {
    key: 'brushEnd',
    value: function () {
      function brushEnd() {
        // let newOptions = this.newBrushOptions(event.selection);

        // this.rerender(newOptions);
        // this.animate();
        this.brushing = false;
      }

      return brushEnd;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.drawColorbar();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        this.drawColorbar();
      }

      return setDimensions;
    }()
  }, {
    key: 'removeColorbar',
    value: function () {
      function removeColorbar() {
        this.pColorbarArea.visible = false;

        if (this.scaleBrush.on('.brush')) {
          this.gColorscaleBrush.call(this.scaleBrush.move, null);
        }

        // turn off the color scale brush
        this.gColorscaleBrush.on('.brush', null);
        this.gColorscaleBrush.selectAll('rect').remove();
      }

      return removeColorbar;
    }()
  }, {
    key: 'drawColorbar',
    value: function () {
      function drawColorbar() {
        this.pColorbar.clear();
        // console.trace('draw colorbar');

        if (!this.options || !this.options.colorbarPosition || this.options.colorbarPosition === 'hidden') {
          this.removeColorbar();

          return;
        }

        this.pColorbarArea.visible = true;

        if (!this.valueScale) {
          return;
        }

        if ((0, _isNan2['default'])(+this.valueScale.domain()[0]) || (0, _isNan2['default'])(+this.valueScale.domain()[1])) {
          return;
        }

        var colorbarAreaHeight = Math.min(this.dimensions[1] / 2, COLORBAR_MAX_HEIGHT);
        this.colorbarHeight = colorbarAreaHeight - 2 * COLORBAR_MARGIN;

        //  no point in drawing the colorbar if it's not going to be visible
        if (this.colorbarHeight < 0) {
          // turn off the color scale brush
          this.removeColorbar();
          return;
        }

        if (this.valueScale.domain()[1] === this.valueScale.domain()[0]) {
          // degenerate color bar
          this.removeColorbar();
          return;
        }

        var axisValueScale = this.valueScale.copy().range([this.colorbarHeight, 0]);

        // this.scaleBrush = brushY();

        // this is to make the handles of the scale brush stick out away
        // from the colorbar
        if (this.options.colorbarPosition === 'topLeft' || this.options.colorbarPosition === 'bottomLeft') {
          this.scaleBrush.extent([[BRUSH_MARGIN, 0], [BRUSH_WIDTH, this.colorbarHeight]]);
        } else {
          this.scaleBrush.extent([[0, 0], [BRUSH_WIDTH - BRUSH_MARGIN, this.colorbarHeight]]);
        }

        if (this.options.colorbarPosition === 'topLeft') {
          var _position = (0, _slicedToArray3['default'])(this.position, 2);
          // draw the background for the colorbar


          this.pColorbarArea.x = _position[0];
          this.pColorbarArea.y = _position[1];


          this.pColorbar.y = COLORBAR_MARGIN;
          this.axis.pAxis.y = COLORBAR_MARGIN;

          this.axis.pAxis.x = BRUSH_MARGIN + BRUSH_WIDTH + BRUSH_COLORBAR_GAP + COLORBAR_WIDTH;
          this.pColorbar.x = BRUSH_MARGIN + BRUSH_WIDTH + BRUSH_COLORBAR_GAP;

          this.gColorscaleBrush.attr('transform', 'translate(' + String(this.pColorbarArea.x + BRUSH_MARGIN) + ',' + (this.pColorbarArea.y + this.pColorbar.y - 1) + ')');
        }

        if (this.options.colorbarPosition === 'topRight') {
          // draw the background for the colorbar
          this.pColorbarArea.x = this.position[0] + this.dimensions[0] - COLORBAR_AREA_WIDTH;
          this.pColorbarArea.y = this.position[1];

          this.pColorbar.y = COLORBAR_MARGIN;
          this.axis.pAxis.y = COLORBAR_MARGIN;

          // default to 'inside'
          this.axis.pAxis.x = COLORBAR_LABELS_WIDTH + COLORBAR_MARGIN;

          this.pColorbar.x = COLORBAR_LABELS_WIDTH + COLORBAR_MARGIN;

          this.gColorscaleBrush.attr('transform', 'translate(' + String(this.pColorbarArea.x + this.pColorbar.x + COLORBAR_WIDTH + 2) + ',' + (this.pColorbarArea.y + this.pColorbar.y - 1) + ')');
        }

        if (this.options.colorbarPosition === 'bottomRight') {
          this.pColorbarArea.x = this.position[0] + this.dimensions[0] - COLORBAR_AREA_WIDTH;
          this.pColorbarArea.y = this.position[1] + this.dimensions[1] - colorbarAreaHeight;

          this.pColorbar.y = COLORBAR_MARGIN;
          this.axis.pAxis.y = COLORBAR_MARGIN;

          // default to "inside"
          this.axis.pAxis.x = COLORBAR_LABELS_WIDTH + COLORBAR_MARGIN;
          this.pColorbar.x = COLORBAR_LABELS_WIDTH + COLORBAR_MARGIN;

          this.gColorscaleBrush.attr('transform', 'translate(' + String(this.pColorbarArea.x + this.pColorbar.x + COLORBAR_WIDTH + BRUSH_COLORBAR_GAP) + ',' + (this.pColorbarArea.y + this.pColorbar.y - 1) + ')');
        }

        if (this.options.colorbarPosition === 'bottomLeft') {
          this.pColorbarArea.x = this.position[0];
          this.pColorbarArea.y = this.position[1] + this.dimensions[1] - colorbarAreaHeight;

          this.pColorbar.y = COLORBAR_MARGIN;
          this.axis.pAxis.y = COLORBAR_MARGIN;

          // default to "inside"
          this.axis.pAxis.x = BRUSH_MARGIN + BRUSH_WIDTH + BRUSH_COLORBAR_GAP + COLORBAR_WIDTH;
          this.pColorbar.x = BRUSH_MARGIN + BRUSH_WIDTH + BRUSH_COLORBAR_GAP;

          this.gColorscaleBrush.attr('transform', 'translate(' + String(this.pColorbarArea.x + 2) + ',' + (this.pColorbarArea.y + this.pColorbar.y - 1) + ')');
        }

        this.pColorbarArea.clear();
        this.pColorbarArea.beginFill((0, _utils.colorToHex)(this.options.colorbarBackgroundColor || 'white'), +this.options.colorbarBackgroundOpacity >= 0 ? +this.options.colorbarBackgroundOpacity : 0.6);
        this.pColorbarArea.drawRect(0, 0, COLORBAR_AREA_WIDTH, colorbarAreaHeight);

        if (!this.options) {
          this.options = { scaleStartPercent: 0, scaleEndPercent: 1 };
        } else {
          if (!this.options.scaleStartPercent) {
            this.options.scaleStartPercent = 0;
          }
          if (!this.options.scaleEndPercent) {
            this.options.scaleEndPercent = 1;
          }
        }

        var domainWidth = axisValueScale.domain()[1] - axisValueScale.domain()[0];

        var startBrush = axisValueScale(this.options.scaleStartPercent * domainWidth + axisValueScale.domain()[0]);
        var endBrush = axisValueScale(this.options.scaleEndPercent * domainWidth + axisValueScale.domain()[0]);

        // endBrush and startBrush are reversed because lower values come first
        // only set if the user isn't brushing at the moment
        if (!this.brushing) {
          this.scaleBrush.on('start', this.brushStart.bind(this)).on('brush', this.brushMoved.bind(this)).on('end', this.brushEnd.bind(this)).handleSize(0);

          this.gColorscaleBrush.on('.brush', null);
          this.gColorscaleBrush.call(this.scaleBrush);

          this.northHandle = this.gColorscaleBrush.selectAll('.handle--custom').data([{ type: 'n' }, { type: 's' }]).enter().append('rect').classed('handle--custom', true).attr('cursor', 'ns-resize').attr('width', BRUSH_WIDTH).attr('height', BRUSH_HEIGHT).style('fill', '#666').style('stroke', 'white');

          if (this.flipText) {
            this.northHandle.attr('cursor', 'ew-resize');
          }

          this.gColorscaleBrush.call(this.scaleBrush.move, [endBrush, startBrush]);
        }

        var posScale = (0, _d3Scale.scaleLinear)().domain([0, 255]).range([0, this.colorbarHeight]);

        // draw a small rectangle for each color of the colorbar
        for (var i = 0; i < this.colorbarHeight; i++) {
          var value = this.limitedValueScale(axisValueScale.invert(i));

          var rgbIdx = Math.max(0, Math.min(254, Math.floor(value)));

          this.pColorbar.beginFill((0, _utils.colorToHex)('rgb(' + String(this.colorScale[rgbIdx][0]) + ',' + String(this.colorScale[rgbIdx][1]) + ',' + String(this.colorScale[rgbIdx][2]) + ')'));

          // each rectangle in the colorbar will be one pixel high
          this.pColorbar.drawRect(0, i, COLORBAR_WIDTH, 1);
        }

        // draw an axis on the right side of the colorbar
        this.pAxis.position.x = COLORBAR_WIDTH;
        this.pAxis.position.y = posScale(0);

        if (this.options.colorbarPosition === 'topLeft' || this.options.colorbarPosition === 'bottomLeft') {
          this.axis.drawAxisRight(axisValueScale, this.colorbarHeight);
        } else if (this.options.colorbarPosition === 'topRight' || this.options.colorbarPosition === 'bottomRight') {
          this.axis.drawAxisLeft(axisValueScale, this.colorbarHeight);
        }
      }

      return drawColorbar;
    }()
  }, {
    key: 'exportColorBarSVG',
    value: function () {
      function exportColorBarSVG() {
        var gColorbarArea = document.createElement('g');
        gColorbarArea.setAttribute('class', 'color-bar');

        if (!this.options.colorbarPosition || this.options.colorbarPosition === 'hidden') {
          // if there's no visible colorbar, we don't need to export anything
          return gColorbarArea;
        }

        // no value scale, no colorbar
        if (!this.valueScale) return gColorbarArea;

        gColorbarArea.setAttribute('transform', 'translate(' + String(this.pColorbarArea.x) + ', ' + String(this.pColorbarArea.y) + ')');

        var rectColorbarArea = document.createElement('rect');
        gColorbarArea.appendChild(rectColorbarArea);

        var gColorbar = document.createElement('g');
        gColorbarArea.appendChild(gColorbar);

        gColorbar.setAttribute('transform', 'translate(' + String(this.pColorbar.x) + ', ' + String(this.pColorbar.y) + ')');

        var colorbarAreaHeight = Math.min(this.dimensions[1] / 2, COLORBAR_MAX_HEIGHT);
        this.colorbarHeight = colorbarAreaHeight - 2 * COLORBAR_MARGIN;

        rectColorbarArea.setAttribute('x', 0);
        rectColorbarArea.setAttribute('y', 0);
        rectColorbarArea.setAttribute('width', COLORBAR_AREA_WIDTH);
        rectColorbarArea.setAttribute('height', colorbarAreaHeight);
        rectColorbarArea.setAttribute('style', 'fill: white; stroke-width: 0; opacity: 0.7');

        var barsToDraw = 256;
        var posScale = (0, _d3Scale.scaleLinear)().domain([0, barsToDraw - 1]).range([0, this.colorbarHeight]);
        var colorHeight = this.colorbarHeight / barsToDraw;

        for (var i = 0; i < barsToDraw; i++) {
          var rectColor = document.createElement('rect');
          gColorbar.appendChild(rectColor);

          rectColor.setAttribute('x', 0);
          rectColor.setAttribute('y', posScale(i));
          rectColor.setAttribute('width', COLORBAR_WIDTH);
          rectColor.setAttribute('height', colorHeight);
          rectColor.setAttribute('class', 'color-rect');

          var limitedIndex = Math.min(this.colorScale.length - 1, Math.max(0, Math.floor(this.limitedValueScale(this.valueScale.invert(i)))));

          var color = this.colorScale[limitedIndex];
          if (color) {
            rectColor.setAttribute('style', 'fill: rgb(' + String(color[0]) + ', ' + String(color[1]) + ', ' + String(color[2]) + ')');
          } else {
            // when no tiles are loaded, color will be undefined and we don't want to crash
            rectColor.setAttribute('style', 'fill: rgb(255,255,255,0)');
          }
        }

        var gAxisHolder = document.createElement('g');
        gColorbarArea.appendChild(gAxisHolder);
        gAxisHolder.setAttribute('transform', 'translate(' + String(this.axis.pAxis.position.x) + ',' + String(this.axis.pAxis.position.y) + ')');

        var gAxis = null;

        var axisValueScale = this.valueScale.copy().range([this.colorbarHeight, 0]);
        if (this.options.colorbarPosition === 'topLeft' || this.options.colorbarPosition === 'bottomLeft') {
          gAxis = this.axis.exportAxisRightSVG(axisValueScale, this.colorbarHeight);
        } else if (this.options.colorbarPosition === 'topRight' || this.options.colorbarPosition === 'bottomRight') {
          gAxis = this.axis.exportAxisLeftSVG(axisValueScale, this.colorbarHeight);
        }

        gAxisHolder.appendChild(gAxis);

        return gColorbarArea;
      }

      return exportColorBarSVG;
    }()

    /**
     * Set data lens size
     *
     * @param  {Integer}  newDataLensSize  New data lens size. Needs to be an odd
     *   integer.
     */

  }, {
    key: 'setDataLensSize',
    value: function () {
      function setDataLensSize(newDataLensSize) {
        this.dataLensPadding = Math.max(0, Math.floor((newDataLensSize - 1) / 2));
        this.dataLensSize = this.dataLensPadding * 2 + 1;
      }

      return setDataLensSize;
    }()
  }, {
    key: 'binsPerTile',
    value: function () {
      function binsPerTile() {
        return this.tilesetInfo.bins_per_dimension || BINS_PER_TILE;
      }

      return binsPerTile;
    }()

    /**
     * Get the data in the visible rectangle
     *
     * The parameter coordinates are in pixel coordinates
     *
     * @param {int} x: The upper left corner of the rectangle in pixel coordinates
     * @param {int} y: The upper left corner of the rectangle in pixel coordinates
     * @param {int} width: The width of the rectangle (pixels)
     * @param {int} height: The height of the rectangle (pixels)
     *
     * @returns {Array} A numjs array containing the data in the visible region
     *
     */

  }, {
    key: 'getVisibleRectangleData',
    value: function () {
      function getVisibleRectangleData(x, y, width, height) {
        var _this4 = this;

        var zoomLevel = this.calculateZoomLevel();
        zoomLevel = this.tilesetInfo.max_zoom ? Math.min(this.tilesetInfo.max_zoom, zoomLevel) : zoomLevel;

        var calculatedWidth = _services.tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.binsPerTile());

        // BP resolution of a tile's bin (i.e., numbe of base pairs per bin / pixel)
        var tileRes = calculatedWidth / this.binsPerTile();

        // the data domain of the currently visible region
        var xDomain = [this._xScale.invert(x), this._xScale.invert(x + width)];
        var yDomain = [this._yScale.invert(y), this._yScale.invert(y + height)];

        // we need to limit the domain of the requested region
        // to the bounds of the data
        var limitedXDomain = [Math.max(xDomain[0], this.tilesetInfo.min_pos[0]), Math.min(xDomain[1], this.tilesetInfo.max_pos[0])];

        var limitedYDomain = [Math.max(yDomain[0], this.tilesetInfo.min_pos[1]), Math.min(yDomain[1], this.tilesetInfo.max_pos[1])];

        // the bounds of the currently visible region in bins
        var leftXBin = Math.floor(limitedXDomain[0] / tileRes);
        var leftYBin = Math.floor(limitedYDomain[0] / tileRes);
        var binWidth = Math.max(0, Math.ceil((limitedXDomain[1] - limitedXDomain[0]) / tileRes));
        var binHeight = Math.max(0, Math.ceil((limitedYDomain[1] - limitedYDomain[0]) / tileRes));

        var out = (0, _ndarray2['default'])(new Array(binHeight * binWidth).fill(NaN), [binHeight, binWidth]);

        // iterate through all the visible tiles
        this.visibleAndFetchedTiles().forEach(function (tile) {
          var tilePos = tile.mirrored ? [tile.tileData.tilePos[1], tile.tileData.tilePos[0]] : tile.tileData.tilePos;

          // get the tile's position and width (in data coordinates)
          // if it's mirrored then we have to switch the position indeces

          var _getTilePosAndDimensi2 = _this4.getTilePosAndDimensions(tile.tileData.zoomLevel, tilePos, _this4.binsPerTile()),
              tileX = _getTilePosAndDimensi2.tileX,
              tileY = _getTilePosAndDimensi2.tileY,
              tileWidth = _getTilePosAndDimensi2.tileWidth,
              tileHeight = _getTilePosAndDimensi2.tileHeight;

          // calculate the tile's position in bins


          var tileXStartBin = Math.floor(tileX / tileRes);
          var tileXEndBin = Math.floor((tileX + tileWidth) / tileRes);
          var tileYStartBin = Math.floor(tileY / tileRes);
          var tileYEndBin = Math.floor((tileY + tileHeight) / tileRes);

          // calculate which part of this tile is present in the current window
          var tileSliceXStart = Math.max(leftXBin, tileXStartBin) - tileXStartBin;
          var tileSliceYStart = Math.max(leftYBin, tileYStartBin) - tileYStartBin;
          var tileSliceXEnd = Math.min(leftXBin + binWidth, tileXEndBin) - tileXStartBin;
          var tileSliceYEnd = Math.min(leftYBin + binHeight, tileYEndBin) - tileYStartBin;

          // where in the output array will the portion of this tile which is in the
          // visible window be placed?
          var tileXOffset = Math.max(tileXStartBin - leftXBin, 0);
          var tileYOffset = Math.max(tileYStartBin - leftYBin, 0);
          var tileSliceWidth = tileSliceXEnd - tileSliceXStart;
          var tileSliceHeight = tileSliceYEnd - tileSliceYStart;

          // the region is outside of this tile
          if (tileSliceWidth < 0 || tileSliceHeight < 0) return;

          if (tile.mirrored && tileSliceXStart > tileSliceYStart) {
            var tmp = tileSliceXStart;
            tileSliceXStart = tileSliceYStart;
            tileSliceYStart = tmp;
          }

          (0, _utils.ndarrayAssign)(out.hi(tileYOffset + tileSliceHeight, tileXOffset + tileSliceWidth).lo(tileYOffset, tileXOffset), tile.dataArray.hi(tileSliceYStart + tileSliceHeight, tileSliceXStart + tileSliceWidth).lo(tileSliceYStart, tileSliceXStart));
        });

        return out;
      }

      return getVisibleRectangleData;
    }()

    /**
     * Convert the raw tile data to a rendered array of values which can be represented as a sprite.
     *
     * @param tile: The data structure containing all the tile information. Relevant to
     *              this function are tile.tileData = \{'dense': [...], ...\}
     *              and tile.graphics
     */

  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'initTile', this).call(this, tile);

        // prepare the data for fast retrieval in getVisibleRectangleData
        if (tile.tileData.dense.length === Math.pow(this.binsPerTile(), 2)) {
          tile.dataArray = (0, _ndarray2['default'])((0, _from2['default'])(tile.tileData.dense), [this.binsPerTile(), this.binsPerTile()]);

          // Recompute DenseDataExtrema for diagonal tiles which have been mirrored
          if (this.continuousScaling && tile.tileData.tilePos[0] === tile.tileData.tilePos[1] && tile.mirrored) {
            tile.tileData.denseDataExtrema.mirrorPrecomputedExtrema();
            (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'initTile', this).call(this, tile);
          }
        }

        // no data present
        if (this.scale.minValue === null || this.scale.maxValue === null) {
          return;
        }

        this.renderTile(tile);
      }

      return initTile;
    }()

    // /**
    //  * Draw a border around tiles
    //  *
    //  * @param  {Array}  pixData  Pixel data to be adjusted
    //  */
    // addBorder(pixData) {
    //   for (let i = 0; i < 256; i++) {
    //     if (i === 0) {
    //       const prefix = i * 256 * 4;
    //       for (let j = 0; j < 255; j++) {
    //         pixData[prefix + (j * 4)] = 0;
    //         pixData[prefix + (j * 4) + 1] = 0;
    //         pixData[prefix + (j * 4) + 2] = 255;
    //         pixData[prefix + (j * 4) + 3] = 255;
    //       }
    //     }
    //     pixData[(i * 256 * 4)] = 0;
    //     pixData[(i * 256 * 4) + 1] = 0;
    //     pixData[(i * 256 * 4) + 2] = 255;
    //     pixData[(i * 256 * 4) + 3] = 255;
    //   }
    // }
    //

  }, {
    key: 'updateTile',
    value: function () {
      function updateTile(tile) {
        if (tile.scale && this.scale && this.scale.minValue === tile.scale.minValue && this.scale.maxValue === tile.scale.maxValue) {
          // already rendered properly, no need to rerender
        } else {
          // not rendered using the current scale, so we need to rerender
          this.renderTile(tile);
          this.drawColorbar();
        }
      }

      return updateTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile) {
        // sprite have to be explicitly destroyed in order to
        // free the texture cache
        tile.sprite.destroy(true);

        tile.canvas = null;
        tile.sprite = null;
        tile.texture = null;

        // this is a handy method for checking what's in the texture
        // cache
        // console.log('destroy', PIXI.utils.BaseTextureCache);
      }

      return destroyTile;
    }()
  }, {
    key: 'pixDataFunction',
    value: function () {
      function pixDataFunction(tile, pixData) {
        // the tileData has been converted to pixData by the worker script and
        // needs to be loaded as a sprite
        if (pixData) {
          var graphics = tile.graphics;

          var canvas = this.tileDataToCanvas(pixData.pixData);

          if (tile.sprite) {
            // if this tile has already been rendered with a sprite, we
            // have to destroy it before creating a new one
            tile.sprite.destroy(true);
          }

          var texture = _configs.GLOBALS.PIXI.VERSION[0] === '4' ? _configs.GLOBALS.PIXI.Texture.fromCanvas(canvas, _configs.GLOBALS.PIXI.SCALE_MODES.NEAREST) : _configs.GLOBALS.PIXI.Texture.from(canvas, {
            scaleMode: _configs.GLOBALS.PIXI.SCALE_MODES.NEAREST
          });

          var sprite = new _configs.GLOBALS.PIXI.Sprite(texture);

          tile.sprite = sprite;
          tile.texture = texture;
          // store the pixData so that we can export it
          tile.canvas = canvas;
          this.setSpriteProperties(tile.sprite, tile.tileData.zoomLevel, tile.tileData.tilePos, tile.mirrored);

          graphics.removeChildren();
          graphics.addChild(tile.sprite);
        }
        this.renderingTiles['delete'](tile.tileId);
      }

      return pixDataFunction;
    }()

    /**
     * Render / draw a tile.
     *
     * @param {Object}  tile  Tile data to be rendered.
     */

  }, {
    key: 'renderTile',
    value: function () {
      function renderTile(tile) {
        var _this5 = this;

        var _updateValueScale = this.updateValueScale(),
            _updateValueScale2 = (0, _slicedToArray3['default'])(_updateValueScale, 1),
            scaleType = _updateValueScale2[0];

        var pseudocount = 0;

        this.renderingTiles.add(tile.tileId);

        if (this.tilesetInfo.tile_size) {
          if (tile.tileData.dense.length < this.tilesetInfo.tile_size) {
            // we haven't gotten a full tile from the server so we want to pad
            // it with nan values
            var newArray = new Float32Array(this.tilesetInfo.tile_size);

            newArray.fill(NaN);
            newArray.set(tile.tileData.dense);

            tile.tileData.dense = newArray;
          }
        }

        _services.tileProxy.tileDataToPixData(tile, scaleType, this.limitedValueScale.domain(), pseudocount, // used as a pseudocount to prevent taking the log of 0
        this.colorScale, function (pixData) {
          return _this5.pixDataFunction(tile, pixData);
        }, this.mirrorTiles() && !tile.mirrored && tile.tileData.tilePos[0] === tile.tileData.tilePos[1], this.options.extent === 'upper-right' && tile.tileData.tilePos[0] === tile.tileData.tilePos[1], this.options.zeroValueColor ? (0, _utils.colorToRgba)(this.options.zeroValueColor) : undefined, {
          selectedRows: this.options.selectRows,
          selectedRowsAggregationMode: this.options.selectRowsAggregationMode,
          selectedRowsAggregationWithRelativeHeight: this.options.selectRowsAggregationWithRelativeHeight,
          selectedRowsAggregationMethod: this.options.selectRowsAggregationMethod
        });
      }

      return renderTile;
    }()

    /**
     * Remove this track from the view
     */

  }, {
    key: 'remove',
    value: function () {
      function remove() {
        this.gMain.remove();
        this.gMain = null;

        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'remove', this).call(this);
      }

      return remove;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        var _this6 = this;

        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'refScalesChanged', this).call(this, refXScale, refYScale);

        (0, _utils.objVals)(this.fetchedTiles).filter(function (tile) {
          return tile.sprite;
        }).forEach(function (tile) {
          return _this6.setSpriteProperties(tile.sprite, tile.tileData.zoomLevel, tile.tileData.tilePos, tile.mirrored);
        });
      }

      return refScalesChanged;
    }()

    /**
     * Bypass this track's exportSVG function
     */

  }, {
    key: 'superSVG',
    value: function () {
      function superSVG() {
        return (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'exportSVG', this).call(this);
      }

      return superSVG;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }

        var output = document.createElement('g');
        track.appendChild(output);

        output.setAttribute('transform', 'translate(' + String(this.pMain.position.x) + ',' + String(this.pMain.position.y) + ') scale(' + String(this.pMain.scale.x) + ',' + String(this.pMain.scale.y) + ')');

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tile = _step.value;

            var rotation = tile.sprite.rotation * 180 / Math.PI;
            var g = document.createElement('g');
            g.setAttribute('transform', 'translate(' + String(tile.sprite.x) + ',' + String(tile.sprite.y) + ') rotate(' + rotation + ') scale(' + String(tile.sprite.scale.x) + ',' + String(tile.sprite.scale.y) + ')');

            var image = document.createElement('image');
            image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', tile.canvas.toDataURL());
            image.setAttribute('width', tile.canvas.width);
            image.setAttribute('height', tile.canvas.height);
            image.setAttribute('style', 'image-rendering: pixelated');

            g.appendChild(image);
            output.appendChild(g);
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var gColorbar = this.exportColorBarSVG();
        track.appendChild(gColorbar);

        return [base, base];
      }

      return exportSVG;
    }()

    // This function gets the indices of the visible part of the upper left tile.
    // The indices are 'rounded' to the grid used by the DenseDataExrema module.
    // It is used to determine if we should check for a new value scale in
    // the case of continuous scaling

  }, {
    key: 'getVisiblePartOfUppLeftTile',
    value: function () {
      function getVisiblePartOfUppLeftTile() {
        var tilePositions = this.visibleAndFetchedTiles().map(function (tile) {
          var tilePos = tile.mirrored ? [tile.tileData.tilePos[1], tile.tileData.tilePos[0]] : tile.tileData.tilePos;
          return [tilePos[0], tilePos[1], tile.tileId];
        });

        if (tilePositions.length === 0) return null;

        var minTilePosition = tilePositions[0];

        for (var i = 0; i < tilePositions.length; i++) {
          var curPos = tilePositions[i];
          if (curPos[0] < minTilePosition[0] || curPos[1] < minTilePosition[1]) {
            minTilePosition = curPos;
          }
        }

        var numSubsets = Math.min(_denseDataExtremaConfig.NUM_PRECOMP_SUBSETS_PER_2D_TTILE, this.binsPerTile());
        var subsetSize = this.binsPerTile() / numSubsets;

        var upperLeftTile = this.visibleAndFetchedTiles().filter(function (tile) {
          return tile.tileId === minTilePosition[2];
        })[0];

        var upperLeftTileInd = this.getIndicesOfVisibleDataInTile(upperLeftTile);

        var startX = upperLeftTileInd[0];
        var startY = upperLeftTileInd[1];
        // round to nearest grid point as used in the DenseDataExtrema Module
        var startXadjusted = startX - startX % subsetSize;
        var startYadjusted = startY - startY % subsetSize;

        return [upperLeftTile.tileId, startXadjusted, startYadjusted];
      }

      return getVisiblePartOfUppLeftTile;
    }()
  }, {
    key: 'getIndicesOfVisibleDataInTile',
    value: function () {
      function getIndicesOfVisibleDataInTile(tile) {
        var visibleX = this._xScale.range();
        var visibleY = this._yScale.range();

        var tilePos = tile.mirrored ? [tile.tileData.tilePos[1], tile.tileData.tilePos[0]] : tile.tileData.tilePos;

        var _getTilePosAndDimensi3 = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tilePos, this.binsPerTile()),
            tileX = _getTilePosAndDimensi3.tileX,
            tileY = _getTilePosAndDimensi3.tileY,
            tileWidth = _getTilePosAndDimensi3.tileWidth,
            tileHeight = _getTilePosAndDimensi3.tileHeight;

        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, this.binsPerTile()]).range([tileX, tileX + tileWidth]);

        var startX = Math.max(0, Math.round(tileXScale.invert(this._xScale.invert(visibleX[0]))) - 1);

        var endX = Math.min(this.binsPerTile(), Math.round(tileXScale.invert(this._xScale.invert(visibleX[1]))));

        var tileYScale = (0, _d3Scale.scaleLinear)().domain([0, this.binsPerTile()]).range([tileY, tileY + tileHeight]);

        var startY = Math.max(0, Math.round(tileYScale.invert(this._yScale.invert(visibleY[0]))) - 1);

        var endY = Math.min(this.binsPerTile(), Math.round(tileYScale.invert(this._yScale.invert(visibleY[1]))));

        var result = tile.mirrored && tilePos[0] !== tilePos[1] ? [startY, startX, endY, endX] : [startX, startY, endX, endY];

        return result;
      }

      return getIndicesOfVisibleDataInTile;
    }()
  }, {
    key: 'minVisibleValue',
    value: function () {
      function minVisibleValue() {
        var _this7 = this;

        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        var minimumsPerTile = this.visibleAndFetchedTiles().map(function (tile) {
          if (tile.tileData.denseDataExtrema === undefined) {
            return null;
          }
          var ind = _this7.getIndicesOfVisibleDataInTile(tile);
          return tile.tileData.denseDataExtrema.getMinNonZeroInSubset(ind);
        });

        if (minimumsPerTile.length === 0 && this.valueScaleMax === null) {
          return null;
        }

        var min = Math.min.apply(null, minimumsPerTile);

        // If there is no data or no denseDataExtrema, go to parent method
        if (min === _maxSafeInteger2['default']) {
          return (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'minVisibleValue', this).call(this, ignoreFixedScale);
        }

        if (ignoreFixedScale) return min;

        return this.valueScaleMin !== null ? this.valueScaleMin : min;
      }

      return minVisibleValue;
    }()
  }, {
    key: 'maxVisibleValue',
    value: function () {
      function maxVisibleValue() {
        var _this8 = this;

        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        var maximumsPerTile = this.visibleAndFetchedTiles().map(function (tile) {
          if (tile.tileData.denseDataExtrema === undefined) {
            return null;
          }

          var ind = _this8.getIndicesOfVisibleDataInTile(tile);

          return tile.tileData.denseDataExtrema.getMaxNonZeroInSubset(ind);
        });

        if (maximumsPerTile.length === 0 && this.valueScaleMax === null) {
          return null;
        }

        var max = Math.max.apply(null, maximumsPerTile);

        // If there is no data  or no deseDataExtrema, go to parent method
        if (max === _minSafeInteger2['default']) {
          return (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'maxVisibleValue', this).call(this, ignoreFixedScale);
        }

        if (ignoreFixedScale) return max;

        return this.valueScaleMax !== null ? this.valueScaleMax : max;
      }

      return maxVisibleValue;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, tx, ty) {
        if (this.brushing) {
          return;
        }

        (0, _get3['default'])(HeatmapTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapTiledPixiTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);

        this.pMain.position.x = tx; // translateX;
        this.pMain.position.y = ty; // translateY;

        this.pMain.scale.x = k; // scaleX;
        this.pMain.scale.y = k; // scaleY;

        var isValueScaleLocked = this.isValueScaleLocked();

        if (this.continuousScaling && this.minValue() !== undefined && this.maxValue() !== undefined) {
          // Get the indices of the visible part of the upper left tile.
          // Helps to determine if we zoomed far enough to justify a min/max computation
          var indUpperLeftTile = (0, _stringify2['default'])(this.getVisiblePartOfUppLeftTile());

          if (this.valueScaleMin === null && this.valueScaleMax === null && !isValueScaleLocked &&
          // syncs the recomputation with the grid used in the DenseDataExtrema module
          indUpperLeftTile !== this.prevIndUpperLeftTile) {
            var newMin = this.minVisibleValue();
            var newMax = this.maxVisibleValue();

            var epsilon = 1e-6;

            if (newMin !== null && // can happen if tiles haven't loaded
            newMax !== null && (Math.abs(this.minValue() - newMin) > epsilon || Math.abs(this.maxValue() - newMax) > epsilon)) {
              this.minValue(newMin);
              this.maxValue(newMax);

              this.scheduleRerender();
            }
            this.prevIndUpperLeftTile = indUpperLeftTile;
          }

          if (isValueScaleLocked) {
            this.onValueScaleChanged();
          }
        }

        this.mouseMoveZoomHandler();
      }

      return zoomed;
    }()

    /**
     * Helper method for adding a tile ID in place. Used by `tilesToId()`.
     *
     * @param  {Array}  tiles  Array tile ID should be added to.
     * @param  {Integer}  zoomLevel  Zoom level.
     * @param  {Integer}  row  Column ID, i.e., y.
     * @param  {Integer}  column  Column ID, i.e., x.
     * @param  {Objwect}  dataTransform  ??
     * @param  {Boolean}  mirrored  If `true` tile is mirrored.
     */

  }, {
    key: 'addTileId',
    value: function () {
      function addTileId(tiles, zoomLevel, row, column, dataTransform) {
        var mirrored = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;

        var newTile = [zoomLevel, row, column];
        newTile.mirrored = mirrored;
        newTile.dataTransform = dataTransform;
        tiles.push(newTile);
      }

      return addTileId;
    }()

    /**
     * Convert tile positions to tile IDs
     *
     * @param  {Array}  xTiles  X positions of tiles
     * @param  {Array}  yTiles  Y positions of tiles
     * @param  {Array}  zoomLevel  Current zoom level
     * @return  {Array}  List of tile IDs
     */

  }, {
    key: 'tilesToId',
    value: function () {
      function tilesToId(xTiles, yTiles, zoomLevel) {
        var rows = xTiles;
        var cols = yTiles;
        var dataTransform = this.options && this.options.dataTransform || 'default';

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < rows.length; i++) {
          for (var j = 0; j < cols.length; j++) {
            if (this.mirrorTiles()) {
              if (rows[i] >= cols[j]) {
                if (this.options.extent !== 'lower-left') {
                  // if we're in the upper triangular part of the matrix, then we need
                  // to load a mirrored tile
                  this.addTileId(tiles, zoomLevel, cols[j], rows[i], dataTransform, true);
                }
              } else if (this.options.extent !== 'upper-right') {
                // otherwise, load an original tile
                this.addTileId(tiles, zoomLevel, rows[i], cols[j], dataTransform);
              }

              if (rows[i] === cols[j] && this.options.extent === 'lower-left') {
                // on the diagonal, load original tiles
                this.addTileId(tiles, zoomLevel, rows[i], cols[j], dataTransform);
              }
            } else {
              this.addTileId(tiles, zoomLevel, rows[i], cols[j], dataTransform);
            }
          }
        }

        return tiles;
      }

      return tilesToId;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        this.zoomLevel = this.calculateZoomLevel();

        // this.zoomLevel = 0;
        if (this.tilesetInfo.resolutions) {
          var sortedResolutions = this.tilesetInfo.resolutions.map(function (x) {
            return +x;
          }).sort(function (a, b) {
            return b - a;
          });

          this.xTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
          this.yTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], this._yScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
        } else {
          this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

          this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._yScale, this.options.reverseYAxis ? -this.tilesetInfo.max_pos[1] : this.tilesetInfo.min_pos[1], this.options.reverseYAxis ? -this.tilesetInfo.min_pos[1] : this.tilesetInfo.max_pos[1], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width1 || this.tilesetInfo.max_width);
        }

        this.setVisibleTiles(this.tilesToId(this.xTiles, this.yTiles, this.zoomLevel));
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'mirrorTiles',
    value: function () {
      function mirrorTiles() {
        return !(this.tilesetInfo.mirror_tiles && (this.tilesetInfo.mirror_tiles === false || this.tilesetInfo.mirror_tiles === 'false'));
      }

      return mirrorTiles;
    }()
  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX, trackY) {
        if (!this.options || !this.options.showTooltip) {
          return '';
        }

        if (!this.tilesetInfo) {
          return '';
        }

        var currentResolution = _services.tileProxy.calculateResolution(this.tilesetInfo, this.zoomLevel);

        var maxWidth = Math.max(this.tilesetInfo.max_pos[1] - this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[0] - this.tilesetInfo.min_pos[0]);

        var formatResolution = Math.ceil(Math.log(maxWidth / currentResolution) / Math.log(10));

        this.setDataLensSize(1);

        var dataX = this._xScale.invert(trackX);
        var dataY = this._yScale.invert(trackY);

        var positionText = '<b>Position:</b> ';

        if (this.chromInfo) {
          var atcX = (0, _utils.absToChr)(dataX, this.chromInfo);
          var atcY = (0, _utils.absToChr)(dataY, this.chromInfo);

          var f = function () {
            function f(n) {
              return (0, _d3Format.format)('.' + String(formatResolution) + 's')(n);
            }

            return f;
          }();

          positionText += String(atcX[0]) + ':' + String(f(atcX[1])) + ' & ' + String(atcY[0]) + ':' + String(f(atcY[1]));
          positionText += '<br/>';
        }

        var data = null;
        try {
          data = this.getVisibleRectangleData(trackX, trackY, 1, 1).get(0, 0);
        } catch (err) {
          return '';
        }

        if (this.options && this.options.heatmapValueScaling === 'log') {
          if (data > 0) {
            return positionText + '<b>Value:</b> 1e' + String((0, _d3Format.format)('.3f')(Math.log(data) / Math.log(10)));
          }

          if (data === 0) {
            return positionText + '<b>Value:</b> 0';
          }

          return positionText + '<b>Value:</b> N/A';
        }
        return positionText + '<b>Value:</b> ' + String((0, _d3Format.format)('.3f')(data));
      }

      return getMouseOverHtml;
    }()

    /**
     * Get the tile's position in its coordinate system.
     *
     * @description
     * Normally the absolute coordinate system are the genome basepair positions
     */

  }, {
    key: 'getTilePosAndDimensions',
    value: function () {
      function getTilePosAndDimensions(zoomLevel, tilePos, binsPerTileIn) {
        /**
         * Get the tile's position in its coordinate system.
         */
        var binsPerTile = binsPerTileIn || this.binsPerTile();

        if (this.tilesetInfo.resolutions) {
          var sortedResolutions = this.tilesetInfo.resolutions.map(function (x) {
            return +x;
          }).sort(function (a, b) {
            return b - a;
          });

          var chosenResolution = sortedResolutions[zoomLevel];

          var _tileWidth = chosenResolution * binsPerTile;
          var _tileHeight = _tileWidth;

          var _tileX = chosenResolution * binsPerTile * tilePos[0];
          var _tileY = chosenResolution * binsPerTile * tilePos[1];

          return {
            tileX: _tileX,
            tileY: _tileY,
            tileWidth: _tileWidth,
            tileHeight: _tileHeight
          };
        }

        var xTilePos = tilePos[0];
        var yTilePos = tilePos[1];

        var minX = this.tilesetInfo.min_pos[0];

        var minY = this.options.reverseYAxis ? -this.tilesetInfo.max_pos[1] : this.tilesetInfo.min_pos[1];

        var tileWidth = this.tilesetInfo.max_width / Math.pow(2, zoomLevel);
        var tileHeight = this.tilesetInfo.max_width / Math.pow(2, zoomLevel);

        var tileX = minX + xTilePos * tileWidth;
        var tileY = minY + yTilePos * tileHeight;

        return {
          tileX: tileX,
          tileY: tileY,
          tileWidth: tileWidth,
          tileHeight: tileHeight
        };
      }

      return getTilePosAndDimensions;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var minX = this.tilesetInfo.min_pos[0];
        var maxX = this.tilesetInfo.max_pos[0];

        var minY = this.tilesetInfo.min_pos[1];
        var maxY = this.tilesetInfo.max_pos[1];

        var zoomLevel = null;

        if (this.tilesetInfo.resolutions) {
          var zoomIndexX = _services.tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, minX, maxX);
          var zoomIndexY = _services.tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._yScale, minY, maxY);

          zoomLevel = Math.min(zoomIndexX, zoomIndexY);
        } else {
          var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.binsPerTile());

          var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1], this.binsPerTile());

          zoomLevel = Math.max(xZoomLevel, yZoomLevel);
          zoomLevel = Math.min(zoomLevel, this.maxZoom);
        }

        if (this.options && this.options.maxZoom) {
          if (this.options.maxZoom >= 0) {
            zoomLevel = Math.min(this.options.maxZoom, zoomLevel);
          } else {
            console.error('Invalid maxZoom on track:', this);
          }
        }

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()

    /**
     * The local tile identifier
     *
     * @param {array}  tile  Tile definition array to be converted to id. Tile
     *   array must contain `[zoomLevel, xPos, yPos]` and two props `mirrored` and
     *   `dataTransform`.
     */

  }, {
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        // tile
        if (tile.dataTransform && tile.dataTransform !== 'default') {
          return String(tile.join('.')) + '.' + String(tile.mirrored) + '.' + String(tile.dataTransform);
        }
        return String(tile.join('.')) + '.' + String(tile.mirrored);
      }

      return tileToLocalId;
    }()

    /**
     * The tile identifier used on the server
     */

  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        // tile contains [zoomLevel, xPos, yPos]
        if (tile.dataTransform && tile.dataTransform !== 'default') {
          return String(tile.join('.')) + '.' + String(tile.dataTransform);
        }
        return '' + String(tile.join('.'));
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'localToRemoteId',
    value: function () {
      function localToRemoteId(remoteId) {
        var idParts = remoteId.split('.');
        return idParts.slice(0, idParts.length - 1).join('.');
      }

      return localToRemoteId;
    }()
  }]);
  return HeatmapTiledPixiTrack;
}(_TiledPixiTrack3['default']);

exports['default'] = HeatmapTiledPixiTrack;

/***/ }),
/* 136 */
/***/ (function(module, exports, __nested_webpack_require_789883__) {

var iota = __nested_webpack_require_789883__(243)
var isBuffer = __nested_webpack_require_789883__(244)

var hasTypedArrays  = ((typeof Float64Array) !== "undefined")

function compare1st(a, b) {
  return a[0] - b[0]
}

function order() {
  var stride = this.stride
  var terms = new Array(stride.length)
  var i
  for(i=0; i<terms.length; ++i) {
    terms[i] = [Math.abs(stride[i]), i]
  }
  terms.sort(compare1st)
  var result = new Array(terms.length)
  for(i=0; i<result.length; ++i) {
    result[i] = terms[i][1]
  }
  return result
}

function compileConstructor(dtype, dimension) {
  var className = ["View", dimension, "d", dtype].join("")
  if(dimension < 0) {
    className = "View_Nil" + dtype
  }
  var useGetters = (dtype === "generic")

  if(dimension === -1) {
    //Special case for trivial arrays
    var code =
      "function "+className+"(a){this.data=a;};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return -1};\
proto.size=0;\
proto.dimension=-1;\
proto.shape=proto.stride=proto.order=[];\
proto.lo=proto.hi=proto.transpose=proto.step=\
function(){return new "+className+"(this.data);};\
proto.get=proto.set=function(){};\
proto.pick=function(){return null};\
return function construct_"+className+"(a){return new "+className+"(a);}"
    var procedure = new Function(code)
    return procedure()
  } else if(dimension === 0) {
    //Special case for 0d arrays
    var code =
      "function "+className+"(a,d) {\
this.data = a;\
this.offset = d\
};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return this.offset};\
proto.dimension=0;\
proto.size=1;\
proto.shape=\
proto.stride=\
proto.order=[];\
proto.lo=\
proto.hi=\
proto.transpose=\
proto.step=function "+className+"_copy() {\
return new "+className+"(this.data,this.offset)\
};\
proto.pick=function "+className+"_pick(){\
return TrivialArray(this.data);\
};\
proto.valueOf=proto.get=function "+className+"_get(){\
return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
"};\
proto.set=function "+className+"_set(v){\
return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
};\
return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}"
    var procedure = new Function("TrivialArray", code)
    return procedure(CACHED_CONSTRUCTORS[dtype][0])
  }

  var code = ["'use strict'"]

  //Create constructor for view
  var indices = iota(dimension)
  var args = indices.map(function(i) { return "i"+i })
  var index_str = "this.offset+" + indices.map(function(i) {
        return "this.stride[" + i + "]*i" + i
      }).join("+")
  var shapeArg = indices.map(function(i) {
      return "b"+i
    }).join(",")
  var strideArg = indices.map(function(i) {
      return "c"+i
    }).join(",")
  code.push(
    "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
      "this.shape=[" + shapeArg + "]",
      "this.stride=[" + strideArg + "]",
      "this.offset=d|0}",
    "var proto="+className+".prototype",
    "proto.dtype='"+dtype+"'",
    "proto.dimension="+dimension)

  //view.size:
  code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
"}})")

  //view.order:
  if(dimension === 1) {
    code.push("proto.order=[0]")
  } else {
    code.push("Object.defineProperty(proto,'order',{get:")
    if(dimension < 4) {
      code.push("function "+className+"_order(){")
      if(dimension === 2) {
        code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})")
      } else if(dimension === 3) {
        code.push(
"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
if(s0>s1){\
if(s1>s2){\
return [2,1,0];\
}else if(s0>s2){\
return [1,2,0];\
}else{\
return [1,0,2];\
}\
}else if(s0>s2){\
return [2,0,1];\
}else if(s2>s1){\
return [0,1,2];\
}else{\
return [0,2,1];\
}}})")
      }
    } else {
      code.push("ORDER})")
    }
  }

  //view.set(i0, ..., v):
  code.push(
"proto.set=function "+className+"_set("+args.join(",")+",v){")
  if(useGetters) {
    code.push("return this.data.set("+index_str+",v)}")
  } else {
    code.push("return this.data["+index_str+"]=v}")
  }

  //view.get(i0, ...):
  code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
  if(useGetters) {
    code.push("return this.data.get("+index_str+")}")
  } else {
    code.push("return this.data["+index_str+"]}")
  }

  //view.index:
  code.push(
    "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")

  //view.hi():
  code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
    indices.map(function(i) {
      return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
    }).join(",")+","+
    indices.map(function(i) {
      return "this.stride["+i + "]"
    }).join(",")+",this.offset)}")

  //view.lo():
  var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" })
  var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" })
  code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
  for(var i=0; i<dimension; ++i) {
    code.push(
"if(typeof i"+i+"==='number'&&i"+i+">=0){\
d=i"+i+"|0;\
b+=c"+i+"*d;\
a"+i+"-=d}")
  }
  code.push("return new "+className+"(this.data,"+
    indices.map(function(i) {
      return "a"+i
    }).join(",")+","+
    indices.map(function(i) {
      return "c"+i
    }).join(",")+",b)}")

  //view.step():
  code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
    indices.map(function(i) {
      return "a"+i+"=this.shape["+i+"]"
    }).join(",")+","+
    indices.map(function(i) {
      return "b"+i+"=this.stride["+i+"]"
    }).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
  for(var i=0; i<dimension; ++i) {
    code.push(
"if(typeof i"+i+"==='number'){\
d=i"+i+"|0;\
if(d<0){\
c+=b"+i+"*(a"+i+"-1);\
a"+i+"=ceil(-a"+i+"/d)\
}else{\
a"+i+"=ceil(a"+i+"/d)\
}\
b"+i+"*=d\
}")
  }
  code.push("return new "+className+"(this.data,"+
    indices.map(function(i) {
      return "a" + i
    }).join(",")+","+
    indices.map(function(i) {
      return "b" + i
    }).join(",")+",c)}")

  //view.transpose():
  var tShape = new Array(dimension)
  var tStride = new Array(dimension)
  for(var i=0; i<dimension; ++i) {
    tShape[i] = "a[i"+i+"]"
    tStride[i] = "b[i"+i+"]"
  }
  code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
    args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
    "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}")

  //view.pick():
  code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset")
  for(var i=0; i<dimension; ++i) {
    code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}")
  }
  code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")

  //Add return statement
  code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
    indices.map(function(i) {
      return "shape["+i+"]"
    }).join(",")+","+
    indices.map(function(i) {
      return "stride["+i+"]"
    }).join(",")+",offset)}")

  //Compile procedure
  var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
  return procedure(CACHED_CONSTRUCTORS[dtype], order)
}

function arrayDType(data) {
  if(isBuffer(data)) {
    return "buffer"
  }
  if(hasTypedArrays) {
    switch(Object.prototype.toString.call(data)) {
      case "[object Float64Array]":
        return "float64"
      case "[object Float32Array]":
        return "float32"
      case "[object Int8Array]":
        return "int8"
      case "[object Int16Array]":
        return "int16"
      case "[object Int32Array]":
        return "int32"
      case "[object Uint8Array]":
        return "uint8"
      case "[object Uint16Array]":
        return "uint16"
      case "[object Uint32Array]":
        return "uint32"
      case "[object Uint8ClampedArray]":
        return "uint8_clamped"
    }
  }
  if(Array.isArray(data)) {
    return "array"
  }
  return "generic"
}

var CACHED_CONSTRUCTORS = {
  "float32":[],
  "float64":[],
  "int8":[],
  "int16":[],
  "int32":[],
  "uint8":[],
  "uint16":[],
  "uint32":[],
  "array":[],
  "uint8_clamped":[],
  "buffer":[],
  "generic":[]
}

;(function() {
  for(var id in CACHED_CONSTRUCTORS) {
    CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
  }
});

function wrappedNDArrayCtor(data, shape, stride, offset) {
  if(data === undefined) {
    var ctor = CACHED_CONSTRUCTORS.array[0]
    return ctor([])
  } else if(typeof data === "number") {
    data = [data]
  }
  if(shape === undefined) {
    shape = [ data.length ]
  }
  var d = shape.length
  if(stride === undefined) {
    stride = new Array(d)
    for(var i=d-1, sz=1; i>=0; --i) {
      stride[i] = sz
      sz *= shape[i]
    }
  }
  if(offset === undefined) {
    offset = 0
    for(var i=0; i<d; ++i) {
      if(stride[i] < 0) {
        offset -= (shape[i]-1)*stride[i]
      }
    }
  }
  var dtype = arrayDType(data)
  var ctor_list = CACHED_CONSTRUCTORS[dtype]
  while(ctor_list.length <= d+1) {
    ctor_list.push(compileConstructor(dtype, ctor_list.length-1))
  }
  var ctor = ctor_list[d+1]
  return ctor(data, shape, stride, offset)
}

module.exports = wrappedNDArrayCtor


/***/ }),
/* 137 */
/***/ (function(module, exports, __nested_webpack_require_799652__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_799652__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _minSafeInteger = __nested_webpack_require_799652__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

var _maxSafeInteger = __nested_webpack_require_799652__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _log = __nested_webpack_require_799652__(248);

var _log2 = _interopRequireDefault(_log);

var _classCallCheck2 = __nested_webpack_require_799652__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_799652__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _denseDataExtremaConfig = __nested_webpack_require_799652__(114);

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

var DenseDataExtrema1D = function () {
  /**
   * This module efficiently computes extrema of arbitrary subsets of a given data array.
   * The array is subdivided into 'numSubsets' subsets where extrema are precomputed.
   * These values are used to compute extrema given arbitrary start and end indices via
   * the getMinNonZeroInSubset and getMaxNonZeroInSubset methods.
   * @param   {array}  data
   */
  function DenseDataExtrema1D(data) {
    (0, _classCallCheck3['default'])(this, DenseDataExtrema1D);

    this.epsilon = 1e-6;
    this.data = data;

    this.tileSize = this.data.length; // might not be a power of 2
    this.paddedTileSize = Math.pow(2, Math.ceil((0, _log2['default'])(this.tileSize)));

    // This controls how many subsets are created and precomputed.
    // Setting numSubsets to 1, is equivalent to no precomputation in
    // most cases
    this.numSubsets = Math.min(_denseDataExtremaConfig.NUM_PRECOMP_SUBSETS_PER_1D_TTILE, this.paddedTileSize);
    this.subsetSize = this.paddedTileSize / this.numSubsets;

    this.subsetMinimums = this.computeSubsetNonZeroMinimums();
    this.subsetMaximums = this.computeSubsetNonZeroMaximums();
    this.minNonZeroInTile = this.getMinNonZeroInTile();
    this.maxNonZeroInTile = this.getMaxNonZeroInTile();
  }

  /**
   * Computes the non-zero minimum in a subset using precomputed values,
   * if possible. data[end] is not considered.
   * @param   {array}  indexBounds  [start, end]
   * @return  {number}  non-zero minium of the subset
   */


  (0, _createClass3['default'])(DenseDataExtrema1D, [{
    key: 'getMinNonZeroInSubset',
    value: function () {
      function getMinNonZeroInSubset(indexBounds) {
        var start = indexBounds[0];
        var end = indexBounds[1];
        var curMin = _maxSafeInteger2['default'];

        if (start === 0 && end === this.tileSize) {
          return this.minNonZeroInTile;
        }

        var firstSubsetIndex = Math.ceil(start / this.subsetSize);
        var lastSubsetIndex = Math.floor((end - 1) / this.subsetSize);

        if (firstSubsetIndex >= lastSubsetIndex) {
          // No precomputation was found.
          return this.minNonZero(this.data, start, end);
        }

        // Compute from original data if the beginning is not covered by precomputations
        if (start < firstSubsetIndex * this.subsetSize) {
          curMin = Math.min(curMin, this.minNonZero(this.data, start, firstSubsetIndex * this.subsetSize));
        }

        // Use the precomputed values
        curMin = Math.min(curMin, this.minNonZero(this.subsetMinimums, firstSubsetIndex, lastSubsetIndex));

        // Compute from original data if the end is not covered by precomputations
        if (end > lastSubsetIndex * this.subsetSize) {
          curMin = Math.min(curMin, this.minNonZero(this.data, lastSubsetIndex * this.subsetSize, end));
        }

        return curMin;
      }

      return getMinNonZeroInSubset;
    }()

    /**
     * Computes the non-zero maximum in a subset using precomputed values,
     * if possible
     * @param   {array}  indexBounds  [start, end]
     * @return  {number}  non-zero maxium of the subset
     */

  }, {
    key: 'getMaxNonZeroInSubset',
    value: function () {
      function getMaxNonZeroInSubset(indexBounds) {
        var start = indexBounds[0];
        var end = indexBounds[1];
        var curMax = _minSafeInteger2['default'];

        if (start === 0 && end === this.tileSize) {
          return this.maxNonZeroInTile;
        }

        var firstSubsetIndex = Math.ceil(start / this.subsetSize);
        var lastSubsetIndex = Math.floor((end - 1) / this.subsetSize);

        if (firstSubsetIndex >= lastSubsetIndex) {
          // No precomputation was found.
          return this.maxNonZero(this.data, start, end);
        }

        // Compute from original data if the beginning is not covered by precomputations
        if (start < firstSubsetIndex * this.subsetSize) {
          curMax = Math.max(curMax, this.maxNonZero(this.data, start, firstSubsetIndex * this.subsetSize));
        }

        // Use the precomputed values
        curMax = Math.max(curMax, this.maxNonZero(this.subsetMaximums, firstSubsetIndex, lastSubsetIndex));

        // Compute from original data if the end is not covered by precomputations
        if (end > lastSubsetIndex * this.subsetSize) {
          curMax = Math.max(curMax, this.maxNonZero(this.data, lastSubsetIndex * this.subsetSize, end));
        }

        return curMax;
      }

      return getMaxNonZeroInSubset;
    }()

    /**
     * Precomputes non-zero minimums of subsets of the given data vector
     * @return  {array}  array containing minimums of the regularly subdivided
     *                   data vector
     */

  }, {
    key: 'computeSubsetNonZeroMinimums',
    value: function () {
      function computeSubsetNonZeroMinimums() {
        var minimums = [];

        for (var i = 0; i < this.numSubsets; i++) {
          var curMin = _maxSafeInteger2['default'];

          for (var j = 0; j < this.subsetSize; j++) {
            var x = this.data[i * this.subsetSize + j];
            // if the tilesize is not a power of 2 we might access
            // a value that is not there
            if (x === undefined) {
              continue;
            }

            if (x < this.epsilon && x > -this.epsilon) {
              continue;
            }
            if (x < curMin) {
              curMin = x;
            }
          }
          minimums.push(curMin);
        }
        return minimums;
      }

      return computeSubsetNonZeroMinimums;
    }()

    /**
     * Precomputes non-zero maximums of subsets of the given data vector
     * @return  {array}  array containing maximums of the regularly subdivided
     *                   data vector
     */

  }, {
    key: 'computeSubsetNonZeroMaximums',
    value: function () {
      function computeSubsetNonZeroMaximums() {
        var maximums = [];

        for (var i = 0; i < this.numSubsets; i++) {
          var curMax = _minSafeInteger2['default'];

          for (var j = 0; j < this.subsetSize; j++) {
            var x = this.data[i * this.subsetSize + j];
            // if the tilesize is not a power of 2 we might access
            // a value that is not there
            if (x === undefined) {
              continue;
            }

            if (x < this.epsilon && x > -this.epsilon) {
              continue;
            }
            if (x > curMax) {
              curMax = x;
            }
          }
          maximums.push(curMax);
        }
        return maximums;
      }

      return computeSubsetNonZeroMaximums;
    }()

    /**
     * Computes the non-zero minimum in the entire data array using precomputed values
     * @return  {number}  non-zeros maximum of the data
     */

  }, {
    key: 'getMinNonZeroInTile',
    value: function () {
      function getMinNonZeroInTile() {
        return Math.min.apply(Math, (0, _toConsumableArray3['default'])(this.subsetMinimums));
      }

      return getMinNonZeroInTile;
    }()

    /**
     * Computes the non-zero maximum in the entire data array using precomputed values
     * @return  {number}  non-zeros maximum of the data
     */

  }, {
    key: 'getMaxNonZeroInTile',
    value: function () {
      function getMaxNonZeroInTile() {
        return Math.max.apply(Math, (0, _toConsumableArray3['default'])(this.subsetMaximums));
      }

      return getMaxNonZeroInTile;
    }()

    /**
     * Calculate the minimum non-zero value in the data from start
     * to end. No precomputations are used to compute the min.
     *
     * @param {Float32Array} data
     * @param {int} start
     * @param {int} end
     * @return {number} non-zero min in subset
     */

  }, {
    key: 'minNonZero',
    value: function () {
      function minNonZero(data, start, end) {
        var minNonZeroNum = _maxSafeInteger2['default'];

        for (var i = start; i < end; i++) {
          var x = data[i];

          if (x < this.epsilon && x > -this.epsilon) {
            continue;
          }

          if (x < minNonZeroNum) {
            minNonZeroNum = x;
          }
        }

        return minNonZeroNum;
      }

      return minNonZero;
    }()

    /**
     * Calculate the maximum non-zero value in the data from start
     * to end. No precomputations are used to compute the max.
     *
     * @param {Float32Array} data
    ` * @param {int} start
     * @param {int} end
     * @return {number} non-zero max in subset
     */

  }, {
    key: 'maxNonZero',
    value: function () {
      function maxNonZero(data, start, end) {
        var maxNonZeroNum = _minSafeInteger2['default'];

        for (var i = start; i < end; i++) {
          var x = data[i];

          if (x < this.epsilon && x > -this.epsilon) {
            continue;
          }

          if (x > maxNonZeroNum) {
            maxNonZeroNum = x;
          }
        }

        return maxNonZeroNum;
      }

      return maxNonZero;
    }()
  }]);
  return DenseDataExtrema1D;
}();

exports['default'] = DenseDataExtrema1D;

/***/ }),
/* 138 */
/***/ (function(module, exports, __nested_webpack_require_809735__) {

"use strict";


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

var _minSafeInteger = __nested_webpack_require_809735__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

var _maxSafeInteger = __nested_webpack_require_809735__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _from = __nested_webpack_require_809735__(95);

var _from2 = _interopRequireDefault(_from);

var _isSafeInteger = __nested_webpack_require_809735__(251);

var _isSafeInteger2 = _interopRequireDefault(_isSafeInteger);

var _classCallCheck2 = __nested_webpack_require_809735__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_809735__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _ndarray = __nested_webpack_require_809735__(136);

var _ndarray2 = _interopRequireDefault(_ndarray);

var _denseDataExtremaConfig = __nested_webpack_require_809735__(114);

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

var DenseDataExtrema2D = function () {
  /**
   * This module efficiently computes extrema of subsets of a given data matrix.
   * The matrix is subdivided into 'numSubsets' subsets where extrema are precomputed.
   * These values are used to efficiently approximate extrema given arbitrary subsets.
   * Larger values of 'numSubsets' lead to more accurate approximations (more expensive).
   *
   * @param   {array}  data array of quadratic length
   */
  function DenseDataExtrema2D(data) {
    (0, _classCallCheck3['default'])(this, DenseDataExtrema2D);

    this.epsilon = 1e-6;

    this.tileSize = Math.sqrt(data.length);

    if (!(0, _isSafeInteger2['default'])(this.tileSize)) {
      console.error('The DenseDataExtrema2D module only works for data of quadratic length.');
    }

    // if this.numSubsets == this.tilesize the extrema are computed exactly (expensive).
    this.numSubsets = Math.min(_denseDataExtremaConfig.NUM_PRECOMP_SUBSETS_PER_2D_TTILE, this.tileSize);
    this.subsetSize = this.tileSize / this.numSubsets;

    // Convert data to 2d array
    var dataMatrix = (0, _ndarray2['default'])((0, _from2['default'])(data), [this.tileSize, this.tileSize]);

    this.subsetMinimums = this.computeSubsetNonZeroMinimums(dataMatrix);
    this.subsetMaximums = this.computeSubsetNonZeroMaximums(dataMatrix);
    this.minNonZeroInTile = this.getMinNonZeroInTile();
    this.maxNonZeroInTile = this.getMaxNonZeroInTile();
  }

  /**
   * Computes an approximation of the non-zero minimum in a subset
   * @param   {array}  indexBounds  [startX, startY, endX, endY]
   * @return  {number}  non-zero minium of the subset
   */


  (0, _createClass3['default'])(DenseDataExtrema2D, [{
    key: 'getMinNonZeroInSubset',
    value: function () {
      function getMinNonZeroInSubset(indexBounds) {
        var startX = indexBounds[0];
        var startY = indexBounds[1];
        var endX = indexBounds[2];
        var endY = indexBounds[3];

        // transform indices to the corresponding entries in the
        // precomputed minimum matrix
        var rowOffsetStart = Math.floor(startY / this.subsetSize);
        var colOffsetStart = Math.floor(startX / this.subsetSize);
        var height = Math.ceil((endY + 1) / this.subsetSize) - rowOffsetStart;
        var width = Math.ceil((endX + 1) / this.subsetSize) - colOffsetStart;

        var min = this.getMinNonZeroInNdarraySubset(this.subsetMinimums, rowOffsetStart, colOffsetStart, width, height);

        return min;
      }

      return getMinNonZeroInSubset;
    }()

    /**
     * Computes an approximation of the non-zero maximum in a subset
     * @param   {array}  indexBounds  [startX, startY, endX, endY]
     * @return  {number}  non-zero maxium of the subset
     */

  }, {
    key: 'getMaxNonZeroInSubset',
    value: function () {
      function getMaxNonZeroInSubset(indexBounds) {
        var startX = indexBounds[0];
        var startY = indexBounds[1];
        var endX = indexBounds[2];
        var endY = indexBounds[3];

        // transform indices to the corresponding entries in the
        // precomputed maximum matrix
        var rowOffsetStart = Math.floor(startY / this.subsetSize);
        var colOffsetStart = Math.floor(startX / this.subsetSize);
        var height = Math.ceil((endY + 1) / this.subsetSize) - rowOffsetStart;
        var width = Math.ceil((endX + 1) / this.subsetSize) - colOffsetStart;

        var max = this.getMaxNonZeroInNdarraySubset(this.subsetMaximums, rowOffsetStart, colOffsetStart, width, height);

        return max;
      }

      return getMaxNonZeroInSubset;
    }()

    /**
     * Precomputes non-zero minimums of subsets of a given matrix
     * @param   {ndarray}  dataMatrix
     * @return  {ndarray}  matrix containing minimums of the dataMatrix
     *                     after subdivision using a regular grid
     */

  }, {
    key: 'computeSubsetNonZeroMinimums',
    value: function () {
      function computeSubsetNonZeroMinimums(dataMatrix) {
        var minimums = new Array(Math.pow(this.numSubsets, 2));
        minimums = (0, _ndarray2['default'])(minimums, [this.numSubsets, this.numSubsets]);

        for (var i = 0; i < this.numSubsets; i++) {
          for (var j = 0; j < this.numSubsets; j++) {
            var curMin = this.getMinNonZeroInNdarraySubset(dataMatrix, i * this.subsetSize, j * this.subsetSize, this.subsetSize, this.subsetSize);
            minimums.set(i, j, curMin);
          }
        }
        return minimums;
      }

      return computeSubsetNonZeroMinimums;
    }()

    /**
     * Precomputes non-zero maximums of subsets of a given matrix
     * @param   {ndarray}  dataMatrix
     * @return  {ndarray}  matrix containing maximums of the dataMatrix
     *                     after subdivision using a regular grid
     */

  }, {
    key: 'computeSubsetNonZeroMaximums',
    value: function () {
      function computeSubsetNonZeroMaximums(dataMatrix) {
        var maximums = new Array(Math.pow(this.numSubsets, 2));
        maximums = (0, _ndarray2['default'])(maximums, [this.numSubsets, this.numSubsets]);

        for (var i = 0; i < this.numSubsets; i++) {
          for (var j = 0; j < this.numSubsets; j++) {
            var curMax = this.getMaxNonZeroInNdarraySubset(dataMatrix, i * this.subsetSize, j * this.subsetSize, this.subsetSize, this.subsetSize);
            maximums.set(i, j, curMax);
          }
        }
        return maximums;
      }

      return computeSubsetNonZeroMaximums;
    }()

    /**
     * Computes the non-zero minimum of a subset of a matrix (ndarray)
     * @param   {ndarray}  arr
     * @param   {int}  rowOffset Starting row of the subset
     * @param   {int}  colOffset Starting column of the subset
     * @param   {int}  width Width (num columns) of the subset
     * @param   {int}  height Height (num rows) of the subset
     * @return  {number}  non-zeros minimum of the subset
     */

  }, {
    key: 'getMinNonZeroInNdarraySubset',
    value: function () {
      function getMinNonZeroInNdarraySubset(arr, rowOffset, colOffset, width, height) {
        var curMin = _maxSafeInteger2['default'];

        for (var k = 0; k < width; k++) {
          for (var l = 0; l < height; l++) {
            var x = arr.get(rowOffset + l, colOffset + k);
            if (x < this.epsilon && x > -this.epsilon) {
              continue;
            }
            if (x < curMin) {
              curMin = x;
            }
          }
        }

        return curMin;
      }

      return getMinNonZeroInNdarraySubset;
    }()

    /**
     * Computes the non-zero maximum of a subset of a matrix (ndarray)
     * @param   {ndarray}  arr
     * @param   {int}  rowOffset Starting row of the subset
     * @param   {int}  colOffset Starting column of the subset
     * @param   {int}  width Width (num columns) of the subset
     * @param   {int}  height Height (num rows) of the subset
     * @return  {number}  non-zeros maximum of the subset
     */

  }, {
    key: 'getMaxNonZeroInNdarraySubset',
    value: function () {
      function getMaxNonZeroInNdarraySubset(arr, rowOffset, colOffset, width, height) {
        var curMax = _minSafeInteger2['default'];

        for (var k = 0; k < width; k++) {
          for (var l = 0; l < height; l++) {
            var x = arr.get(rowOffset + l, colOffset + k);
            if (x < this.epsilon && x > -this.epsilon) {
              continue;
            }
            if (x > curMax) {
              curMax = x;
            }
          }
        }

        return curMax;
      }

      return getMaxNonZeroInNdarraySubset;
    }()
  }, {
    key: 'mirrorPrecomputedExtrema',
    value: function () {
      function mirrorPrecomputedExtrema() {
        for (var row = 1; row < this.numSubsets; row++) {
          for (var col = 0; col < row; col++) {
            this.subsetMinimums.set(col, row, this.subsetMinimums.get(row, col));
            this.subsetMaximums.set(col, row, this.subsetMaximums.get(row, col));
          }
        }
      }

      return mirrorPrecomputedExtrema;
    }()

    /**
     * Computes the non-zero minimum in the entire data array using precomputed values
     * @return  {number}  non-zeros minimum of the data
     */

  }, {
    key: 'getMinNonZeroInTile',
    value: function () {
      function getMinNonZeroInTile() {
        return this.getMinNonZeroInNdarraySubset(this.subsetMinimums, 0, 0, this.numSubsets, this.numSubsets);
      }

      return getMinNonZeroInTile;
    }()

    /**
     * Computes the non-zero maximum in the entire data array using precomputed values
     * @return  {number}  non-zeros maximum of the data
     */

  }, {
    key: 'getMaxNonZeroInTile',
    value: function () {
      function getMaxNonZeroInTile() {
        return this.getMaxNonZeroInNdarraySubset(this.subsetMaximums, 0, 0, this.numSubsets, this.numSubsets);
      }

      return getMaxNonZeroInTile;
    }()
  }]);
  return DenseDataExtrema2D;
}();

exports['default'] = DenseDataExtrema2D;

/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Compute the size associated with a potentially 2d array of selected item indices.
 * For example, this can be used to compute the total height of a `horizontal-multivec` track
 * where rows are selected individually or in aggregation groups.
 * @param {array} selectedItems The 1d or 2d array of items or groups of items.
 * @param {boolean} withRelativeSize Does a group of indices count as 1 unit size
 * or is its size relative to the group size?
 * @returns {number} The computed size value.
 * Between 0 and the total number of items in the (flattened) input array.
 */
var selectedItemsToSize = function selectedItemsToSize(selectedItems, withRelativeSize) {
  return selectedItems.reduce(function (a, h) {
    return a + (Array.isArray(h) && withRelativeSize ? h.length : 1);
  }, 0);
};

exports["default"] = selectedItemsToSize;

/***/ }),
/* 140 */
/***/ (function(module, exports, __nested_webpack_require_820801__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_820801__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _isNan = __nested_webpack_require_820801__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _classCallCheck2 = __nested_webpack_require_820801__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_820801__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _d3Array = __nested_webpack_require_820801__(8);

var _d3Format = __nested_webpack_require_820801__(20);

var _utils = __nested_webpack_require_820801__(10);

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

var SearchField = function () {
  function SearchField(chromInfo) {
    (0, _classCallCheck3['default'])(this, SearchField);

    this.chromInfo = chromInfo;
    this.chromInfoBisector = (0, _d3Array.bisector)(function (d) {
      return d.pos;
    }).left;
  }

  (0, _createClass3['default'])(SearchField, [{
    key: 'scalesToPositionText',
    value: function () {
      function scalesToPositionText(xScale, yScale) {
        var twoD = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

        if (this.chromInfo === null) {
          return '';
        } // chromosome info hasn't been loaded yet

        if (!xScale || !yScale) {
          return '';
        }

        var x1 = (0, _utils.absToChr)(xScale.domain()[0], this.chromInfo);
        var x2 = (0, _utils.absToChr)(xScale.domain()[1], this.chromInfo);

        var y1 = (0, _utils.absToChr)(yScale.domain()[0], this.chromInfo);
        var y2 = (0, _utils.absToChr)(yScale.domain()[1], this.chromInfo);

        var positionString = null;
        var stringFormat = (0, _d3Format.format)(',d');

        if (x1[0] !== x2[0]) {
          // different chromosomes

          positionString = String(x1[0]) + ':' + String(stringFormat(Math.floor(x1[1]))) + '-' + String(x2[0]) + ':' + String(stringFormat(Math.ceil(x2[1])));
        } else {
          // same chromosome

          positionString = String(x1[0]) + ':' + String(stringFormat(Math.floor(x1[1]))) + '-' + String(stringFormat(Math.ceil(x2[1])));
        }

        if (twoD) {
          if (y1[0] !== y2[0]) {
            // different chromosomes
            positionString += ' & ' + String(y1[0]) + ':' + String(stringFormat(Math.floor(y1[1]))) + '-' + String(y2[0]) + ':' + String(stringFormat(Math.ceil(y2[1])));
          } else {
            // same chromosome
            positionString += ' & ' + String(y1[0]) + ':' + String(stringFormat(Math.floor(y1[1]))) + '-' + String(stringFormat(Math.ceil(y2[1])));
          }
        }

        if (x1[2] <= 0 || x2[2] > 0 || twoD && (y1[2] <= 0 || y2[2] > 0)) {
          // did any of the coordinates exceed the genome boundaries
          positionString += ' [offset ' + String(x1[2]) + ',' + String(x2[2]);
          if (twoD) {
            positionString += ':' + String(y1[2]) + ',' + String(y2[2]);
          }

          positionString += ']';
        }

        return positionString;
      }

      return scalesToPositionText;
    }()
  }, {
    key: 'convertNumberNotation',
    value: function () {
      function convertNumberNotation(numStr) {
        // Convert K or M notations
        // e.g. "1.5M" to "1500000"
        // or "0.05M" to "50000"
        // or even "00.05M" or "00.050M" to "50000"
        var newNumStr = numStr;

        if (!newNumStr.includes('M', newNumStr.length - 1) && !newNumStr.includes('K', newNumStr.length - 1)) {
          // Nothing to convert
          return newNumStr;
        }

        var numZerosToAdd = 0;
        var decPointPosFromEnd = 0;

        // Handle 'M' or 'N' notations
        if (newNumStr.includes('M', newNumStr.length - 1)) {
          numZerosToAdd = 6;
          newNumStr = newNumStr.replace('M', '');
        } else {
          numZerosToAdd = 3;
          newNumStr = newNumStr.replace('K', '');
        }

        if ((0, _isNan2['default'])(+newNumStr)) {
          // Without 'K' or 'M' notation, the string should be converted to a valid number.
          return numStr;
        }

        // Drop the needless characters for the simplicity (e.g., "00.5" to "0.5" or "1,000" to "1000").
        newNumStr = (+newNumStr).toString();

        // Handle a decimal point
        if (newNumStr.includes('.')) {
          decPointPosFromEnd = newNumStr.length - 1 - newNumStr.indexOf('.');
          newNumStr = (+newNumStr.replace('.', '')).toString();
        }

        var totalZerosToAdd = numZerosToAdd - decPointPosFromEnd;
        if (totalZerosToAdd < 0) {
          // The value is smaller than 1 (e.g. "0.00005K")
          return numStr;
        }

        // Finally, add zeros at the end.
        newNumStr += '0'.repeat(totalZerosToAdd);

        return newNumStr;
      }

      return convertNumberNotation;
    }()
  }, {
    key: 'parsePosition',
    value: function () {
      function parsePosition(positionText) {
        var prevChr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

        // Parse chr:position strings...
        // i.e. chr1:1000
        // or   chr2:20000
        var positionParts = positionText.split(':');
        var chr = null;
        var pos = 0;

        if (positionParts.length > 1) {
          chr = positionParts[0];
          pos = +this.convertNumberNotation(positionParts[1].replace(/,/g, '')); // chromosome specified
        } else if (positionParts[0] in this.chromInfo.chrPositions) {
          // is this an entire chromosome
          chr = positionParts[0];
          pos = 0;

          if (prevChr !== null) {
            // this chromosome is part of a range so we actually
            // want to search to the end of it
            pos = +this.chromInfo.chromLengths[chr];
          }
        } else {
          // no it's just a position without a chromosome
          pos = +this.convertNumberNotation(positionParts[0].replace(/,/g, '')); // no chromosome specified
          chr = null;

          if (prevChr) chr = prevChr;
        }

        // If chromosome doesn't exit
        var retPos = null;

        if (chr === null) {
          // queries like chr1:1000-2000
          chr = prevChr;
          // no chromosome provided, so this is just a number
          retPos = pos;
        } else if (chr in this.chromInfo.chrPositions) {
          // chromosome provided, everything is fine
          retPos = this.chromInfo.chrPositions[chr].pos + pos;
        }

        // retPos is the genome position of this pair
        return [chr, pos, retPos];
      }

      return parsePosition;
    }()
  }, {
    key: 'matchRangesToLarger',
    value: function () {
      function matchRangesToLarger(range1, range2) {
        // if one range is wider than the other, then adjust the other
        // so that it is just as wide
        if (range1[1] - range1[0] < range2[1] - range2[0]) {
          var _toExpand = range2[1] - range2[0] - (range1[1] - range1[0]);
          return [[range1[0] - _toExpand / 2, range1[1] + _toExpand / 2], range2];
        }
        var toExpand = range1[1] - range1[0] - (range2[1] - range2[0]);
        return [range1, [range2[0] - toExpand / 2, range2[1] + toExpand / 2]];
      }

      return matchRangesToLarger;
    }()
  }, {
    key: 'getSearchRange',
    value: function () {
      function getSearchRange(term) {
        // Get the genomic regions associated with this term
        // Example terms:
        // tp53
        // tp53 (nm_000546)
        // tp53 to adh1b
        // tp53 (nm_000546) to adh1b

        if (term.length === 0) {
          return null;
        }

        // shitty ass regex to deal with negative positions
        // (which aren't even valid genomic coordinates)
        var parts = term.split('-'); // split on a
        parts = parts.filter(function (d) {
          return d.length > 0;
        });

        var range = null;

        if (parts[0].indexOf('-') === 0) {
          parts[0] = parts[0].slice(3, parts[0].length);
        }

        if (parts.length > 1) {
          // calculate the range in one direction
          var _parsePosition = this.parsePosition(parts[0]),
              _parsePosition2 = (0, _slicedToArray3['default'])(_parsePosition, 3),
              chr1 = _parsePosition2[0],
              chrPos1 = _parsePosition2[1],
              genomePos1 = _parsePosition2[2];

          var _parsePosition3 = this.parsePosition(parts[1], chr1),
              _parsePosition4 = (0, _slicedToArray3['default'])(_parsePosition3, 3),
              chr2 = _parsePosition4[0],
              chrPos2 = _parsePosition4[1],
              genomePos2 = _parsePosition4[2];
          /* eslint-enable no-unused-vars */

          var tempRange1 = [genomePos1, genomePos2];

          var _parsePosition5 = this.parsePosition(parts[1]);

          var _parsePosition6 = (0, _slicedToArray3['default'])(_parsePosition5, 3);

          chr1 = _parsePosition6[0];
          chrPos1 = _parsePosition6[1];
          genomePos1 = _parsePosition6[2];

          var _parsePosition7 = this.parsePosition(parts[0], chr1);

          var _parsePosition8 = (0, _slicedToArray3['default'])(_parsePosition7, 3);

          chr2 = _parsePosition8[0];
          chrPos2 = _parsePosition8[1];
          genomePos2 = _parsePosition8[2];


          if (chr1 === null && chr2 !== null) {
            var _parsePosition9 = this.parsePosition(parts[1], chr2);
            // somembody entered a string like chr17:1000-2000
            // and when we try to search the rever, the first chromosome
            // is null
            // we have to pass in the previous chromosome as a prevChrom


            var _parsePosition10 = (0, _slicedToArray3['default'])(_parsePosition9, 3);

            chr1 = _parsePosition10[0];
            chrPos1 = _parsePosition10[1];
            genomePos1 = _parsePosition10[2];
          }

          var tempRange2 = [genomePos1, genomePos2];

          // return the wider of the two ranges
          // e.g. searching for chr1-chr2 vs chr2-chr1
          if (tempRange2[1] - tempRange2[0] > tempRange1[1] - tempRange1[0]) return tempRange2;
          return tempRange1;
        }
        // only a locus specified and no range
        // is the locus an entire chromosome?

        if (parts[0] in this.chromInfo.chrPositions) {
          var chromPosition = +this.chromInfo.chrPositions[parts[0]].pos;

          // if somebody has entered an entire chromosome, we return
          // it's length as the range
          range = [chromPosition, chromPosition + +this.chromInfo.chromLengths[parts[0]]];
        } else {
          // e.g. ("chr1:540340")
          var _parsePosition11 = this.parsePosition(parts[0]),
              _parsePosition12 = (0, _slicedToArray3['default'])(_parsePosition11, 3),
              _chr = _parsePosition12[0],
              _chrPos = _parsePosition12[1],
              pos1 = _parsePosition12[2];

          range = [pos1 - 8000000, pos1 + 8000000];
        }

        if (range[0] > range[1]) {
          return [range[1], range[0]];
        }

        return range;
      }

      return getSearchRange;
    }()
  }, {
    key: 'parseOffset',
    value: function () {
      function parseOffset(offsetText) {
        /**
         * Convert offset text to a 2D array of offsets
         *
         * @param offsetText(string): 14,17:20,22
         *
         * @return offsetArray: [[14,17],[20,22]]
         */

        var parts = offsetText.split(':');

        if (parts.length === 0) {
          return [[0, 0], [0, 0]];
        }

        if (parts.length === 1) {
          var sparts = parts[0].split(',');
          return [[+sparts[0], +sparts[1]], [0, 0]];
        }
        var sparts0 = parts[0].split(',');
        var sparts1 = parts[1].split(',');
        return [[+sparts0[0], +sparts0[1]], [+sparts1[0], +sparts1[1]]];
      }

      return parseOffset;
    }()
  }, {
    key: 'searchPosition',
    value: function () {
      function searchPosition(text) {
        var range1 = null;

        var range2 = null;
        text = text.trim(); // remove whitespace from the ends of the string

        // extract offset
        var offsetRe = /\[offset (.+?)\]/.exec(text);

        // the offset is the distance before the first chromosome
        // or the distance after the last chromosome of the given
        var offset = [[0, 0], [0, 0]];
        if (offsetRe) {
          text = text.replace(offsetRe[0], '');

          //
          offset = this.parseOffset(offsetRe[1]);
        }

        var parts = text.split(' & ');

        if (parts.length > 1) {
          // we need to move both axes
          // although it's possible that the first axis will be empty
          // i.e. someone enters " and p53"
          // in that case, we only move the second axis and keep the first where it is
          range1 = this.getSearchRange(parts[0].split(' ')[0]);
          range2 = this.getSearchRange(parts[1].split(' ')[0]);
        } else {
          // we just need to position the first axis
          range1 = this.getSearchRange(parts[0]);
        }

        if (range1 !== null && range2 !== null) {
          var _matchRangesToLarger = this.matchRangesToLarger(range1, range2);

          var _matchRangesToLarger2 = (0, _slicedToArray3['default'])(_matchRangesToLarger, 2);

          range1 = _matchRangesToLarger2[0];
          range2 = _matchRangesToLarger2[1];
        }

        if (range1) {
          range1[0] += offset[0][0];
          range1[1] += offset[0][1];
        }

        if (range2) {
          range2[0] += offset[1][0];
          range2[1] += offset[1][1];
        }

        return [range1, range2];
      }

      return searchPosition;
    }()
  }]);
  return SearchField;
}();

exports['default'] = SearchField;

/***/ }),
/* 141 */
/***/ (function(module, exports, __nested_webpack_require_834784__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_834784__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _toConsumableArray2 = __nested_webpack_require_834784__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _keys = __nested_webpack_require_834784__(18);

var _keys2 = _interopRequireDefault(_keys);

var _isNan = __nested_webpack_require_834784__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _set = __nested_webpack_require_834784__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_834784__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_834784__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_834784__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_834784__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_834784__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_834784__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _slugid = __nested_webpack_require_834784__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _PixiTrack2 = __nested_webpack_require_834784__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _services = __nested_webpack_require_834784__(24);

var _utils = __nested_webpack_require_834784__(10);

var _configs = __nested_webpack_require_834784__(11);

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

// Utils
var OSMTilesTrack = function (_PixiTrack) {
  (0, _inherits3['default'])(OSMTilesTrack, _PixiTrack);

  /**
   * A track that must pull remote tiles
   *
   * @param scene: A PIXI.js scene to draw everything to.
   * @param server: The server to pull tiles from.
   * @param tilesetUid: The data set to get the tiles from the server
   */
  function OSMTilesTrack(context, options) {
    (0, _classCallCheck3['default'])(this, OSMTilesTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (OSMTilesTrack.__proto__ || (0, _getPrototypeOf2['default'])(OSMTilesTrack)).call(this, context, options));

    var animate = context.animate;

    // Force OpenStreetMaps copyright
    // this.options.name = `© OpenStreetMap${options.name ? `\n${options.name}` : ''}`;

    // the tiles which should be visible (although they're not necessarily fetched)

    _this.visibleTiles = new _set2['default']();
    _this.visibleTileIds = new _set2['default']();

    // the tiles we already have requests out for
    _this.fetching = new _set2['default']();

    // tiles we have fetched and ready to be rendered
    _this.fetchedTiles = {};

    // the graphics that have already been drawn for this track
    _this.tileGraphics = {};

    _this.minX = typeof _this.options.minPos !== 'undefined' && !(0, _isNan2['default'])(+_this.options.minPos) ? +_this.options.minPos : -180;
    _this.maxX = +_this.options.maxPos || 180;

    _this.maxX = typeof _this.options.maxPos !== 'undefined' && !(0, _isNan2['default'])(+_this.options.maxPos) ? +_this.options.maxPos : 180;

    // HiGlass currently only supports squared tile sets but maybe in the
    // future...
    _this.minY = _this.options.minY || _this.minX;
    _this.maxY = _this.options.maxY || _this.maxX;

    _this.maxZoom = 19;
    _this.maxWidth = _this.maxX - _this.minX;
    _this.animate = animate;

    _this.uuid = _slugid2['default'].nice();
    _this.refreshTilesDebounced = (0, _utils.debounce)(_this.refreshTiles.bind(_this), _configs.ZOOM_DEBOUNCE);
    return _this;
  }

  /**
   * Return the set of ids of all tiles which are both visible and fetched.
   */


  (0, _createClass3['default'])(OSMTilesTrack, [{
    key: 'visibleAndFetchedIds',
    value: function () {
      function visibleAndFetchedIds() {
        var _this2 = this;

        return (0, _keys2['default'])(this.fetchedTiles).filter(function (x) {
          return _this2.visibleTileIds.has(x);
        });
      }

      return visibleAndFetchedIds;
    }()
  }, {
    key: 'visibleAndFetchedTiles',
    value: function () {
      function visibleAndFetchedTiles() {
        var _this3 = this;

        return this.visibleAndFetchedIds().map(function (x) {
          return _this3.fetchedTiles[x];
        });
      }

      return visibleAndFetchedTiles;
    }()

    /**
     * Set which tiles are visible right now.
     *
     * @param tiles: A set of tiles which will be considered the currently visible
     * tile positions.
     */

  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this4 = this;

        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this4.tileToLocalId(x),
            remoteId: _this4.tileToRemoteId(x),
            mirrored: x.mirrored
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.tileId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'removeAllTiles',
    value: function () {
      function removeAllTiles() {
        var fetchedTileIDs = new _set2['default']((0, _keys2['default'])(this.fetchedTiles));

        this.removeTiles([].concat((0, _toConsumableArray3['default'])(fetchedTileIDs)));
      }

      return removeAllTiles;
    }()
  }, {
    key: 'refreshTiles',
    value: function () {
      function refreshTiles() {
        var _this5 = this;

        this.calculateVisibleTiles();

        // tiles that are fetched
        var fetchedTileIDs = new _set2['default']((0, _keys2['default'])(this.fetchedTiles));

        // fetch the tiles that should be visible but haven't been fetched
        // and aren't in the process of being fetched
        var toFetch = [].concat((0, _toConsumableArray3['default'])(this.visibleTiles)).filter(function (x) {
          return !_this5.fetching.has(x.remoteId) && !fetchedTileIDs.has(x.tileId);
        });

        for (var i = 0; i < toFetch.length; i++) {
          this.fetching.add(toFetch[i].remoteId);
        }

        // calculate which tiles are obsolete and remove them
        // fetchedTileID are remote ids
        var toRemove = [].concat((0, _toConsumableArray3['default'])(fetchedTileIDs)).filter(function (x) {
          return !_this5.visibleTileIds.has(x);
        });

        this.removeTiles(toRemove);
        this.fetchNewTiles(toFetch);
      }

      return refreshTiles;
    }()

    /**
     * Remove obsolete tiles
     *
     * @param toRemoveIds: An array of tile ids to remove from the list of fetched tiles.
     */

  }, {
    key: 'removeTiles',
    value: function () {
      function removeTiles(toRemoveIds) {
        var _this6 = this;

        // if there's nothing to remove, don't bother doing anything
        if (!toRemoveIds.length) {
          return;
        }

        if (!this.areAllVisibleTilesLoaded()) {
          return;
        }

        toRemoveIds.forEach(function (x) {
          var tileIdStr = x;
          _this6.destroyTile(_this6.fetchedTiles[tileIdStr]);

          if (tileIdStr in _this6.tileGraphics) {
            _this6.pMain.removeChild(_this6.tileGraphics[tileIdStr]);
            delete _this6.tileGraphics[tileIdStr];
          }

          delete _this6.fetchedTiles[tileIdStr];
        });

        this.synchronizeTilesAndGraphics();
        this.draw();
      }

      return removeTiles;
    }()

    /*
     * The local tile identifier.
     * @param  {array}  tile  Contains `[zoomLevel, xPos, yPos]`.
     * @return  {string}  Remote ID string
     */

  }, {
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        // tile contains
        return tile.join('.');
      }

      return tileToLocalId;
    }()

    /**
     * The tile identifier used on the server.
     * @param   {array}  tile  Contains `[zoomLevel, xPos, yPos]`.
     * @return  {string}  Remote ID string
     */

  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        return tile.join('.');
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'localToRemoteId',
    value: function () {
      function localToRemoteId(remoteId) {
        var idParts = remoteId.split('.');
        return idParts.slice(0, idParts.length - 1).join('.');
      }

      return localToRemoteId;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.minX, this.maxX);
        var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.minY, this.maxY);

        var zoomLevel = Math.min(Math.max(xZoomLevel, yZoomLevel), this.maxZoom);

        if (this.options.maxZoom) {
          if (this.options.maxZoom >= 0) {
            zoomLevel = Math.min(this.options.maxZoom, zoomLevel);
          } else {
            console.error('Invalid maxZoom on track:', this);
          }
        }

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        // if we don't know anything about this dataset, no point
        // in trying to get tiles

        this.zoomLevel = this.calculateZoomLevel();

        this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._xScale, this.minX, this.maxX, this.maxZoom, this.maxWidth);

        this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._yScale, this.minY, this.maxY, this.maxZoom, this.maxWidth);

        var rows = this.xTiles;
        var cols = this.yTiles;
        var zoomLevel = this.zoomLevel;

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];
        // console.log('this.options:', this.options);

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < rows.length; i++) {
          for (var j = 0; j < cols.length; j++) {
            var newTile = [zoomLevel, rows[i], cols[j]];

            tiles.push(newTile);
          }
        }

        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, tx, ty) {
        (0, _get3['default'])(OSMTilesTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OSMTilesTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);

        this.xScale(newXScale);
        this.yScale(newYScale);

        this.pMain.position.x = tx; // translateX;
        this.pMain.position.y = ty; // translateY;

        this.pMain.scale.x = k; // scaleX;
        this.pMain.scale.y = k; // scaleY;

        this.refreshTilesDebounced();
        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(OSMTilesTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OSMTilesTrack.prototype), 'setPosition', this).call(this, newPosition);
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(OSMTilesTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OSMTilesTrack.prototype), 'setDimensions', this).call(this, newDimensions);
      }

      return setDimensions;
    }()

    /**
     * Check to see if all the visible tiles are loaded.
     *
     * If they are, remove all other tiles.
     */

  }, {
    key: 'areAllVisibleTilesLoaded',
    value: function () {
      function areAllVisibleTilesLoaded() {
        // tiles that are fetched
        var fetchedTileIDs = new _set2['default']((0, _keys2['default'])(this.fetchedTiles));

        var visibleTileIdsList = [].concat((0, _toConsumableArray3['default'])(this.visibleTileIds));

        for (var i = 0; i < visibleTileIdsList.length; i++) {
          if (!fetchedTileIDs.has(visibleTileIdsList[i])) {
            return false;
          }
        }

        return true;
      }

      return areAllVisibleTilesLoaded;
    }()

    /**
     * Function is called when all tiles that should be visible have
     * been received.
     */

  }, {
    key: 'allTilesLoaded',
    value: function () {
      function allTilesLoaded() {}

      return allTilesLoaded;
    }()
  }, {
    key: 'minValue',
    value: function () {
      function minValue(_) {
        if (_) {
          this.scale.minValue = _;
        }
        return this.scale.minValue;
      }

      return minValue;
    }()
  }, {
    key: 'maxValue',
    value: function () {
      function maxValue(_) {
        if (_) {
          this.scale.maxValue = _;
        }
        return this.scale.maxValue;
      }

      return maxValue;
    }()
  }, {
    key: 'minRawValue',
    value: function () {
      function minRawValue() {
        // this is the minimum value from all the tiles that
        // hasn't been externally modified by locked scales
        return this.scale.minRawValue;
      }

      return minRawValue;
    }()
  }, {
    key: 'maxRawValue',
    value: function () {
      function maxRawValue() {
        // this is the maximum value from all the tiles that
        // hasn't been externally modified by locked scales
        return this.scale.maxRawValue;
      }

      return maxRawValue;
    }()

    /**
     * Get the tile's position in its coordinate system.
     */

  }, {
    key: 'getTilePosAndDimensions',
    value: function () {
      function getTilePosAndDimensions(zoomLevel, tilePos) {
        var tileWidth = this.maxWidth / Math.pow(2, zoomLevel);
        var tileHeight = tileWidth;

        var tileX = this.minX + tilePos[0] * tileWidth;
        var tileY = this.minY + tilePos[1] * tileHeight;

        return {
          tileX: tileX,
          tileY: tileY,
          tileWidth: tileWidth,
          tileHeight: tileHeight
        };
      }

      return getTilePosAndDimensions;
    }()
  }, {
    key: 'setSpriteProperties',
    value: function () {
      function setSpriteProperties(sprite, zoomLevel, tilePos) {
        var _getTilePosAndDimensi = this.getTilePosAndDimensions(zoomLevel, tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileY = _getTilePosAndDimensi.tileY,
            tileWidth = _getTilePosAndDimensi.tileWidth,
            tileHeight = _getTilePosAndDimensi.tileHeight;

        sprite.x = this._refXScale(tileX);
        sprite.y = this._refYScale(tileY);

        var tileEndX = tileX + tileWidth;
        var tileEndY = tileY + tileHeight;

        sprite.width = this._refXScale(tileEndX) - this._refXScale(tileX);
        sprite.height = this._refYScale(tileEndY) - this._refYScale(tileY);
      }

      return setSpriteProperties;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        // create the tile
        // should be overwritten by child classes
        var texture = new _configs.GLOBALS.PIXI.Texture(new _configs.GLOBALS.PIXI.BaseTexture(tile.tileData.img));
        var sprite = new _configs.GLOBALS.PIXI.Sprite(texture);

        var graphics = tile.graphics;

        tile.sprite = sprite;

        this.setSpriteProperties(tile.sprite, tile.tileData.zoomLevel, tile.tileData.tilePos);

        graphics.removeChildren();
        graphics.addChild(tile.sprite);
      }

      return initTile;
    }()
  }, {
    key: 'updateTile',
    value: function () {
      function updateTile(tile) {
        // console.log("ERROR: unimplemented updateTile:", this);
      }

      return updateTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile) {}
      // remove all data structures needed to draw this tile


      /**
       * Add graphics for tiles that have no graphics
       */


      return destroyTile;
    }()
  }, {
    key: 'addMissingGraphics',
    value: function () {
      function addMissingGraphics() {
        var fetchedTileIDs = (0, _keys2['default'])(this.fetchedTiles);

        for (var i = 0; i < fetchedTileIDs.length; i++) {
          if (!(fetchedTileIDs[i] in this.tileGraphics)) {
            var newGraphics = new _configs.GLOBALS.PIXI.Graphics();
            this.pMain.addChild(newGraphics);

            this.fetchedTiles[fetchedTileIDs[i]].graphics = newGraphics;
            this.initTile(this.fetchedTiles[fetchedTileIDs[i]]);

            this.tileGraphics[fetchedTileIDs[i]] = newGraphics;
          }
        }
      }

      return addMissingGraphics;
    }()

    /**
     * Change the graphics for existing tiles
     */

  }, {
    key: 'updateExistingGraphics',
    value: function () {
      function updateExistingGraphics() {
        var fetchedTileIDs = (0, _keys2['default'])(this.fetchedTiles);

        for (var i = 0; i < fetchedTileIDs.length; i++) {
          this.updateTile(this.fetchedTiles[fetchedTileIDs[i]]);
        }
      }

      return updateExistingGraphics;
    }()

    /**
     * Make sure that we have a one to one mapping between tiles
     * and graphics objects
     */

  }, {
    key: 'synchronizeTilesAndGraphics',
    value: function () {
      function synchronizeTilesAndGraphics() {
        // keep track of which tiles are visible at the moment
        this.addMissingGraphics();
        this.updateExistingGraphics();
      }

      return synchronizeTilesAndGraphics;
    }()

    /**
     * Extract drawable data from a tile loaded by a generic tile loader
     *
     * @param tile: A tile returned by a TiledArea.
     * @param dataLoader: A function for extracting drawable data from a tile. This
     *                    usually means differentiating the between dense and sparse
     *                    tiles and putting the data into an array.
     */

  }, {
    key: 'loadTileData',
    value: function () {
      function loadTileData(tile, dataLoader) {
        // see if the data is already cached
        var loadedTileData = this.lruCache.get(tile.tileId);

        // if not, load it and put it in the cache
        if (!loadedTileData) {
          loadedTileData = dataLoader(tile.data, tile.type);
          this.lruCache.put(tile.tileId, loadedTileData);
        }

        return loadedTileData;
      }

      return loadTileData;
    }()

    /**
     * Get the url used to fetch the tile data
     */

  }, {
    key: 'getTileUrl',
    value: function () {
      function getTileUrl(tileZxy) {
        var serverPrefixes = ['a', 'b', 'c'];
        var serverPrefixIndex = Math.floor(Math.random() * serverPrefixes.length);
        var src = 'https://' + String(serverPrefixes[serverPrefixIndex]) + '.tile.openstreetmap.org/' + String(tileZxy[0]) + '/' + String(tileZxy[1]) + '/' + String(tileZxy[2]) + '.png';

        return src;
      }

      return getTileUrl;
    }()
  }, {
    key: 'fetchNewTiles',
    value: function () {
      function fetchNewTiles(toFetch) {
        var _this7 = this;

        if (toFetch.length > 0) {
          var toFetchList = [].concat((0, _toConsumableArray3['default'])(new _set2['default'](toFetch.map(function (x) {
            return x.remoteId;
          }))));

          var _loop = function () {
            function _loop(tileId) {
              var parts = tileId.split('.');
              var src = _this7.getTileUrl(parts);

              var img = new Image();
              img.crossOrigin = 'Anonymous';
              img.src = src;

              img.onload = function () {
                var loadedTiles = {};
                loadedTiles[tileId] = {
                  tileId: tileId,
                  img: img,
                  zoomLevel: +parts[0],
                  tilePos: [+parts[1], +parts[2]],
                  tileSrc: src
                };

                _this7.receivedTiles(loadedTiles);
              };
            }

            return _loop;
          }();

          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = undefined;

          try {
            for (var _iterator = (0, _getIterator3['default'])(toFetchList), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              var tileId = _step.value;

              _loop(tileId);
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator['return']) {
                _iterator['return']();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }
        }
      }

      return fetchNewTiles;
    }()

    /**
     * We've gotten a bunch of tiles from the server in
     * response to a request from fetchTiles.
     */

  }, {
    key: 'receivedTiles',
    value: function () {
      function receivedTiles(loadedTiles) {
        for (var i = 0; i < this.visibleTiles.length; i++) {
          var tileId = this.visibleTiles[i].tileId;

          if (!loadedTiles[this.visibleTiles[i].remoteId]) continue;

          if (this.visibleTiles[i].remoteId in loadedTiles) {
            if (!(tileId in this.fetchedTiles)) {
              // this tile may have graphics associated with it
              this.fetchedTiles[tileId] = this.visibleTiles[i];
            }

            this.fetchedTiles[tileId].tileData = loadedTiles[this.visibleTiles[i].remoteId];
          }
        }

        for (var key in loadedTiles) {
          if (loadedTiles[key]) {
            if (this.fetching.has(key)) {
              this.fetching['delete'](key);
            }
          }
        }

        this.synchronizeTilesAndGraphics();

        // Mainly called to remove old unnecessary tiles
        this.refreshTiles();

        // we need to draw when we receive new data
        this.draw();

        // Let HiGlass know we need to re-render
        this.animate();
      }

      return receivedTiles;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        if (this.delayDrawing) return;

        (0, _get3['default'])(OSMTilesTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OSMTilesTrack.prototype), 'draw', this).call(this);
      }

      return draw;
    }()

    /**
     * Draw a tile on some graphics
     */

  }, {
    key: 'drawTile',
    value: function () {
      function drawTile() {}

      return drawTile;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        (0, _get3['default'])(OSMTilesTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OSMTilesTrack.prototype), 'refScalesChanged', this).call(this, refXScale, refYScale);

        for (var uid in this.fetchedTiles) {
          var tile = this.fetchedTiles[uid];

          if (tile.sprite) {
            this.setSpriteProperties(tile.sprite, tile.tileData.zoomLevel, tile.tileData.tilePos);
          } else {
            // console.log('skipping...', tile.tileId);
          }
        }
      }

      return refScalesChanged;
    }()
  }]);
  return OSMTilesTrack;
}(_PixiTrack3['default']);

// Configs


// Services


exports['default'] = OSMTilesTrack;

/***/ }),
/* 142 */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  var type = typeof value;
  length = length == null ? MAX_SAFE_INTEGER : length;

  return !!length &&
    (type == 'number' ||
      (type != 'symbol' && reIsUint.test(value))) &&
        (value > -1 && value % 1 == 0 && value < length);
}

module.exports = isIndex;


/***/ }),
/* 143 */
/***/ (function(module, exports) {

/**
 * This method returns the first argument it receives.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Util
 * @param {*} value Any value.
 * @returns {*} Returns `value`.
 * @example
 *
 * var object = { 'a': 1 };
 *
 * console.log(_.identity(object) === object);
 * // => true
 */
function identity(value) {
  return value;
}

module.exports = identity;


/***/ }),
/* 144 */
/***/ (function(module, exports, __nested_webpack_require_859754__) {

var baseMatches = __nested_webpack_require_859754__(744),
    baseMatchesProperty = __nested_webpack_require_859754__(785),
    identity = __nested_webpack_require_859754__(143),
    isArray = __nested_webpack_require_859754__(31),
    property = __nested_webpack_require_859754__(794);

/**
 * The base implementation of `_.iteratee`.
 *
 * @private
 * @param {*} [value=_.identity] The value to convert to an iteratee.
 * @returns {Function} Returns the iteratee.
 */
function baseIteratee(value) {
  // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
  // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
  if (typeof value == 'function') {
    return value;
  }
  if (value == null) {
    return identity;
  }
  if (typeof value == 'object') {
    return isArray(value)
      ? baseMatchesProperty(value[0], value[1])
      : baseMatches(value);
  }
  return property(value);
}

module.exports = baseIteratee;


/***/ }),
/* 145 */
/***/ (function(module, exports, __nested_webpack_require_860727__) {

var isSymbol = __nested_webpack_require_860727__(194);

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/**
 * Converts `value` to a string key if it's not a string or symbol.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {string|symbol} Returns the key.
 */
function toKey(value) {
  if (typeof value == 'string' || isSymbol(value)) {
    return value;
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}

module.exports = toKey;


/***/ }),
/* 146 */
/***/ (function(module, exports, __nested_webpack_require_861332__) {

var baseForOwn = __nested_webpack_require_861332__(407),
    createBaseEach = __nested_webpack_require_861332__(798);

/**
 * The base implementation of `_.forEach` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 */
var baseEach = createBaseEach(baseForOwn);

module.exports = baseEach;


/***/ }),
/* 147 */
/***/ (function(module, exports, __nested_webpack_require_861862__) {

var arrayEach = __nested_webpack_require_861862__(286),
    baseEach = __nested_webpack_require_861862__(146),
    castFunction = __nested_webpack_require_861862__(411),
    isArray = __nested_webpack_require_861862__(31);

/**
 * Iterates over elements of `collection` and invokes `iteratee` for each element.
 * The iteratee is invoked with three arguments: (value, index|key, collection).
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * **Note:** As with other "Collections" methods, objects with a "length"
 * property are iterated like arrays. To avoid this behavior use `_.forIn`
 * or `_.forOwn` for object iteration.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @alias each
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Array|Object} Returns `collection`.
 * @see _.forEachRight
 * @example
 *
 * _.forEach([1, 2], function(value) {
 *   console.log(value);
 * });
 * // => Logs `1` then `2`.
 *
 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
 *   console.log(key);
 * });
 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
 */
function forEach(collection, iteratee) {
  var func = isArray(collection) ? arrayEach : baseEach;
  return func(collection, castFunction(iteratee));
}

module.exports = forEach;


/***/ }),
/* 148 */
/***/ (function(module, exports, __nested_webpack_require_863300__) {

var Parser = __nested_webpack_require_863300__(455);
var DomHandler = __nested_webpack_require_863300__(459);

function defineProp(name, value) {
    delete module.exports[name];
    module.exports[name] = value;
    return value;
}

module.exports = {
    Parser: Parser,
    Tokenizer: __nested_webpack_require_863300__(456),
    ElementType: __nested_webpack_require_863300__(123),
    DomHandler: DomHandler,
    get FeedHandler() {
        return defineProp("FeedHandler", __nested_webpack_require_863300__(958));
    },
    get Stream() {
        return defineProp("Stream", __nested_webpack_require_863300__(968));
    },
    get WritableStream() {
        return defineProp("WritableStream", __nested_webpack_require_863300__(461));
    },
    get ProxyHandler() {
        return defineProp("ProxyHandler", __nested_webpack_require_863300__(970));
    },
    get DomUtils() {
        return defineProp("DomUtils", __nested_webpack_require_863300__(101));
    },
    get CollectingHandler() {
        return defineProp(
            "CollectingHandler",
            __nested_webpack_require_863300__(971)
        );
    },
    // For legacy support
    DefaultHandler: DomHandler,
    get RssHandler() {
        return defineProp("RssHandler", this.FeedHandler);
    },
    //helper methods
    parseDOM: function(data, options) {
        var handler = new DomHandler(options);
        new Parser(handler, options).end(data);
        return handler.dom;
    },
    parseFeed: function(feed, options) {
        var handler = new module.exports.FeedHandler(options);
        new Parser(handler, options).end(feed);
        return handler.dom;
    },
    createDomStream: function(cb, options, elementCb) {
        var handler = new DomHandler(cb, options, elementCb);
        return new Parser(handler, options);
    },
    // List of all events that the parser emits
    EVENTS: {
        /* Format: eventname: number of arguments */
        attribute: 2,
        cdatastart: 0,
        cdataend: 0,
        text: 1,
        processinginstruction: 2,
        comment: 1,
        commentend: 0,
        closetag: 1,
        opentag: 2,
        opentagname: 1,
        error: 1,
        end: 0
    }
};


/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.REPLACEMENT_CHARACTER = '\uFFFD';

exports.CODE_POINTS = {
    EOF: -1,
    NULL: 0x00,
    TABULATION: 0x09,
    CARRIAGE_RETURN: 0x0D,
    LINE_FEED: 0x0A,
    FORM_FEED: 0x0C,
    SPACE: 0x20,
    EXCLAMATION_MARK: 0x21,
    QUOTATION_MARK: 0x22,
    NUMBER_SIGN: 0x23,
    AMPERSAND: 0x26,
    APOSTROPHE: 0x27,
    HYPHEN_MINUS: 0x2D,
    SOLIDUS: 0x2F,
    DIGIT_0: 0x30,
    DIGIT_9: 0x39,
    SEMICOLON: 0x3B,
    LESS_THAN_SIGN: 0x3C,
    EQUALS_SIGN: 0x3D,
    GREATER_THAN_SIGN: 0x3E,
    QUESTION_MARK: 0x3F,
    LATIN_CAPITAL_A: 0x41,
    LATIN_CAPITAL_F: 0x46,
    LATIN_CAPITAL_X: 0x58,
    LATIN_CAPITAL_Z: 0x5A,
    GRAVE_ACCENT: 0x60,
    LATIN_SMALL_A: 0x61,
    LATIN_SMALL_F: 0x66,
    LATIN_SMALL_X: 0x78,
    LATIN_SMALL_Z: 0x7A,
    REPLACEMENT_CHARACTER: 0xFFFD
};

exports.CODE_POINT_SEQUENCES = {
    DASH_DASH_STRING: [0x2D, 0x2D], //--
    DOCTYPE_STRING: [0x44, 0x4F, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE
    CDATA_START_STRING: [0x5B, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5B], //[CDATA[
    CDATA_END_STRING: [0x5D, 0x5D, 0x3E], //]]>
    SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script
    PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4C, 0x49, 0x43], //PUBLIC
    SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4D] //SYSTEM
};


/***/ }),
/* 150 */
/***/ (function(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; };


/***/ }),
/* 151 */
/***/ (function(module, exports, __nested_webpack_require_872289__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.

function isArray(arg) {
  if (Array.isArray) {
    return Array.isArray(arg);
  }
  return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;

function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;

function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;

function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;

function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;

function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;

function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;

function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;

function isRegExp(re) {
  return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;

function isDate(d) {
  return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;

function isError(e) {
  return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;

function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;

function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;

exports.isBuffer = Buffer.isBuffer;

function objectToString(o) {
  return Object.prototype.toString.call(o);
}

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_872289__(113).Buffer))

/***/ }),
/* 152 */
/***/ (function(module, exports, __nested_webpack_require_875509__) {

var parse = __nested_webpack_require_875509__(198),
    render = __nested_webpack_require_875509__(299),
    assign = __nested_webpack_require_875509__(472);

/**
 * HTML Tags
 */

var tags = { tag: true, script: true, style: true };

/**
 * Check if the DOM element is a tag
 *
 * isTag(type) includes <script> and <style> tags
 */

exports.isTag = function(type) {
  if (type.type) type = type.type;
  return tags[type] || false;
};

/**
 * Convert a string to camel case notation.
 * @param  {String} str String to be converted.
 * @return {String}     String in camel case notation.
 */

exports.camelCase = function(str) {
  return str.replace(/[_.-](\w|$)/g, function(_, x) {
    return x.toUpperCase();
  });
};

/**
 * Convert a string from camel case to "CSS case", where word boundaries are
 * described by hyphens ("-") and all characters are lower-case.
 * @param  {String} str String to be converted.
 * @return {string}     String in "CSS case".
 */
exports.cssCase = function(str) {
  return str.replace(/[A-Z]/g, '-$&').toLowerCase();
};

/**
 * Iterate over each DOM element without creating intermediary Cheerio instances.
 *
 * This is indented for use internally to avoid otherwise unnecessary memory pressure introduced
 * by _make.
 */

exports.domEach = function(cheerio, fn) {
  var i = 0, len = cheerio.length;
  while (i < len && fn.call(cheerio, i, cheerio[i]) !== false) ++i;
  return cheerio;
};

/**
 * Create a deep copy of the given DOM structure by first rendering it to a
 * string and then parsing the resultant markup.
 *
 * @argument {Object} dom - The htmlparser2-compliant DOM structure
 * @argument {Object} options - The parsing/rendering options
 */
exports.cloneDom = function(dom, options) {
  options = assign({}, options, { _useHtmlParser2: true });

  return parse(render(dom, options), options, false).children;
};

/*
 * A simple way to check for HTML strings or ID strings
 */

var quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;

/*
 * Check if string is HTML
 */
exports.isHtml = function(str) {
  // Faster than running regex, if str starts with `<` and ends with `>`, assume it's HTML
  if (str.charAt(0) === '<' && str.charAt(str.length - 1) === '>' && str.length >= 3) return true;

  // Run the regex
  var match = quickExpr.exec(str);
  return !!(match && match[1]);
};


/***/ }),
/* 153 */
/***/ (function(module, exports) {

module.exports = {
	trueFunc: function trueFunc(){
		return true;
	},
	falseFunc: function falseFunc(){
		return false;
	}
};

/***/ }),
/* 154 */
/***/ (function(module, exports, __nested_webpack_require_878065__) {

"use strict";


var define = __nested_webpack_require_878065__(52);
var bind = __nested_webpack_require_878065__(53);

var implementation = __nested_webpack_require_878065__(490);
var getPolyfill = __nested_webpack_require_878065__(500);
var polyfill = getPolyfill();
var shim = __nested_webpack_require_878065__(1058);

var boundFlat = bind.call(Function.call, polyfill);

define(boundFlat, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = boundFlat;


/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var fnToStr = Function.prototype.toString;

var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
	try {
		var fnStr = fnToStr.call(value);
		return constructorRegex.test(fnStr);
	} catch (e) {
		return false; // not a function
	}
};

var tryFunctionObject = function tryFunctionToStr(value) {
	try {
		if (isES6ClassFn(value)) { return false; }
		fnToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isCallable(value) {
	if (!value) { return false; }
	if (typeof value !== 'function' && typeof value !== 'object') { return false; }
	if (typeof value === 'function' && !value.prototype) { return true; }
	if (hasToStringTag) { return tryFunctionObject(value); }
	if (isES6ClassFn(value)) { return false; }
	var strClass = toStr.call(value);
	return strClass === fnClass || strClass === genClass;
};


/***/ }),
/* 156 */
/***/ (function(module, exports, __nested_webpack_require_879766__) {

"use strict";


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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.propsOfNode = propsOfNode;
exports.childrenOfNode = childrenOfNode;
exports.hasClassName = hasClassName;
exports.treeForEach = treeForEach;
exports.treeFilter = treeFilter;
exports.findParentNode = findParentNode;
exports.pathToNode = pathToNode;
exports.parentsOfNode = parentsOfNode;
exports.nodeHasId = nodeHasId;
exports.nodeMatchesObjectProps = nodeMatchesObjectProps;
exports.getTextFromNode = getTextFromNode;

var _object = __nested_webpack_require_879766__(122);

var _object2 = _interopRequireDefault(_object);

var _arrayPrototype = __nested_webpack_require_879766__(154);

var _arrayPrototype2 = _interopRequireDefault(_arrayPrototype);

var _object3 = __nested_webpack_require_879766__(502);

var _object4 = _interopRequireDefault(_object3);

var _isSubset = __nested_webpack_require_879766__(1063);

var _isSubset2 = _interopRequireDefault(_isSubset);

var _functionPrototype = __nested_webpack_require_879766__(314);

var _functionPrototype2 = _interopRequireDefault(_functionPrototype);

var _isRegex = __nested_webpack_require_879766__(499);

var _isRegex2 = _interopRequireDefault(_isRegex);

var _getAdapter = __nested_webpack_require_879766__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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); } }

function propsOfNode(node) {
  return node && node.props || {};
}

function childrenOfNode(node) {
  if (!node) return [];

  var adapter = (0, _getAdapter2['default'])();
  var adapterHasIsFragment = adapter.isFragment && typeof adapter.isFragment === 'function';

  var renderedArray = Array.isArray(node.rendered) ? (0, _arrayPrototype2['default'])(node.rendered, 1) : [node.rendered];

  // React adapters before 16 will not have isFragment
  if (!adapterHasIsFragment) {
    return renderedArray;
  }

  return (0, _arrayPrototype2['default'])(renderedArray.map(function (currentChild) {
    // If the node is a Fragment, we want to return its children, not the fragment itself
    if (adapter.isFragment(currentChild)) {
      return childrenOfNode(currentChild);
    }

    return currentChild;
  }), 1);
}

function hasClassName(node, className) {
  var classes = propsOfNode(node).className || '';
  classes = String(classes).replace(/\s/g, ' ');
  if ((0, _isRegex2['default'])(className)) return className.test(classes);
  return (' ' + String(classes) + ' ').indexOf(' ' + String(className) + ' ') > -1;
}

function treeForEach(tree, fn) {
  if (tree) {
    fn(tree);
  }
  childrenOfNode(tree).forEach(function (node) {
    return treeForEach(node, fn);
  });
}

function treeFilter(tree, fn) {
  var results = [];
  treeForEach(tree, function (node) {
    if (fn(node)) {
      results.push(node);
    }
  });
  return results;
}

/**
 * To support sibling selectors we need to be able to find
 * the siblings of a node. The easiest way to do that is find
 * the parent of the node and access its children.
 *
 * This would be unneeded if the RST spec included sibling pointers
 * such as node.nextSibling and node.prevSibling
 * @param {*} root
 * @param {*} targetNode
 */
function findParentNode(root, targetNode) {
  var results = treeFilter(root, function (node) {
    if (!node.rendered) {
      return false;
    }

    return childrenOfNode(node).indexOf(targetNode) !== -1;
  });
  return results[0] || null;
}

function pathFilter(path, fn) {
  return path.filter(function (tree) {
    return treeFilter(tree, fn).length !== 0;
  });
}

function pathToNode(node, root) {
  var queue = [root];
  var path = [];

  var hasNode = function hasNode(testNode) {
    return node === testNode;
  };

  while (queue.length) {
    var current = queue.pop();
    var children = childrenOfNode(current);
    if (current === node) return pathFilter(path, hasNode);

    path.push(current);

    if (children.length === 0) {
      // leaf node. if it isn't the node we are looking for, we pop.
      path.pop();
    }
    queue.push.apply(queue, _toConsumableArray(children));
  }

  return null;
}

function parentsOfNode(node, root) {
  return (pathToNode(node, root) || []).reverse();
}

function nodeHasId(node, id) {
  return propsOfNode(node).id === id;
}

var CAN_NEVER_MATCH = {};
function replaceUndefined(v) {
  return typeof v !== 'undefined' ? v : CAN_NEVER_MATCH;
}
function replaceUndefinedValues(obj) {
  return (0, _object4['default'])(obj).reduce(function (acc, _ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        k = _ref2[0],
        v = _ref2[1];

    return (0, _object2['default'])({}, acc, _defineProperty({}, k, replaceUndefined(v)));
  }, {});
}

function nodeMatchesObjectProps(node, props) {
  return (0, _isSubset2['default'])(propsOfNode(node), replaceUndefinedValues(props));
}

function getTextFromNode(node) {
  if (node == null) {
    return '';
  }

  if (typeof node === 'string' || typeof node === 'number') {
    return String(node);
  }

  if (node.type && typeof node.type === 'function') {
    return '<' + String(node.type.displayName || (0, _functionPrototype2['default'])(node.type)) + ' />';
  }

  return childrenOfNode(node).map(getTextFromNode).join('');
}

/***/ }),
/* 157 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_886067__) {

"use strict";
__nested_webpack_require_886067__.r(__webpack_exports__);

// EXTERNAL MODULE: ../node_modules/d3-dispatch/src/index.js + 1 modules
var src = __nested_webpack_require_886067__(65);

// EXTERNAL MODULE: ../node_modules/d3-drag/src/index.js + 5 modules
var d3_drag_src = __nested_webpack_require_886067__(84);

// EXTERNAL MODULE: ../node_modules/d3-interpolate/src/index.js + 24 modules
var d3_interpolate_src = __nested_webpack_require_886067__(15);

// EXTERNAL MODULE: ../node_modules/d3-selection/src/index.js + 50 modules
var d3_selection_src = __nested_webpack_require_886067__(0);

// EXTERNAL MODULE: ../node_modules/d3-transition/src/index.js + 41 modules
var d3_transition_src = __nested_webpack_require_886067__(85);

// CONCATENATED MODULE: ../node_modules/d3-zoom/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-zoom/src/event.js
function ZoomEvent(target, type, transform) {
  this.target = target;
  this.type = type;
  this.transform = transform;
}

// CONCATENATED MODULE: ../node_modules/d3-zoom/src/transform.js
function Transform(k, x, y) {
  this.k = k;
  this.x = x;
  this.y = y;
}

Transform.prototype = {
  constructor: Transform,
  scale: function(k) {
    return k === 1 ? this : new Transform(this.k * k, this.x, this.y);
  },
  translate: function(x, y) {
    return x === 0 & y === 0 ? this : new Transform(this.k, this.x + this.k * x, this.y + this.k * y);
  },
  apply: function(point) {
    return [point[0] * this.k + this.x, point[1] * this.k + this.y];
  },
  applyX: function(x) {
    return x * this.k + this.x;
  },
  applyY: function(y) {
    return y * this.k + this.y;
  },
  invert: function(location) {
    return [(location[0] - this.x) / this.k, (location[1] - this.y) / this.k];
  },
  invertX: function(x) {
    return (x - this.x) / this.k;
  },
  invertY: function(y) {
    return (y - this.y) / this.k;
  },
  rescaleX: function(x) {
    return x.copy().domain(x.range().map(this.invertX, this).map(x.invert, x));
  },
  rescaleY: function(y) {
    return y.copy().domain(y.range().map(this.invertY, this).map(y.invert, y));
  },
  toString: function() {
    return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
  }
};

var identity = new Transform(1, 0, 0);

transform_transform.prototype = Transform.prototype;

function transform_transform(node) {
  return node.__zoom || identity;
}

// CONCATENATED MODULE: ../node_modules/d3-zoom/src/noevent.js


function nopropagation() {
  d3_selection_src["event"].stopImmediatePropagation();
}

/* harmony default export */ var noevent = (function() {
  d3_selection_src["event"].preventDefault();
  d3_selection_src["event"].stopImmediatePropagation();
});

// CONCATENATED MODULE: ../node_modules/d3-zoom/src/zoom.js










// Ignore right-click, since that should open the context menu.
function defaultFilter() {
  return !d3_selection_src["event"].button;
}

function defaultExtent() {
  var e = this, w, h;
  if (e instanceof SVGElement) {
    e = e.ownerSVGElement || e;
    w = e.width.baseVal.value;
    h = e.height.baseVal.value;
  } else {
    w = e.clientWidth;
    h = e.clientHeight;
  }
  return [[0, 0], [w, h]];
}

function defaultTransform() {
  return this.__zoom || identity;
}

function defaultWheelDelta() {
  return -d3_selection_src["event"].deltaY * (d3_selection_src["event"].deltaMode ? 120 : 1) / 500;
}

function defaultTouchable() {
  return "ontouchstart" in this;
}

function defaultConstrain(transform, extent, translateExtent) {
  var dx0 = transform.invertX(extent[0][0]) - translateExtent[0][0],
      dx1 = transform.invertX(extent[1][0]) - translateExtent[1][0],
      dy0 = transform.invertY(extent[0][1]) - translateExtent[0][1],
      dy1 = transform.invertY(extent[1][1]) - translateExtent[1][1];
  return transform.translate(
    dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),
    dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)
  );
}

/* harmony default export */ var src_zoom = (function() {
  var filter = defaultFilter,
      extent = defaultExtent,
      constrain = defaultConstrain,
      wheelDelta = defaultWheelDelta,
      touchable = defaultTouchable,
      scaleExtent = [0, Infinity],
      translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]],
      duration = 250,
      interpolate = d3_interpolate_src["i" /* interpolateZoom */],
      gestures = [],
      listeners = Object(src["a" /* dispatch */])("start", "zoom", "end"),
      touchstarting,
      touchending,
      touchDelay = 500,
      wheelDelay = 150,
      clickDistance2 = 0;

  function zoom(selection) {
    selection
        .property("__zoom", defaultTransform)
        .on("wheel.zoom", wheeled)
        .on("mousedown.zoom", mousedowned)
        .on("dblclick.zoom", dblclicked)
      .filter(touchable)
        .on("touchstart.zoom", touchstarted)
        .on("touchmove.zoom", touchmoved)
        .on("touchend.zoom touchcancel.zoom", touchended)
        .style("touch-action", "none")
        .style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }

  zoom.transform = function(collection, transform) {
    var selection = collection.selection ? collection.selection() : collection;
    selection.property("__zoom", defaultTransform);
    if (collection !== selection) {
      schedule(collection, transform);
    } else {
      selection.interrupt().each(function() {
        gesture(this, arguments)
            .start()
            .zoom(null, typeof transform === "function" ? transform.apply(this, arguments) : transform)
            .end();
      });
    }
  };

  zoom.scaleBy = function(selection, k) {
    zoom.scaleTo(selection, function() {
      var k0 = this.__zoom.k,
          k1 = typeof k === "function" ? k.apply(this, arguments) : k;
      return k0 * k1;
    });
  };

  zoom.scaleTo = function(selection, k) {
    zoom.transform(selection, function() {
      var e = extent.apply(this, arguments),
          t0 = this.__zoom,
          p0 = centroid(e),
          p1 = t0.invert(p0),
          k1 = typeof k === "function" ? k.apply(this, arguments) : k;
      return constrain(translate(scale(t0, k1), p0, p1), e, translateExtent);
    });
  };

  zoom.translateBy = function(selection, x, y) {
    zoom.transform(selection, function() {
      return constrain(this.__zoom.translate(
        typeof x === "function" ? x.apply(this, arguments) : x,
        typeof y === "function" ? y.apply(this, arguments) : y
      ), extent.apply(this, arguments), translateExtent);
    });
  };

  zoom.translateTo = function(selection, x, y) {
    zoom.transform(selection, function() {
      var e = extent.apply(this, arguments),
          t = this.__zoom,
          p = centroid(e);
      return constrain(identity.translate(p[0], p[1]).scale(t.k).translate(
        typeof x === "function" ? -x.apply(this, arguments) : -x,
        typeof y === "function" ? -y.apply(this, arguments) : -y
      ), e, translateExtent);
    });
  };

  function scale(transform, k) {
    k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k));
    return k === transform.k ? transform : new Transform(k, transform.x, transform.y);
  }

  function translate(transform, p0, p1) {
    var x = p0[0] - p1[0] * transform.k, y = p0[1] - p1[1] * transform.k;
    return x === transform.x && y === transform.y ? transform : new Transform(transform.k, x, y);
  }

  function centroid(extent) {
    return [(+extent[0][0] + +extent[1][0]) / 2, (+extent[0][1] + +extent[1][1]) / 2];
  }

  function schedule(transition, transform, center) {
    transition
        .on("start.zoom", function() { gesture(this, arguments).start(); })
        .on("interrupt.zoom end.zoom", function() { gesture(this, arguments).end(); })
        .tween("zoom", function() {
          var that = this,
              args = arguments,
              g = gesture(that, args),
              e = extent.apply(that, args),
              p = center || centroid(e),
              w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]),
              a = that.__zoom,
              b = typeof transform === "function" ? transform.apply(that, args) : transform,
              i = interpolate(a.invert(p).concat(w / a.k), b.invert(p).concat(w / b.k));
          return function(t) {
            if (t === 1) t = b; // Avoid rounding error on end.
            else { var l = i(t), k = w / l[2]; t = new Transform(k, p[0] - l[0] * k, p[1] - l[1] * k); }
            g.zoom(null, t);
          };
        });
  }

  function gesture(that, args) {
    for (var i = 0, n = gestures.length, g; i < n; ++i) {
      if ((g = gestures[i]).that === that) {
        return g;
      }
    }
    return new Gesture(that, args);
  }

  function Gesture(that, args) {
    this.that = that;
    this.args = args;
    this.index = -1;
    this.active = 0;
    this.extent = extent.apply(that, args);
  }

  Gesture.prototype = {
    start: function() {
      if (++this.active === 1) {
        this.index = gestures.push(this) - 1;
        this.emit("start");
      }
      return this;
    },
    zoom: function(key, transform) {
      if (this.mouse && key !== "mouse") this.mouse[1] = transform.invert(this.mouse[0]);
      if (this.touch0 && key !== "touch") this.touch0[1] = transform.invert(this.touch0[0]);
      if (this.touch1 && key !== "touch") this.touch1[1] = transform.invert(this.touch1[0]);
      this.that.__zoom = transform;
      this.emit("zoom");
      return this;
    },
    end: function() {
      if (--this.active === 0) {
        gestures.splice(this.index, 1);
        this.index = -1;
        this.emit("end");
      }
      return this;
    },
    emit: function(type) {
      Object(d3_selection_src["customEvent"])(new ZoomEvent(zoom, type, this.that.__zoom), listeners.apply, listeners, [type, this.that, this.args]);
    }
  };

  function wheeled() {
    if (!filter.apply(this, arguments)) return;
    var g = gesture(this, arguments),
        t = this.__zoom,
        k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t.k * Math.pow(2, wheelDelta.apply(this, arguments)))),
        p = Object(d3_selection_src["mouse"])(this);

    // If the mouse is in the same location as before, reuse it.
    // If there were recent wheel events, reset the wheel idle timeout.
    if (g.wheel) {
      if (g.mouse[0][0] !== p[0] || g.mouse[0][1] !== p[1]) {
        g.mouse[1] = t.invert(g.mouse[0] = p);
      }
      clearTimeout(g.wheel);
    }

    // If this wheel event won’t trigger a transform change, ignore it.
    else if (t.k === k) return;

    // Otherwise, capture the mouse point and location at the start.
    else {
      g.mouse = [p, t.invert(p)];
      Object(d3_transition_src["interrupt"])(this);
      g.start();
    }

    noevent();
    g.wheel = setTimeout(wheelidled, wheelDelay);
    g.zoom("mouse", constrain(translate(scale(t, k), g.mouse[0], g.mouse[1]), g.extent, translateExtent));

    function wheelidled() {
      g.wheel = null;
      g.end();
    }
  }

  function mousedowned() {
    if (touchending || !filter.apply(this, arguments)) return;
    var g = gesture(this, arguments),
        v = Object(d3_selection_src["select"])(d3_selection_src["event"].view).on("mousemove.zoom", mousemoved, true).on("mouseup.zoom", mouseupped, true),
        p = Object(d3_selection_src["mouse"])(this),
        x0 = d3_selection_src["event"].clientX,
        y0 = d3_selection_src["event"].clientY;

    Object(d3_drag_src["dragDisable"])(d3_selection_src["event"].view);
    nopropagation();
    g.mouse = [p, this.__zoom.invert(p)];
    Object(d3_transition_src["interrupt"])(this);
    g.start();

    function mousemoved() {
      noevent();
      if (!g.moved) {
        var dx = d3_selection_src["event"].clientX - x0, dy = d3_selection_src["event"].clientY - y0;
        g.moved = dx * dx + dy * dy > clickDistance2;
      }
      g.zoom("mouse", constrain(translate(g.that.__zoom, g.mouse[0] = Object(d3_selection_src["mouse"])(g.that), g.mouse[1]), g.extent, translateExtent));
    }

    function mouseupped() {
      v.on("mousemove.zoom mouseup.zoom", null);
      Object(d3_drag_src["dragEnable"])(d3_selection_src["event"].view, g.moved);
      noevent();
      g.end();
    }
  }

  function dblclicked() {
    if (!filter.apply(this, arguments)) return;
    var t0 = this.__zoom,
        p0 = Object(d3_selection_src["mouse"])(this),
        p1 = t0.invert(p0),
        k1 = t0.k * (d3_selection_src["event"].shiftKey ? 0.5 : 2),
        t1 = constrain(translate(scale(t0, k1), p0, p1), extent.apply(this, arguments), translateExtent);

    noevent();
    if (duration > 0) Object(d3_selection_src["select"])(this).transition().duration(duration).call(schedule, t1, p0);
    else Object(d3_selection_src["select"])(this).call(zoom.transform, t1);
  }

  function touchstarted() {
    if (!filter.apply(this, arguments)) return;
    var g = gesture(this, arguments),
        touches = d3_selection_src["event"].changedTouches,
        started,
        n = touches.length, i, t, p;

    nopropagation();
    for (i = 0; i < n; ++i) {
      t = touches[i], p = Object(d3_selection_src["touch"])(this, touches, t.identifier);
      p = [p, this.__zoom.invert(p), t.identifier];
      if (!g.touch0) g.touch0 = p, started = true;
      else if (!g.touch1) g.touch1 = p;
    }

    // If this is a dbltap, reroute to the (optional) dblclick.zoom handler.
    if (touchstarting) {
      touchstarting = clearTimeout(touchstarting);
      if (!g.touch1) {
        g.end();
        p = Object(d3_selection_src["select"])(this).on("dblclick.zoom");
        if (p) p.apply(this, arguments);
        return;
      }
    }

    if (started) {
      touchstarting = setTimeout(function() { touchstarting = null; }, touchDelay);
      Object(d3_transition_src["interrupt"])(this);
      g.start();
    }
  }

  function touchmoved() {
    var g = gesture(this, arguments),
        touches = d3_selection_src["event"].changedTouches,
        n = touches.length, i, t, p, l;

    noevent();
    if (touchstarting) touchstarting = clearTimeout(touchstarting);
    for (i = 0; i < n; ++i) {
      t = touches[i], p = Object(d3_selection_src["touch"])(this, touches, t.identifier);
      if (g.touch0 && g.touch0[2] === t.identifier) g.touch0[0] = p;
      else if (g.touch1 && g.touch1[2] === t.identifier) g.touch1[0] = p;
    }
    t = g.that.__zoom;
    if (g.touch1) {
      var p0 = g.touch0[0], l0 = g.touch0[1],
          p1 = g.touch1[0], l1 = g.touch1[1],
          dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp,
          dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
      t = scale(t, Math.sqrt(dp / dl));
      p = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
      l = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
    }
    else if (g.touch0) p = g.touch0[0], l = g.touch0[1];
    else return;
    g.zoom("touch", constrain(translate(t, p, l), g.extent, translateExtent));
  }

  function touchended() {
    var g = gesture(this, arguments),
        touches = d3_selection_src["event"].changedTouches,
        n = touches.length, i, t;

    nopropagation();
    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() { touchending = null; }, touchDelay);
    for (i = 0; i < n; ++i) {
      t = touches[i];
      if (g.touch0 && g.touch0[2] === t.identifier) delete g.touch0;
      else if (g.touch1 && g.touch1[2] === t.identifier) delete g.touch1;
    }
    if (g.touch1 && !g.touch0) g.touch0 = g.touch1, delete g.touch1;
    if (g.touch0) g.touch0[1] = this.__zoom.invert(g.touch0[0]);
    else g.end();
  }

  zoom.wheelDelta = function(_) {
    return arguments.length ? (wheelDelta = typeof _ === "function" ? _ : constant(+_), zoom) : wheelDelta;
  };

  zoom.filter = function(_) {
    return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), zoom) : filter;
  };

  zoom.touchable = function(_) {
    return arguments.length ? (touchable = typeof _ === "function" ? _ : constant(!!_), zoom) : touchable;
  };

  zoom.extent = function(_) {
    return arguments.length ? (extent = typeof _ === "function" ? _ : constant([[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]]), zoom) : extent;
  };

  zoom.scaleExtent = function(_) {
    return arguments.length ? (scaleExtent[0] = +_[0], scaleExtent[1] = +_[1], zoom) : [scaleExtent[0], scaleExtent[1]];
  };

  zoom.translateExtent = function(_) {
    return arguments.length ? (translateExtent[0][0] = +_[0][0], translateExtent[1][0] = +_[1][0], translateExtent[0][1] = +_[0][1], translateExtent[1][1] = +_[1][1], zoom) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]];
  };

  zoom.constrain = function(_) {
    return arguments.length ? (constrain = _, zoom) : constrain;
  };

  zoom.duration = function(_) {
    return arguments.length ? (duration = +_, zoom) : duration;
  };

  zoom.interpolate = function(_) {
    return arguments.length ? (interpolate = _, zoom) : interpolate;
  };

  zoom.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? zoom : value;
  };

  zoom.clickDistance = function(_) {
    return arguments.length ? (clickDistance2 = (_ = +_) * _, zoom) : Math.sqrt(clickDistance2);
  };

  return zoom;
});

// CONCATENATED MODULE: ../node_modules/d3-zoom/src/index.js
/* concated harmony reexport zoom */__nested_webpack_require_886067__.d(__webpack_exports__, "zoom", function() { return src_zoom; });
/* concated harmony reexport zoomTransform */__nested_webpack_require_886067__.d(__webpack_exports__, "zoomTransform", function() { return transform_transform; });
/* concated harmony reexport zoomIdentity */__nested_webpack_require_886067__.d(__webpack_exports__, "zoomIdentity", function() { return identity; });




/***/ }),
/* 158 */
/***/ (function(module, exports, __nested_webpack_require_903943__) {

var has = __nested_webpack_require_903943__(47);
var toIObject = __nested_webpack_require_903943__(48);
var arrayIndexOf = __nested_webpack_require_903943__(210)(false);
var IE_PROTO = __nested_webpack_require_903943__(90)('IE_PROTO');

module.exports = function (object, names) {
  var O = toIObject(object);
  var i = 0;
  var result = [];
  var key;
  for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
  // Don't enum bug & hidden keys
  while (names.length > i) if (has(O, key = names[i++])) {
    ~arrayIndexOf(result, key) || result.push(key);
  }
  return result;
};


/***/ }),
/* 159 */
/***/ (function(module, exports, __nested_webpack_require_904559__) {

module.exports = !__nested_webpack_require_904559__(36) && !__nested_webpack_require_904559__(50)(function () {
  return Object.defineProperty(__nested_webpack_require_904559__(108)('div'), 'a', { get: function () { return 7; } }).a != 7;
});


/***/ }),
/* 160 */
/***/ (function(module, exports) {

module.exports = function (done, value) {
  return { value: value, done: !!done };
};


/***/ }),
/* 161 */
/***/ (function(module, exports, __nested_webpack_require_904983__) {

module.exports = __nested_webpack_require_904983__(43);


/***/ }),
/* 162 */
/***/ (function(module, exports, __nested_webpack_require_905104__) {

var dP = __nested_webpack_require_905104__(32);
var anObject = __nested_webpack_require_905104__(39);
var getKeys = __nested_webpack_require_905104__(60);

module.exports = __nested_webpack_require_905104__(36) ? Object.defineProperties : function defineProperties(O, Properties) {
  anObject(O);
  var keys = getKeys(Properties);
  var length = keys.length;
  var i = 0;
  var P;
  while (length > i) dP.f(O, P = keys[i++], Properties[P]);
  return O;
};


/***/ }),
/* 163 */
/***/ (function(module, exports, __nested_webpack_require_905583__) {

var document = __nested_webpack_require_905583__(23).document;
module.exports = document && document.documentElement;


/***/ }),
/* 164 */
/***/ (function(module, exports) {



/***/ }),
/* 165 */
/***/ (function(module, exports, __nested_webpack_require_905824__) {

// call something on iterator step with safe closing on error
var anObject = __nested_webpack_require_905824__(39);
module.exports = function (iterator, fn, value, entries) {
  try {
    return entries ? fn(anObject(value)[0], value[1]) : fn(value);
  // 7.4.6 IteratorClose(iterator, completion)
  } catch (e) {
    var ret = iterator['return'];
    if (ret !== undefined) anObject(ret.call(iterator));
    throw e;
  }
};


/***/ }),
/* 166 */
/***/ (function(module, exports, __nested_webpack_require_906313__) {

// check on default Array iterator
var Iterators = __nested_webpack_require_906313__(51);
var ITERATOR = __nested_webpack_require_906313__(21)('iterator');
var ArrayProto = Array.prototype;

module.exports = function (it) {
  return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};


/***/ }),
/* 167 */
/***/ (function(module, exports, __nested_webpack_require_906677__) {

var ITERATOR = __nested_webpack_require_906677__(21)('iterator');
var SAFE_CLOSING = false;

try {
  var riter = [7][ITERATOR]();
  riter['return'] = function () { SAFE_CLOSING = true; };
  // eslint-disable-next-line no-throw-literal
  Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }

module.exports = function (exec, skipClosing) {
  if (!skipClosing && !SAFE_CLOSING) return false;
  var safe = false;
  try {
    var arr = [7];
    var iter = arr[ITERATOR]();
    iter.next = function () { return { done: safe = true }; };
    arr[ITERATOR] = function () { return iter; };
    exec(arr);
  } catch (e) { /* empty */ }
  return safe;
};


/***/ }),
/* 168 */
/***/ (function(module, exports, __nested_webpack_require_907407__) {

exports.f = __nested_webpack_require_907407__(21);


/***/ }),
/* 169 */
/***/ (function(module, exports, __nested_webpack_require_907523__) {

"use strict";


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

var _getClassName2 = __nested_webpack_require_907523__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_907523__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_907523__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Button = __nested_webpack_require_907523__(170);

var _Button2 = _interopRequireDefault(_Button);

var _Cross = __nested_webpack_require_907523__(332);

var _Cross2 = _interopRequireDefault(_Cross);

var _Modal = __nested_webpack_require_907523__(574);

var _Modal2 = _interopRequireDefault(_Modal);

var _withModal = __nested_webpack_require_907523__(132);

var _withModal2 = _interopRequireDefault(_withModal);

__nested_webpack_require_907523__(576);

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

var _styleModuleImportMap = {
  '../styles/Dialog.module.scss': {
    'dialog-header': 'Dialog-module_dialog-header-2mk2M',
    'dialog-main-max-height': 'Dialog-module_dialog-main-max-height-1EAb2',
    'dialog-footer': 'Dialog-module_dialog-footer-1BnEv',
    'dialog-footer-max-height': 'Dialog-module_dialog-footer-max-height-KjDek'
  }
};


var Dialog = function Dialog(props) {
  var handleCancel = function handleCancel() {
    props.modal.close();
    if (props.onCancel) props.onCancel();
  };

  var handleOkay = function handleOkay() {
    props.modal.close();
    if (props.onOkay) props.onOkay();
  };

  return _react2['default'].createElement(
    _Modal2['default'],
    { closeButton: false, hide: props.hide, maxHeight: props.maxHeight },
    _react2['default'].createElement(
      'header',
      { className: 'Dialog-module_dialog-header-2mk2M' },
      _react2['default'].createElement(
        'h3',
        null,
        props.title
      ),
      _react2['default'].createElement(
        _Button2['default'],
        { onClick: handleCancel },
        _react2['default'].createElement(_Cross2['default'], null)
      )
    ),
    props.maxHeight ? _react2['default'].createElement(
      'main',
      {
        className: (0, _getClassName3['default'])(props.maxHeight ? 'dialog-main-max-height' : '', _styleModuleImportMap)
      },
      props.children
    ) : _react2['default'].createElement(
      'main',
      null,
      props.children
    ),
    _react2['default'].createElement(
      'footer',
      {
        className: (0, _getClassName3['default'])(props.maxHeight ? 'dialog-footer-max-height' : 'dialog-footer', _styleModuleImportMap)
      },
      props.okayOnly ? _react2['default'].createElement('div', null) : _react2['default'].createElement(
        _Button2['default'],
        { onClick: handleCancel, shortcut: props.cancelShortcut },
        props.cancelTitle
      ),
      _react2['default'].createElement(
        _Button2['default'],
        { onClick: handleOkay, shortcut: props.okayShortcut },
        props.okayTitle
      )
    )
  );
};

Dialog.defaultProps = {
  cancelTitle: 'Cancel',
  hide: false,
  maxHeight: false,
  okayOnly: false,
  okayTitle: 'Ok'
};

Dialog.propTypes = {
  cancelShortcut: _propTypes2['default'].string,
  cancelTitle: _propTypes2['default'].string,
  children: _propTypes2['default'].func.isRequired,
  hide: _propTypes2['default'].bool,
  maxHeight: _propTypes2['default'].bool,
  modal: _propTypes2['default'].object.isRequired,
  okayShortcut: _propTypes2['default'].string,
  okayTitle: _propTypes2['default'].string,
  okayOnly: _propTypes2['default'].bool,
  onCancel: _propTypes2['default'].func.isRequired,
  onOkay: _propTypes2['default'].func.isRequired,
  title: _propTypes2['default'].string.isRequired
};

exports['default'] = (0, _withModal2['default'])(Dialog);

/***/ }),
/* 170 */
/***/ (function(module, exports, __nested_webpack_require_911333__) {

"use strict";


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

var _react = __nested_webpack_require_911333__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_911333__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

__nested_webpack_require_911333__(572);

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

var Button = _react2['default'].forwardRef(function (props, ref) {
  return _react2['default'].createElement(
    'button',
    {
      ref: ref,
      disable: props.disable,
      onBlur: props.onBlur,
      onClick: props.onClick,
      onMouseDown: props.onMouseDown,
      onMouseOut: props.onMouseOut,
      onMouseUp: props.onMouseUp,
      className: 'Button-module_button-3YXsQ',
      type: 'button'
    },
    props.children,
    props.shortcut && _react2['default'].createElement(
      'span',
      { className: 'Button-module_button-shortcut-1zMAn' },
      props.shortcut
    )
  );
});

Button.defaultProps = {
  onClick: function () {
    function onClick() {}

    return onClick;
  }(),
  styleName: '',
  type: 'button'
};

Button.propTypes = {
  children: _propTypes2['default'].func.isRequired,
  disable: _propTypes2['default'].func.isRequired,
  onBlur: _propTypes2['default'].func,
  onClick: _propTypes2['default'].func,
  onMouseDown: _propTypes2['default'].func,
  onMouseOut: _propTypes2['default'].func,
  onMouseUp: _propTypes2['default'].func,
  shortcut: _propTypes2['default'].string,
  type: _propTypes2['default'].string
};

exports['default'] = Button;

/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


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

exports["default"] = toVoid;

/***/ }),
/* 172 */
/***/ (function(module, exports, __nested_webpack_require_913216__) {

/* WEBPACK VAR INJECTION */(function(global, module) {/**
 * Lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright JS Foundation and other contributors <https://js.foundation/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    asyncTag = '[object AsyncFunction]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    nullTag = '[object Null]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    proxyTag = '[object Proxy]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]',
    undefinedTag = '[object Undefined]',
    weakMapTag = '[object WeakMap]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

/** Detect free variable `exports`. */
var freeExports =   true && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;

/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
  try {
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}());

/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;

/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}

/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}

/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}

/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);

  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}

/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}

/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);

  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}

/** Used for built-in method references. */
var arrayProto = Array.prototype,
    funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
    Symbol = root.Symbol,
    Uint8Array = root.Uint8Array,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    splice = arrayProto.splice,
    symToStringTag = Symbol ? Symbol.toStringTag : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols,
    nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
    nativeKeys = overArg(Object.keys, Object);

/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
    Map = getNative(root, 'Map'),
    Promise = getNative(root, 'Promise'),
    Set = getNative(root, 'Set'),
    WeakMap = getNative(root, 'WeakMap'),
    nativeCreate = getNative(Object, 'create');

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
    mapCtorString = toSource(Map),
    promiseCtorString = toSource(Promise),
    setCtorString = toSource(Set),
    weakMapCtorString = toSource(WeakMap);

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
  this.size = 0;
}

/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  return this;
}

// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;

/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}

/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  return index < 0 ? undefined : data[index][1];
}

/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}

/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}

// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;

/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new Hash,
    'map': new (Map || ListCache),
    'string': new Hash
  };
}

/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  var result = getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}

/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}

/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  var data = getMapData(this, key),
      size = data.size;

  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;

/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;

  this.__data__ = new MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED);
  return this;
}

/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}

// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;

/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  var data = this.__data__ = new ListCache(entries);
  this.size = data.size;
}

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache;
  this.size = 0;
}

/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);

  this.size = data.size;
  return result;
}

/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache) {
    var pairs = data.__data__;
    if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}

// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  var isArr = isArray(value),
      isArg = !isArr && isArguments(value),
      isBuff = !isArr && !isArg && isBuffer(value),
      isType = !isArr && !isArg && !isBuff && isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (
           // Safari 9 has enumerable `arguments.length` in strict mode.
           key == 'length' ||
           // Node.js 0.10 has enumerable non-index properties on buffers.
           (isBuff && (key == 'offset' || key == 'parent')) ||
           // PhantomJS 2 has enumerable non-index properties on typed arrays.
           (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
           // Skip index properties.
           isIndex(key, length)
        ))) {
      result.push(key);
    }
  }
  return result;
}

/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}

/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}

/**
 * The base implementation of `getTag` without fallbacks for buggy environments.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
function baseGetTag(value) {
  if (value == null) {
    return value === undefined ? undefinedTag : nullTag;
  }
  return (symToStringTag && symToStringTag in Object(value))
    ? getRawTag(value)
    : objectToString(value);
}

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments(value) {
  return isObjectLike(value) && baseGetTag(value) == argsTag;
}

/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
    return value !== value && other !== other;
  }
  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = isArray(object),
      othIsArr = isArray(other),
      objTag = objIsArr ? arrayTag : getTag(object),
      othTag = othIsArr ? arrayTag : getTag(other);

  objTag = objTag == argsTag ? objectTag : objTag;
  othTag = othTag == argsTag ? objectTag : othTag;

  var objIsObj = objTag == objectTag,
      othIsObj = othTag == objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && isBuffer(object)) {
    if (!isBuffer(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new Stack);
    return (objIsArr || isTypedArray(object))
      ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
      : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;

      stack || (stack = new Stack);
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new Stack);
  return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray(value) {
  return isObjectLike(value) &&
    isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!isPrototype(object)) {
    return nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(array);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  var index = -1,
      result = true,
      seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;

  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, arrValue, index, other, array, stack)
        : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!arraySome(other, function(othValue, othIndex) {
            if (!cacheHas(seen, othIndex) &&
                (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
        result = false;
        break;
      }
    } else if (!(
          arrValue === othValue ||
            equalFunc(arrValue, othValue, bitmask, customizer, stack)
        )) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case dataViewTag:
      if ((object.byteLength != other.byteLength) ||
          (object.byteOffset != other.byteOffset)) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;

    case arrayBufferTag:
      if ((object.byteLength != other.byteLength) ||
          !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
        return false;
      }
      return true;

    case boolTag:
    case dateTag:
    case numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return eq(+object, +other);

    case errorTag:
      return object.name == other.name && object.message == other.message;

    case regexpTag:
    case stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == (other + '');

    case mapTag:
      var convert = mapToArray;

    case setTag:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
      convert || (convert = setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= COMPARE_UNORDERED_FLAG;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case symbolTag:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }
  }
  return false;
}

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      objProps = getAllKeys(object),
      objLength = objProps.length,
      othProps = getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
      return false;
    }
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(object);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);

  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, objValue, key, other, object, stack)
        : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined
          ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
          : compared
        )) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor &&
        ('constructor' in object && 'constructor' in other) &&
        !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
          typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}

/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return baseGetAllKeys(object, keys, getSymbols);
}

/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}

/**
 * Gets the native function at `key` of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the method to get.
 * @returns {*} Returns the function if it's native, else `undefined`.
 */
function getNative(object, key) {
  var value = getValue(object, key);
  return baseIsNative(value) ? value : undefined;
}

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag(value) {
  var isOwn = hasOwnProperty.call(value, symToStringTag),
      tag = value[symToStringTag];

  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter(nativeGetSymbols(object), function(symbol) {
    return propertyIsEnumerable.call(object, symbol);
  });
};

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
    (Map && getTag(new Map) != mapTag) ||
    (Promise && getTag(Promise.resolve()) != promiseTag) ||
    (Set && getTag(new Set) != setTag) ||
    (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  getTag = function(value) {
    var result = baseGetTag(value),
        Ctor = result == objectTag ? value.constructor : undefined,
        ctorString = Ctor ? toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString: return dataViewTag;
        case mapCtorString: return mapTag;
        case promiseCtorString: return promiseTag;
        case setCtorString: return setTag;
        case weakMapCtorString: return weakMapTag;
      }
    }
    return result;
  };
}

/**
 * Checks if `value` is a valid array-like index.
 *
 * @private
 * @param {*} value The value to check.
 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
 */
function isIndex(value, length) {
  length = length == null ? MAX_SAFE_INTEGER : length;
  return !!length &&
    (typeof value == 'number' || reIsUint.test(value)) &&
    (value > -1 && value % 1 == 0 && value < length);
}

/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;

  return value === proto;
}

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString(value) {
  return nativeObjectToString.call(value);
}

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}

/**
 * Performs a
 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * comparison between two values to determine if they are equivalent.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.eq(object, object);
 * // => true
 *
 * _.eq(object, other);
 * // => false
 *
 * _.eq('a', 'a');
 * // => true
 *
 * _.eq('a', Object('a'));
 * // => false
 *
 * _.eq(NaN, NaN);
 * // => true
 */
function eq(value, other) {
  return value === other || (value !== value && other !== other);
}

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
    !propertyIsEnumerable.call(value, 'callee');
};

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || stubFalse;

/**
 * Performs a deep comparison between two values to determine if they are
 * equivalent.
 *
 * **Note:** This method supports comparing arrays, array buffers, booleans,
 * date objects, error objects, maps, numbers, `Object` objects, regexes,
 * sets, strings, symbols, and typed arrays. `Object` objects are compared
 * by their own, not inherited, enumerable properties. Functions and DOM
 * nodes are compared by strict equality, i.e. `===`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 * @example
 *
 * var object = { 'a': 1 };
 * var other = { 'a': 1 };
 *
 * _.isEqual(object, other);
 * // => true
 *
 * object === other;
 * // => false
 */
function isEqual(value, other) {
  return baseIsEqual(value, other);
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  if (!isObject(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return value != null && (type == 'object' || type == 'function');
}

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return value != null && typeof value == 'object';
}

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;

/**
 * Creates an array of the own enumerable property names of `object`.
 *
 * **Note:** Non-object values are coerced to objects. See the
 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * for more details.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.keys(new Foo);
 * // => ['a', 'b'] (iteration order is not guaranteed)
 *
 * _.keys('hi');
 * // => ['0', '1']
 */
function keys(object) {
  return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}

/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

module.exports = isEqual;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_913216__(27), __nested_webpack_require_913216__(173)(module)))

/***/ }),
/* 173 */
/***/ (function(module, exports) {

module.exports = function(module) {
	if (!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if (!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),
/* 174 */
/***/ (function(module, exports, __nested_webpack_require_963581__) {

"use strict";


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

var _assign = __nested_webpack_require_963581__(44);

var _assign2 = _interopRequireDefault(_assign);

var _keys = __nested_webpack_require_963581__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getClassName2 = __nested_webpack_require_963581__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_963581__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_963581__(1);

var _react2 = _interopRequireDefault(_react);

var _reactSortableHoc = __nested_webpack_require_963581__(125);

var _withTheme = __nested_webpack_require_963581__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _configs = __nested_webpack_require_963581__(11);

__nested_webpack_require_963581__(608);

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

var _styleModuleImportMap = {
  '../styles/TrackControl.module.scss': {
    'track-control': 'TrackControl-module_track-control-2zDf3',
    'track-control-vertical': 'TrackControl-module_track-control-vertical-2McB_',
    'track-control-dark': 'TrackControl-module_track-control-dark-fP2uZ',
    'track-control-active': 'TrackControl-module_track-control-active-2JD9i TrackControl-module_track-control-2zDf3',
    'track-control-left': 'TrackControl-module_track-control-left-zHd9W',
    'track-control-vertical-active': 'TrackControl-module_track-control-vertical-active-1QCKn',
    'track-control-padding-right': 'TrackControl-module_track-control-padding-right-2p6Lp',
    'track-control-button': 'TrackControl-module_track-control-button-2fdIb',
    'track-control-button-vertical': 'TrackControl-module_track-control-button-vertical-1s22z'
  }
};

// Styles

var getClassNames = function getClassNames(props) {
  var className = props.isVisible ? 'track-control-active' : 'track-control';

  className += props.isAlignLeft ? ' track-control-left' : '';

  className += props.isVertical ? ' track-control-vertical' : '';

  className += props.paddingRight ? ' track-control-padding-right' : '';

  if (props.theme === _configs.THEME_DARK) className += ' track-control-dark';

  return className;
};

var getButtonClassNames = function getButtonClassNames(props) {
  var buttonClassName = 'track-control-button';

  buttonClassName += props.isVertical ? ' track-control-button-vertical' : '';

  return buttonClassName;
};

var oldProps = null;
var DragHandle = null;

var TrackControl = function TrackControl(props) {
  // Avoid constant recreating that button when the props didn't change.
  // Damn React could be a little smarter here...
  if (!props || !oldProps || (0, _keys2['default'])(props).some(function (key) {
    return oldProps[key] !== props[key];
  })) {
    oldProps = props;
    DragHandle = (0, _reactSortableHoc.SortableHandle)(function () {
      return _react2['default'].createElement(
        'svg',
        {
          style: (0, _assign2['default'])({ height: '20px', width: '20px' }, props.imgStyleMove),
          className: 'no-zoom ' + (0, _getClassName3['default'])(getButtonClassNames(props), _styleModuleImportMap)
        },
        _react2['default'].createElement(
          'title',
          null,
          'Move track'
        ),
        _react2['default'].createElement('use', { xlinkHref: '#move' })
      );
    });
  }

  var imgConfig = void 0;
  var imgClose = void 0;

  return _react2['default'].createElement(
    'div',
    {
      className: (0, _getClassName3['default'])(getClassNames(props), _styleModuleImportMap)
    },
    props.isMoveable && _react2['default'].createElement(DragHandle, null),
    _react2['default'].createElement(
      'svg',
      {
        ref: function () {
          function ref(c) {
            imgConfig = c;
          }

          return ref;
        }(),

        onClick: function () {
          function onClick() {
            props.onConfigTrackMenuOpened(props.uid, imgConfig.getBoundingClientRect());
          }

          return onClick;
        }(),
        style: (0, _assign2['default'])({ height: '20px', width: '20px' }, props.imgStyleSettings),
        className: 'no-zoom ' + (0, _getClassName3['default'])(getButtonClassNames(props), _styleModuleImportMap)
      },
      _react2['default'].createElement(
        'title',
        null,
        'Configure track'
      ),
      _react2['default'].createElement('use', { xlinkHref: '#cog' })
    ),
    props.onAddSeries && _react2['default'].createElement(
      'svg',
      {
        onClick: function () {
          function onClick() {
            return props.onAddSeries(props.uid);
          }

          return onClick;
        }(),
        style: (0, _assign2['default'])({ height: '20px', width: '20px' }, props.imgStyleAdd),
        className: 'no-zoom ' + (0, _getClassName3['default'])(getButtonClassNames(props), _styleModuleImportMap)
      },
      _react2['default'].createElement(
        'title',
        null,
        'Add series'
      ),
      _react2['default'].createElement('use', { xlinkHref: '#plus' })
    ),
    _react2['default'].createElement(
      'svg',
      {
        ref: function () {
          function ref(c) {
            imgClose = c;
          }

          return ref;
        }(),

        onClick: function () {
          function onClick() {
            props.onCloseTrackMenuOpened(props.uid, imgClose.getBoundingClientRect());
          }

          return onClick;
        }(),
        style: (0, _assign2['default'])({ height: '20px', width: '20px' }, props.imgStyleClose),
        className: 'no-zoom ' + (0, _getClassName3['default'])(getButtonClassNames(props), _styleModuleImportMap)
      },
      _react2['default'].createElement(
        'title',
        null,
        'Close track'
      ),
      _react2['default'].createElement('use', { xlinkHref: '#cross' })
    )
  );
};

TrackControl.propTypes = {
  imgStyleAdd: _propTypes2['default'].object,
  imgStyleClose: _propTypes2['default'].object,
  imgStyleMove: _propTypes2['default'].object,
  imgStyleSettings: _propTypes2['default'].object,
  isAlignLeft: _propTypes2['default'].bool,
  isMoveable: _propTypes2['default'].bool,
  isVertical: _propTypes2['default'].bool,
  isVisible: _propTypes2['default'].bool,
  onConfigTrackMenuOpened: _propTypes2['default'].func,
  onCloseTrackMenuOpened: _propTypes2['default'].func,
  onAddSeries: _propTypes2['default'].func,
  paddingRight: _propTypes2['default'].bool,
  theme: _propTypes2['default'].symbol.isRequired,
  uid: _propTypes2['default'].string
};

exports['default'] = (0, _withTheme2['default'])(TrackControl);

/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"track-range-selection":"Track-module_track-range-selection-1yrDf","track-range-selection-active":"Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf","track-range-selection-active-primary":"Track-module_track-range-selection-active-primary-29M73 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf","track-range-selection-active-secondary":"Track-module_track-range-selection-active-secondary-1s0t5 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf","track-range-selection-group-inactive":"Track-module_track-range-selection-group-inactive-YNRM4","track-range-selection-group-brush-selection":"Track-module_track-range-selection-group-brush-selection-2VYDl"};

/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"tiled-plot":"TiledPlot-module_tiled-plot-uFHiB","horizontalList":"TiledPlot-module_horizontalList-1c1P8","list":"TiledPlot-module_list-24zgV","stylizedList":"TiledPlot-module_stylizedList-Mt4JL","stylizedItem":"TiledPlot-module_stylizedItem-2bQBK","stylizedHelper":"TiledPlot-module_stylizedHelper-3IVEu","horizontalItem":"TiledPlot-module_horizontalItem-2-ZjU","resizable-track":"TiledPlot-module_resizable-track-2oLT9","domain":"TiledPlot-module_domain-qYw6K"};

/***/ }),
/* 177 */
/***/ (function(module, exports, __nested_webpack_require_971770__) {

"use strict";


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

var _classCallCheck2 = __nested_webpack_require_971770__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_971770__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _d3Scale = __nested_webpack_require_971770__(28);

var _withPubSub = __nested_webpack_require_971770__(69);

var _utils = __nested_webpack_require_971770__(10);

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

var Track = function () {
  function Track(_ref) {
    var id = _ref.id,
        pubSub = _ref.pubSub,
        getTheme = _ref.getTheme;
    (0, _classCallCheck3['default'])(this, Track);

    if (pubSub) {
      this.pubSub = pubSub;
    } else {
      this.pubSub = _withPubSub.fake;
    }

    this.id = id;
    this._xScale = (0, _d3Scale.scaleLinear)();
    this._yScale = (0, _d3Scale.scaleLinear)();

    // reference scales used for tracks that can translate and scale
    // their graphics
    // They will draw their graphics on the reference scales and then translate
    // and pan them as needed
    this._refXScale = (0, _d3Scale.scaleLinear)();
    this._refYScale = (0, _d3Scale.scaleLinear)();

    this.position = [0, 0];
    this.dimensions = [1, 1];
    this.options = {};
    this.pubSubs = [];

    if (getTheme) {
      this.getTheme = getTheme;
    } else {
      this.getTheme = function () {};
    }

    this.pubSubs.push(this.pubSub.subscribe('app.mouseMove', this.defaultMouseMoveHandler.bind(this)));
  }

  /**
   * Check if a 2d location (x, y) is within the bounds of this track.
   *
   * @param {Number}  x  X position to be tested.
   * @param {Number}  y  Y position to be tested.
   * @return {Boolean}  If `true` location is within the track.
   */


  (0, _createClass3['default'])(Track, [{
    key: 'isWithin',
    value: function () {
      function isWithin(x, y) {
        var xx = x;
        var yy = y;
        var left = this.position[0];
        var top = this.position[1];

        if (this.isLeftModified) {
          xx = y;
          yy = x;
          left = this.position[1];
          top = this.position[0];
        }

        return (0, _utils.isWithin)(xx, yy, left, this.dimensions[0] + left, top, this.dimensions[1] + top);
      }

      return isWithin;
    }()
  }, {
    key: 'getProp',
    value: function () {
      function getProp(prop) {
        var _this = this;

        return function () {
          return _this[prop];
        };
      }

      return getProp;
    }()
  }, {
    key: 'getData',
    value: function () {
      function getData() {}

      return getData;
    }()
  }, {
    key: 'getDimensions',
    value: function () {
      function getDimensions() {
        return this.dimensions;
      }

      return getDimensions;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        this.dimensions = newDimensions;

        this._xScale.range([0, this.dimensions[0]]);
        this._yScale.range([0, this.dimensions[1]]);
      }

      return setDimensions;
    }()

    /**
     * Either get or set the reference xScale
     */

  }, {
    key: 'refXScale',
    value: function () {
      function refXScale(_) {
        if (!arguments.length) return this._refXScale;

        this._refXScale = _;

        return this;
      }

      return refXScale;
    }()

    /**
     * Either get or set the reference yScale
     */

  }, {
    key: 'refYScale',
    value: function () {
      function refYScale(_) {
        if (!arguments.length) return this._refYScale;

        this._refYScale = _;

        return this;
      }

      return refYScale;
    }()

    /**
     * Either get or set the xScale
     */

  }, {
    key: 'xScale',
    value: function () {
      function xScale(_) {
        if (!arguments.length) return this._xScale;

        this._xScale = _;

        return this;
      }

      return xScale;
    }()

    /**
     * Either get or set the yScale
     */

  }, {
    key: 'yScale',
    value: function () {
      function yScale(_) {
        if (!arguments.length) {
          return this._yScale;
        }

        this._yScale = _;

        return this;
      }

      return yScale;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);
      }

      return zoomed;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        this._refXScale = refXScale;
        this._refYScale = refYScale;
      }

      return refScalesChanged;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {}

      return draw;
    }()
  }, {
    key: 'getPosition',
    value: function () {
      function getPosition() {
        return this.position;
      }

      return getPosition;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        this.position = newPosition;
      }

      return setPosition;
    }()

    /*
     * A blank handler for MouseMove / Zoom events. Should be overriden
     * by individual tracks to provide
     *
     * @param {obj} evt:
     *
     * @returns nothing
     */

  }, {
    key: 'defaultMouseMoveHandler',
    value: function () {
      function defaultMouseMoveHandler(evt) {}

      return defaultMouseMoveHandler;
    }()
  }, {
    key: 'remove',
    value: function () {
      function remove() {
        var _this2 = this;

        // Clear all pubSub subscriptions
        this.pubSubs.forEach(function (subscription) {
          return _this2.pubSub.unsubscribe(subscription);
        });
        this.pubSubs = [];
      }

      return remove;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender() {}

      return rerender;
    }()

    /*
     * This function is for seeing whether this track should respond
     * to events at this mouse position. The difference to `isWithin()` is that it
     * can be overwritten if a track is inactive for example.
     */

  }, {
    key: 'respondsToPosition',
    value: function () {
      function respondsToPosition(x, y) {
        return this.isWithin(x, y);
      }

      return respondsToPosition;
    }()
  }, {
    key: 'zoomedY',
    value: function () {
      function zoomedY(trackY, kMultiplier) {}

      return zoomedY;
    }()
  }, {
    key: 'movedY',
    value: function () {
      function movedY(dY) {}

      return movedY;
    }()
  }]);
  return Track;
}();

// Services


exports['default'] = Track;

/***/ }),
/* 178 */
/***/ (function(module, exports, __nested_webpack_require_978562__) {

// 20.1.2.3 Number.isInteger(number)
var isObject = __nested_webpack_require_978562__(33);
var floor = Math.floor;
module.exports = function isInteger(it) {
  return !isObject(it) && isFinite(it) && floor(it) === it;
};


/***/ }),
/* 179 */
/***/ (function(module, exports, __nested_webpack_require_978847__) {

"use strict";


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

var _classCallCheck2 = __nested_webpack_require_978847__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_978847__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _d3Format = __nested_webpack_require_978847__(20);

var _configs = __nested_webpack_require_978847__(11);

var _utils = __nested_webpack_require_978847__(10);

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

// Configs
var TICK_HEIGHT = 40;
var TICK_MARGIN = 0;
var TICK_LENGTH = 5;
var TICK_LABEL_MARGIN = 4;

var AxisPixi = function () {
  function AxisPixi(track) {
    (0, _classCallCheck3['default'])(this, AxisPixi);

    this.pAxis = new _configs.GLOBALS.PIXI.Graphics();
    this.track = track;

    this.axisTexts = [];
    this.axisTextFontFamily = 'Arial';
    this.axisTextFontSize = 10;
  }

  (0, _createClass3['default'])(AxisPixi, [{
    key: 'startAxis',
    value: function () {
      function startAxis(axisHeight) {
        var graphics = this.pAxis;

        graphics.clear();
        graphics.lineStyle(1, this.track.getTheme() === _configs.THEME_DARK ? (0, _utils.colorToHex)('#ffffff') : 0x000000, 1);

        // draw the axis line
        graphics.moveTo(0, 0);
        graphics.lineTo(0, axisHeight);
      }

      return startAxis;
    }()
  }, {
    key: 'createAxisTexts',
    value: function () {
      function createAxisTexts(valueScale, axisHeight) {
        this.tickValues = this.calculateAxisTickValues(valueScale, axisHeight);
        var i = 0;

        var color = this.track.getTheme() === _configs.THEME_DARK ? 'white' : 'black';

        if (!this.track.options || !this.track.options.axisLabelFormatting || this.track.options.axisLabelFormatting === 'scientific') {
          this.tickFormat = (0, _d3Format.format)('.2');
        } else {
          this.tickFormat = function (x) {
            return x;
          };
        }

        while (i < this.tickValues.length) {
          var tick = this.tickValues[i];

          while (this.axisTexts.length <= i) {
            var newText = new _configs.GLOBALS.PIXI.Text(tick, {
              fontSize: String(this.axisTextFontSize) + 'px',
              fontFamily: this.axisTextFontFamily,
              fill: color
            });
            this.axisTexts.push(newText);

            this.pAxis.addChild(newText);
          }

          this.axisTexts[i].text = this.tickFormat(tick);
          this.axisTexts[i].anchor.y = 0.5;
          this.axisTexts[i].anchor.x = 0.5;
          i++;
        }

        while (this.axisTexts.length > this.tickValues.length) {
          var lastText = this.axisTexts.pop();
          this.pAxis.removeChild(lastText);
          lastText.destroy(true);
        }
      }

      return createAxisTexts;
    }()
  }, {
    key: 'calculateAxisTickValues',
    value: function () {
      function calculateAxisTickValues(valueScale, axisHeight) {
        var tickCount = Math.max(Math.ceil(axisHeight / TICK_HEIGHT), 1);

        // create scale ticks but not all the way to the top
        // tick values have not been formatted here
        var tickValues = valueScale.ticks(tickCount);

        if (tickValues.length < 1) {
          tickValues = valueScale.ticks(tickCount + 1);

          if (tickValues.length > 1) {
            // sometimes the ticks function will return 0 and then 2
            // if it didn't return enough previously, we probably only want a single
            // tick
            tickValues = [tickValues[0]];
          }
        }

        return tickValues;
      }

      return calculateAxisTickValues;
    }()
  }, {
    key: 'drawAxisLeft',
    value: function () {
      function drawAxisLeft(valueScale, axisHeight) {
        // Draw a left-oriented axis (ticks pointing to the right)
        this.startAxis(axisHeight);
        this.createAxisTexts(valueScale, axisHeight);

        var graphics = this.pAxis;

        if (this.track.getTheme() === _configs.THEME_DARK) {
          graphics.lineStyle(graphics.lineWidth || graphics._lineStyle.width, (0, _utils.colorToHex)('#ffffff'));
        }

        // draw the top, potentially unlabelled, ticke
        graphics.moveTo(0, 0);
        graphics.lineTo(-(TICK_MARGIN + TICK_LENGTH), 0);

        graphics.moveTo(0, axisHeight);
        graphics.lineTo(-(TICK_MARGIN + TICK_LENGTH), axisHeight);

        for (var i = 0; i < this.axisTexts.length; i++) {
          var tick = this.tickValues[i];

          // draw ticks to the left of the axis
          this.axisTexts[i].x = -(TICK_MARGIN + TICK_LENGTH + TICK_LABEL_MARGIN + this.axisTexts[i].width / 2);
          this.axisTexts[i].y = valueScale(tick);

          graphics.moveTo(-TICK_MARGIN, valueScale(tick));
          graphics.lineTo(-(TICK_MARGIN + TICK_LENGTH), valueScale(tick));

          if (this.track && this.track.flipText) {
            this.axisTexts[i].scale.x = -1;
          }
        }

        this.hideOverlappingAxisLabels();
      }

      return drawAxisLeft;
    }()
  }, {
    key: 'drawAxisRight',
    value: function () {
      function drawAxisRight(valueScale, axisHeight) {
        // Draw a right-oriented axis (ticks pointint to the left)
        this.startAxis(axisHeight);
        this.createAxisTexts(valueScale, axisHeight);

        var graphics = this.pAxis;

        if (this.track.getTheme() === _configs.THEME_DARK) {
          graphics.lineStyle(graphics.lineWidth || graphics._lineStyle.width, (0, _utils.colorToHex)('#ffffff'));
        }

        // draw the top, potentially unlabelled, ticke
        graphics.moveTo(0, 0);
        graphics.lineTo(TICK_MARGIN + TICK_LENGTH, 0);

        graphics.moveTo(0, axisHeight);
        graphics.lineTo(TICK_MARGIN + TICK_LENGTH, axisHeight);

        for (var i = 0; i < this.axisTexts.length; i++) {
          var tick = this.tickValues[i];

          this.axisTexts[i].x = TICK_MARGIN + TICK_LENGTH + TICK_LABEL_MARGIN + this.axisTexts[i].width / 2;
          this.axisTexts[i].y = valueScale(tick);

          graphics.moveTo(TICK_MARGIN, valueScale(tick));
          graphics.lineTo(TICK_MARGIN + TICK_LENGTH, valueScale(tick));

          if (this.track && this.track.flipText) {
            this.axisTexts[i].scale.x = -1;
          }
        }

        this.hideOverlappingAxisLabels();
      }

      return drawAxisRight;
    }()
  }, {
    key: 'hideOverlappingAxisLabels',
    value: function () {
      function hideOverlappingAxisLabels() {
        // show all tick marks initially
        for (var i = this.axisTexts.length - 1; i >= 0; i--) {
          this.axisTexts[i].visible = true;
        }

        for (var _i = this.axisTexts.length - 1; _i >= 0; _i--) {
          // if this tick mark is invisible, it's not going to
          // overlap with any others
          if (!this.axisTexts[_i].visible) {
            continue;
          }

          var j = _i - 1;

          while (j >= 0) {
            // go through and hide all overlapping tick marks
            if (this.axisTexts[_i].y + this.axisTexts[_i].height / 2 > this.axisTexts[j].y - this.axisTexts[j].height / 2) {
              this.axisTexts[j].visible = false;
            } else {
              // because the tick marks are ordered from top to bottom, if this
              // one doesn't overlap, then the ones below it won't either, so
              // we can stop looking
              break;
            }

            j -= 1;
          }
        }
      }

      return hideOverlappingAxisLabels;
    }()
  }, {
    key: 'exportVerticalAxis',
    value: function () {
      function exportVerticalAxis(axisHeight) {
        var gAxis = document.createElement('g');
        gAxis.setAttribute('class', 'axis-vertical');

        var stroke = 'black';

        if (this.track && this.track.options.lineStrokeColor) {
          stroke = this.track.options.lineStrokeColor;
        }
        // TODO: On the canvas, there is no vertical line beside the scale,
        // but it also has the draggable control to the right.
        // Confirm that this difference between SVG and Canvas is intentional,
        // and if not, remove this.
        if (this.track.getTheme() === _configs.THEME_DARK) stroke = '#cccccc';

        var line = document.createElement('path');

        line.setAttribute('fill', 'transparent');
        line.setAttribute('stroke', stroke);
        line.setAttribute('id', 'axis-line');

        line.setAttribute('d', 'M0,0 L0,' + String(axisHeight));

        gAxis.appendChild(line);

        return gAxis;
      }

      return exportVerticalAxis;
    }()
  }, {
    key: 'createAxisSVGLine',
    value: function () {
      function createAxisSVGLine() {
        // factor out the styling for axis lines
        var stroke = 'black';

        if (this.track && this.track.options.lineStrokeColor) {
          stroke = this.track.options.lineStrokeColor;
        }

        if (this.track.getTheme() === _configs.THEME_DARK) stroke = '#cccccc';

        var line = document.createElement('path');
        line.setAttribute('id', 'tick-mark');
        line.setAttribute('fill', 'transparent');
        line.setAttribute('stroke', stroke);

        return line;
      }

      return createAxisSVGLine;
    }()
  }, {
    key: 'createAxisSVGText',
    value: function () {
      function createAxisSVGText(text) {
        // factor out the creation of axis texts
        var t = document.createElement('text');

        t.innerHTML = text;
        t.setAttribute('id', 'axis-text');
        t.setAttribute('text-anchor', 'middle');
        t.setAttribute('font-family', this.axisTextFontFamily);
        t.setAttribute('font-size', this.axisTextFontSize);
        t.setAttribute('dy', this.axisTextFontSize / 2 - 2);

        return t;
      }

      return createAxisSVGText;
    }()
  }, {
    key: 'exportAxisLeftSVG',
    value: function () {
      function exportAxisLeftSVG(valueScale, axisHeight) {
        var gAxis = this.exportVerticalAxis(axisHeight);

        var topTickLine = this.createAxisSVGLine();
        gAxis.appendChild(topTickLine);
        topTickLine.setAttribute('d', 'M0,0 L' + +(TICK_MARGIN + TICK_LENGTH) + ',0');

        var bottomTickLine = this.createAxisSVGLine();
        gAxis.appendChild(bottomTickLine);
        bottomTickLine.setAttribute('d', 'M0,' + String(axisHeight) + ' L' + +(TICK_MARGIN + TICK_LENGTH) + ',' + String(axisHeight));

        for (var i = 0; i < this.axisTexts.length; i++) {
          var tick = this.tickValues[i];
          var text = this.axisTexts[i];

          var tickLine = this.createAxisSVGLine();

          gAxis.appendChild(tickLine);

          tickLine.setAttribute('d', 'M' + +TICK_MARGIN + ',' + String(valueScale(tick)) + ' L' + +(TICK_MARGIN + TICK_LENGTH) + ',' + String(valueScale(tick)));

          var g = document.createElement('g');
          gAxis.appendChild(g);
          if (text.visible) {
            var t = this.createAxisSVGText(text.text);
            g.appendChild(t);
          }

          g.setAttribute('transform', 'translate(' + String(text.position.x) + ',' + String(text.position.y) + ')\n             scale(' + String(text.scale.x) + ',' + String(text.scale.y) + ')');
        }

        return gAxis;
      }

      return exportAxisLeftSVG;
    }()
  }, {
    key: 'exportAxisRightSVG',
    value: function () {
      function exportAxisRightSVG(valueScale, axisHeight) {
        var gAxis = this.exportVerticalAxis(axisHeight);

        var topTickLine = this.createAxisSVGLine();
        gAxis.appendChild(topTickLine);
        topTickLine.setAttribute('d', 'M0,0 L' + -(TICK_MARGIN + TICK_LENGTH) + ',0');

        var bottomTickLine = this.createAxisSVGLine();
        gAxis.appendChild(bottomTickLine);
        bottomTickLine.setAttribute('d', 'M0,' + String(axisHeight) + ' L' + -(TICK_MARGIN + TICK_LENGTH) + ',' + String(axisHeight));

        for (var i = 0; i < this.axisTexts.length; i++) {
          var tick = this.tickValues[i];
          var text = this.axisTexts[i];

          var tickLine = this.createAxisSVGLine();

          gAxis.appendChild(tickLine);

          tickLine.setAttribute('d', 'M' + -TICK_MARGIN + ',' + String(valueScale(tick)) + ' L' + -(TICK_MARGIN + TICK_LENGTH) + ',' + String(valueScale(tick)));

          var g = document.createElement('g');
          gAxis.appendChild(g);

          if (text.visible) {
            var t = this.createAxisSVGText(text.text);
            g.appendChild(t);
          }

          g.setAttribute('transform', 'translate(' + String(text.position.x) + ',' + String(text.position.y) + ')\n             scale(' + String(text.scale.x) + ',' + String(text.scale.y) + ')');
        }

        return gAxis;
      }

      return exportAxisRightSVG;
    }()
  }, {
    key: 'clearAxis',
    value: function () {
      function clearAxis() {
        var graphics = this.pAxis;
        while (this.axisTexts.length) {
          var axisText = this.axisTexts.pop();
          graphics.removeChild(axisText);
        }

        graphics.clear();
      }

      return clearAxis;
    }()
  }]);
  return AxisPixi;
}();

exports['default'] = AxisPixi;

/***/ }),
/* 180 */
/***/ (function(module, exports, __nested_webpack_require_992144__) {

"use strict";


module.exports = boxIntersectWrapper

var pool = __nested_webpack_require_992144__(257)
var sweep = __nested_webpack_require_992144__(353)
var boxIntersectIter = __nested_webpack_require_992144__(622)

function boxEmpty(d, box) {
  for(var j=0; j<d; ++j) {
    if(!(box[j] <= box[j+d])) {
      return true
    }
  }
  return false
}

//Unpack boxes into a flat typed array, remove empty boxes
function convertBoxes(boxes, d, data, ids) {
  var ptr = 0
  var count = 0
  for(var i=0, n=boxes.length; i<n; ++i) {
    var b = boxes[i]
    if(boxEmpty(d, b)) {
      continue
    }
    for(var j=0; j<2*d; ++j) {
      data[ptr++] = b[j]
    }
    ids[count++] = i
  }
  return count
}

//Perform type conversions, check bounds
function boxIntersect(red, blue, visit, full) {
  var n = red.length
  var m = blue.length

  //If either array is empty, then we can skip this whole thing
  if(n <= 0 || m <= 0) {
    return
  }

  //Compute dimension, if it is 0 then we skip
  var d = (red[0].length)>>>1
  if(d <= 0) {
    return
  }

  var retval

  //Convert red boxes
  var redList  = pool.mallocDouble(2*d*n)
  var redIds   = pool.mallocInt32(n)
  n = convertBoxes(red, d, redList, redIds)

  if(n > 0) {
    if(d === 1 && full) {
      //Special case: 1d complete
      sweep.init(n)
      retval = sweep.sweepComplete(
        d, visit, 
        0, n, redList, redIds,
        0, n, redList, redIds)
    } else {

      //Convert blue boxes
      var blueList = pool.mallocDouble(2*d*m)
      var blueIds  = pool.mallocInt32(m)
      m = convertBoxes(blue, d, blueList, blueIds)

      if(m > 0) {
        sweep.init(n+m)

        if(d === 1) {
          //Special case: 1d bipartite
          retval = sweep.sweepBipartite(
            d, visit, 
            0, n, redList,  redIds,
            0, m, blueList, blueIds)
        } else {
          //General case:  d>1
          retval = boxIntersectIter(
            d, visit,    full,
            n, redList,  redIds,
            m, blueList, blueIds)
        }

        pool.free(blueList)
        pool.free(blueIds)
      }
    }

    pool.free(redList)
    pool.free(redIds)
  }

  return retval
}


var RESULT

function appendItem(i,j) {
  RESULT.push([i,j])
}

function intersectFullArray(x) {
  RESULT = []
  boxIntersect(x, x, appendItem, true)
  return RESULT
}

function intersectBipartiteArray(x, y) {
  RESULT = []
  boxIntersect(x, y, appendItem, false)
  return RESULT
}

//User-friendly wrapper, handle full input and no-visitor cases
function boxIntersectWrapper(arg0, arg1, arg2) {
  var result
  switch(arguments.length) {
    case 1:
      return intersectFullArray(arg0)
    case 2:
      if(typeof arg1 === 'function') {
        return boxIntersect(arg0, arg0, arg1, true)
      } else {
        return intersectBipartiteArray(arg0, arg1)
      }
    case 3:
      return boxIntersect(arg0, arg1, arg2, false)
    default:
      throw new Error('box-intersect: Invalid arguments')
  }
}

/***/ }),
/* 181 */
/***/ (function(module, exports, __nested_webpack_require_995156__) {

"use strict";


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

var _d3Array = __nested_webpack_require_995156__(8);

/**
 * Get an aggregation function from a function name.
 * @param {string} name The name of an aggregation function
 * ('mean', 'sum', 'variance', 'deviation'). If an unknown string is passed,
 * the mean function will be used, and a console warning will be thrown.
 * @returns {function} The function of interest as determined by the string,
 */
var getAggregationFunction = function getAggregationFunction(name) {
  var aggFunc = void 0;
  var lowerCaseName = name ? name.toLowerCase() : name;
  switch (lowerCaseName) {
    case 'mean':
      aggFunc = _d3Array.mean;
      break;
    case 'sum':
      aggFunc = _d3Array.sum;
      break;
    case 'variance':
      aggFunc = _d3Array.variance;
      break;
    case 'deviation':
      aggFunc = _d3Array.deviation;
      break;
    default:
      aggFunc = _d3Array.mean;
      console.warn('Encountered an unsupported selectedRowsAggregationMode option.');
  }
  return aggFunc;
};

exports['default'] = getAggregationFunction;

/***/ }),
/* 182 */
/***/ (function(module, exports, __nested_webpack_require_996341__) {

"use strict";


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

var _stringify = __nested_webpack_require_996341__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _keys = __nested_webpack_require_996341__(18);

var _keys2 = _interopRequireDefault(_keys);

var _extends2 = __nested_webpack_require_996341__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _getIterator2 = __nested_webpack_require_996341__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _isNan = __nested_webpack_require_996341__(30);

var _isNan2 = _interopRequireDefault(_isNan);

exports.workerSetPix = workerSetPix;
exports.tileResponseToData = tileResponseToData;
exports.workerGetTiles = workerGetTiles;

var _d3Scale = __nested_webpack_require_996341__(28);

var _getAggregationFunction = __nested_webpack_require_996341__(181);

var _getAggregationFunction2 = _interopRequireDefault(_getAggregationFunction);

var _selectedItemsToSize = __nested_webpack_require_996341__(139);

var _selectedItemsToSize2 = _interopRequireDefault(_selectedItemsToSize);

var _DenseDataExtrema1D = __nested_webpack_require_996341__(137);

var _DenseDataExtrema1D2 = _interopRequireDefault(_DenseDataExtrema1D);

var _DenseDataExtrema2D = __nested_webpack_require_996341__(138);

var _DenseDataExtrema2D2 = _interopRequireDefault(_DenseDataExtrema2D);

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

/*
function countTransform(count) {
    return Math.sqrt(Math.sqrt(count + 1));
}

function countTransform(count) {
    return Math.log(count+0.0001);
}
*/

/**
 * This function helps to fill in pixData by calling setPixData()
 * when selectedRowsOptions have been passed to workerSetPix().
 * @param {array} data The tile data array.
 * @param {array} shape Array `[numRows, numCols]`, used when iterating over a subset of rows,
 * when one needs to know the width of each column.
 * @param {function} setPixData The setPixData function created by workerSetPix().
 * @param {number[]} selectedRows Array of row indices, for ordering and filtering rows.
 * Used by the HorizontalMultivecTrack.
 * @param {string} selectedRowsAggregationMode String that specifies the aggregation function to use ("mean", "sum", etc).
 * @param {boolean} selectedRowsAggregationWithRelativeHeight Boolean that determines whether the height of row groups should be relative to the size of the group.
 * @param {string} selectedRowsAggregationMethod Where will the aggregation be performed? Possible values: "client", "server".
 */
function setPixDataForSelectedRows(data, shape, setPixData, selectedRows, selectedRowsAggregationMode, selectedRowsAggregationWithRelativeHeight, selectedRowsAggregationMethod) {
  // We need to set the pixels in the order specified by the `selectedRows` parameter.
  var aggFunc = void 0;
  var aggFromDataFunc = void 0;
  if (selectedRowsAggregationMode) {
    aggFunc = (0, _getAggregationFunction2['default'])(selectedRowsAggregationMode);
    aggFromDataFunc = function aggFromDataFunc(colI, rowIs) {
      return aggFunc(rowIs.map(function (rowI) {
        return data[rowI * shape[1] + colI];
      }));
    };
  }
  var d = void 0;
  var pixRowI = void 0;
  var colI = void 0;
  var selectedRowI = void 0;
  var selectedRowGroupItemI = void 0;
  for (colI = 0; colI < shape[1]; colI++) {
    // For this column, aggregate along the row axis.
    pixRowI = 0;
    for (selectedRowI = 0; selectedRowI < selectedRows.length; selectedRowI++) {
      if (aggFunc && selectedRowsAggregationMethod === 'server') {
        d = data[selectedRowI * shape[1] + colI];
      } else if (Array.isArray(selectedRows[selectedRowI]) && aggFunc) {
        // An aggregation step must be performed for this data point.
        d = aggFromDataFunc(colI, selectedRows[selectedRowI]);
      } else {
        d = data[selectedRows[selectedRowI] * shape[1] + colI];
      }

      if (selectedRowsAggregationWithRelativeHeight && Array.isArray(selectedRows[selectedRowI])) {
        // Set a pixel for multiple rows, proportionate to the size of the row aggregation group.
        for (selectedRowGroupItemI = 0; selectedRowGroupItemI < selectedRows[selectedRowI].length; selectedRowGroupItemI++) {
          setPixData(pixRowI * shape[1] + colI, // pixData index
          d // data point
          );
          pixRowI++;
        }
      } else {
        // Set a single pixel, either representing a single row or an entire row group, if the vertical height for each group should be uniform (i.e. should not depend on group size).
        setPixData(pixRowI * shape[1] + colI, // pixData index
        d // data point
        );
        pixRowI++;
      }
    } // end row group for
  } // end col for
}

/**
 * This function takes in tile data and other rendering parameters,
 * and generates an array of pixel data that can be passed to a canvas
 * (and subsequently passed to a PIXI sprite).
 * @param {number} size The length of the `data` parameter. Often set to a tile's
 * `tile.tileData.dense.length` value.
 * @param {array} data The tile data array.
 * @param {string} valueScaleType 'log' or 'linear'.
 * @param {array} valueScaleDomain
 * @param {number} pseudocount The pseudocount is generally the minimum non-zero value and is
 * used so that our log scaling doesn't lead to NaN values.
 * @param {array} colorScale
 * @param {boolean} ignoreUpperRight
 * @param {boolean} ignoreLowerLeft
 * @param {array} shape Array `[numRows, numCols]`, used when iterating over a subset of rows,
 * when one needs to know the width of each column.
 * @param {array} zeroValueColor The color to use for rendering zero data values, [r, g, b, a].
 * @param {object} selectedRowsOptions Rendering options when using a `selectRows` track option.
 * @returns {Uint8ClampedArray} A flattened array of pixel values.
 */
function workerSetPix(size, data, valueScaleType, valueScaleDomain, pseudocount, colorScale) {
  var ignoreUpperRight = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
  var ignoreLowerLeft = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
  var shape = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null;
  var zeroValueColor = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null;
  var selectedRowsOptions = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : null;

  var valueScale = null;

  if (valueScaleType === 'log') {
    valueScale = (0, _d3Scale.scaleLog)().range([254, 0]).domain(valueScaleDomain);
  } else {
    if (valueScaleType !== 'linear') {
      console.warn('Unknown value scale type:', valueScaleType, ' Defaulting to linear');
    }
    valueScale = (0, _d3Scale.scaleLinear)().range([254, 0]).domain(valueScaleDomain);
  }

  // De-structure the selectedRowsOptions object.

  var _ref = selectedRowsOptions || {},
      _ref$selectedRows = _ref.selectedRows,
      selectedRows = _ref$selectedRows === undefined ? null : _ref$selectedRows,
      _ref$selectedRowsAggr = _ref.selectedRowsAggregationMode,
      selectedRowsAggregationMode = _ref$selectedRowsAggr === undefined ? null : _ref$selectedRowsAggr,
      _ref$selectedRowsAggr2 = _ref.selectedRowsAggregationWithRelativeHeight,
      selectedRowsAggregationWithRelativeHeight = _ref$selectedRowsAggr2 === undefined ? null : _ref$selectedRowsAggr2,
      _ref$selectedRowsAggr3 = _ref.selectedRowsAggregationMethod,
      selectedRowsAggregationMethod = _ref$selectedRowsAggr3 === undefined ? null : _ref$selectedRowsAggr3;

  var filteredSize = size;
  if (shape && selectedRows) {
    // If using the `selectedRows` parameter, then the size of the `pixData` array
    // will likely be different than `size` (the total size of the tile data array).
    // The potential for aggregation groups in `selectedRows` also must be taken into account.
    filteredSize = (0, _selectedItemsToSize2['default'])(selectedRows, selectedRowsAggregationWithRelativeHeight) * shape[1];
  }

  var rgb = void 0;
  var rgbIdx = 0;
  var tileWidth = shape ? shape[1] : Math.sqrt(size);
  var pixData = new Uint8ClampedArray(filteredSize * 4);

  /**
   * Set the ith element of the pixData array, using value d.
   * (well not really, since i is scaled to make space for each rgb value).
   * @param i Index of the element.
   * @param d The value to be transformed and then inserted.
   */
  var setPixData = function setPixData(i, d) {
    // Transparent
    rgbIdx = 255;

    if (
    // ignore the upper right portion of a tile because it's on the diagonal
    // and its mirror will fill in that space
    !(ignoreUpperRight && Math.floor(i / tileWidth) < i % tileWidth) && !(ignoreLowerLeft && Math.floor(i / tileWidth) > i % tileWidth) &&
    // Ignore color if the value is invalid
    !(0, _isNan2['default'])(+d)) {
      // values less than espilon are considered NaNs and made transparent (rgbIdx 255)
      rgbIdx = Math.max(0, Math.min(254, Math.floor(valueScale(d + pseudocount))));
    }
    // let rgbIdx = qScale(d); //Math.max(0, Math.min(255, Math.floor(valueScale(ct))))
    if (rgbIdx < 0 || rgbIdx > 255) {
      console.warn('out of bounds rgbIdx:', rgbIdx, ' (should be 0 <= rgbIdx <= 255)');
    }

    if (zeroValueColor && !(0, _isNan2['default'])(+d) && +d === 0.0) {
      rgb = zeroValueColor;
    } else {
      rgb = colorScale[rgbIdx];
    }

    pixData[i * 4] = rgb[0];
    pixData[i * 4 + 1] = rgb[1];
    pixData[i * 4 + 2] = rgb[2];
    pixData[i * 4 + 3] = rgb[3];
  };

  var d = void 0;
  try {
    if (selectedRows) {
      // We need to set the pixels in the order specified by the `selectedRows` parameter.
      // Call the setPixDataForSelectedRows helper function,
      // which will loop over the data for us and call setPixData().
      setPixDataForSelectedRows(data, shape, setPixData, selectedRows, selectedRowsAggregationMode, selectedRowsAggregationWithRelativeHeight, selectedRowsAggregationMethod);
    } else {
      // The `selectedRows` array has not been passed, so we want to use all of the tile data values,
      // in their default ordering.
      for (var i = 0; i < data.length; i++) {
        d = data[i];
        setPixData(i, d);
      }
    }
  } catch (err) {
    console.warn('Odd datapoint');
    console.warn('valueScale.domain():', valueScale.domain());
    console.warn('valueScale.range():', valueScale.range());
    console.warn('value:', valueScale(d + pseudocount));
    console.warn('pseudocount:', pseudocount);
    console.warn('rgbIdx:', rgbIdx, 'd:', d, 'ct:', valueScale(d));
    console.error('ERROR:', err);
    return pixData;
  }

  return pixData;
}

function float32(h) {
  /**
   * Yanked from https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c#L466
   *
   * Does not support infinities or NaN. All requests with such
   * values should be encoded as float32
   */

  var hExp = h & 0x7c00;
  var hSig = void 0;
  var fExp = void 0;
  var fSig = void 0;

  var fSgn = (h & 0x8000) << 16;
  switch (hExp) {
    /* 0 or subnormal */
    case 0x0000:
      hSig = h & 0x03ff;
      /* Signed zero */
      if (hSig === 0) {
        return fSgn;
      }
      /* Subnormal */
      hSig <<= 1;
      while ((hSig & 0x0400) === 0) {
        hSig <<= 1;
        hExp++;
      }
      fExp = 127 - 15 - hExp << 23;
      fSig = (hSig & 0x03ff) << 13;
      return fSgn + fExp + fSig;

    /* inf or NaN */
    case 0x7c00:
      /* All-ones exponent and a copy of the significand */
      return fSgn + 0x7f800000 + ((h & 0x03ff) << 13);

    default:
      /* normalized */
      /* Just need to adjust the exponent and shift */
      return fSgn + ((h & 0x7fff) + 0x1c000 << 13);
  }
}

function _base64ToArrayBuffer(base64) {
  var binaryString = atob(base64);
  var len = binaryString.length;

  var bytes = new Uint8Array(len);

  for (var i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  return bytes.buffer;
}

function _uint16ArrayToFloat32Array(uint16array) {
  var bytes = new Uint32Array(uint16array.length);

  for (var i = 0; i < uint16array.length; i++) {
    bytes[i] = float32(uint16array[i]);
  }

  var newBytes = new Float32Array(bytes.buffer);

  return newBytes;
}

/**
 * Convert a response from the tile server to
 * data that can be used by higlass
 */
function tileResponseToData(data, server, theseTileIds) {
  if (!data) {
    // probably an error
    data = {};
  }

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3['default'])(theseTileIds), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var thisId = _step.value;

      if (!(thisId in data)) {
        // the server didn't return any data for this tile
        data[thisId] = {};
      }
      var key = thisId;
      // let's hope the payload doesn't contain a tileId field
      var keyParts = key.split('.');

      data[key].server = server;
      data[key].tileId = key;
      data[key].zoomLevel = +keyParts[1];

      // slice from position 2 to exclude tileId and zoomLevel
      // filter by NaN to exclude metadata portions of the tile request
      data[key].tilePos = keyParts.slice(2, keyParts.length).map(function (x) {
        return +x;
      }).filter(function (x) {
        return !(0, _isNan2['default'])(x);
      });
      data[key].tilesetUid = keyParts[0];

      if ('dense' in data[key]) {
        var arrayBuffer = _base64ToArrayBuffer(data[key].dense);
        var a = void 0;

        if (data[key].dtype === 'float16') {
          // data is encoded as float16s
          /* comment out until next empty line for 32 bit arrays */
          var uint16Array = new Uint16Array(arrayBuffer);
          var newDense = _uint16ArrayToFloat32Array(uint16Array);
          a = newDense;
        } else {
          // data is encoded as float32s
          a = new Float32Array(arrayBuffer);
        }

        var dde = data[key].tilePos.length === 2 ? new _DenseDataExtrema2D2['default'](a) : new _DenseDataExtrema1D2['default'](a);

        data[key].dense = a;
        data[key].denseDataExtrema = dde;
        data[key].minNonZero = dde.minNonZeroInTile;
        data[key].maxNonZero = dde.maxNonZeroInTile;
        /*
        if (data[key]['minNonZero'] === Number.MAX_SAFE_INTEGER &&
            data[key]['maxNonZero'] === Number.MIN_SAFE_INTEGER) {
            // if there's no values except 0,
            // then do use it as the min value
             data[key]['minNonZero'] = 0;
            data[key]['maxNonZero'] = 1;
        }
        */
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator['return']) {
        _iterator['return']();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return data;
}

function workerGetTiles(outUrl, server, theseTileIds, authHeader, done, requestBody) {
  var headers = {
    'content-type': 'application/json'
  };

  if (authHeader) headers.Authorization = authHeader;

  fetch(outUrl, (0, _extends3['default'])({
    credentials: 'same-origin',
    headers: headers
  }, requestBody && (0, _keys2['default'])(requestBody).length > 0 ? {
    method: 'POST',
    body: (0, _stringify2['default'])(requestBody)
  } : {})).then(function (response) {
    return response.json();
  }).then(function (data) {
    done(tileResponseToData(data, server, theseTileIds));
    /*
    const denses = Object.values(data)
      .filter(x => x.dense)
      .map(x => x.dense);
    */
    // .map(x => x.dense.buffer);

    // done.transfer(data, denses);
  })['catch'](function (err) {
    return console.warn('err:', err);
  });
}

/***/ }),
/* 183 */
/***/ (function(module, exports, __nested_webpack_require_1012204__) {

"use strict";


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

var _keys = __nested_webpack_require_1012204__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getIterator2 = __nested_webpack_require_1012204__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _react = __nested_webpack_require_1012204__(1);

var _react2 = _interopRequireDefault(_react);

var _ContextMenuItem = __nested_webpack_require_1012204__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _configs = __nested_webpack_require_1012204__(11);

__nested_webpack_require_1012204__(68);

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

/**
 * Return a list of all the tracks and subtracks from
 * the list of tracks
 *
 * @param {array} tracks: A list of tracks to go through
 */
var getAllTracksAndSubtracks = exports.getAllTracksAndSubtracks = function getAllTracksAndSubtracks(tracks) {
  var series = [];

  // check if this is a combined track (has contents)
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3['default'])(tracks), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var track = _step.value;

      if (track.contents) {
        series = series.concat(track.contents);
      } else {
        series.push(track);
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator['return']) {
        _iterator['return']();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return series;
};

/**
 * Get a list of menu items corresponding to the
 * series present in a set of tracks. If any of
 * the tracks a combined tracks, this function will
 * return individual menu items for each of the
 * combined tracks.
 *
 * @param {object} tracks: An array of track definitions (from the viewconf)
 * @param {func} onItemMouseEnter: Event handler for mouseEnter
 * @param {func} onItemMouseLeave: Event handler for mouseLeave
 * @param {func} onItemClick: Event handler for mouseLeave
 *
 * @returns {array} A list of ReactComponents for the generated ContextMenuItems
 */
var getSeriesItems = exports.getSeriesItems = function getSeriesItems(tracks, onItemMouseEnter, onItemMouseLeave, onItemClick) {
  if (!tracks) return null;

  if (window.higlassTracksByType) {
    (0, _keys2['default'])(window.higlassTracksByType).forEach(function (pluginTrackType) {
      _configs.TRACKS_INFO_BY_TYPE[pluginTrackType] = window.higlassTracksByType[pluginTrackType].config;
    });
  }

  return getAllTracksAndSubtracks(tracks).map(function (x) {
    var thumbnail = _configs.TRACKS_INFO_BY_TYPE[x.type] ? _configs.TRACKS_INFO_BY_TYPE[x.type].thumbnail : null;

    var imgTag = thumbnail ? _react2['default'].createElement('div', {
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML: { __html: thumbnail.outerHTML },
      className: 'ContextMenu-module_context-menu-icon-I4kiw'
    }) : _react2['default'].createElement(
      'div',
      { className: 'ContextMenu-module_context-menu-icon-I4kiw' },
      _react2['default'].createElement('svg', null)
    );

    return _react2['default'].createElement(
      _ContextMenuItem2['default'],
      {
        key: x.uid,
        onClick: function () {
          function onClick() {
            if (onItemClick) onItemClick(x.uid);
          }

          return onClick;
        }(),
        onMouseEnter: function () {
          function onMouseEnter(e) {
            if (onItemMouseEnter) onItemMouseEnter(e, x);
          }

          return onMouseEnter;
        }(),
        onMouseLeave: function () {
          function onMouseLeave(e) {
            if (onItemMouseLeave) onItemMouseLeave(e);
          }

          return onMouseLeave;
        }(),
        className: 'ContextMenu-module_context-menu-item-1HeVv'
      },
      imgTag,
      _react2['default'].createElement(
        'span',
        { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
        x.options && x.options.name && x.options.name.length ? x.options.name : x.type,
        onItemMouseEnter && onItemMouseLeave ? _react2['default'].createElement(
          'svg',
          { className: 'ContextMenu-module_play-icon-R4pIO' },
          _react2['default'].createElement('use', { xlinkHref: '#play' })
        ) : null
      )
    );
  });
};

/***/ }),
/* 184 */
/***/ (function(module, exports, __nested_webpack_require_1016896__) {

var baseIsArguments = __nested_webpack_require_1016896__(739),
    isObjectLike = __nested_webpack_require_1016896__(56);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
    !propertyIsEnumerable.call(value, 'callee');
};

module.exports = isArguments;


/***/ }),
/* 185 */
/***/ (function(module, exports, __nested_webpack_require_1017994__) {

/* WEBPACK VAR INJECTION */(function(module) {var root = __nested_webpack_require_1017994__(41),
    stubFalse = __nested_webpack_require_1017994__(740);

/** Detect free variable `exports`. */
var freeExports =   true && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || stubFalse;

module.exports = isBuffer;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1017994__(173)(module)))

/***/ }),
/* 186 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Checks if `value` is likely a prototype object.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
 */
function isPrototype(value) {
  var Ctor = value && value.constructor,
      proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;

  return value === proto;
}

module.exports = isPrototype;


/***/ }),
/* 187 */
/***/ (function(module, exports, __nested_webpack_require_1019832__) {

var ListCache = __nested_webpack_require_1019832__(188),
    stackClear = __nested_webpack_require_1019832__(751),
    stackDelete = __nested_webpack_require_1019832__(752),
    stackGet = __nested_webpack_require_1019832__(753),
    stackHas = __nested_webpack_require_1019832__(754),
    stackSet = __nested_webpack_require_1019832__(755);

/**
 * Creates a stack cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Stack(entries) {
  var data = this.__data__ = new ListCache(entries);
  this.size = data.size;
}

// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;

module.exports = Stack;


/***/ }),
/* 188 */
/***/ (function(module, exports, __nested_webpack_require_1020651__) {

var listCacheClear = __nested_webpack_require_1020651__(746),
    listCacheDelete = __nested_webpack_require_1020651__(747),
    listCacheGet = __nested_webpack_require_1020651__(748),
    listCacheHas = __nested_webpack_require_1020651__(749),
    listCacheSet = __nested_webpack_require_1020651__(750);

/**
 * Creates an list cache object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function ListCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;

module.exports = ListCache;


/***/ }),
/* 189 */
/***/ (function(module, exports, __nested_webpack_require_1021584__) {

var eq = __nested_webpack_require_1021584__(120);

/**
 * Gets the index at which the `key` is found in `array` of key-value pairs.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} key The key to search for.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function assocIndexOf(array, key) {
  var length = array.length;
  while (length--) {
    if (eq(array[length][0], key)) {
      return length;
    }
  }
  return -1;
}

module.exports = assocIndexOf;


/***/ }),
/* 190 */
/***/ (function(module, exports, __nested_webpack_require_1022159__) {

var getNative = __nested_webpack_require_1022159__(99);

/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');

module.exports = nativeCreate;


/***/ }),
/* 191 */
/***/ (function(module, exports, __nested_webpack_require_1022425__) {

var isKeyable = __nested_webpack_require_1022425__(768);

/**
 * Gets the data for `map`.
 *
 * @private
 * @param {Object} map The map to query.
 * @param {string} key The reference key.
 * @returns {*} Returns the map data.
 */
function getMapData(map, key) {
  var data = map.__data__;
  return isKeyable(key)
    ? data[typeof key == 'string' ? 'string' : 'hash']
    : data.map;
}

module.exports = getMapData;


/***/ }),
/* 192 */
/***/ (function(module, exports, __nested_webpack_require_1022905__) {

var DataView = __nested_webpack_require_1022905__(781),
    Map = __nested_webpack_require_1022905__(279),
    Promise = __nested_webpack_require_1022905__(782),
    Set = __nested_webpack_require_1022905__(783),
    WeakMap = __nested_webpack_require_1022905__(422),
    baseGetTag = __nested_webpack_require_1022905__(97),
    toSource = __nested_webpack_require_1022905__(414);

/** `Object#toString` result references. */
var mapTag = '[object Map]',
    objectTag = '[object Object]',
    promiseTag = '[object Promise]',
    setTag = '[object Set]',
    weakMapTag = '[object WeakMap]';

var dataViewTag = '[object DataView]';

/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
    mapCtorString = toSource(Map),
    promiseCtorString = toSource(Promise),
    setCtorString = toSource(Set),
    weakMapCtorString = toSource(WeakMap);

/**
 * Gets the `toStringTag` of `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the `toStringTag`.
 */
var getTag = baseGetTag;

// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
    (Map && getTag(new Map) != mapTag) ||
    (Promise && getTag(Promise.resolve()) != promiseTag) ||
    (Set && getTag(new Set) != setTag) ||
    (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  getTag = function(value) {
    var result = baseGetTag(value),
        Ctor = result == objectTag ? value.constructor : undefined,
        ctorString = Ctor ? toSource(Ctor) : '';

    if (ctorString) {
      switch (ctorString) {
        case dataViewCtorString: return dataViewTag;
        case mapCtorString: return mapTag;
        case promiseCtorString: return promiseTag;
        case setCtorString: return setTag;
        case weakMapCtorString: return weakMapTag;
      }
    }
    return result;
  };
}

module.exports = getTag;


/***/ }),
/* 193 */
/***/ (function(module, exports, __nested_webpack_require_1024845__) {

var isArray = __nested_webpack_require_1024845__(31),
    isKey = __nested_webpack_require_1024845__(285),
    stringToPath = __nested_webpack_require_1024845__(787),
    toString = __nested_webpack_require_1024845__(790);

/**
 * Casts `value` to a path array if it's not one.
 *
 * @private
 * @param {*} value The value to inspect.
 * @param {Object} [object] The object to query keys on.
 * @returns {Array} Returns the cast property path array.
 */
function castPath(value, object) {
  if (isArray(value)) {
    return value;
  }
  return isKey(value, object) ? [value] : stringToPath(toString(value));
}

module.exports = castPath;


/***/ }),
/* 194 */
/***/ (function(module, exports, __nested_webpack_require_1025502__) {

var baseGetTag = __nested_webpack_require_1025502__(97),
    isObjectLike = __nested_webpack_require_1025502__(56);

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (isObjectLike(value) && baseGetTag(value) == symbolTag);
}

module.exports = isSymbol;


/***/ }),
/* 195 */
/***/ (function(module, exports, __nested_webpack_require_1026260__) {

var baseAssignValue = __nested_webpack_require_1026260__(287),
    eq = __nested_webpack_require_1026260__(120);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Assigns `value` to `key` of `object` if the existing value is not equivalent
 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignValue(object, key, value) {
  var objValue = object[key];
  if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
      (value === undefined && !(key in object))) {
    baseAssignValue(object, key, value);
  }
}

module.exports = assignValue;


/***/ }),
/* 196 */
/***/ (function(module, exports) {

/**
 * Copies the values of `source` to `array`.
 *
 * @private
 * @param {Array} source The array to copy values from.
 * @param {Array} [array=[]] The array to copy values to.
 * @returns {Array} Returns `array`.
 */
function copyArray(source, array) {
  var index = -1,
      length = source.length;

  array || (array = Array(length));
  while (++index < length) {
    array[index] = source[index];
  }
  return array;
}

module.exports = copyArray;


/***/ }),
/* 197 */
/***/ (function(module, exports, __nested_webpack_require_1027754__) {

var isObject = __nested_webpack_require_1027754__(45);

/** Built-in value references. */
var objectCreate = Object.create;

/**
 * The base implementation of `_.create` without support for assigning
 * properties to the created object.
 *
 * @private
 * @param {Object} proto The object to inherit from.
 * @returns {Object} Returns the new object.
 */
var baseCreate = (function() {
  function object() {}
  return function(proto) {
    if (!isObject(proto)) {
      return {};
    }
    if (objectCreate) {
      return objectCreate(proto);
    }
    object.prototype = proto;
    var result = new object;
    object.prototype = undefined;
    return result;
  };
}());

module.exports = baseCreate;


/***/ }),
/* 198 */
/***/ (function(module, exports, __nested_webpack_require_1028521__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {/*
  Module Dependencies
*/
var htmlparser = __nested_webpack_require_1028521__(148),
    parse5 = __nested_webpack_require_1028521__(972);

/*
  Parser
*/
exports = module.exports = function(content, options, isDocument) {
  var dom = exports.evaluate(content, options, isDocument),
      // Generic root element
      root = exports.evaluate('<root></root>', options, false)[0];

  root.type = 'root';
  root.parent = null;

  // Update the dom using the root
  exports.update(dom, root);

  return root;
};

function parseWithParse5 (content, isDocument) {
  var parse = isDocument ? parse5.parse : parse5.parseFragment,
      root = parse(content, { treeAdapter: parse5.treeAdapters.htmlparser2 });

  return root.children;
}

exports.evaluate = function(content, options, isDocument) {
  // options = options || $.fn.options;

  var dom;

  if (Buffer.isBuffer(content))
    content = content.toString();

  if (typeof content === 'string') {
    var useHtmlParser2 = options.xmlMode || options._useHtmlParser2;

    dom = useHtmlParser2 ? htmlparser.parseDOM(content, options) : parseWithParse5(content, isDocument);
  } else {
    dom = content;
  }

  return dom;
};

/*
  Update the dom structure, for one changed layer
*/
exports.update = function(arr, parent) {
  // normalize
  if (!Array.isArray(arr)) arr = [arr];

  // Update parent
  if (parent) {
    parent.children = arr;
  } else {
    parent = null;
  }

  // Update neighbors
  for (var i = 0; i < arr.length; i++) {
    var node = arr[i];

    // Cleanly remove existing nodes from their previous structures.
    var oldParent = node.parent || node.root,
        oldSiblings = oldParent && oldParent.children;
    if (oldSiblings && oldSiblings !== arr) {
      oldSiblings.splice(oldSiblings.indexOf(node), 1);
      if (node.prev) {
        node.prev.next = node.next;
      }
      if (node.next) {
        node.next.prev = node.prev;
      }
    }

    if (parent) {
      node.prev = arr[i - 1] || null;
      node.next = arr[i + 1] || null;
    } else {
      node.prev = node.next = null;
    }

    if (parent && parent.type === 'root') {
      node.root = parent;
      node.parent = null;
    } else {
      node.root = null;
      node.parent = parent;
    }
  }

  return parent;
};

// module.exports = $.extend(exports);

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1028521__(113).Buffer))

/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
  ? R.apply
  : function ReflectApply(target, receiver, args) {
    return Function.prototype.apply.call(target, receiver, args);
  }

var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
  ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target)
      .concat(Object.getOwnPropertySymbols(target));
  };
} else {
  ReflectOwnKeys = function ReflectOwnKeys(target) {
    return Object.getOwnPropertyNames(target);
  };
}

function ProcessEmitWarning(warning) {
  if (console && console.warn) console.warn(warning);
}

var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
  return value !== value;
}

function EventEmitter() {
  EventEmitter.init.call(this);
}
module.exports = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;

Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  enumerable: true,
  get: function() {
    return defaultMaxListeners;
  },
  set: function(arg) {
    if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
      throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
    }
    defaultMaxListeners = arg;
  }
});

EventEmitter.init = function() {

  if (this._events === undefined ||
      this._events === Object.getPrototypeOf(this)._events) {
    this._events = Object.create(null);
    this._eventsCount = 0;
  }

  this._maxListeners = this._maxListeners || undefined;
};

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
    throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
  }
  this._maxListeners = n;
  return this;
};

function $getMaxListeners(that) {
  if (that._maxListeners === undefined)
    return EventEmitter.defaultMaxListeners;
  return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  return $getMaxListeners(this);
};

EventEmitter.prototype.emit = function emit(type) {
  var args = [];
  for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
  var doError = (type === 'error');

  var events = this._events;
  if (events !== undefined)
    doError = (doError && events.error === undefined);
  else if (!doError)
    return false;

  // If there is no 'error' event listener then throw.
  if (doError) {
    var er;
    if (args.length > 0)
      er = args[0];
    if (er instanceof Error) {
      // Note: The comments on the `throw` lines are intentional, they show
      // up in Node's output if this results in an unhandled exception.
      throw er; // Unhandled 'error' event
    }
    // At least give some kind of context to the user
    var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
    err.context = er;
    throw err; // Unhandled 'error' event
  }

  var handler = events[type];

  if (handler === undefined)
    return false;

  if (typeof handler === 'function') {
    ReflectApply(handler, this, args);
  } else {
    var len = handler.length;
    var listeners = arrayClone(handler, len);
    for (var i = 0; i < len; ++i)
      ReflectApply(listeners[i], this, args);
  }

  return true;
};

function _addListener(target, type, listener, prepend) {
  var m;
  var events;
  var existing;

  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }

  events = target._events;
  if (events === undefined) {
    events = target._events = Object.create(null);
    target._eventsCount = 0;
  } else {
    // To avoid recursion in the case that type === "newListener"! Before
    // adding it to the listeners, first emit "newListener".
    if (events.newListener !== undefined) {
      target.emit('newListener', type,
                  listener.listener ? listener.listener : listener);

      // Re-assign `events` because a newListener handler could have caused the
      // this._events to be assigned to a new object
      events = target._events;
    }
    existing = events[type];
  }

  if (existing === undefined) {
    // Optimize the case of one listener. Don't need the extra array object.
    existing = events[type] = listener;
    ++target._eventsCount;
  } else {
    if (typeof existing === 'function') {
      // Adding the second element, need to change to array.
      existing = events[type] =
        prepend ? [listener, existing] : [existing, listener];
      // If we've already got an array, just append.
    } else if (prepend) {
      existing.unshift(listener);
    } else {
      existing.push(listener);
    }

    // Check for listener leak
    m = $getMaxListeners(target);
    if (m > 0 && existing.length > m && !existing.warned) {
      existing.warned = true;
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      var w = new Error('Possible EventEmitter memory leak detected. ' +
                          existing.length + ' ' + String(type) + ' listeners ' +
                          'added. Use emitter.setMaxListeners() to ' +
                          'increase limit');
      w.name = 'MaxListenersExceededWarning';
      w.emitter = target;
      w.type = type;
      w.count = existing.length;
      ProcessEmitWarning(w);
    }
  }

  return target;
}

EventEmitter.prototype.addListener = function addListener(type, listener) {
  return _addListener(this, type, listener, false);
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.prependListener =
    function prependListener(type, listener) {
      return _addListener(this, type, listener, true);
    };

function onceWrapper() {
  var args = [];
  for (var i = 0; i < arguments.length; i++) args.push(arguments[i]);
  if (!this.fired) {
    this.target.removeListener(this.type, this.wrapFn);
    this.fired = true;
    ReflectApply(this.listener, this.target, args);
  }
}

function _onceWrap(target, type, listener) {
  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  var wrapped = onceWrapper.bind(state);
  wrapped.listener = listener;
  state.wrapFn = wrapped;
  return wrapped;
}

EventEmitter.prototype.once = function once(type, listener) {
  if (typeof listener !== 'function') {
    throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
  }
  this.on(type, _onceWrap(this, type, listener));
  return this;
};

EventEmitter.prototype.prependOnceListener =
    function prependOnceListener(type, listener) {
      if (typeof listener !== 'function') {
        throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
      }
      this.prependListener(type, _onceWrap(this, type, listener));
      return this;
    };

// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
    function removeListener(type, listener) {
      var list, events, position, i, originalListener;

      if (typeof listener !== 'function') {
        throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
      }

      events = this._events;
      if (events === undefined)
        return this;

      list = events[type];
      if (list === undefined)
        return this;

      if (list === listener || list.listener === listener) {
        if (--this._eventsCount === 0)
          this._events = Object.create(null);
        else {
          delete events[type];
          if (events.removeListener)
            this.emit('removeListener', type, list.listener || listener);
        }
      } else if (typeof list !== 'function') {
        position = -1;

        for (i = list.length - 1; i >= 0; i--) {
          if (list[i] === listener || list[i].listener === listener) {
            originalListener = list[i].listener;
            position = i;
            break;
          }
        }

        if (position < 0)
          return this;

        if (position === 0)
          list.shift();
        else {
          spliceOne(list, position);
        }

        if (list.length === 1)
          events[type] = list[0];

        if (events.removeListener !== undefined)
          this.emit('removeListener', type, originalListener || listener);
      }

      return this;
    };

EventEmitter.prototype.off = EventEmitter.prototype.removeListener;

EventEmitter.prototype.removeAllListeners =
    function removeAllListeners(type) {
      var listeners, events, i;

      events = this._events;
      if (events === undefined)
        return this;

      // not listening for removeListener, no need to emit
      if (events.removeListener === undefined) {
        if (arguments.length === 0) {
          this._events = Object.create(null);
          this._eventsCount = 0;
        } else if (events[type] !== undefined) {
          if (--this._eventsCount === 0)
            this._events = Object.create(null);
          else
            delete events[type];
        }
        return this;
      }

      // emit removeListener for all listeners on all events
      if (arguments.length === 0) {
        var keys = Object.keys(events);
        var key;
        for (i = 0; i < keys.length; ++i) {
          key = keys[i];
          if (key === 'removeListener') continue;
          this.removeAllListeners(key);
        }
        this.removeAllListeners('removeListener');
        this._events = Object.create(null);
        this._eventsCount = 0;
        return this;
      }

      listeners = events[type];

      if (typeof listeners === 'function') {
        this.removeListener(type, listeners);
      } else if (listeners !== undefined) {
        // LIFO order
        for (i = listeners.length - 1; i >= 0; i--) {
          this.removeListener(type, listeners[i]);
        }
      }

      return this;
    };

function _listeners(target, type, unwrap) {
  var events = target._events;

  if (events === undefined)
    return [];

  var evlistener = events[type];
  if (evlistener === undefined)
    return [];

  if (typeof evlistener === 'function')
    return unwrap ? [evlistener.listener || evlistener] : [evlistener];

  return unwrap ?
    unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}

EventEmitter.prototype.listeners = function listeners(type) {
  return _listeners(this, type, true);
};

EventEmitter.prototype.rawListeners = function rawListeners(type) {
  return _listeners(this, type, false);
};

EventEmitter.listenerCount = function(emitter, type) {
  if (typeof emitter.listenerCount === 'function') {
    return emitter.listenerCount(type);
  } else {
    return listenerCount.call(emitter, type);
  }
};

EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
  var events = this._events;

  if (events !== undefined) {
    var evlistener = events[type];

    if (typeof evlistener === 'function') {
      return 1;
    } else if (evlistener !== undefined) {
      return evlistener.length;
    }
  }

  return 0;
}

EventEmitter.prototype.eventNames = function eventNames() {
  return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};

function arrayClone(arr, n) {
  var copy = new Array(n);
  for (var i = 0; i < n; ++i)
    copy[i] = arr[i];
  return copy;
}

function spliceOne(list, index) {
  for (; index + 1 < list.length; index++)
    list[index] = list[index + 1];
  list.pop();
}

function unwrapListeners(arr) {
  var ret = new Array(arr.length);
  for (var i = 0; i < ret.length; ++i) {
    ret[i] = arr[i].listener || arr[i];
  }
  return ret;
}


/***/ }),
/* 200 */
/***/ (function(module, exports, __nested_webpack_require_1044682__) {

/* eslint-disable node/no-deprecated-api */
var buffer = __nested_webpack_require_1044682__(113)
var Buffer = buffer.Buffer

// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
  for (var key in src) {
    dst[key] = src[key]
  }
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  module.exports = buffer
} else {
  // Copy properties from require('buffer')
  copyProps(buffer, exports)
  exports.Buffer = SafeBuffer
}

function SafeBuffer (arg, encodingOrOffset, length) {
  return Buffer(arg, encodingOrOffset, length)
}

// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)

SafeBuffer.from = function (arg, encodingOrOffset, length) {
  if (typeof arg === 'number') {
    throw new TypeError('Argument must not be a number')
  }
  return Buffer(arg, encodingOrOffset, length)
}

SafeBuffer.alloc = function (size, fill, encoding) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  var buf = Buffer(size)
  if (fill !== undefined) {
    if (typeof encoding === 'string') {
      buf.fill(fill, encoding)
    } else {
      buf.fill(fill)
    }
  } else {
    buf.fill(0)
  }
  return buf
}

SafeBuffer.allocUnsafe = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return Buffer(size)
}

SafeBuffer.allocUnsafeSlow = function (size) {
  if (typeof size !== 'number') {
    throw new TypeError('Argument must be a number')
  }
  return buffer.SlowBuffer(size)
}


/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var Mixin = module.exports = function (host) {
    var originalMethods = {},
        overriddenMethods = this._getOverriddenMethods(this, originalMethods);

    Object.keys(overriddenMethods).forEach(function (key) {
        if (typeof overriddenMethods[key] === 'function') {
            originalMethods[key] = host[key];
            host[key] = overriddenMethods[key];
        }
    });
};

Mixin.prototype._getOverriddenMethods = function () {
    throw new Error('Not implemented');
};



/***/ }),
/* 202 */
/***/ (function(module, exports, __nested_webpack_require_1046883__) {

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

module.exports = Stream;

var EE = __nested_webpack_require_1046883__(199).EventEmitter;
var inherits = __nested_webpack_require_1046883__(58);

inherits(Stream, EE);
Stream.Readable = __nested_webpack_require_1046883__(304);
Stream.Writable = __nested_webpack_require_1046883__(988);
Stream.Duplex = __nested_webpack_require_1046883__(989);
Stream.Transform = __nested_webpack_require_1046883__(990);
Stream.PassThrough = __nested_webpack_require_1046883__(991);

// Backwards-compat with node 0.4.x
Stream.Stream = Stream;



// old-style streams.  Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.

function Stream() {
  EE.call(this);
}

Stream.prototype.pipe = function(dest, options) {
  var source = this;

  function ondata(chunk) {
    if (dest.writable) {
      if (false === dest.write(chunk) && source.pause) {
        source.pause();
      }
    }
  }

  source.on('data', ondata);

  function ondrain() {
    if (source.readable && source.resume) {
      source.resume();
    }
  }

  dest.on('drain', ondrain);

  // If the 'end' option is not supplied, dest.end() will be called when
  // source gets the 'end' or 'close' events.  Only dest.end() once.
  if (!dest._isStdio && (!options || options.end !== false)) {
    source.on('end', onend);
    source.on('close', onclose);
  }

  var didOnEnd = false;
  function onend() {
    if (didOnEnd) return;
    didOnEnd = true;

    dest.end();
  }


  function onclose() {
    if (didOnEnd) return;
    didOnEnd = true;

    if (typeof dest.destroy === 'function') dest.destroy();
  }

  // don't leave dangling pipes when there are errors.
  function onerror(er) {
    cleanup();
    if (EE.listenerCount(this, 'error') === 0) {
      throw er; // Unhandled stream error in pipe.
    }
  }

  source.on('error', onerror);
  dest.on('error', onerror);

  // remove all the event listeners that were added.
  function cleanup() {
    source.removeListener('data', ondata);
    dest.removeListener('drain', ondrain);

    source.removeListener('end', onend);
    source.removeListener('close', onclose);

    source.removeListener('error', onerror);
    dest.removeListener('error', onerror);

    source.removeListener('end', cleanup);
    source.removeListener('close', cleanup);

    dest.removeListener('close', cleanup);
  }

  source.on('end', cleanup);
  source.on('close', cleanup);

  dest.on('close', cleanup);

  dest.emit('pipe', source);

  // Allow for unix-like usage: A.pipe(B).pipe(C)
  return dest;
};


/***/ }),
/* 203 */
/***/ (function(module, exports, __nested_webpack_require_1050528__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process) {

if (!process.version ||
    process.version.indexOf('v0.') === 0 ||
    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  module.exports = { nextTick: nextTick };
} else {
  module.exports = process
}

function nextTick(fn, arg1, arg2, arg3) {
  if (typeof fn !== 'function') {
    throw new TypeError('"callback" argument must be a function');
  }
  var len = arguments.length;
  var args, i;
  switch (len) {
  case 0:
  case 1:
    return process.nextTick(fn);
  case 2:
    return process.nextTick(function afterTickOne() {
      fn.call(null, arg1);
    });
  case 3:
    return process.nextTick(function afterTickTwo() {
      fn.call(null, arg1, arg2);
    });
  case 4:
    return process.nextTick(function afterTickThree() {
      fn.call(null, arg1, arg2, arg3);
    });
  default:
    args = new Array(len - 1);
    i = 0;
    while (i < args.length) {
      args[i++] = arguments[i];
    }
    return process.nextTick(function afterTick() {
      fn.apply(null, args);
    });
  }
}


/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1050528__(150)))

/***/ }),
/* 204 */
/***/ (function(module, exports, __nested_webpack_require_1051767__) {

var assign = __nested_webpack_require_1051767__(472);

/*
 * Cheerio default options
 */

exports.default = {
  withDomLvl1: true,
  normalizeWhitespace: false,
  xml: false,
  decodeEntities: true
};

exports.flatten = function(options) {
  return options && options.xml ? assign({xmlMode: true}, options.xml) : options;
};

/***/ }),
/* 205 */
/***/ (function(module, exports, __nested_webpack_require_1052155__) {

var baseCreate = __nested_webpack_require_1052155__(197),
    isObject = __nested_webpack_require_1052155__(45);

/**
 * Creates a function that produces an instance of `Ctor` regardless of
 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
 *
 * @private
 * @param {Function} Ctor The constructor to wrap.
 * @returns {Function} Returns the new wrapped function.
 */
function createCtor(Ctor) {
  return function() {
    // Use a `switch` statement to work with class constructors. See
    // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
    // for more details.
    var args = arguments;
    switch (args.length) {
      case 0: return new Ctor;
      case 1: return new Ctor(args[0]);
      case 2: return new Ctor(args[0], args[1]);
      case 3: return new Ctor(args[0], args[1], args[2]);
      case 4: return new Ctor(args[0], args[1], args[2], args[3]);
      case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
      case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
      case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
    }
    var thisBinding = baseCreate(Ctor.prototype),
        result = Ctor.apply(thisBinding, args);

    // Mimic the constructor's `return` behavior.
    // See https://es5.github.io/#x13.2.2 for more details.
    return isObject(result) ? result : thisBinding;
  };
}

module.exports = createCtor;


/***/ }),
/* 206 */
/***/ (function(module, exports) {

/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';

/**
 * Replaces all `placeholder` elements in `array` with an internal placeholder
 * and returns an array of their indexes.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {*} placeholder The placeholder to replace.
 * @returns {Array} Returns the new array of placeholder indexes.
 */
function replaceHolders(array, placeholder) {
  var index = -1,
      length = array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (value === placeholder || value === PLACEHOLDER) {
      array[index] = PLACEHOLDER;
      result[resIndex++] = index;
    }
  }
  return result;
}

module.exports = replaceHolders;


/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* globals
	Set,
	Map,
	WeakSet,
	WeakMap,

	Promise,

	Symbol,
	Proxy,

	Atomics,
	SharedArrayBuffer,

	ArrayBuffer,
	DataView,
	Uint8Array,
	Float32Array,
	Float64Array,
	Int8Array,
	Int16Array,
	Int32Array,
	Uint8ClampedArray,
	Uint16Array,
	Uint32Array,
*/

var undefined; // eslint-disable-line no-shadow-restricted-names

var ThrowTypeError = Object.getOwnPropertyDescriptor
	? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }())
	: function () { throw new TypeError(); };

var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';

var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto

var generator; // = function * () {};
var generatorFunction = generator ? getProto(generator) : undefined;
var asyncFn; // async function() {};
var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
var asyncGen; // async function * () {};
var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
var asyncGenIterator = asyncGen ? asyncGen() : undefined;

var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);

var INTRINSICS = {
	'$ %Array%': Array,
	'$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
	'$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
	'$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
	'$ %ArrayPrototype%': Array.prototype,
	'$ %ArrayProto_entries%': Array.prototype.entries,
	'$ %ArrayProto_forEach%': Array.prototype.forEach,
	'$ %ArrayProto_keys%': Array.prototype.keys,
	'$ %ArrayProto_values%': Array.prototype.values,
	'$ %AsyncFromSyncIteratorPrototype%': undefined,
	'$ %AsyncFunction%': asyncFunction,
	'$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
	'$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
	'$ %AsyncGeneratorFunction%': asyncGenFunction,
	'$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
	'$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
	'$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
	'$ %Boolean%': Boolean,
	'$ %BooleanPrototype%': Boolean.prototype,
	'$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView,
	'$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,
	'$ %Date%': Date,
	'$ %DatePrototype%': Date.prototype,
	'$ %decodeURI%': decodeURI,
	'$ %decodeURIComponent%': decodeURIComponent,
	'$ %encodeURI%': encodeURI,
	'$ %encodeURIComponent%': encodeURIComponent,
	'$ %Error%': Error,
	'$ %ErrorPrototype%': Error.prototype,
	'$ %eval%': eval, // eslint-disable-line no-eval
	'$ %EvalError%': EvalError,
	'$ %EvalErrorPrototype%': EvalError.prototype,
	'$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
	'$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
	'$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
	'$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
	'$ %Function%': Function,
	'$ %FunctionPrototype%': Function.prototype,
	'$ %Generator%': generator ? getProto(generator()) : undefined,
	'$ %GeneratorFunction%': generatorFunction,
	'$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
	'$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
	'$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
	'$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
	'$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
	'$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
	'$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
	'$ %isFinite%': isFinite,
	'$ %isNaN%': isNaN,
	'$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
	'$ %JSON%': JSON,
	'$ %JSONParse%': JSON.parse,
	'$ %Map%': typeof Map === 'undefined' ? undefined : Map,
	'$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
	'$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,
	'$ %Math%': Math,
	'$ %Number%': Number,
	'$ %NumberPrototype%': Number.prototype,
	'$ %Object%': Object,
	'$ %ObjectPrototype%': Object.prototype,
	'$ %ObjProto_toString%': Object.prototype.toString,
	'$ %ObjProto_valueOf%': Object.prototype.valueOf,
	'$ %parseFloat%': parseFloat,
	'$ %parseInt%': parseInt,
	'$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise,
	'$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
	'$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
	'$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
	'$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
	'$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
	'$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
	'$ %RangeError%': RangeError,
	'$ %RangeErrorPrototype%': RangeError.prototype,
	'$ %ReferenceError%': ReferenceError,
	'$ %ReferenceErrorPrototype%': ReferenceError.prototype,
	'$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
	'$ %RegExp%': RegExp,
	'$ %RegExpPrototype%': RegExp.prototype,
	'$ %Set%': typeof Set === 'undefined' ? undefined : Set,
	'$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
	'$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
	'$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
	'$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
	'$ %String%': String,
	'$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
	'$ %StringPrototype%': String.prototype,
	'$ %Symbol%': hasSymbols ? Symbol : undefined,
	'$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
	'$ %SyntaxError%': SyntaxError,
	'$ %SyntaxErrorPrototype%': SyntaxError.prototype,
	'$ %ThrowTypeError%': ThrowTypeError,
	'$ %TypedArray%': TypedArray,
	'$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
	'$ %TypeError%': TypeError,
	'$ %TypeErrorPrototype%': TypeError.prototype,
	'$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
	'$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
	'$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
	'$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
	'$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
	'$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
	'$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
	'$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
	'$ %URIError%': URIError,
	'$ %URIErrorPrototype%': URIError.prototype,
	'$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
	'$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
	'$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
	'$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
};

module.exports = function GetIntrinsic(name, allowMissing) {
	if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
		throw new TypeError('"allowMissing" argument must be a boolean');
	}

	var key = '$ ' + name;
	if (!(key in INTRINSICS)) {
		throw new SyntaxError('intrinsic ' + name + ' does not exist!');
	}

	// istanbul ignore if // hopefully this is impossible to test :-)
	if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
		throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
	}
	return INTRINSICS[key];
};


/***/ }),
/* 208 */
/***/ (function(module, exports, __nested_webpack_require_1063220__) {

__nested_webpack_require_1063220__(209);
module.exports = __nested_webpack_require_1063220__(12).Object.keys;


/***/ }),
/* 209 */
/***/ (function(module, exports, __nested_webpack_require_1063379__) {

// 19.1.2.14 Object.keys(O)
var toObject = __nested_webpack_require_1063379__(54);
var $keys = __nested_webpack_require_1063379__(60);

__nested_webpack_require_1063379__(126)('keys', function () {
  return function keys(it) {
    return $keys(toObject(it));
  };
});


/***/ }),
/* 210 */
/***/ (function(module, exports, __nested_webpack_require_1063681__) {

// false -> Array#indexOf
// true  -> Array#includes
var toIObject = __nested_webpack_require_1063681__(48);
var toLength = __nested_webpack_require_1063681__(88);
var toAbsoluteIndex = __nested_webpack_require_1063681__(211);
module.exports = function (IS_INCLUDES) {
  return function ($this, el, fromIndex) {
    var O = toIObject($this);
    var length = toLength(O.length);
    var index = toAbsoluteIndex(fromIndex, length);
    var value;
    // Array#includes uses SameValueZero equality algorithm
    // eslint-disable-next-line no-self-compare
    if (IS_INCLUDES && el != el) while (length > index) {
      value = O[index++];
      // eslint-disable-next-line no-self-compare
      if (value != value) return true;
    // Array#indexOf ignores holes, Array#includes - not
    } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
      if (O[index] === el) return IS_INCLUDES || index || 0;
    } return !IS_INCLUDES && -1;
  };
};


/***/ }),
/* 211 */
/***/ (function(module, exports, __nested_webpack_require_1064676__) {

var toInteger = __nested_webpack_require_1064676__(89);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
  index = toInteger(index);
  return index < 0 ? max(index + length, 0) : min(index, length);
};


/***/ }),
/* 212 */
/***/ (function(module, exports, __nested_webpack_require_1064977__) {

"use strict";

var addToUnscopables = __nested_webpack_require_1064977__(213);
var step = __nested_webpack_require_1064977__(160);
var Iterators = __nested_webpack_require_1064977__(51);
var toIObject = __nested_webpack_require_1064977__(48);

// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __nested_webpack_require_1064977__(109)(Array, 'Array', function (iterated, kind) {
  this._t = toIObject(iterated); // target
  this._i = 0;                   // next index
  this._k = kind;                // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
  var O = this._t;
  var kind = this._k;
  var index = this._i++;
  if (!O || index >= O.length) {
    this._t = undefined;
    return step(1);
  }
  if (kind == 'keys') return step(0, index);
  if (kind == 'values') return step(0, O[index]);
  return step(0, [index, O[index]]);
}, 'values');

// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;

addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');


/***/ }),
/* 213 */
/***/ (function(module, exports) {

module.exports = function () { /* empty */ };


/***/ }),
/* 214 */
/***/ (function(module, exports, __nested_webpack_require_1066268__) {

"use strict";

var create = __nested_webpack_require_1066268__(110);
var descriptor = __nested_webpack_require_1066268__(66);
var setToStringTag = __nested_webpack_require_1066268__(77);
var IteratorPrototype = {};

// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__nested_webpack_require_1066268__(43)(IteratorPrototype, __nested_webpack_require_1066268__(21)('iterator'), function () { return this; });

module.exports = function (Constructor, NAME, next) {
  Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
  setToStringTag(Constructor, NAME + ' Iterator');
};


/***/ }),
/* 215 */
/***/ (function(module, exports, __nested_webpack_require_1066870__) {

var toInteger = __nested_webpack_require_1066870__(89);
var defined = __nested_webpack_require_1066870__(87);
// true  -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
  return function (that, pos) {
    var s = String(defined(that));
    var i = toInteger(pos);
    var l = s.length;
    var a, b;
    if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
    a = s.charCodeAt(i);
    return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
      ? TO_STRING ? s.charAt(i) : a
      : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
  };
};


/***/ }),
/* 216 */
/***/ (function(module, exports, __nested_webpack_require_1067570__) {

__nested_webpack_require_1067570__(76);
__nested_webpack_require_1067570__(61);
module.exports = __nested_webpack_require_1067570__(217);


/***/ }),
/* 217 */
/***/ (function(module, exports, __nested_webpack_require_1067742__) {

var anObject = __nested_webpack_require_1067742__(39);
var get = __nested_webpack_require_1067742__(112);
module.exports = __nested_webpack_require_1067742__(12).getIterator = function (it) {
  var iterFn = get(it);
  if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
  return anObject(iterFn.call(it));
};


/***/ }),
/* 218 */
/***/ (function(module, exports) {

module.exports = function (it, Constructor, name, forbiddenField) {
  if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
    throw TypeError(name + ': incorrect invocation!');
  } return it;
};


/***/ }),
/* 219 */
/***/ (function(module, exports, __nested_webpack_require_1068404__) {

"use strict";

// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __nested_webpack_require_1068404__(92);

function PromiseCapability(C) {
  var resolve, reject;
  this.promise = new C(function ($$resolve, $$reject) {
    if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
    resolve = $$resolve;
    reject = $$reject;
  });
  this.resolve = aFunction(resolve);
  this.reject = aFunction(reject);
}

module.exports.f = function (C) {
  return new PromiseCapability(C);
};


/***/ }),
/* 220 */
/***/ (function(module, exports, __nested_webpack_require_1068987__) {

var hide = __nested_webpack_require_1068987__(43);
module.exports = function (target, src, safe) {
  for (var key in src) {
    if (safe && target[key]) target[key] = src[key];
    else hide(target, key, src[key]);
  } return target;
};


/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var XMLNS = 'http://www.w3.org/2000/svg';

/**
 * Check if an HTML or SVG element has a certain class
 * @param   {object}  el  HTML or SVG element to be checked.
 * @param   {string}  className  Class name to be checked for.
 * @return  {boolean}  If `true` `el` has the class name.
 */
var hasClass = function hasClass(el, className) {
  if (el.namespaceURI === XMLNS) {
    var _class = el.getAttribute('class');
    return _class && !!_class.match(new RegExp('(\\s|^)' + String(className) + '(\\s|$)'));
  }

  if (el.classList) return el.classList.contains(className);

  return !!el.className.match(new RegExp('(\\s|^)' + String(className) + '(\\s|$)'));
};

exports['default'] = hasClass;

/***/ }),
/* 222 */
/***/ (function(module, exports, __nested_webpack_require_1070143__) {

__nested_webpack_require_1070143__(223);
module.exports = __nested_webpack_require_1070143__(12).Object.assign;


/***/ }),
/* 223 */
/***/ (function(module, exports, __nested_webpack_require_1070304__) {

// 19.1.3.1 Object.assign(target, source)
var $export = __nested_webpack_require_1070304__(16);

$export($export.S + $export.F, 'Object', { assign: __nested_webpack_require_1070304__(224) });


/***/ }),
/* 224 */
/***/ (function(module, exports, __nested_webpack_require_1070545__) {

"use strict";

// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __nested_webpack_require_1070545__(60);
var gOPS = __nested_webpack_require_1070545__(130);
var pIE = __nested_webpack_require_1070545__(93);
var toObject = __nested_webpack_require_1070545__(54);
var IObject = __nested_webpack_require_1070545__(105);
var $assign = Object.assign;

// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __nested_webpack_require_1070545__(50)(function () {
  var A = {};
  var B = {};
  // eslint-disable-next-line no-undef
  var S = Symbol();
  var K = 'abcdefghijklmnopqrst';
  A[S] = 7;
  K.split('').forEach(function (k) { B[k] = k; });
  return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  var T = toObject(target);
  var aLen = arguments.length;
  var index = 1;
  var getSymbols = gOPS.f;
  var isEnum = pIE.f;
  while (aLen > index) {
    var S = IObject(arguments[index++]);
    var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
    var length = keys.length;
    var j = 0;
    var key;
    while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
  } return T;
} : $assign;


/***/ }),
/* 225 */
/***/ (function(module, exports, __nested_webpack_require_1071823__) {

module.exports = { "default": __nested_webpack_require_1071823__(547), __esModule: true };

/***/ }),
/* 226 */
/***/ (function(module, exports, __nested_webpack_require_1071977__) {

var META = __nested_webpack_require_1071977__(91)('meta');
var isObject = __nested_webpack_require_1071977__(33);
var has = __nested_webpack_require_1071977__(47);
var setDesc = __nested_webpack_require_1071977__(32).f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
  return true;
};
var FREEZE = !__nested_webpack_require_1071977__(50)(function () {
  return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
  setDesc(it, META, { value: {
    i: 'O' + ++id, // object ID
    w: {}          // weak collections IDs
  } });
};
var fastKey = function (it, create) {
  // return primitive with prefix
  if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return 'F';
    // not necessary to add metadata
    if (!create) return 'E';
    // add missing metadata
    setMeta(it);
  // return object ID
  } return it[META].i;
};
var getWeak = function (it, create) {
  if (!has(it, META)) {
    // can't set metadata to uncaught frozen object
    if (!isExtensible(it)) return true;
    // not necessary to add metadata
    if (!create) return false;
    // add missing metadata
    setMeta(it);
  // return hash weak collections IDs
  } return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
  if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
  return it;
};
var meta = module.exports = {
  KEY: META,
  NEED: false,
  fastKey: fastKey,
  getWeak: getWeak,
  onFreeze: onFreeze
};


/***/ }),
/* 227 */
/***/ (function(module, exports, __nested_webpack_require_1073630__) {

var global = __nested_webpack_require_1073630__(23);
var core = __nested_webpack_require_1073630__(12);
var LIBRARY = __nested_webpack_require_1073630__(75);
var wksExt = __nested_webpack_require_1073630__(168);
var defineProperty = __nested_webpack_require_1073630__(32).f;
module.exports = function (name) {
  var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
  if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};


/***/ }),
/* 228 */
/***/ (function(module, exports, __nested_webpack_require_1074139__) {

var pIE = __nested_webpack_require_1074139__(93);
var createDesc = __nested_webpack_require_1074139__(66);
var toIObject = __nested_webpack_require_1074139__(48);
var toPrimitive = __nested_webpack_require_1074139__(127);
var has = __nested_webpack_require_1074139__(47);
var IE8_DOM_DEFINE = __nested_webpack_require_1074139__(159);
var gOPD = Object.getOwnPropertyDescriptor;

exports.f = __nested_webpack_require_1074139__(36) ? gOPD : function getOwnPropertyDescriptor(O, P) {
  O = toIObject(O);
  P = toPrimitive(P, true);
  if (IE8_DOM_DEFINE) try {
    return gOPD(O, P);
  } catch (e) { /* empty */ }
  if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};


/***/ }),
/* 229 */
/***/ (function(module, exports, __nested_webpack_require_1074787__) {

var core = __nested_webpack_require_1074787__(12);
var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify });
module.exports = function stringify(it) { // eslint-disable-line no-unused-vars
  return $JSON.stringify.apply($JSON, arguments);
};


/***/ }),
/* 230 */
/***/ (function(module, exports, __nested_webpack_require_1075105__) {

__nested_webpack_require_1075105__(231);
var $Object = __nested_webpack_require_1075105__(12).Object;
module.exports = function defineProperty(it, key, desc) {
  return $Object.defineProperty(it, key, desc);
};


/***/ }),
/* 231 */
/***/ (function(module, exports, __nested_webpack_require_1075365__) {

var $export = __nested_webpack_require_1075365__(16);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__nested_webpack_require_1075365__(36), 'Object', { defineProperty: __nested_webpack_require_1075365__(32).f });


/***/ }),
/* 232 */
/***/ (function(module, exports, __nested_webpack_require_1075662__) {

"use strict";


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

var _extends2 = __nested_webpack_require_1075662__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _isNan = __nested_webpack_require_1075662__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _typeof2 = __nested_webpack_require_1075662__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

var _promise = __nested_webpack_require_1075662__(62);

var _promise2 = _interopRequireDefault(_promise);

var _toConsumableArray2 = __nested_webpack_require_1075662__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _keys = __nested_webpack_require_1075662__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getIterator2 = __nested_webpack_require_1075662__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _stringify = __nested_webpack_require_1075662__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _values = __nested_webpack_require_1075662__(37);

var _values2 = _interopRequireDefault(_values);

var _slicedToArray2 = __nested_webpack_require_1075662__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _entries = __nested_webpack_require_1075662__(577);

var _entries2 = _interopRequireDefault(_entries);

var _assign = __nested_webpack_require_1075662__(44);

var _assign2 = _interopRequireDefault(_assign);

var _set = __nested_webpack_require_1075662__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1075662__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1075662__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1075662__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1075662__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1075662__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_1075662__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_1075662__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_1075662__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _d3Selection = __nested_webpack_require_1075662__(0);

var _d3Scale = __nested_webpack_require_1075662__(28);

var _slugid = __nested_webpack_require_1075662__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _pixi = __nested_webpack_require_1075662__(325);

var PIXI = _interopRequireWildcard(_pixi);

var _reactDom = __nested_webpack_require_1075662__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _reactGridLayout = __nested_webpack_require_1075662__(594);

var _reactGridLayout2 = _interopRequireDefault(_reactGridLayout);

var _cssElementQueries = __nested_webpack_require_1075662__(344);

var _vkbeautify = __nested_webpack_require_1075662__(602);

var _vkbeautify2 = _interopRequireDefault(_vkbeautify);

var _urlParse = __nested_webpack_require_1075662__(603);

var _urlParse2 = _interopRequireDefault(_urlParse);

var _pubSubEs = __nested_webpack_require_1075662__(134);

var _pubSubEs2 = _interopRequireDefault(_pubSubEs);

var _TiledPlot = __nested_webpack_require_1075662__(606);

var _TiledPlot2 = _interopRequireDefault(_TiledPlot);

var _GenomePositionSearchBox = __nested_webpack_require_1075662__(676);

var _GenomePositionSearchBox2 = _interopRequireDefault(_GenomePositionSearchBox);

var _ExportLinkDialog = __nested_webpack_require_1075662__(682);

var _ExportLinkDialog2 = _interopRequireDefault(_ExportLinkDialog);

var _ViewHeader = __nested_webpack_require_1075662__(684);

var _ViewHeader2 = _interopRequireDefault(_ViewHeader);

var _ChromosomeInfo = __nested_webpack_require_1075662__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _ViewConfigEditor = __nested_webpack_require_1075662__(688);

var _ViewConfigEditor2 = _interopRequireDefault(_ViewConfigEditor);

var _symbol = __nested_webpack_require_1075662__(725);

var _symbol2 = _interopRequireDefault(_symbol);

var _icons = __nested_webpack_require_1075662__(266);

var _api = __nested_webpack_require_1075662__(726);

var _api2 = _interopRequireDefault(_api);

var _withPubSub = __nested_webpack_require_1075662__(69);

var _withModal = __nested_webpack_require_1075662__(132);

var _withTheme = __nested_webpack_require_1075662__(78);

var _services = __nested_webpack_require_1075662__(24);

var _utils = __nested_webpack_require_1075662__(10);

var _configs = __nested_webpack_require_1075662__(11);

var _HiGlassModule = __nested_webpack_require_1075662__(730);

var _HiGlassModule2 = _interopRequireDefault(_HiGlassModule);

var _ViewHeaderModule = __nested_webpack_require_1075662__(267);

var _ViewHeaderModule2 = _interopRequireDefault(_ViewHeaderModule);

var _HiGlass = __nested_webpack_require_1075662__(731);

var _HiGlass2 = _interopRequireDefault(_HiGlass);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

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

// eslint-disable-line no-unused-vars

// eslint-disable-line no-unused-vars


// Configs


// Services
var _styleModuleImportMap = {
  'styles': {
    'higlass': 'HiGlass-module_higlass-1NHR2',
    'higlass-dark-theme': 'HiGlass-module_higlass-dark-theme-2visd',
    'higlass-container-overflow': 'HiGlass-module_higlass-container-overflow-zNXnY',
    'higlass-scroll-container-overflow': 'HiGlass-module_higlass-scroll-container-overflow-2FS0w',
    'higlass-scroll-container-scroll': 'HiGlass-module_higlass-scroll-container-scroll-2lAU4',
    'higlass-canvas': 'HiGlass-module_higlass-canvas-_mP9r',
    'higlass-drawing-surface': 'HiGlass-module_higlass-drawing-surface-3aQQo',
    'higlass-svg': 'HiGlass-module_higlass-svg-JJZbf',
    'tiled-area': 'HiGlass-module_tiled-area-22H1L',
    'track-mouseover-menu': 'HiGlass-module_track-mouseover-menu-1AoaP'
  },
  'stylesMTHeader': {
    'multitrack-header': 'ViewHeader-module_multitrack-header-3XnZx',
    'multitrack-header-focus': 'ViewHeader-module_multitrack-header-focus-3akkN',
    'multitrack-header-squeazed': 'ViewHeader-module_multitrack-header-squeazed-GHIVd',
    'multitrack-header-dark': 'ViewHeader-module_multitrack-header-dark-97tZt',
    'multitrack-header-id': 'ViewHeader-module_multitrack-header-id-3YURk',
    'multitrack-header-left': 'ViewHeader-module_multitrack-header-left-Qj9Sm',
    'multitrack-header-grabber': 'ViewHeader-module_multitrack-header-grabber-3jrIz',
    'multitrack-header-grabber-squeazed': 'ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z',
    'multitrack-header-search': 'ViewHeader-module_multitrack-header-search-1X_3_',
    'multitrack-header-nav-list': 'ViewHeader-module_multitrack-header-nav-list-2nvcu',
    'multitrack-header-icon': 'ViewHeader-module_multitrack-header-icon-16QKZ',
    'multitrack-header-icon-squeazed': 'ViewHeader-module_multitrack-header-icon-squeazed-25lkF',
    'mouse-tool-selection': 'ViewHeader-module_mouse-tool-selection-1pg2m'
  },
  'stylesGlobal': {
    'higlass': 'HiGlass_higlass-3aU-_',
    'react-resizable-handle': 'HiGlass_react-resizable-handle-3kCAE'
  }
}; // eslint-disable-line no-unused-vars

// Styles


// Utils


// Higher-order components

var NUM_GRID_COLUMNS = 12;
var DEFAULT_NEW_VIEW_HEIGHT = 12;
var VIEW_HEADER_HEIGHT = 20;
var SIZE_MODE_DEFAULT = 'default';
var SIZE_MODE_BOUNDED = 'bounded';
var SIZE_MODE_OVERFLOW = 'overflow';
var SIZE_MODE_SCROLL = 'scroll';

var HiGlassComponent = function (_React$Component) {
  (0, _inherits3['default'])(HiGlassComponent, _React$Component);

  function HiGlassComponent(props) {
    (0, _classCallCheck3['default'])(this, HiGlassComponent);

    // Check React version
    var _this = (0, _possibleConstructorReturn3['default'])(this, (HiGlassComponent.__proto__ || (0, _getPrototypeOf2['default'])(HiGlassComponent)).call(this, props));

    if ((0, _utils.numericifyVersion)(_react2['default'].version) < 15.6) {
      console.warn('HiGlass requires React v15.6 or higher. Current version: ', _react2['default'].version);
    }

    _this.pubSub = (0, _pubSubEs2['default'])();
    _this.domEvent = (0, _services.createDomEvent)(_this.pubSub);

    _this.pubSubs = [];

    _this.minHorizontalHeight = 20;
    _this.minVerticalWidth = 20;
    _this.resizeSensor = null;

    _this.uid = _slugid2['default'].nice();
    _this.tiledPlots = {};
    _this.genomePositionSearchBoxes = {};

    // keep track of the xScales of each Track Renderer
    _this.xScales = {};
    _this.yScales = {};
    _this.projectionXDomains = {};
    _this.projectionYDomains = {};
    _this.topDiv = null;
    _this.zoomToDataExtentOnInit = new _set2['default']();

    // a reference of view / track combinations
    // to be used with combined to viewAndTrackUid
    _this.viewTrackUidsToCombinedUid = {};
    _this.combinedUidToViewTrack = {};

    // event listeners for when the scales of a view change
    // bypasses the React event framework because this needs
    // to be fast
    // indexed by view uid and then listener uid
    _this.scalesChangedListeners = {};
    _this.draggingChangedListeners = {};
    _this.valueScalesChangedListeners = {};

    // locks that keep the location and zoom synchronized
    // between views
    _this.zoomLocks = {};
    _this.locationLocks = {};

    // axis-specific location lock
    _this.locationLocksAxisWise = { x: {}, y: {} };

    // locks that keep the value scales synchronized between
    // *tracks* (which can be in different views)
    _this.valueScaleLocks = {};

    _this.prevAuthToken = props.options.authToken;
    _this.setCenters = {};

    _this.plusImg = {};
    _this.configImg = {};

    // allow a different PIXI to be passed in case the
    // caller wants to use a different version
    _configs.GLOBALS.PIXI = props.options && props.options.PIXI || PIXI;

    _this.viewMarginTop = +props.options.viewMarginTop >= 0 ? +props.options.viewMarginTop : _configs.DEFAULT_VIEW_MARGIN;
    _this.viewMarginBottom = +props.options.viewMarginBottom >= 0 ? +props.options.viewMarginBottom : _configs.DEFAULT_VIEW_MARGIN;
    _this.viewMarginLeft = +props.options.viewMarginLeft >= 0 ? +props.options.viewMarginLeft : _configs.DEFAULT_VIEW_MARGIN;
    _this.viewMarginRight = +props.options.viewMarginRight >= 0 ? +props.options.viewMarginRight : _configs.DEFAULT_VIEW_MARGIN;

    _this.viewPaddingTop = +props.options.viewPaddingTop >= 0 ? +props.options.viewPaddingTop : _configs.DEFAULT_VIEW_PADDING;
    _this.viewPaddingBottom = +props.options.viewPaddingBottom >= 0 ? +props.options.viewPaddingBottom : _configs.DEFAULT_VIEW_PADDING;
    _this.viewPaddingLeft = +props.options.viewPaddingLeft >= 0 ? +props.options.viewPaddingLeft : _configs.DEFAULT_VIEW_PADDING;
    _this.viewPaddingRight = +props.options.viewPaddingRight >= 0 ? +props.options.viewPaddingRight : _configs.DEFAULT_VIEW_PADDING;

    _this.genomePositionSearchBox = null;
    _this.viewHeaders = {};

    _this.boundRefreshView = function () {
      _this.refreshView(_configs.LONG_DRAG_TIMEOUT);
    };

    _this.unsetOnLocationChange = [];

    _this.setTheme(props.options.theme, props.options.isDarkTheme);

    _this.viewconfLoaded = false;

    var viewConfig = _this.props.viewConfig;

    var views = _this.loadIfRemoteViewConfig(_this.props.viewConfig);

    if (props.options.authToken) {
      (0, _services.setTileProxyAuthHeader)(props.options.authToken);
    }

    _this.pixiRoot = new _configs.GLOBALS.PIXI.Container();
    _this.pixiRoot.interactive = true;

    _this.pixiStage = new _configs.GLOBALS.PIXI.Container();
    _this.pixiStage.interactive = true;
    _this.pixiRoot.addChild(_this.pixiStage);

    _this.pixiMask = new _configs.GLOBALS.PIXI.Graphics();
    _this.pixiRoot.addChild(_this.pixiMask);
    _this.pixiStage.mask = _this.pixiMask;

    _this.element = null;
    _this.scrollTop = 0;

    var mouseTool = _configs.MOUSE_TOOL_MOVE;

    if (_this.props.options) {
      switch (_this.props.options.mouseTool) {
        case _configs.MOUSE_TOOL_SELECT:
          mouseTool = _configs.MOUSE_TOOL_SELECT;
          break;
        default:
          break;
      }
    }

    if (_this.props.options.pluginTracks) {
      window.higlassTracksByType = (0, _assign2['default'])(window.higlassTracksByType || {}, _this.props.options.pluginTracks);
    }

    var pluginTracks = {};
    try {
      if (window.higlassTracksByType) {
        (0, _entries2['default'])(window.higlassTracksByType).forEach(function (_ref) {
          var _ref2 = (0, _slicedToArray3['default'])(_ref, 2),
              trackType = _ref2[0],
              trackDef = _ref2[1];

          pluginTracks[trackType] = trackDef;
        });
      }
    } catch (e) {
      console.warn('Broken config of a plugin track');
    }

    if (_this.props.options.pluginDataFetchers) {
      window.higlassDataFetchersByType = (0, _assign2['default'])(window.higlassDataFetchersByType || {}, _this.props.options.pluginDataFetchers);
    }

    var pluginDataFetchers = window.higlassDataFetchersByType;

    var rowHeight = _this.props.options.pixelPreciseMarginPadding ? 1 : 30;

    _this.mounted = false;
    _this.pluginTracks = pluginTracks;
    _this.pluginDataFetchers = pluginDataFetchers;

    _this.state = {
      currentBreakpoint: 'lg',
      width: 0,
      height: 0,
      rowHeight: rowHeight,
      svgElement: null,
      canvasElement: null,
      views: views,
      viewConfig: viewConfig,
      addTrackPositionMenuPosition: null,
      typedEditable: undefined,
      mouseOverOverlayUid: null,
      mouseTool: mouseTool,
      isDarkTheme: false,
      rangeSelection1dSize: [0, Infinity],
      rangeSelectionToInt: false,
      modal: null
    };

    // monitor whether this element is attached to the DOM so that
    // we can determine whether to add the resizesensor
    _this.attachedToDOM = false;

    // Set up API

    var _createApi = (0, _api2['default'])(_this, _this.pubSub),
        api = _createApi['public'],
        apiDestroy = _createApi.destroy,
        apiPublish = _createApi.publish,
        apiStack = _createApi.stack;

    _this.api = api;
    _this.apiDestroy = apiDestroy;
    _this.apiPublish = apiPublish;
    _this.apiStack = apiStack;

    _this.viewChangeListener = [];

    _this.triggerViewChangeDb = (0, _utils.debounce)(_this.triggerViewChange.bind(_this), 250);

    _this.pubSubs = [];
    _this.rangeSelection = [null, null];

    _this.prevMouseHoverTrack = null;
    _this.zooming = false;

    // Bound functions
    _this.appClickHandlerBound = _this.appClickHandler.bind(_this);
    _this.keyDownHandlerBound = _this.keyDownHandler.bind(_this);
    _this.keyUpHandlerBound = _this.keyUpHandler.bind(_this);
    _this.resizeHandlerBound = _this.resizeHandler.bind(_this);
    _this.resizeHandlerBound = _this.resizeHandler.bind(_this);
    _this.dispatchEventBound = _this.dispatchEvent.bind(_this);
    _this.animateOnMouseMoveHandlerBound = _this.animateOnMouseMoveHandler.bind(_this);
    _this.zoomStartHandlerBound = _this.zoomStartHandler.bind(_this);
    _this.zoomEndHandlerBound = _this.zoomEndHandler.bind(_this);
    _this.zoomHandlerBound = _this.zoomHandler.bind(_this);
    _this.trackDroppedHandlerBound = _this.trackDroppedHandler.bind(_this);
    _this.trackDimensionsModifiedHandlerBound = _this.trackDimensionsModifiedHandler.bind(_this);
    _this.animateBound = _this.animate.bind(_this);
    _this.animateOnGlobalEventBound = _this.animateOnGlobalEvent.bind(_this);
    _this.requestReceivedHandlerBound = _this.requestReceivedHandler.bind(_this);
    _this.wheelHandlerBound = _this.wheelHandler.bind(_this);
    _this.mouseMoveHandlerBound = _this.mouseMoveHandler.bind(_this);
    _this.onMouseLeaveHandlerBound = _this.onMouseLeaveHandler.bind(_this);
    _this.onBlurHandlerBound = _this.onBlurHandler.bind(_this);
    _this.openModalBound = _this.openModal.bind(_this);
    _this.closeModalBound = _this.closeModal.bind(_this);
    _this.handleEditViewConfigBound = _this.handleEditViewConfig.bind(_this);
    _this.onScrollHandlerBound = _this.onScrollHandler.bind(_this);

    // for typed shortcuts (e.g. e-d-i-t) to toggle editable
    _this.typedText = '';
    _this.typedTextTimeout = null;

    _this.modal = {
      open: _this.openModalBound,
      close: _this.closeModalBound
    };

    _this.setBroadcastMousePositionGlobally(_this.props.options.broadcastMousePositionGlobally || _this.props.options.globalMousePosition);
    _this.setShowGlobalMousePosition(_this.props.options.showGlobalMousePosition || _this.props.options.globalMousePosition);
    return _this;
  }

  // eslint-disable-next-line camelcase


  (0, _createClass3['default'])(HiGlassComponent, [{
    key: 'UNSAFE_componentWillMount',
    value: function () {
      function UNSAFE_componentWillMount() {
        this.domEvent.register('keydown', document);
        this.domEvent.register('keyup', document);
        this.domEvent.register('scroll', document);
        this.domEvent.register('resize', window);
        this.domEvent.register('orientationchange', window);

        this.domEvent.register('wheel', window);
        this.domEvent.register('mousedown', window, true);
        this.domEvent.register('mouseup', window, true);
        this.domEvent.register('click', window, true);
        this.domEvent.register('mousemove', window);
        this.domEvent.register('touchmove', window);
        this.domEvent.register('touchstart', window);
        this.domEvent.register('touchend', window);
        this.domEvent.register('touchcancel', window);
        this.domEvent.register('blur', window);

        this.pubSubs.push(this.pubSub.subscribe('app.click', this.appClickHandlerBound), this.pubSub.subscribe('blur', this.onBlurHandlerBound), this.pubSub.subscribe('keydown', this.keyDownHandlerBound), this.pubSub.subscribe('keyup', this.keyUpHandlerBound), this.pubSub.subscribe('resize', this.resizeHandlerBound), this.pubSub.subscribe('wheel', this.wheelHandlerBound), this.pubSub.subscribe('orientationchange', this.resizeHandlerBound), this.pubSub.subscribe('app.event', this.dispatchEventBound), this.pubSub.subscribe('app.animateOnMouseMove', this.animateOnMouseMoveHandlerBound), this.pubSub.subscribe('trackDropped', this.trackDroppedHandlerBound), this.pubSub.subscribe('trackDimensionsModified', this.trackDimensionsModifiedHandlerBound), this.pubSub.subscribe('app.zoomStart', this.zoomStartHandlerBound), this.pubSub.subscribe('app.zoomEnd', this.zoomEndHandlerBound), this.pubSub.subscribe('app.zoom', this.zoomHandlerBound), this.pubSub.subscribe('requestReceived', this.requestReceivedHandlerBound));

        if (this.props.getApi) {
          this.props.getApi(this.api);
        }
      }

      return UNSAFE_componentWillMount;
    }()
  }, {
    key: 'setBroadcastMousePositionGlobally',
    value: function () {
      function setBroadcastMousePositionGlobally() {
        var isBroadcastMousePositionGlobally = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        this.isBroadcastMousePositionGlobally = isBroadcastMousePositionGlobally;
      }

      return setBroadcastMousePositionGlobally;
    }()
  }, {
    key: 'setShowGlobalMousePosition',
    value: function () {
      function setShowGlobalMousePosition() {
        var _this2 = this;

        var isShowGlobalMousePosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        this.isShowGlobalMousePosition = isShowGlobalMousePosition;

        if (this.isShowGlobalMousePosition && !this.globalMousePositionListener) {
          this.globalMousePositionListener = _pubSubEs.globalPubSub.subscribe('higlass.mouseMove', this.animateOnGlobalEventBound);
          this.pubSubs.push(this.globalMousePositionListener);
        }

        if (this.isShowGlobalMousePosition && !this.globalMousePositionListener) {
          var index = this.pubSubs.findIndex(function (listener) {
            return listener === _this2.globalMousePositionListener;
          });

          _pubSubEs.globalPubSub.unsubscribe(this.globalMousePositionListener);

          if (index >= 0) this.pubSubs.splice(index, 1);

          this.globalMousePositionListener = undefined;
        }
      }

      return setShowGlobalMousePosition;
    }()
  }, {
    key: 'zoomStartHandler',
    value: function () {
      function zoomStartHandler() {
        this.hideHoverMenu();
        this.zooming = true;
      }

      return zoomStartHandler;
    }()
  }, {
    key: 'zoomEndHandler',
    value: function () {
      function zoomEndHandler() {
        this.zooming = false;
      }

      return zoomEndHandler;
    }()
  }, {
    key: 'zoomHandler',
    value: function () {
      function zoomHandler(evt) {
        if (!evt.sourceEvent) return;

        this.mouseMoveHandler(evt.sourceEvent);
      }

      return zoomHandler;
    }()
  }, {
    key: 'waitForDOMAttachment',
    value: function () {
      function waitForDOMAttachment(callback) {
        var _this3 = this;

        if (!this.mounted) return;

        var thisElement = _reactDom2['default'].findDOMNode(this);

        if (document.body.contains(thisElement)) {
          callback();
        } else {
          requestAnimationFrame(function () {
            return _this3.waitForDOMAttachment(callback);
          });
        }
      }

      return waitForDOMAttachment;
    }()
  }, {
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        var _this4 = this;

        // the addEventListener is necessary because TrackRenderer determines where to paint
        // all the elements based on their bounding boxes. If the window isn't
        // in focus, everything is drawn at the top and overlaps. When it gains
        // focus we need to redraw everything in its proper place
        this.mounted = true;
        this.element = _reactDom2['default'].findDOMNode(this);
        window.addEventListener('focus', this.boundRefreshView);

        (0, _values2['default'])(this.state.views).forEach(function (view) {
          _this4.adjustLayoutToTrackSizes(view);

          if (!view.layout) {
            view.layout = _this4.generateViewLayout(view);
          } else {
            view.layout.i = view.uid;
          }
        });

        var rendererOptions = {
          width: this.state.width,
          height: this.state.height,
          view: this.canvasElement,
          antialias: true,
          transparent: true,
          resolution: 2,
          autoResize: true
        };

        switch (PIXI.VERSION[0]) {
          case '4':
            console.warn('Deprecation warning: please update Pixi.js to version 5!');
            if (this.props.options.renderer === 'canvas') {
              this.pixiRenderer = new _configs.GLOBALS.PIXI.CanvasRenderer(rendererOptions);
            } else {
              this.pixiRenderer = new _configs.GLOBALS.PIXI.WebGLRenderer(rendererOptions);
            }
            break;

          default:
            console.warn('Deprecation warning: please update Pixi.js to version 5! ' + 'This version of Pixi.js is unsupported. Good luck 🤞');
          // eslint-disable-next-line
          case '5':
            if (this.props.options.renderer === 'canvas') {
              this.pixiRenderer = new _configs.GLOBALS.PIXI.CanvasRenderer(rendererOptions);
            } else {
              this.pixiRenderer = new _configs.GLOBALS.PIXI.Renderer(rendererOptions);
            }
            break;
        }

        // PIXI.RESOLUTION=2;
        this.fitPixiToParentContainer();

        // keep track of the width and height of this element, because it
        // needs to be reflected in the size of our drawing surface
        // eslint-disable-next-line react/no-did-mount-set-state
        this.setState({
          svgElement: this.svgElement,
          canvasElement: this.canvasElement
        });

        this.waitForDOMAttachment(function () {
          _cssElementQueries.ElementQueries.listen();

          _this4.resizeSensor = new _cssElementQueries.ResizeSensor(_this4.element.parentNode, _this4.updateAfterResize.bind(_this4));

          // this.forceUpdate();
          _this4.updateAfterResize();
        });

        this.handleDragStart();
        this.handleDragStop();

        this.animate();
        // this.handleExportViewsAsLink();

        var baseSvg = (0, _d3Selection.select)(this.element).append('svg').style('display', 'none');

        // Add SVG Icons
        _icons.all.forEach(function (icon) {
          return (0, _symbol2['default'])(baseSvg, icon.id, icon.paths, icon.viewBox);
        });
      }

      return componentDidMount;
    }()
  }, {
    key: 'getTrackObject',
    value: function () {
      function getTrackObject(viewUid, trackUid) {
        return this.tiledPlots[viewUid].trackRenderer.getTrackObject(trackUid);
      }

      return getTrackObject;
    }()
  }, {
    key: 'getTrackRenderer',
    value: function () {
      function getTrackRenderer(viewUid) {
        return this.tiledPlots[viewUid].trackRenderer;
      }

      return getTrackRenderer;
    }()

    /**
     * Check if the passed in viewConfig is remote (i.e. is a string).
     * If it is, fetch it before proceeding
     */

  }, {
    key: 'loadIfRemoteViewConfig',
    value: function () {
      function loadIfRemoteViewConfig(viewConfig) {
        var _this5 = this;

        var views = {};
        if (typeof viewConfig === 'string') {
          // Load external viewConfig
          _services.tileProxy.json(viewConfig, function (error, remoteViewConfig) {
            viewConfig = remoteViewConfig;
            _this5.setState({
              views: _this5.processViewConfig(JSON.parse((0, _stringify2['default'])(remoteViewConfig))),
              viewConfig: remoteViewConfig
            });
            _this5.unsetOnLocationChange.forEach(function (_ref3) {
              var viewId = _ref3.viewId,
                  callback = _ref3.callback,
                  callbackId = _ref3.callbackId;

              _this5.onLocationChange(viewId, callback, callbackId);
            });
          }, this.pubSub);
        } else {
          views = this.processViewConfig(JSON.parse((0, _stringify2['default'])(viewConfig)));
          if (this.mounted) {
            this.setState({
              viewConfig: viewConfig
            });
          }
        }

        return views;
      }

      return loadIfRemoteViewConfig;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(newProps) {
        var viewsByUid = this.loadIfRemoteViewConfig(newProps.viewConfig);

        if (newProps.options.authToken !== this.prevAuthToken) {
          // we go a new auth token so we should reload everything
          (0, _services.setTileProxyAuthHeader)(newProps.options.authToken);

          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = undefined;

          try {
            for (var _iterator = (0, _getIterator3['default'])(this.iterateOverViews()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              var viewId = _step.value;

              var trackRenderer = this.getTrackRenderer(viewId);
              var trackDefinitions = JSON.parse(trackRenderer.prevTrackDefinitions);

              // this will remove all the tracks and then recreate them
              // re-requesting all tiles with the new auth key
              trackRenderer.syncTrackObjects([]);
              trackRenderer.syncTrackObjects(trackDefinitions);
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator['return']) {
                _iterator['return']();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }

          this.prevAuthToken = newProps.options.authToken;
        }

        // make sure that the current view is tall enough to display
        // all the tracks (if unbounded, which is checked in adjustLayout...)
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])((0, _utils.dictValues)(viewsByUid)), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var view = _step2.value;

            this.adjustLayoutToTrackSizes(view);
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        this.setState({
          views: viewsByUid
        });
      }

      return UNSAFE_componentWillReceiveProps;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillUpdate',
    value: function () {
      function UNSAFE_componentWillUpdate() {
        // let width = this.element.clientWidth;
        // let height = this.element.clientHeight;

        this.pixiRenderer.render(this.pixiRoot);
      }

      return UNSAFE_componentWillUpdate;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate() {
        this.setTheme(this.props.options.theme, this.props.options.isDarkTheme);

        this.animate();
        this.triggerViewChangeDb();
      }

      return componentDidUpdate;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        var _this6 = this;

        // Destroy PIXI renderer, stages, and assets
        this.mounted = false;
        this.pixiStage.destroy(false);
        this.pixiStage = null;
        this.pixiRenderer.destroy(true);
        this.pixiRenderer = null;

        window.removeEventListener('focus', this.boundRefreshView);

        // if this element was never attached to the DOM
        // then the resize sensor will never have been initiated
        if (this.resizeSensor) this.resizeSensor.detach();

        this.domEvent.unregister('keydown', document);
        this.domEvent.unregister('keyup', document);
        this.domEvent.unregister('scroll', document);
        this.domEvent.unregister('wheel', window);
        this.domEvent.unregister('mousedown', window);
        this.domEvent.unregister('mouseup', window);
        this.domEvent.unregister('click', window);
        this.domEvent.unregister('mousemove', window);
        this.domEvent.unregister('touchmove', window);
        this.domEvent.unregister('touchstart', window);
        this.domEvent.unregister('touchend', window);
        this.domEvent.unregister('touchcancel', window);

        this.pubSubs.forEach(function (subscription) {
          return _this6.pubSub.unsubscribe(subscription);
        });

        this.pubSubs = [];

        this.apiDestroy();
      }

      return componentWillUnmount;
    }()

    /* ---------------------------- Custom Methods ---------------------------- */

  }, {
    key: 'setTheme',
    value: function () {
      function setTheme() {
        var newTheme = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.options.theme;
        var isDarkTheme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.props.options.isDarkTheme;

        if (typeof isDarkTheme !== 'undefined') {
          console.warn('The option `isDarkTheme` is deprecated. Please use `theme` instead.');
          this.theme = isDarkTheme ? 'dark' : 'light';
        } else {
          switch (newTheme) {
            case 'dark':
              this.theme = _configs.THEME_DARK;
              break;
            case 'light':
            case undefined:
              this.theme = _configs.THEME_LIGHT;
              break;
            default:
              console.warn('Unknown theme "' + String(newTheme) + '". Using light theme.');
              this.theme = _configs.THEME_LIGHT;
              break;
          }
        }
      }

      return setTheme;
    }()
  }, {
    key: 'dispatchEvent',
    value: function () {
      function dispatchEvent(e) {
        if (!this.canvasElement) return;

        (0, _utils.forwardEvent)(e, this.canvasElement);
      }

      return dispatchEvent;
    }()
  }, {
    key: 'trackDroppedHandler',
    value: function () {
      function trackDroppedHandler() {
        this.setState({
          draggingHappening: null
        });
      }

      return trackDroppedHandler;
    }()
  }, {
    key: 'requestReceivedHandler',
    value: function () {
      function requestReceivedHandler() {
        if (!this.viewconfLoaded && _services.requestsInFlight === 0) {
          this.viewconfLoaded = true;
          if (this.props.options.onViewConfLoaded) {
            this.props.options.onViewConfLoaded();
          }
        }
      }

      return requestReceivedHandler;
    }()
  }, {
    key: 'animateOnMouseMoveHandler',
    value: function () {
      function animateOnMouseMoveHandler(active) {
        if (active && !this.animateOnMouseMove) {
          this.pubSubs.push(this.pubSub.subscribe('app.mouseMove', this.animateBound));
        }
        this.animateOnMouseMove = active;
      }

      return animateOnMouseMoveHandler;
    }()
  }, {
    key: 'fitPixiToParentContainer',
    value: function () {
      function fitPixiToParentContainer() {
        if (!this.element || !this.element.parentNode) {
          console.warn('No parentNode:', this.element);
          return;
        }

        var width = this.element.parentNode.clientWidth;
        var height = this.element.parentNode.clientHeight;

        this.pixiMask.beginFill(0xffffff).drawRect(0, 0, width, height).endFill();

        this.pixiRenderer.resize(width, height);

        this.pixiRenderer.view.style.width = String(width) + 'px';
        this.pixiRenderer.view.style.height = String(height) + 'px';

        this.pixiRenderer.render(this.pixiRoot);
      }

      return fitPixiToParentContainer;
    }()

    /**
     * Add default track options. These can come from two places:
     *
     * 1. The track definitions (configs/tracks-info.js)
     * 2. The default options passed into the component
     *
     * Of these, #2 takes precendence over #1.
     *
     * @param {array} track The track to add default options to
     */

  }, {
    key: 'addDefaultTrackOptions',
    value: function () {
      function addDefaultTrackOptions(track) {
        var trackInfo = this.getTrackInfo(track.type);
        if (!trackInfo) return;

        if (typeof track.options === 'undefined') {
          track.options = {};
        }

        var trackOptions = track.options ? track.options : {};

        if (this.props.options.defaultTrackOptions) {
          if (this.props.options.defaultTrackOptions.trackSpecific && this.props.options.defaultTrackOptions.trackSpecific[track.type]) {
            // track specific options take precedence over all options

            var options = this.props.options.defaultTrackOptions.trackSpecific[track.type];

            for (var optionName in options) {
              track.options[optionName] = typeof track.options[optionName] !== 'undefined' ? track.options[optionName] : JSON.parse((0, _stringify2['default'])(options[optionName]));
            }
          }

          if (this.props.options.defaultTrackOptions.all) {
            var _options = this.props.options.defaultTrackOptions.all;

            for (var _optionName in _options) {
              track.options[_optionName] = typeof track.options[_optionName] !== 'undefined' ? track.options[_optionName] : JSON.parse((0, _stringify2['default'])(_options[_optionName]));
            }
          }
        }

        if (trackInfo.defaultOptions) {
          var defaultThemeOptions = trackInfo.defaultOptionsByTheme && trackInfo.defaultOptionsByTheme[this.theme] ? trackInfo.defaultOptionsByTheme[this.theme] : {};

          var defaultOptions = (0, _assign2['default'])({}, trackInfo.defaultOptions, defaultThemeOptions);

          if (!track.options) {
            track.options = JSON.parse((0, _stringify2['default'])(defaultOptions));
          } else {
            for (var _optionName2 in defaultOptions) {
              track.options[_optionName2] = typeof track.options[_optionName2] !== 'undefined' ? track.options[_optionName2] : JSON.parse((0, _stringify2['default'])(defaultOptions[_optionName2]));
            }
          }
        } else {
          track.options = trackOptions;
        }
      }

      return addDefaultTrackOptions;
    }()
  }, {
    key: 'toggleTypedEditable',
    value: function () {
      function toggleTypedEditable() {
        this.setState({
          typedEditable: !this.isEditable()
        });
      }

      return toggleTypedEditable;
    }()

    /** Handle typed commands (e.g. e-d-i-t) */

  }, {
    key: 'typedTextHandler',
    value: function () {
      function typedTextHandler(event) {
        var _this7 = this;

        if (!this.props.options.cheatCodesEnabled) {
          return;
        }

        this.typedText = this.typedText.concat(event.key);

        if (this.typedText.endsWith('hgedit')) {
          this.toggleTypedEditable();
          this.typedText = '';
        }

        // 1.5 seconds to type the next letter
        var TYPED_TEXT_TIMEOUT = 750;
        if (this.typedTextTimeout) {
          clearTimeout(this.typedTextTimeout);
        }

        // set a timeout for new typed text
        this.typedTextTimeout = setTimeout(function () {
          _this7.typedText = '';
        }, TYPED_TEXT_TIMEOUT);
      }

      return typedTextHandler;
    }()
  }, {
    key: 'keyDownHandler',
    value: function () {
      function keyDownHandler(event) {
        // handle typed commands (e.g. e-d-i-t)
        this.typedTextHandler(event);

        if (this.props.options.rangeSelectionOnAlt && event.key === 'Alt') {
          this.setState({
            mouseTool: _configs.MOUSE_TOOL_SELECT
          });
        }
      }

      return keyDownHandler;
    }()
  }, {
    key: 'keyUpHandler',
    value: function () {
      function keyUpHandler(event) {
        if (this.props.options.rangeSelectionOnAlt && event.key === 'Alt') {
          this.setState({
            mouseTool: _configs.MOUSE_TOOL_MOVE
          });
        }
      }

      return keyUpHandler;
    }()
  }, {
    key: 'openModal',
    value: function () {
      function openModal(modal) {
        var _this8 = this;

        this.setState({
          // The following is only needed for testing purposes
          modal: _react2['default'].cloneElement(modal, {
            ref: function () {
              function ref(c) {
                _this8.modalRef = c;
              }

              return ref;
            }()
          })
        });
      }

      return openModal;
    }()
  }, {
    key: 'closeModal',
    value: function () {
      function closeModal() {
        this.modalRef = null;
        this.setState({ modal: null });
      }

      return closeModal;
    }()
  }, {
    key: 'handleEditViewConfig',
    value: function () {
      function handleEditViewConfig() {
        var _this9 = this;

        var viewConfigTmp = this.state.viewConfig;

        this.setState({ viewConfigTmp: viewConfigTmp });
        this.openModal(_react2['default'].createElement(_ViewConfigEditor2['default'], {
          onCancel: function () {
            function onCancel() {
              var viewConfig = _this9.state.viewConfigTmp;

              var views = _this9.processViewConfig(viewConfig);
              var _iteratorNormalCompletion3 = true;
              var _didIteratorError3 = false;
              var _iteratorError3 = undefined;

              try {
                for (var _iterator3 = (0, _getIterator3['default'])((0, _utils.dictValues)(views)), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                  var view = _step3.value;

                  _this9.adjustLayoutToTrackSizes(view);
                }
              } catch (err) {
                _didIteratorError3 = true;
                _iteratorError3 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion3 && _iterator3['return']) {
                    _iterator3['return']();
                  }
                } finally {
                  if (_didIteratorError3) {
                    throw _iteratorError3;
                  }
                }
              }

              _this9.setState({
                views: views,
                viewConfig: viewConfig,
                viewConfigTmp: null
              });
            }

            return onCancel;
          }(),
          onChange: function () {
            function onChange(viewConfigJson) {
              var viewConfig = JSON.parse(viewConfigJson);
              var views = _this9.processViewConfig(viewConfig);
              var _iteratorNormalCompletion4 = true;
              var _didIteratorError4 = false;
              var _iteratorError4 = undefined;

              try {
                for (var _iterator4 = (0, _getIterator3['default'])((0, _utils.dictValues)(views)), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                  var view = _step4.value;

                  _this9.adjustLayoutToTrackSizes(view);
                }
              } catch (err) {
                _didIteratorError4 = true;
                _iteratorError4 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion4 && _iterator4['return']) {
                    _iterator4['return']();
                  }
                } finally {
                  if (_didIteratorError4) {
                    throw _iteratorError4;
                  }
                }
              }

              _this9.setState({ views: views, viewConfig: viewConfig });
            }

            return onChange;
          }(),
          onSave: function () {
            function onSave(viewConfigJson) {
              var viewConfig = JSON.parse(viewConfigJson);
              var views = _this9.processViewConfig(viewConfig);
              var _iteratorNormalCompletion5 = true;
              var _didIteratorError5 = false;
              var _iteratorError5 = undefined;

              try {
                for (var _iterator5 = (0, _getIterator3['default'])((0, _utils.dictValues)(views)), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
                  var view = _step5.value;

                  _this9.adjustLayoutToTrackSizes(view);
                }
              } catch (err) {
                _didIteratorError5 = true;
                _iteratorError5 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion5 && _iterator5['return']) {
                    _iterator5['return']();
                  }
                } finally {
                  if (_didIteratorError5) {
                    throw _iteratorError5;
                  }
                }
              }

              _this9.setState({
                views: views,
                viewConfig: viewConfig,
                viewConfigTmp: null
              });
            }

            return onSave;
          }(),
          viewConfig: this.getViewsAsString()
        }));
      }

      return handleEditViewConfig;
    }()
  }, {
    key: 'animate',
    value: function () {
      function animate() {
        var _this10 = this;

        if (this.isRequestingAnimationFrame) return;

        this.isRequestingAnimationFrame = true;

        requestAnimationFrame(function () {
          // component was probably unmounted
          if (!_this10.pixiRenderer) return;

          _this10.pixiRenderer.render(_this10.pixiRoot);

          _this10.isRequestingAnimationFrame = false;
        });
      }

      return animate;
    }()
  }, {
    key: 'animateOnGlobalEvent',
    value: function () {
      function animateOnGlobalEvent() {
        var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            sourceUid = _ref4.sourceUid;

        if (sourceUid !== this.uid && this.animateOnMouseMove) this.animate();
      }

      return animateOnGlobalEvent;
    }()
  }, {
    key: 'measureSize',
    value: function () {
      function measureSize() {
        var _getElementDim = (0, _utils.getElementDim)(this.element),
            _getElementDim2 = (0, _slicedToArray3['default'])(_getElementDim, 2),
            width = _getElementDim2[0],
            height = _getElementDim2[1];

        if (width > 0 && height > 0) {
          this.setState({
            sizeMeasured: true,
            width: width,
            height: height
          });
        }
      }

      return measureSize;
    }()
  }, {
    key: 'updateAfterResize',
    value: function () {
      function updateAfterResize() {
        this.measureSize();
        this.updateRowHeight();
        this.fitPixiToParentContainer();
        this.refreshView(_configs.LONG_DRAG_TIMEOUT);
        this.resizeHandler();
      }

      return updateAfterResize;
    }()
  }, {
    key: 'onBreakpointChange',
    value: function () {
      function onBreakpointChange(breakpoint) {
        this.setState({
          currentBreakpoint: breakpoint
        });
      }

      return onBreakpointChange;
    }()
  }, {
    key: 'handleOverlayMouseEnter',
    value: function () {
      function handleOverlayMouseEnter(uid) {
        this.setState({
          mouseOverOverlayUid: uid
        });
      }

      return handleOverlayMouseEnter;
    }()
  }, {
    key: 'handleOverlayMouseLeave',
    value: function () {
      function handleOverlayMouseLeave() {
        this.setState({
          mouseOverOverlayUid: null
        });
      }

      return handleOverlayMouseLeave;
    }()

    /**
     * We want to lock the zoom of this view to the zoom of another view.
     *
     * First we pick which other view we want to lock to.
     *
     * The we calculate the current zoom offset and center offset. The differences
     * between the center of the two views will always remain the same, as will the
     * different between the zoom levels.
     */

  }, {
    key: 'handleLockLocation',
    value: function () {
      function handleLockLocation(uid) {
        var _this11 = this;

        // create a view chooser and remove the config view menu
        this.setState({
          chooseViewHandler: function () {
            function chooseViewHandler(uid2) {
              return _this11.handleLocationLockChosen(uid, uid2);
            }

            return chooseViewHandler;
          }(),
          mouseOverOverlayUid: uid
        });
      }

      return handleLockLocation;
    }()

    /**
     * Can views be added, removed or rearranged and are the view headers
     * visible?
     */

  }, {
    key: 'isEditable',
    value: function () {
      function isEditable() {
        if (this.state.typedEditable !== undefined) {
          // somebody typed "edit" so we need to follow the directive of
          // this cheat code over all other preferences
          return this.state.typedEditable;
        }

        if (!this.props.options || !('editable' in this.props.options)) {
          return this.state.viewConfig.editable;
        }

        return this.props.options.editable && this.state.viewConfig.editable;
      }

      return isEditable;
    }()

    /**
     * Can views be added, removed or rearranged and are the view headers
     * visible?
     */

  }, {
    key: 'isTrackMenuDisabled',
    value: function () {
      function isTrackMenuDisabled() {
        if (this.props.options && (this.props.options.editable === false || this.props.options.tracksEditable === false)) {
          return true;
        }

        return this.state.viewConfig && (this.state.viewConfig.tracksEditable === false || this.state.viewConfig.editable === false);
      }

      return isTrackMenuDisabled;
    }()

    /**
     * Can views be added, removed or rearranged and are the view headers
     * visible?
     */

  }, {
    key: 'isViewHeaderDisabled',
    value: function () {
      function isViewHeaderDisabled() {
        if (this.props.options && (this.props.options.editable === false || this.props.options.viewEditable === false)) {
          return true;
        }

        return this.state.viewConfig && (this.state.viewConfig.viewEditable === false || this.state.viewConfig.editable === false);
      }

      return isViewHeaderDisabled;
    }()

    /**
     * Iteratate over all of the views in this component
     */

  }, {
    key: 'iterateOverViews',
    value: function () {
      function iterateOverViews() {
        var viewIds = [];

        for (var viewId in (0, _keys2['default'])(this.state.views)) {
          viewIds.push(viewId);
        }

        return viewIds;
      }

      return iterateOverViews;
    }()
  }, {
    key: 'iterateOverTracksInView',
    value: function () {
      function iterateOverTracksInView(viewId) {
        var allTracks = [];
        var tracks = this.state.views[viewId].tracks;


        for (var trackType in tracks) {
          var _iteratorNormalCompletion6 = true;
          var _didIteratorError6 = false;
          var _iteratorError6 = undefined;

          try {
            for (var _iterator6 = (0, _getIterator3['default'])(tracks[trackType]), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
              var track = _step6.value;

              if (track.type === 'combined' && track.contents) {
                var _iteratorNormalCompletion7 = true;
                var _didIteratorError7 = false;
                var _iteratorError7 = undefined;

                try {
                  for (var _iterator7 = (0, _getIterator3['default'])(track.contents), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
                    var subTrack = _step7.value;

                    allTracks.push({ viewId: viewId, trackId: subTrack.uid, track: subTrack });
                  }
                } catch (err) {
                  _didIteratorError7 = true;
                  _iteratorError7 = err;
                } finally {
                  try {
                    if (!_iteratorNormalCompletion7 && _iterator7['return']) {
                      _iterator7['return']();
                    }
                  } finally {
                    if (_didIteratorError7) {
                      throw _iteratorError7;
                    }
                  }
                }
              } else {
                allTracks.push({ viewId: viewId, trackId: track.uid, track: track });
              }
            }
          } catch (err) {
            _didIteratorError6 = true;
            _iteratorError6 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion6 && _iterator6['return']) {
                _iterator6['return']();
              }
            } finally {
              if (_didIteratorError6) {
                throw _iteratorError6;
              }
            }
          }
        }

        return allTracks;
      }

      return iterateOverTracksInView;
    }()

    /**
     * Iterate over all the tracks in this component.
     */

  }, {
    key: 'iterateOverTracks',
    value: function () {
      function iterateOverTracks() {
        var allTracks = [];
        for (var viewId in this.state.views) {
          var tracks = this.state.views[viewId].tracks;


          for (var trackType in tracks) {
            var _iteratorNormalCompletion8 = true;
            var _didIteratorError8 = false;
            var _iteratorError8 = undefined;

            try {
              for (var _iterator8 = (0, _getIterator3['default'])(tracks[trackType]), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
                var track = _step8.value;

                if (track.type === 'combined' && track.contents) {
                  var _iteratorNormalCompletion9 = true;
                  var _didIteratorError9 = false;
                  var _iteratorError9 = undefined;

                  try {
                    for (var _iterator9 = (0, _getIterator3['default'])(track.contents), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
                      var subTrack = _step9.value;

                      allTracks.push({
                        viewId: viewId,
                        trackId: subTrack.uid,
                        track: subTrack
                      });
                    }
                  } catch (err) {
                    _didIteratorError9 = true;
                    _iteratorError9 = err;
                  } finally {
                    try {
                      if (!_iteratorNormalCompletion9 && _iterator9['return']) {
                        _iterator9['return']();
                      }
                    } finally {
                      if (_didIteratorError9) {
                        throw _iteratorError9;
                      }
                    }
                  }
                } else {
                  allTracks.push({ viewId: viewId, trackId: track.uid, track: track });
                }
              }
            } catch (err) {
              _didIteratorError8 = true;
              _iteratorError8 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion8 && _iterator8['return']) {
                  _iterator8['return']();
                }
              } finally {
                if (_didIteratorError8) {
                  throw _iteratorError8;
                }
              }
            }
          }
        }

        return allTracks;
      }

      return iterateOverTracks;
    }()
  }, {
    key: 'setMouseTool',
    value: function () {
      function setMouseTool(mouseTool) {
        this.setState({ mouseTool: mouseTool });
      }

      return setMouseTool;
    }()

    /**
     * Checks if a track's value scale is locked with another track
     */

  }, {
    key: 'isValueScaleLocked',
    value: function () {
      function isValueScaleLocked(viewUid, trackUid) {
        var uid = this.combineViewAndTrackUid(viewUid, trackUid);

        // the view must have been deleted
        if (!this.state.views[viewUid]) {
          return false;
        }

        if (this.valueScaleLocks[uid]) {
          return true;
        }
        return false;
      }

      return isValueScaleLocked;
    }()

    /**
     * Computed the minimal and maximal values of all tracks that are in the same
     * lockGroup as a given track
     * @param   {string}  viewUid  The id of the view containing the track
     * @param   {string}  trackUid   The id of the track
     * @return  {array}  Tuple [min,max] containing the overall extrema - or null.
     */

  }, {
    key: 'getLockGroupExtrema',
    value: function () {
      function getLockGroupExtrema(viewUid, trackUid) {
        var _this12 = this;

        var uid = this.combineViewAndTrackUid(viewUid, trackUid);

        // the view must have been deleted
        if (!this.state.views[viewUid]) {
          return null;
        }

        if (!this.valueScaleLocks[uid]) {
          return null;
        }

        var lockGroup = this.valueScaleLocks[uid];

        var lockedTracks = (0, _values2['default'])(lockGroup).filter(function (track) {
          return _this12.tiledPlots[track.view];
        }).map(function (track) {
          return _this12.tiledPlots[track.view].trackRenderer.getTrackObject(track.track);
        })
        // filter out stale locks with non-existant tracks
        .filter(function (track) {
          return track;
        })
        // if the track is a LeftTrackModifier we want the originalTrack
        .map(function (track) {
          return track.originalTrack === undefined ? track : track.originalTrack;
        });

        var minValues = lockedTracks
        // exclude tracks that don't set min and max values
        .filter(function (track) {
          return track.minRawValue && track.maxRawValue;
        }).map(function (track) {
          return lockGroup.ignoreOffScreenValues ? track.minVisibleValue(true) : track.minVisibleValueInTiles(true);
        });

        var maxValues = lockedTracks
        // exclude tracks that don't set min and max values
        .filter(function (track) {
          return track.minRawValue && track.maxRawValue;
        }).map(function (track) {
          return lockGroup.ignoreOffScreenValues ? track.maxVisibleValue(true) : track.maxVisibleValueInTiles(true);
        });

        if (minValues.length === 0 || minValues.filter(function (x) {
          return x === null || x === Infinity;
        }).length > 0) {
          return null; // Data hasn't loaded completely
        }

        if (maxValues.length === 0 || maxValues.filter(function (x) {
          return x === null || x === -Infinity;
        }).length > 0) {
          return null; // Data hasn't loaded completely
        }

        var allMin = Math.min.apply(Math, (0, _toConsumableArray3['default'])(minValues));
        var allMax = Math.max.apply(Math, (0, _toConsumableArray3['default'])(maxValues));

        return [allMin, allMax];
      }

      return getLockGroupExtrema;
    }()

    /**
     * Syncing the values of locked scales
     *
     * Arguments
     * ---------
     *  viewUid: string
     *    The id of the view containing the track whose value scale initially changed
     *  trackUid: string
     *    The id of the track that whose value scale changed
     *
     * Returns
     * -------
     *    Nothing
     */

  }, {
    key: 'syncValueScales',
    value: function () {
      function syncValueScales(viewUid, trackUid) {
        var _this13 = this;

        var uid = this.combineViewAndTrackUid(viewUid, trackUid);

        if (!this.state.views[viewUid]) return;
        // the view must have been deleted

        var sourceTrack = (0, _utils.getTrackByUid)(this.state.views[viewUid].tracks, trackUid);

        if (this.valueScaleLocks[uid]) {
          var lockGroup = this.valueScaleLocks[uid];

          var lockedTracks = (0, _values2['default'])(lockGroup).filter(function (track) {
            return _this13.tiledPlots[track.view];
          }).map(function (track) {
            return _this13.tiledPlots[track.view].trackRenderer.getTrackObject(track.track);
          })
          // filter out locks with non-existant tracks
          .filter(function (track) {
            return track;
          })
          // if the track is a LeftTrackModifier we want the originalTrack
          .map(function (track) {
            return track.originalTrack === undefined ? track : track.originalTrack;
          });

          var lockGroupExtrema = this.getLockGroupExtrema(viewUid, trackUid);

          if (lockGroupExtrema === null) {
            return; // Data hasn't loaded completely
          }

          var allMin = lockGroupExtrema[0];
          var allMax = lockGroupExtrema[1];

          var epsilon = 1e-6;

          var _iteratorNormalCompletion10 = true;
          var _didIteratorError10 = false;
          var _iteratorError10 = undefined;

          try {
            for (var _iterator10 = (0, _getIterator3['default'])(lockedTracks), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
              var lockedTrack = _step10.value;

              // set the newly calculated minimum and maximum values
              // using d3 style setters
              if (lockedTrack.minValue) {
                lockedTrack.minValue(allMin);
              }
              if (lockedTrack.maxValue) {
                lockedTrack.maxValue(allMax);
              }

              if (!lockedTrack.valueScale) {
                // this track probably hasn't loaded the tiles to
                // create a valueScale
                continue;
              }

              var hasScaleChanged = Math.abs(lockedTrack.minValue() - lockedTrack.valueScale.domain()[0]) > epsilon || Math.abs(lockedTrack.maxValue() - lockedTrack.valueScale.domain()[1]) > epsilon;

              var hasBrushMoved = sourceTrack.options && lockedTrack.options && typeof sourceTrack.options.scaleStartPercent !== 'undefined' && typeof sourceTrack.options.scaleEndPercent !== 'undefined' && (Math.abs(lockedTrack.options.scaleStartPercent - sourceTrack.options.scaleStartPercent) > epsilon || Math.abs(lockedTrack.options.scaleEndPercent - sourceTrack.options.scaleEndPercent) > epsilon);

              // If we do view based scaling we want to minimize the number of rerenders
              // Check if it is necessary to rerender
              if (lockedTrack.continuousScaling && !hasScaleChanged && !hasBrushMoved) {
                continue;
              }

              lockedTrack.valueScale.domain([allMin, allMax]);

              // In TiledPixiTrack, we check if valueScale has changed before
              // calling onValueScaleChanged. If we don't update prevValueScale
              // here, that function won't get called and the value scales won't
              // stay synced
              lockedTrack.prevValueScale = lockedTrack.valueScale.copy();

              if (hasBrushMoved) {
                lockedTrack.options.scaleStartPercent = sourceTrack.options.scaleStartPercent;
                lockedTrack.options.scaleEndPercent = sourceTrack.options.scaleEndPercent;
              }

              // the second parameter forces a rerender even though
              // the options haven't changed
              lockedTrack.rerender(lockedTrack.options, true);
            }
          } catch (err) {
            _didIteratorError10 = true;
            _iteratorError10 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion10 && _iterator10['return']) {
                _iterator10['return']();
              }
            } finally {
              if (_didIteratorError10) {
                throw _iteratorError10;
              }
            }
          }
        }
      }

      return syncValueScales;
    }()
  }, {
    key: 'handleNewTilesLoaded',
    value: function () {
      function handleNewTilesLoaded(viewUid, trackUid) {
        // this.syncValueScales(viewUid, trackUid);
        this.animate();
      }

      return handleNewTilesLoaded;
    }()
  }, {
    key: 'notifyDragChangedListeners',
    value: function () {
      function notifyDragChangedListeners(dragging) {
        // iterate over viewId
        (0, _utils.dictValues)(this.draggingChangedListeners).forEach(function (l) {
          // iterate over listenerId
          (0, _utils.dictValues)(l).forEach(function (listener) {
            return listener(dragging);
          });
        });
      }

      return notifyDragChangedListeners;
    }()

    /**
     * Add a listener that will be called every time the view is updated.
     *
     * @param viewUid: The uid of the view being observed
     * @param listenerUid: The uid of the listener
     * @param eventHandler: The handler to be called when the scales change
     *    Event handler is called with parameters (xScale, yScale)
     */

  }, {
    key: 'addDraggingChangedListener',
    value: function () {
      function addDraggingChangedListener(viewUid, listenerUid, eventHandler) {
        if (!this.draggingChangedListeners.hasOwnProperty(viewUid)) {
          this.draggingChangedListeners[viewUid] = {};
        }

        this.draggingChangedListeners[viewUid][listenerUid] = eventHandler;

        eventHandler(true);
        eventHandler(false);
      }

      return addDraggingChangedListener;
    }()

    /**
     * Remove a scale change event listener
     *
     * @param viewUid: The view that it's listening on.
     * @param listenerUid: The uid of the listener itself.
     */

  }, {
    key: 'removeDraggingChangedListener',
    value: function () {
      function removeDraggingChangedListener(viewUid, listenerUid) {
        if (this.draggingChangedListeners.hasOwnProperty(viewUid)) {
          var listeners = this.draggingChangedListeners[viewUid];

          if (listeners.hasOwnProperty(listenerUid)) {
            // make sure the listener doesn't think we're still
            // dragging
            listeners[listenerUid](false);
            delete listeners[listenerUid];
          }
        }
      }

      return removeDraggingChangedListener;
    }()

    /**
     * Add an event listener that will be called every time the scale
     * of the view with uid viewUid is changed.
     *
     * @param viewUid: The uid of the view being observed
     * @param listenerUid: The uid of the listener
     * @param eventHandler: The handler to be called when the scales change
     *    Event handler is called with parameters (xScale, yScale)
     */

  }, {
    key: 'addScalesChangedListener',
    value: function () {
      function addScalesChangedListener(viewUid, listenerUid, eventHandler) {
        if (!this.scalesChangedListeners[viewUid]) {
          this.scalesChangedListeners[viewUid] = {};
        }

        this.scalesChangedListeners[viewUid][listenerUid] = eventHandler;

        if (!this.xScales[viewUid] || !this.yScales[viewUid]) {
          return;
        }

        // call the handler for the first time
        eventHandler(this.xScales[viewUid], this.yScales[viewUid]);
      }

      return addScalesChangedListener;
    }()

    /**
     * Remove a scale change event listener
     *
     * @param viewUid: The view that it's listening on.
     * @param listenerUid: The uid of the listener itself.
     */

  }, {
    key: 'removeScalesChangedListener',
    value: function () {
      function removeScalesChangedListener(viewUid, listenerUid) {
        if (this.scalesChangedListeners[viewUid]) {
          var listeners = this.scalesChangedListeners[viewUid];

          if (listeners[listenerUid]) {
            delete listeners[listenerUid];
          }
        }
      }

      return removeScalesChangedListener;
    }()
  }, {
    key: 'createSVG',
    value: function () {
      function createSVG() {
        var svg = document.createElement('svg');
        svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
        svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
        svg.setAttribute('version', '1.1');

        var _iteratorNormalCompletion11 = true;
        var _didIteratorError11 = false;
        var _iteratorError11 = undefined;

        try {
          for (var _iterator11 = (0, _getIterator3['default'])((0, _utils.dictValues)(this.tiledPlots)), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
            var tiledPlot = _step11.value;

            if (!tiledPlot) continue; // probably opened and closed

            var _iteratorNormalCompletion12 = true;
            var _didIteratorError12 = false;
            var _iteratorError12 = undefined;

            try {
              for (var _iterator12 = (0, _getIterator3['default'])((0, _utils.dictValues)(tiledPlot.trackRenderer.trackDefObjects)), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
                var trackDefObject = _step12.value;

                if (trackDefObject.trackObject.exportSVG) {
                  var trackSVG = trackDefObject.trackObject.exportSVG();

                  if (trackSVG) svg.appendChild(trackSVG[0]);
                }
              }
            } catch (err) {
              _didIteratorError12 = true;
              _iteratorError12 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion12 && _iterator12['return']) {
                  _iterator12['return']();
                }
              } finally {
                if (_didIteratorError12) {
                  throw _iteratorError12;
                }
              }
            }
          }

          // FF is fussier than Chrome, and requires dimensions on the SVG,
          // if it is to be used as an image src.
        } catch (err) {
          _didIteratorError11 = true;
          _iteratorError11 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion11 && _iterator11['return']) {
              _iterator11['return']();
            }
          } finally {
            if (_didIteratorError11) {
              throw _iteratorError11;
            }
          }
        }

        svg.setAttribute('width', this.canvasElement.style.width);
        svg.setAttribute('height', this.canvasElement.style.height);

        if (this.postCreateSVGCallback) {
          // Allow the callback function to modify the exported SVG string
          // before it is finalized and returned.
          var modifiedSvg = this.postCreateSVGCallback(svg);
          return modifiedSvg;
        }
        return svg;
      }

      return createSVG;
    }()
  }, {
    key: 'createSVGString',
    value: function () {
      function createSVGString() {
        var svg = this.createSVG();

        var svgString = _vkbeautify2['default'].xml(new window.XMLSerializer().serializeToString(svg));

        svgString = svgString.replace(/<a0:/g, '<');
        svgString = svgString.replace(/<\/a0:/g, '</');
        // Remove duplicated xhtml namespace property
        svgString = svgString.replace(/(<svg[\n\r])(\s+xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"[\n\r])/gm, '$1');
        // Remove duplicated svg namespace
        svgString = svgString.replace(/(\s+<clipPath[\n\r]\s+)(xmlns="http:\/\/www\.w3\.org\/2000\/svg")/gm, '$1');

        var xmlDeclaration = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
        var doctype = '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';

        return xmlDeclaration + '\n' + doctype + '\n' + String(svgString);
      }

      return createSVGString;
    }()
  }, {
    key: 'handleExportSVG',
    value: function () {
      function handleExportSVG() {
        (0, _utils.download)('export.svg', new Blob([this.createSVGString()], { type: 'image/svg+xml' }));
      }

      return handleExportSVG;
    }()
  }, {
    key: 'offPostCreateSVG',
    value: function () {
      function offPostCreateSVG() {
        this.postCreateSVGCallback = null;
      }

      return offPostCreateSVG;
    }()
  }, {
    key: 'onPostCreateSVG',
    value: function () {
      function onPostCreateSVG(callback) {
        this.postCreateSVGCallback = callback;
      }

      return onPostCreateSVG;
    }()
  }, {
    key: 'createPNGBlobPromise',
    value: function () {
      function createPNGBlobPromise() {
        var _this14 = this;

        return new _promise2['default'](function (resolve) {
          // It would seem easier to call canvas.toDataURL()...
          // Except that with webgl context, it swaps buffers after drawing
          // and you don't have direct access to what is on-screen.
          // (You end up getting a PNG of the desired dimensions, but it is empty.)
          //
          // We'd either need to
          // - Turn on preserveDrawingBuffer and rerender, and add a callback
          // - Or leave it off, and somehow synchronously export before the swap
          // - Or look into low-level stuff like copyBufferSubData.
          //
          // Basing it on the SVG also guarantees us that the two exports are the same.

          var svgString = _this14.createSVGString();

          var img = new Image(_this14.canvasElement.width, _this14.canvasElement.height);
          img.src = 'data:image/svg+xml;base64,' + String(btoa(svgString));
          img.onload = function () {
            var targetCanvas = document.createElement('canvas');
            // TODO: I have no idea why dimensions are doubled!
            targetCanvas.width = _this14.canvasElement.width / 2;
            targetCanvas.height = _this14.canvasElement.height / 2;
            targetCanvas.getContext('2d').drawImage(img, 0, 0);
            targetCanvas.toBlob(function (blob) {
              resolve(blob);
            });
          };
        });
      }

      return createPNGBlobPromise;
    }()
  }, {
    key: 'handleExportPNG',
    value: function () {
      function handleExportPNG() {
        this.createPNGBlobPromise().then(function (blob) {
          (0, _utils.download)('export.png', blob);
        });
      }

      return handleExportPNG;
    }()

    /*
     * The scales of some view have changed (presumably in response to zooming).
     *
     * Mark the new scales and update any locked views.
     *
     * @param uid: The view of whom the scales have changed.
     */

  }, {
    key: 'handleScalesChanged',
    value: function () {
      function handleScalesChanged(uid, xScale, yScale) {
        var _this15 = this;

        var notify = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

        this.xScales[uid] = xScale;
        this.yScales[uid] = yScale;

        if (notify) {
          if (uid in this.scalesChangedListeners) {
            (0, _utils.dictValues)(this.scalesChangedListeners[uid]).forEach(function (x) {
              x(xScale, yScale);
            });
          }
        }

        if (this.zoomLocks[uid]) {
          // this view is locked to another
          var lockGroup = this.zoomLocks[uid];
          var lockGroupItems = (0, _utils.dictItems)(lockGroup);

          // eslint-disable-next-line no-unused-vars

          var _scalesCenterAndK = (0, _utils.scalesCenterAndK)(this.xScales[uid], this.yScales[uid]),
              _scalesCenterAndK2 = (0, _slicedToArray3['default'])(_scalesCenterAndK, 3),
              centerX = _scalesCenterAndK2[0],
              centerY = _scalesCenterAndK2[1],
              k = _scalesCenterAndK2[2];

          var _loop = function () {
            function _loop(i) {
              var key = lockGroupItems[i][0];
              var value = lockGroupItems[i][1];

              if (!_this15.xScales[key] || !_this15.yScales[key]) {
                return 'continue';
              }

              if (key === uid) {
                // no need to notify oneself that the scales have changed
                return 'continue';
              }

              // eslint-disable-next-line no-unused-vars

              var _scalesCenterAndK3 = (0, _utils.scalesCenterAndK)(_this15.xScales[key], _this15.yScales[key]),
                  _scalesCenterAndK4 = (0, _slicedToArray3['default'])(_scalesCenterAndK3, 3),
                  keyCenterX = _scalesCenterAndK4[0],
                  keyCenterY = _scalesCenterAndK4[1],
                  keyK = _scalesCenterAndK4[2];

              var rk = value[2] / lockGroup[uid][2];

              // let newCenterX = centerX + dx;
              // let newCenterY = centerY + dy;
              var newK = k * rk;

              if (!_this15.setCenters[key]) {
                return 'continue';
              }

              // the key here is the target of zoom lock, so we want to keep its
              // x center and y center unchanged

              var _setCenters$key = _this15.setCenters[key](keyCenterX, keyCenterY, newK, false),
                  _setCenters$key2 = (0, _slicedToArray3['default'])(_setCenters$key, 2),
                  newXScale = _setCenters$key2[0],
                  newYScale = _setCenters$key2[1];

              // because the setCenters call above has a 'false' notify, the new scales won't
              // be propagated from there, so we have to store them here


              _this15.xScales[key] = newXScale;
              _this15.yScales[key] = newYScale;

              // notify the listeners of all locked views that the scales of
              // this view have changed
              if (_this15.scalesChangedListeners.hasOwnProperty(key)) {
                (0, _utils.dictValues)(_this15.scalesChangedListeners[key]).forEach(function (x) {
                  x(newXScale, newYScale);
                });
              }
            }

            return _loop;
          }();

          for (var i = 0; i < lockGroupItems.length; i++) {
            var _ret = _loop(i);

            if (_ret === 'continue') continue;
          }
        }

        if (this.locationLocks[uid]) {
          // this view is locked to another
          var _lockGroup = this.locationLocks[uid];
          var _lockGroupItems = (0, _utils.dictItems)(_lockGroup);

          // eslint-disable-next-line no-unused-vars

          var _scalesCenterAndK5 = (0, _utils.scalesCenterAndK)(this.xScales[uid], this.yScales[uid]),
              _scalesCenterAndK6 = (0, _slicedToArray3['default'])(_scalesCenterAndK5, 3),
              _centerX = _scalesCenterAndK6[0],
              _centerY = _scalesCenterAndK6[1],
              _k = _scalesCenterAndK6[2];

          var _loop2 = function () {
            function _loop2(i) {
              var key = _lockGroupItems[i][0];
              var value = _lockGroupItems[i][1];

              if (!_this15.xScales[key] || !_this15.yScales[key]) {
                return 'continue';
              }

              // eslint-disable-next-line no-unused-vars

              var _scalesCenterAndK7 = (0, _utils.scalesCenterAndK)(_this15.xScales[key], _this15.yScales[key]),
                  _scalesCenterAndK8 = (0, _slicedToArray3['default'])(_scalesCenterAndK7, 3),
                  keyCenterX = _scalesCenterAndK8[0],
                  keyCenterY = _scalesCenterAndK8[1],
                  keyK = _scalesCenterAndK8[2];

              if (key === uid) {
                // no need to notify oneself that the scales have changed
                return 'continue';
              }

              var dx = value[0] - _lockGroup[uid][0];
              var dy = value[1] - _lockGroup[uid][1];

              var newCenterX = _centerX + dx;
              var newCenterY = _centerY + dy;

              if (!_this15.setCenters[key]) {
                return 'continue';
              }

              var _setCenters$key3 = _this15.setCenters[key](newCenterX, newCenterY, keyK, false),
                  _setCenters$key4 = (0, _slicedToArray3['default'])(_setCenters$key3, 2),
                  newXScale = _setCenters$key4[0],
                  newYScale = _setCenters$key4[1];

              // because the setCenters call above has a 'false' notify, the new scales won't
              // be propagated from there, so we have to store them here


              _this15.xScales[key] = newXScale;
              _this15.yScales[key] = newYScale;

              // notify the listeners of all locked views that the scales of
              // this view have changed
              if (_this15.scalesChangedListeners.hasOwnProperty(key)) {
                (0, _utils.dictValues)(_this15.scalesChangedListeners[key]).forEach(function (x) {
                  x(newXScale, newYScale);
                });
              }
            }

            return _loop2;
          }();

          for (var i = 0; i < _lockGroupItems.length; i++) {
            var _ret2 = _loop2(i);

            if (_ret2 === 'continue') continue;
          }
        }

        if (this.locationLocksAxisWise.x[uid]) {
          // the x axis of this view is locked to an axis of another view
          var _lockGroup2 = this.locationLocksAxisWise.x[uid].lock;
          var _lockGroupItems2 = (0, _utils.dictItems)(_lockGroup2);

          // this means the x axis of this view (uid) is locked to the y axis of another view
          var lockCrossAxis = this.locationLocksAxisWise.x[uid].axis !== 'x';

          // eslint-disable-next-line no-unused-vars

          var _scalesCenterAndK9 = (0, _utils.scalesCenterAndK)(this.xScales[uid], this.yScales[uid]),
              _scalesCenterAndK10 = (0, _slicedToArray3['default'])(_scalesCenterAndK9, 3),
              _centerX2 = _scalesCenterAndK10[0],
              _centerY2 = _scalesCenterAndK10[1],
              _k2 = _scalesCenterAndK10[2];

          var _loop3 = function () {
            function _loop3(i) {
              var key = _lockGroupItems2[i][0];
              var value = _lockGroupItems2[i][1];

              if (!_this15.xScales[key] || !_this15.yScales[key]) {
                return 'continue';
              }

              // eslint-disable-next-line no-unused-vars

              var _scalesCenterAndK11 = (0, _utils.scalesCenterAndK)(_this15.xScales[key], _this15.yScales[key]),
                  _scalesCenterAndK12 = (0, _slicedToArray3['default'])(_scalesCenterAndK11, 3),
                  keyCenterX = _scalesCenterAndK12[0],
                  keyCenterY = _scalesCenterAndK12[1],
                  keyK = _scalesCenterAndK12[2];

              if (key === uid) {
                // no need to notify oneself that the scales have changed
                return 'continue';
              }

              var dx = value[0] - _lockGroup2[uid][0];

              var newCenterX = _centerX2 + dx;

              if (!_this15.setCenters[key]) {
                return 'continue';
              }

              var _setCenters$key5 = _this15.setCenters[key](lockCrossAxis ? keyCenterX : newCenterX, lockCrossAxis ? newCenterX : keyCenterY, keyK, false),
                  _setCenters$key6 = (0, _slicedToArray3['default'])(_setCenters$key5, 2),
                  newXScale = _setCenters$key6[0],
                  newYScale = _setCenters$key6[1];

              // because the setCenters call above has a 'false' notify, the new scales won't
              // be propagated from there, so we have to store them here


              _this15.xScales[key] = newXScale;
              _this15.yScales[key] = newYScale;

              // notify the listeners of all locked views that the scales of
              // this view have changed
              if (_this15.scalesChangedListeners.hasOwnProperty(key)) {
                (0, _utils.dictValues)(_this15.scalesChangedListeners[key]).forEach(function (x) {
                  x(newXScale, newYScale);
                });
              }
            }

            return _loop3;
          }();

          for (var i = 0; i < _lockGroupItems2.length; i++) {
            var _ret3 = _loop3(i);

            if (_ret3 === 'continue') continue;
          }
        }

        if (this.locationLocksAxisWise.y[uid]) {
          // the y axis of this view is locked to an axis of another view
          var _lockGroup3 = this.locationLocksAxisWise.y[uid].lock;
          var _lockGroupItems3 = (0, _utils.dictItems)(_lockGroup3);

          // this means the y axis of this view (uid) is locked to the x axis of another view
          var _lockCrossAxis = this.locationLocksAxisWise.y[uid].axis !== 'y';

          // eslint-disable-next-line no-unused-vars

          var _scalesCenterAndK13 = (0, _utils.scalesCenterAndK)(this.xScales[uid], this.yScales[uid]),
              _scalesCenterAndK14 = (0, _slicedToArray3['default'])(_scalesCenterAndK13, 3),
              _centerX3 = _scalesCenterAndK14[0],
              _centerY3 = _scalesCenterAndK14[1],
              _k3 = _scalesCenterAndK14[2];

          var _loop4 = function () {
            function _loop4(i) {
              var key = _lockGroupItems3[i][0];
              var value = _lockGroupItems3[i][1];

              if (!_this15.xScales[key] || !_this15.yScales[key]) {
                return 'continue';
              }

              // eslint-disable-next-line no-unused-vars

              var _scalesCenterAndK15 = (0, _utils.scalesCenterAndK)(_this15.xScales[key], _this15.yScales[key]),
                  _scalesCenterAndK16 = (0, _slicedToArray3['default'])(_scalesCenterAndK15, 3),
                  keyCenterX = _scalesCenterAndK16[0],
                  keyCenterY = _scalesCenterAndK16[1],
                  keyK = _scalesCenterAndK16[2];

              if (key === uid) {
                // no need to notify oneself that the scales have changed
                return 'continue';
              }

              var dy = value[1] - _lockGroup3[uid][1];

              var newCenterY = _centerY3 + dy;

              if (!_this15.setCenters[key]) {
                return 'continue';
              }

              var _setCenters$key7 = _this15.setCenters[key](_lockCrossAxis ? newCenterY : keyCenterX, _lockCrossAxis ? keyCenterY : newCenterY, keyK, false),
                  _setCenters$key8 = (0, _slicedToArray3['default'])(_setCenters$key7, 2),
                  newXScale = _setCenters$key8[0],
                  newYScale = _setCenters$key8[1];

              // because the setCenters call above has a 'false' notify, the new scales won't
              // be propagated from there, so we have to store them here


              _this15.xScales[key] = newXScale;
              _this15.yScales[key] = newYScale;

              // notify the listeners of all locked views that the scales of
              // this view have changed
              if (_this15.scalesChangedListeners.hasOwnProperty(key)) {
                (0, _utils.dictValues)(_this15.scalesChangedListeners[key]).forEach(function (x) {
                  x(newXScale, newYScale);
                });
              }
            }

            return _loop4;
          }();

          for (var i = 0; i < _lockGroupItems3.length; i++) {
            var _ret4 = _loop4(i);

            if (_ret4 === 'continue') continue;
          }
        }

        this.animate();

        // Call view change handler
        this.triggerViewChangeDb();
      }

      return handleScalesChanged;
    }()
  }, {
    key: 'handleProjectViewport',
    value: function () {
      function handleProjectViewport(uid) {
        var _this16 = this;

        /**
         * We want to show the extent of this viewport on another view.
         */

        this.setState({
          chooseTrackHandler: function () {
            function chooseTrackHandler(viewUid, trackUid) {
              return _this16.handleViewportProjected(uid, viewUid, trackUid);
            }

            return chooseTrackHandler;
          }()
        });
      }

      return handleProjectViewport;
    }()

    /**
     * Adjust the zoom level so that all of the data is visible
     *
     * @param viewUid: The view uid for which to adjust the zoom level
     */

  }, {
    key: 'handleZoomToData',
    value: function () {
      function handleZoomToData(viewUid) {
        if (viewUid && !this.tiledPlots[viewUid]) {
          throw new Error('View uid ' + String(viewUid) + ' does not exist in the current viewConfig');
        }

        if (viewUid) {
          this.tiledPlots[viewUid].handleZoomToData();
        } else {
          (0, _values2['default'])(this.tiledPlots).forEach(function (tiledPlot) {
            return tiledPlot.handleZoomToData();
          });
        }
      }

      return handleZoomToData;
    }()

    /**
     * Reset the viewport to the initial x and y domain
     * @param  {number} viewId - ID of the view for which the viewport should be
     *  reset.
     */

  }, {
    key: 'resetViewport',
    value: function () {
      function resetViewport(viewId) {
        if (viewId && !this.tiledPlots[viewId]) {
          throw new Error('View uid ' + String(viewId) + ' does not exist in the current viewConfig');
        }

        if (viewId) {
          this.tiledPlots[viewId].resetViewport();
        } else {
          (0, _values2['default'])(this.tiledPlots).forEach(function (tiledPlot) {
            return tiledPlot.resetViewport();
          });
        }
      }

      return resetViewport;
    }()

    /**
     * We want to yank some attributes from another view.
     *
     * This will create a view selection overlay and then call the selected
     * provided function.
     */

  }, {
    key: 'handleYankFunction',
    value: function () {
      function handleYankFunction(uid, yankFunction) {
        this.setState({
          chooseViewHandler: function () {
            function chooseViewHandler(uid2) {
              return yankFunction(uid, uid2);
            }

            return chooseViewHandler;
          }(),
          mouseOverOverlayUid: uid
        });
      }

      return handleYankFunction;
    }()

    /**
     * We want to unlock uid from the zoom group that it's in.
     *
     * @param uid: The uid of a view.
     */

  }, {
    key: 'handleUnlock',
    value: function () {
      function handleUnlock(uid, lockGroups) {
        // if this function is being called, lockGroup has to exist
        var lockGroup = lockGroups[uid];
        var lockGroupKeys = (0, _utils.dictKeys)(lockGroup);

        if (lockGroupKeys.length === 2) {
          // there's only two items in this lock group so we need to
          // remove them both (no point in having one view locked to itself)
          delete lockGroups[lockGroupKeys[0]];
          delete lockGroups[lockGroupKeys[1]];

          return;
        }
        // delete this view from the zoomLockGroup
        if (lockGroups[uid]) {
          if (lockGroups[uid][uid]) {
            delete lockGroups[uid][uid];
          }
        }

        // remove the handler
        if (lockGroups[uid]) {
          delete lockGroups[uid];
        }
      }

      return handleUnlock;
    }()
  }, {
    key: 'viewScalesLockData',
    value: function () {
      function viewScalesLockData(uid) {
        if (!this.xScales[uid] || !this.yScales[uid]) {
          console.warn("View scale lock doesn't correspond to existing uid: ", uid);
          return null;
        }

        return (0, _utils.scalesCenterAndK)(this.xScales[uid], this.yScales[uid]);
      }

      return viewScalesLockData;
    }()

    /*
     * :param uid1 (string): The uid of the first element to be locked (e.g. viewUid)
     * :param uid2 (string): The uid of the second element to be locked (e.g. viewUid)
     * :param lockGroups (dict): The set of locks where to store this lock (e.g. this.locationLocks)
     * :parma lockData (function): A function that takes two uids and calculates some extra data
     * to store with this lock data (e.g. scalesCenterAndK(this.xScales[uid1], this.yScales[uid1]))
     */

  }, {
    key: 'addLock',
    value: function () {
      function addLock(uid1, uid2, lockGroups, lockData) {
        var _this17 = this;

        var group1Members = [];
        var group2Members = [];

        if (!lockGroups[uid1]) {
          // view1 isn't already in a group
          group1Members = [[uid1, lockData.bind(this)(uid1)]];
        } else {
          // view1 is already in a group
          group1Members = (0, _utils.dictItems)(lockGroups[uid1]).filter(function (x) {
            return lockData(x[0]);
          }) // make sure we can create the necessary data for this lock
          // in the case of location locks, this implies that the
          // views it's locking exist
          .map(function (x) {
            return [x[0], lockData(x[0])];
          }); // x is [uid, [centerX, centerY, k]]
        }

        if (!lockGroups[uid2]) {
          // view1 isn't already in a group
          group2Members = [[uid2, lockData.bind(this)(uid2)]];
        } else {
          // view2 is already in a group
          group2Members = (0, _utils.dictItems)(lockGroups[uid2]).filter(function (x) {
            return lockData.bind(_this17)(x[0]);
          })
          // make sure we can create the necessary data for this lock
          // in the case of location locks, this implies that the
          // views it's locking exist
          .map(function (x) {
            return (
              // x is [uid, [centerX, centerY, k]]
              [x[0], lockData.bind(_this17)(x[0])]
            );
          });
        }

        var allMembers = group1Members.concat(group2Members);

        var groupDict = (0, _utils.dictFromTuples)(allMembers);

        allMembers.forEach(function (m) {
          lockGroups[m[0]] = groupDict;
        });
      }

      return addLock;
    }()

    /* Views uid1 and uid2 need to be locked so that they always maintain the current
     * zoom and translation difference.
     * @param uid1: The view that the lock was called from
     * @param uid2: The view that the lock was called on (the view that was selected)
     */

  }, {
    key: 'handleLocationLockChosen',
    value: function () {
      function handleLocationLockChosen(uid1, uid2) {
        if (uid1 === uid2) {
          this.setState({
            chooseViewHandler: null
          });

          return; // locking a view to itself is silly
        }

        this.addLock(uid1, uid2, this.locationLocks, this.viewScalesLockData.bind(this));

        this.setState({
          chooseViewHandler: null
        });
      }

      return handleLocationLockChosen;
    }()

    /* Views uid1 and uid2 need to be locked so that they always maintain the current
     * zoom and translation difference.
     * @param uid1: The view that the lock was called from
     * @param uid2: The view that the lock was called on (the view that was selected)
     */

  }, {
    key: 'handleZoomLockChosen',
    value: function () {
      function handleZoomLockChosen(uid1, uid2) {
        if (uid1 === uid2) {
          this.setState({
            chooseViewHandler: null
          });

          return; // locking a view to itself is silly
        }

        this.addLock(uid1, uid2, this.zoomLocks, this.viewScalesLockData.bind(this));

        this.setState({
          chooseViewHandler: null
        });
      }

      return handleZoomLockChosen;
    }()

    /**
     * We want to project the viewport of fromView onto toTrack of toView.
     *
     * @param fromView: The uid of the view that we want to project
     * @param toView: The uid of the view that we want to project to
     * @param toTrack: The track we want to project to
     *
     * Returns
     * -------
     *
     *  newTrackUid: string
     *      The uid of the newly created viewport projection track
     */

  }, {
    key: 'handleViewportProjected',
    value: function () {
      function handleViewportProjected(fromView, toView, toTrack) {
        var newTrackUid = null;

        if (fromView === toView) {
          console.warn('A view can not show its own viewport.');
        } else {
          var hostTrack = (0, _utils.getTrackByUid)(this.state.views[toView].tracks, toTrack);
          var position = (0, _utils.getTrackPositionByUid)(this.state.views[toView].tracks, toTrack);
          newTrackUid = _slugid2['default'].nice();

          var projectionTypes = {
            top: 'horizontal',
            bottom: 'horizontal',
            center: 'center',
            left: 'vertical',
            right: 'vertical'
          };

          var newTrack = {
            uid: newTrackUid,
            type: 'viewport-projection-' + String(projectionTypes[position]),
            fromViewUid: fromView
          };

          this.addCallbacks(toView, newTrack);
          this.handleTrackAdded(toView, newTrack, position, hostTrack);
        }
        this.setState({
          chooseTrackHandler: null
        });

        return newTrackUid;
      }

      return handleViewportProjected;
    }()

    /**
     * Uid1 is copying the center of uid2
     */

  }, {
    key: 'handleLocationYanked',
    value: function () {
      function handleLocationYanked(uid1, uid2) {
        // where we're taking the zoom from
        var sourceXScale = this.xScales[uid2];
        var sourceYScale = this.yScales[uid2];

        var targetXScale = this.xScales[uid1];
        var targetYScale = this.yScales[uid1];

        // eslint-disable-next-line no-unused-vars

        var _scalesCenterAndK17 = (0, _utils.scalesCenterAndK)(targetXScale, targetYScale),
            _scalesCenterAndK18 = (0, _slicedToArray3['default'])(_scalesCenterAndK17, 3),
            targetCenterX = _scalesCenterAndK18[0],
            targetCenterY = _scalesCenterAndK18[1],
            targetK = _scalesCenterAndK18[2];
        // eslint-disable-next-line no-unused-vars


        var _scalesCenterAndK19 = (0, _utils.scalesCenterAndK)(sourceXScale, sourceYScale),
            _scalesCenterAndK20 = (0, _slicedToArray3['default'])(_scalesCenterAndK19, 3),
            sourceCenterX = _scalesCenterAndK20[0],
            sourceCenterY = _scalesCenterAndK20[1],
            sourceK = _scalesCenterAndK20[2];

        // set target center


        this.setCenters[uid1](sourceCenterX, sourceCenterY, targetK, true);

        this.setState({
          chooseViewHandler: null
        });
      }

      return handleLocationYanked;
    }()

    /**
     * Uid1 yanked the zoom of uid2, now  make sure that they're synchronized.
     */

  }, {
    key: 'handleZoomYanked',
    value: function () {
      function handleZoomYanked(uid1, uid2) {
        // where we're taking the zoom from
        var sourceXScale = this.xScales[uid2];
        var sourceYScale = this.yScales[uid2];

        var targetXScale = this.xScales[uid1];
        var targetYScale = this.yScales[uid1];

        // eslint-disable-next-line no-unused-vars

        var _scalesCenterAndK21 = (0, _utils.scalesCenterAndK)(targetXScale, targetYScale),
            _scalesCenterAndK22 = (0, _slicedToArray3['default'])(_scalesCenterAndK21, 3),
            targetCenterX = _scalesCenterAndK22[0],
            targetCenterY = _scalesCenterAndK22[1],
            targetK = _scalesCenterAndK22[2];
        // eslint-disable-next-line no-unused-vars


        var _scalesCenterAndK23 = (0, _utils.scalesCenterAndK)(sourceXScale, sourceYScale),
            _scalesCenterAndK24 = (0, _slicedToArray3['default'])(_scalesCenterAndK23, 3),
            sourceCenterX = _scalesCenterAndK24[0],
            sourceCenterY = _scalesCenterAndK24[1],
            sourceK = _scalesCenterAndK24[2];

        // set target center


        this.setCenters[uid1](targetCenterX, targetCenterY, sourceK, true);

        this.setState({
          chooseViewHandler: null
        });
      }

      return handleZoomYanked;
    }()

    /**
     * The user has chosen a position for the new track. The actual
     * track selection will be handled by TiledPlot
     *
     * We just need to close the menu here.
     */

  }, {
    key: 'handleTrackPositionChosen',
    value: function () {
      function handleTrackPositionChosen(viewUid, position) {
        this.setState({
          addTrackPosition: position,
          addTrackPositionView: viewUid
        });
      }

      return handleTrackPositionChosen;
    }()

    /**
     * Update the height of each row in the layout so that it takes up all
     * of the available space in the div.
     */

  }, {
    key: 'updateRowHeight',
    value: function () {
      function updateRowHeight() {
        if (!this.props.options || this.sizeMode !== SIZE_MODE_BOUNDED || this.props.options.pixelPreciseMarginPadding) {
          // not bounded so we don't need to update the row height
          return;
        }

        // const width = this.element.parentNode.clientWidth;
        var height = this.element.parentNode.clientHeight;

        var maxHeight = 0;
        var _iteratorNormalCompletion13 = true;
        var _didIteratorError13 = false;
        var _iteratorError13 = undefined;

        try {
          for (var _iterator13 = (0, _getIterator3['default'])((0, _utils.dictValues)(this.state.views)), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
            var view = _step13.value;

            maxHeight = Math.max(maxHeight, view.layout.y + view.layout.h);
          }
        } catch (err) {
          _didIteratorError13 = true;
          _iteratorError13 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion13 && _iterator13['return']) {
              _iterator13['return']();
            }
          } finally {
            if (_didIteratorError13) {
              throw _iteratorError13;
            }
          }
        }

        this.handleDragStart();
        this.handleDragStop();

        var MARGIN_HEIGHT = this.isEditable() ? 10 : 0;

        var marginHeight = MARGIN_HEIGHT * maxHeight - 1;
        var availableHeight = height - marginHeight;

        // const currentRowHeight = this.state.rowHeight;
        var prospectiveRowHeight = availableHeight / maxHeight; // maxHeight is the number of
        // rows necessary to display this view

        var chosenRowHeight = Math.floor(prospectiveRowHeight);

        // for (const view of dictValues(this.state.views)) {
        //   const {
        //     totalWidth,
        //     totalHeight,
        //     topHeight,
        //     bottomHeight,
        //     leftWidth,
        //     rightWidth,
        //     centerWidth,
        //     centerHeight,
        //     minNecessaryHeight
        //   } = this.calculateViewDimensions(view);

        //   // If the view is bounded, then we always fit everything inside the container
        //   //
        //   // It used to be that if the viewconfig was too long, we just let it overflow,
        //   // but I think it's better that it's always contained.

        //   /*
        //         if (minNecessaryHeight > view.layout.h * (prospectiveRowHeight + MARGIN_HEIGHT)) {
        //             // we don't have space for one of the containers, so let them exceed the bounds
        //             // of the box
        //             chosenRowHeight = currentRowHeight;
        //             break;
        //         }
        //         */
        // }

        this.setState({
          rowHeight: chosenRowHeight
        });
      }

      return updateRowHeight;
    }()

    /**
     * Notify the children that the layout has changed so that they
     * know to redraw themselves
     */

  }, {
    key: 'handleLayoutChange',
    value: function () {
      function handleLayoutChange(layout) {
        var _this18 = this;

        if (!this.element) return;

        layout.forEach(function (l) {
          var view = _this18.state.views[l.i];

          if (view) {
            // Bad design pattern. We directly manipulate the state and rely on
            // `this.updateRowHeight()` to trigger that the state updated
            view.layout.x = l.x;
            view.layout.y = l.y;
            view.layout.w = l.w;
            view.layout.h = l.h;
            view.layout.i = l.i;
          }
        });

        // The following method actually trigger a state update
        this.updateRowHeight();
        this.refreshView(_configs.LONG_DRAG_TIMEOUT);
      }

      return handleLayoutChange;
    }()

    /**
     * Maybe somebody started dragging again before the previous drag
     * timeout fired. In that case, we need to clear this timeout so
     * that it doesn't override a previously set one.
     */

  }, {
    key: 'clearDragTimeout',
    value: function () {
      function clearDragTimeout() {
        if (this.dragTimeout) {
          clearTimeout(this.dragTimeout);
          this.dragTimeout = null;
        }
      }

      return clearDragTimeout;
    }()
  }, {
    key: 'getTrackInfo',
    value: function () {
      function getTrackInfo(trackType) {
        if (_configs.TRACKS_INFO_BY_TYPE[trackType]) {
          return _configs.TRACKS_INFO_BY_TYPE[trackType];
        }

        if (this.pluginTracks && this.pluginTracks[trackType]) {
          return this.pluginTracks[trackType].config;
        }

        if (window.higlassTracksByType && window.higlassTracksByType[trackType]) {
          return window.higlassTracksByType[trackType].config;
        }

        console.warn('Track type not found:', trackType, '(check app/scripts/config/ for a list of defined track types)');
        return undefined;
      }

      return getTrackInfo;
    }()
  }, {
    key: 'forceRefreshView',
    value: function () {
      function forceRefreshView() {
        // force everything to rerender
        this.setState(this.state); // eslint-disable-line react/no-access-state-in-setstate
      }

      return forceRefreshView;
    }()
  }, {
    key: 'refreshView',
    value: function () {
      function refreshView() {
        var _this19 = this;

        var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _configs.SHORT_DRAG_TIMEOUT;

        this.clearDragTimeout();

        this.notifyDragChangedListeners(true);

        this.clearDragTimeout();
        this.dragTimeout = setTimeout(function () {
          _this19.notifyDragChangedListeners(false);
        }, timeout);
      }

      return refreshView;
    }()
  }, {
    key: 'handleDragStart',
    value: function () {
      function handleDragStart() /* layout, oldItem, newItem, placeholder, e, element */{
        this.clearDragTimeout();
        this.notifyDragChangedListeners(true);
      }

      return handleDragStart;
    }()
  }, {
    key: 'handleDragStop',
    value: function () {
      function handleDragStop() {
        var _this20 = this;

        // wait for the CSS transitions to end before
        // turning off the dragging state
        //
        this.clearDragTimeout();
        this.dragTimeout = setTimeout(function () {
          _this20.notifyDragChangedListeners(false);
        }, _configs.LONG_DRAG_TIMEOUT);
      }

      return handleDragStop;
    }()
  }, {
    key: 'resizeHandler',
    value: function () {
      function resizeHandler() {
        (0, _utils.objVals)(this.viewHeaders).filter(function (x) {
          return x;
        }).forEach(function (viewHeader) {
          return viewHeader.checkWidth();
        });
      }

      return resizeHandler;
    }()

    /**
     * Get the dimensions for this view, counting just the tracks
     * that are present in it
     *
     * @param view: A view containing a list of tracks as a member.
     * @return: A width and a height pair (e.g. [width, height])
     */

  }, {
    key: 'calculateViewDimensions',
    value: function () {
      function calculateViewDimensions(view) {
        var defaultHorizontalHeight = 20;
        var defaultVerticalWidth = 0;
        var defaultCenterHeight = 100;
        var defaultCenterWidth = 100;
        var currHeight = this.viewMarginTop + this.viewMarginBottom + this.viewPaddingTop + this.viewPaddingBottom;
        var currWidth = this.viewMarginLeft + this.viewMarginRight + this.viewPaddingLeft + this.viewPaddingRight;
        // currWidth will generally be ignored because it will just be set to
        // the width of the enclosing container
        var minNecessaryHeight = 0;
        minNecessaryHeight += 10; // the header

        var MIN_VERTICAL_HEIGHT = 20;

        if (view.tracks.top) {
          // tally up the height of the top tracks

          for (var i = 0; i < view.tracks.top.length; i++) {
            var track = view.tracks.top[i];
            currHeight += track.height ? track.height : defaultHorizontalHeight;
            minNecessaryHeight += track.height ? track.height : defaultHorizontalHeight;
          }
        }

        if (view.tracks.bottom) {
          // tally up the height of the top tracks

          for (var _i = 0; _i < view.tracks.bottom.length; _i++) {
            var _track = view.tracks.bottom[_i];
            currHeight += _track.height ? _track.height : defaultHorizontalHeight;
            minNecessaryHeight += _track.height ? _track.height : defaultHorizontalHeight;
          }
        }

        if (view.tracks.left && view.tracks.left.length > 0 || view.tracks.right && view.tracks.right.length > 0 || view.tracks.center && view.tracks.center.length > 0) {
          minNecessaryHeight += MIN_VERTICAL_HEIGHT;
        }

        var leftHeight = 0;
        if (view.tracks.left) {
          // tally up the height of the top tracks

          for (var _i2 = 0; _i2 < view.tracks.left.length; _i2++) {
            var _track2 = view.tracks.left[_i2];
            var thisHeight = _track2.height ? _track2.height : defaultCenterHeight;
            currWidth += _track2.width ? _track2.width : defaultVerticalWidth;

            leftHeight = Math.max(leftHeight, thisHeight);
          }
        }

        var rightHeight = 0;

        if (view.tracks.right) {
          // tally up the height of the top tracks

          for (var _i3 = 0; _i3 < view.tracks.right.length; _i3++) {
            var _track3 = view.tracks.right[_i3];
            var _thisHeight = _track3.height ? _track3.height : defaultCenterHeight;
            currWidth += _track3.width ? _track3.width : defaultVerticalWidth;

            rightHeight = Math.max(rightHeight, _thisHeight);
          }
        }

        var sideHeight = Math.max(leftHeight, rightHeight);

        var centerHeight = 0;
        var centerWidth = 0;

        if (view.tracks.center && (0, _utils.dictValues)(view.tracks.center).length > 0) {
          if (!view.tracks.center[0].contents || view.tracks.center[0].contents.length > 0) {
            var height = null;
            var width = null;

            if (view.tracks.center[0].contents) {
              // combined track in the center
              var _iteratorNormalCompletion14 = true;
              var _didIteratorError14 = false;
              var _iteratorError14 = undefined;

              try {
                for (var _iterator14 = (0, _getIterator3['default'])(view.tracks.center[0].contents), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) {
                  var _track4 = _step14.value;

                  height = Math.max(height, _track4.height ? _track4.height : defaultCenterHeight);
                  width = Math.max(width, _track4.width ? _track4.width : defaultCenterWidth);
                }
              } catch (err) {
                _didIteratorError14 = true;
                _iteratorError14 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion14 && _iterator14['return']) {
                    _iterator14['return']();
                  }
                } finally {
                  if (_didIteratorError14) {
                    throw _iteratorError14;
                  }
                }
              }
            } else {
              height = view.tracks.center[0].height ? view.tracks.center[0].height : defaultCenterHeight;
              width = view.tracks.center[0].width ? view.tracks.center[0].width : defaultCenterWidth;
            }

            currHeight += height;
            currWidth += width;
          }
        } else if ((view.tracks.top && (0, _utils.dictValues)(view.tracks.top).length > 1 || view.tracks.bottom && (0, _utils.dictValues)(view.tracks.bottom).length > 1) && (view.tracks.left && (0, _utils.dictValues)(view.tracks.left).length || view.tracks.right && (0, _utils.dictValues)(view.tracks.right).length)) {
          centerWidth = defaultCenterWidth;
          centerHeight = defaultCenterHeight;
        }

        // make the total height the greater of the left height
        // and the center height
        if (sideHeight > centerHeight) {
          currHeight += sideHeight;
        } else {
          currHeight += centerHeight;
        }

        var topHeight = 0;
        var bottomHeight = 0;
        var leftWidth = 0;
        var rightWidth = 0;

        if ('top' in view.tracks) {
          topHeight = view.tracks.top.map(function (x) {
            return x.height ? x.height : defaultHorizontalHeight;
          }).reduce(function (a, b) {
            return a + b;
          }, 0);
        }
        if ('bottom' in view.tracks) {
          bottomHeight = view.tracks.bottom.map(function (x) {
            return x.height ? x.height : defaultHorizontalHeight;
          }).reduce(function (a, b) {
            return a + b;
          }, 0);
        }
        if ('left' in view.tracks) {
          leftWidth = view.tracks.left.map(function (x) {
            return x.width ? x.width : defaultVerticalWidth;
          }).reduce(function (a, b) {
            return a + b;
          }, 0);
        }
        if ('right' in view.tracks) {
          rightWidth = view.tracks.right.map(function (x) {
            return x.width ? x.width : defaultVerticalWidth;
          }).reduce(function (a, b) {
            return a + b;
          }, 0);
        }

        return {
          totalWidth: currWidth,
          totalHeight: currHeight,
          topHeight: topHeight,
          bottomHeight: bottomHeight,
          leftWidth: leftWidth,
          rightWidth: rightWidth,
          centerWidth: centerWidth,
          centerHeight: centerHeight,
          minNecessaryHeight: minNecessaryHeight
        };
      }

      return calculateViewDimensions;
    }()
  }, {
    key: 'calculateZoomLimits',
    value: function () {
      function calculateZoomLimits(view, initialXDomain) {
        var limits = [0, Infinity];

        // By default, highest zoom resolution is 1bp
        var viewConfLimit = view.zoomLimits || [1, null];
        var diffX = initialXDomain[1] - initialXDomain[0];

        if (viewConfLimit.length !== 2) {
          return limits;
        }

        if (viewConfLimit[0] !== null && viewConfLimit[0] > 0) {
          var upperLimit = diffX / viewConfLimit[0];
          limits[1] = Math.max(upperLimit, 1);
          if (upperLimit < 1) {
            console.warn('Invalid zoom limits. Lower limit set to ' + diffX);
          }
        }

        if (viewConfLimit[1] !== null && viewConfLimit[1] > viewConfLimit[0]) {
          var lowerLimit = diffX / viewConfLimit[1];
          limits[0] = Math.min(lowerLimit, 1);
          if (lowerLimit > 1) {
            console.warn('Invalid zoom limits. Upper limit set to ' + diffX);
          }
        }
        return limits;
      }

      return calculateZoomLimits;
    }()
  }, {
    key: 'generateViewLayout',
    value: function () {
      function generateViewLayout(view) {
        var layout = null;

        if ('layout' in view) {
          layout = view.layout.layout;
        } else {
          /*
          const minTrackHeight = 30;
          const elementWidth = this.element.clientWidth;
           let { totalWidth, totalHeight,
            topHeight, bottomHeight,
            leftWidth, rightWidth,
            centerWidth, centerHeight } = this.calculateViewDimensions(view);
           if (view.searchBox) { totalHeight += 30; }
           const heightGrid = Math.ceil(totalHeight / this.rowHeight);
           */

          // we're keeping this simple, just make the view 12x12
          layout = {
            x: 0,
            y: 0,
            w: NUM_GRID_COLUMNS,
            h: DEFAULT_NEW_VIEW_HEIGHT
          };

          // the height should be adjusted when the layout changes

          /*
            if ('center' in view.tracks || 'left' in view.tracks || 'right' in view.tracks) {
                let desiredHeight = ((elementWidth - leftWidth - rightWidth - 2 * this.viewMarginTop) );
                desiredHeight +=  topHeight + bottomHeight + 2*this.viewMarginBottom + 20;
                 // how much height is left in the browser?
                 // limit the height of the container to the window height
                // the number 160 is relatively arbitrary and should be
                // replaced with a concrete measure of the element below and
                // above the canvas area
                let availableHeight = window.innerHeight - 160;
                 if (desiredHeight > availableHeight )
                    desiredHeight = availableHeight;
                 // stretch the view out
                layout.h = Math.ceil(desiredHeight / this.rowHeight);
            }
            else
                layout.h = heightGrid;
             layout.minH = heightGrid;
            layout.i = slugid.nice();
            */
        }

        return layout;
      }

      return generateViewLayout;
    }()

    /**
     * Remove all the tracks from a view
     *
     * @param {viewUid} Thie view's identifier
     */

  }, {
    key: 'handleClearView',
    value: function () {
      function handleClearView(viewUid) {
        var views = this.state.views;


        views[viewUid].tracks.top = [];
        views[viewUid].tracks.bottom = [];
        views[viewUid].tracks.center = [];
        views[viewUid].tracks.left = [];
        views[viewUid].tracks.right = [];
        views[viewUid].tracks.whole = [];

        this.setState({
          views: views
        });
      }

      return handleClearView;
    }()

    /**
     * A view needs to be closed. Remove it from from the viewConfig and then clean
     * up all of its connections (zoom links, workers, etc...)
     *
     * @param {uid} This view's identifier
     */

  }, {
    key: 'handleCloseView',
    value: function () {
      function handleCloseView(uid) {
        var _this21 = this;

        // check if this is the only view
        // if it is, don't close it (display an error message)
        if ((0, _utils.dictValues)(this.state.views).length === 1) {
          return;
        }

        // if this view was zoom locked to another, we need to unlock it
        this.handleUnlock(uid, this.zoomLocks);

        // might want to notify the views that they're beig closed
        this.setState(function (prevState) {
          delete prevState.views[uid];

          var viewsByUid = _this21.removeInvalidTracks(prevState.views);
          return {
            views: viewsByUid
          };
        });
      }

      return handleCloseView;
    }()

    /**
     * We're adding a new dataset to an existing track
     *
     * @param newTrack: The new track to be added.
     * @param position: Where the new series should be placed.
     *  (This could also be inferred from the hostTrack, but since
     *  we already have it, we might as well use it)
     * @param hostTrack: The track that will host the new series.
     */

  }, {
    key: 'handleSeriesAdded',
    value: function () {
      function handleSeriesAdded(viewId, newTrack, position, hostTrack) {
        // is the host track a combined track?
        // if so, easy, just append the new track to its contents
        // if not, remove the current track from the track list
        // create a new combined track, add the current and the new
        // tracks and then update the whole track list
        var tracks = this.state.views[viewId].tracks;


        if (hostTrack.type === 'combined') {
          hostTrack.contents.push(newTrack);

          if (newTrack.type === 'heatmap') {
            // For stacked heatmaps we will adjust some options automatically for convenience
            this.compatibilityfyStackedHeatmaps(newTrack, hostTrack);
          }
        } else {
          var newHost = {
            type: 'combined',
            uid: _slugid2['default'].nice(),
            height: hostTrack.height,
            width: hostTrack.width,
            contents: [hostTrack, newTrack]
          };

          var positionTracks = tracks[position];

          for (var i = 0; i < positionTracks.length; i++) {
            if (positionTracks[i].uid === hostTrack.uid) {
              positionTracks[i] = newHost;
            }
          }
        }

        this.setState(function (prevState) {
          return {
            views: prevState.views
          };
        });
      }

      return handleSeriesAdded;
    }()
  }, {
    key: 'handleNoTrackAdded',
    value: function () {
      function handleNoTrackAdded() {
        if (this.state.addTrackPosition) {
          // we've already added the track, remove the add track dialog
          this.setState({
            addTrackPosition: null
          });
        }
      }

      return handleNoTrackAdded;
    }()

    /**
     * Add multiple new tracks (likely from the AddTrackModal dialog)
     *
     * @param trackInfo: A JSON object that can be used as a track
     *                   definition
     * @param position: The position the track is being added to
     * @param host: If this track is being added to another track
     */

  }, {
    key: 'handleTracksAdded',
    value: function () {
      function handleTracksAdded(viewId, newTracks, position, host) {
        this.storeTrackSizes(viewId);

        var _iteratorNormalCompletion15 = true;
        var _didIteratorError15 = false;
        var _iteratorError15 = undefined;

        try {
          for (var _iterator15 = (0, _getIterator3['default'])(newTracks), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) {
            var newTrack = _step15.value;

            this.handleTrackAdded(viewId, newTrack, position, host);
          }
        } catch (err) {
          _didIteratorError15 = true;
          _iteratorError15 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion15 && _iterator15['return']) {
              _iterator15['return']();
            }
          } finally {
            if (_didIteratorError15) {
              throw _iteratorError15;
            }
          }
        }
      }

      return handleTracksAdded;
    }()

    /**
     * Change the type of a track. For example, convert a line to a bar track.
     *
     * Parameters
     * ----------
     *  viewUid: string
     *    The view containing the track to be changed
     *  trackUid: string
     *    The uid identifying the existin track
     *  newType: string
     *    The type to switch this track to.
     */

  }, {
    key: 'handleChangeTrackType',
    value: function () {
      function handleChangeTrackType(viewUid, trackUid, newType) {
        var view = this.state.views[viewUid];
        var trackConfig = (0, _utils.getTrackByUid)(view.tracks, trackUid);

        // this track needs a new uid so that it will be rerendered
        var oldUid = trackConfig.uid;
        trackConfig.uid = _slugid2['default'].nice();
        trackConfig.type = newType;
        var newUid = trackConfig.uid;

        this.updateTrackLocks(viewUid, oldUid, newUid);
        this.setState(function (prevState) {
          return {
            views: prevState.views
          };
        });
      }

      return handleChangeTrackType;
    }()

    /**
     * Change the data source for a track. E.g. when adding or
     * removing a divisor.
     *
     * Parameters
     * ----------
     *  viewUid: string
     *    The view containing the track to be changed
     *  trackUid: string
     *    The uid identifying the existin track
     *  newData: object
     *    The new data source section
     */

  }, {
    key: 'handleChangeTrackData',
    value: function () {
      function handleChangeTrackData(viewUid, trackUid, newData) {
        var view = this.state.views[viewUid];
        var trackConfig = (0, _utils.getTrackByUid)(view.tracks, trackUid);

        // this track needs a new uid so that it will be rerendered
        trackConfig.uid = _slugid2['default'].nice();
        trackConfig.data = newData;

        this.setState(function (prevState) {
          return {
            views: prevState.views
          };
        });
      }

      return handleChangeTrackData;
    }()

    /**
     * A track was added from the AddTrackModal dialog.
     *
     * @param trackInfo: A JSON object that can be used as a track
     *                   definition
     * @param position: The position the track is being added to
     * @param host: If this track is being added to another track
     *
     * @returns {Object}: A trackConfig (\{ uid: "", width: x \})
     *  describing this track
     */

  }, {
    key: 'handleTrackAdded',
    value: function () {
      function handleTrackAdded(viewId, newTrack, position) {
        var host = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

        this.addDefaultTrackOptions(newTrack);

        // make sure the new track has a uid
        if (!newTrack.uid) newTrack.uid = _slugid2['default'].nice();

        if (newTrack.contents) {
          // add default options to combined tracks
          var _iteratorNormalCompletion16 = true;
          var _didIteratorError16 = false;
          var _iteratorError16 = undefined;

          try {
            for (var _iterator16 = (0, _getIterator3['default'])(newTrack.contents), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) {
              var ct = _step16.value;

              this.addDefaultTrackOptions(ct);
            }
          } catch (err) {
            _didIteratorError16 = true;
            _iteratorError16 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion16 && _iterator16['return']) {
                _iterator16['return']();
              }
            } finally {
              if (_didIteratorError16) {
                throw _iteratorError16;
              }
            }
          }
        }

        if (this.state.addTrackPosition) {
          // we've already added the track, remove the add track dialog
          this.setState({
            addTrackPosition: null
          });
        }

        if (host) {
          // we're adding a series rather than a whole new track
          this.handleSeriesAdded(viewId, newTrack, position, host);
          return null;
        }

        newTrack.position = position;

        var trackInfo = this.getTrackInfo(newTrack.type);

        newTrack.width = trackInfo.defaultWidth || trackInfo.defaultOptions && trackInfo.defaultOptions.minWidth || this.minVerticalWidth;
        newTrack.height = trackInfo.defaultHeight || trackInfo.defaultOptions && trackInfo.defaultOptions.minHeight || this.minHorizontalHeight;

        var tracks = this.state.views[viewId].tracks;


        var numTracks = 0;
        (0, _utils.visitPositionedTracks)(tracks, function () {
          return numTracks++;
        });

        if (position === 'left' || position === 'top') {
          // if we're adding a track on the left or the top, we want the
          // new track to appear at the begginning of the track list
          tracks[position].unshift(newTrack);
        } else if (position === 'center') {
          // we're going to have to either overlay the existing track with a new one
          // or add another one on top
          if (tracks.center.length === 0) {
            // no existing tracks
            var newCombined = {
              uid: _slugid2['default'].nice(),
              type: 'combined',
              contents: [newTrack]
            };
            tracks.center = [newCombined];
          } else if (tracks.center[0].type === 'combined') {
            // if it's a combined track, we just need to add this track to the
            // contents
            tracks.center[0].contents.push(newTrack);

            if (newTrack.type === 'heatmap') {
              // For stacked heatmaps we will adjust some options automatically for convenience
              this.compatibilityfyStackedHeatmaps(newTrack, tracks.center[0]);
            }
          } else {
            // if it's not, we have to create a new combined track
            var _newCombined = {
              uid: _slugid2['default'].nice(),
              type: 'combined',
              contents: [tracks.center[0], newTrack]
            };

            tracks.center = [_newCombined];

            if (newTrack.type === 'heatmap') {
              this.compatibilityfyStackedHeatmaps(newTrack, _newCombined);
            }
          }
        } else {
          // otherwise, we want it at the end of the track list
          if (!tracks[position]) {
            // this position wasn't defined in the original viewconf
            tracks[position] = [];
          }

          tracks[position].push(newTrack);
        }

        this.adjustLayoutToTrackSizes(this.state.views[viewId]);

        if ((0, _keys2['default'])(this.state.views).length === 1 && numTracks === 0) {
          // Zoom to data extent since this is the first track we added and we only
          // have one view

          // This doesn't work because the tilesetInfo is probably not there yet
          this.handleZoomToData(viewId);

          // This might work but sometimes `TiledPlot.handleTilesetInfoReceived`
          // isn't triggered. E.g., when adding `dm6` as `chromosome-labels`.
          this.zoomToDataExtentOnInit.add(viewId);
        }

        return newTrack;
      }

      return handleTrackAdded;
    }()

    /**
     * We're adding a new heatmap to a combined track. We need to make sure that
     * their options are compatible.
     *
     * @param   {object}  newTrack  New heatmap track
     * @param   {object}  combinedTrack  Combined track the new heatmap is added to
     */

  }, {
    key: 'compatibilityfyStackedHeatmaps',
    value: function () {
      function compatibilityfyStackedHeatmaps(newTrack, combinedTrack) {
        var otherHeatmap = void 0;

        var hasHeatmaps = combinedTrack.contents.some(function (track) {
          otherHeatmap = track;
          return track.type === 'heatmap';
        });

        if (hasHeatmaps) {
          // There already exist a heatmap let's set the background of the new
          // heatmap to `transparent`
          newTrack.options.backgroundColor = 'transparent';
          newTrack.options.showTooltip = otherHeatmap.options.showTooltip;
          newTrack.options.showMousePosition = otherHeatmap.options.showMousePosition;
          newTrack.options.mousePositionColor = otherHeatmap.options.mousePositionColor;
        }
      }

      return compatibilityfyStackedHeatmaps;
    }()

    /**
     * Go through each track and store its size in the viewconf.
     *
     * This is so that sizes don't get lost when the view is unbounded
     * and new tracks are added.
     *
     * Parameters
     * ----------
     *
     *  viewId : string
     *      The id of the view whose tracks we're measuring
     *
     * Returns
     * -------
     *
     *  Nothing
     */

  }, {
    key: 'storeTrackSizes',
    value: function () {
      function storeTrackSizes(viewId) {
        var _this22 = this;

        (0, _utils.visitPositionedTracks)(this.state.views[viewId].tracks, function (track) {
          var trackObj = _this22.tiledPlots[viewId].trackRenderer.getTrackObject(track.uid);

          if (trackObj) {
            ;

            var _trackObj$dimensions = (0, _slicedToArray3['default'])(trackObj.dimensions, 2);

            track.width = _trackObj$dimensions[0];
            track.height = _trackObj$dimensions[1];
          }
        });
      }

      return storeTrackSizes;
    }()

    /*
     * Adjust the layout to match the size of the contained tracks. If tracks
     * are added, the layout size needs to expand. If they're removed, it needs
     * to contract.
     *
     * This function should be called from handleTrackAdded and handleCloseTrack.
     *
     * Parameters
     * ----------
     *
     *  view : {...}
     *      The definition from the viewconf
     */

  }, {
    key: 'adjustLayoutToTrackSizes',
    value: function () {
      function adjustLayoutToTrackSizes(view) {
        // if the view is too short, expand the view so that it fits this track
        if (!view.layout) return;

        var isEditable = this.isEditable();

        var totalTrackHeight = 0;

        // we are not checking for this.viewHeaders because this function may be
        // called before the component is mounted
        if (isEditable) totalTrackHeight += VIEW_HEADER_HEIGHT;

        // the tracks are larger than the height of the current view, so we need
        // to extend it

        var _calculateViewDimensi = this.calculateViewDimensions(view),
            totalHeight = _calculateViewDimensi.totalHeight;

        totalTrackHeight += totalHeight;

        var MARGIN_HEIGHT = this.isEditable() ? 10 : 0;

        totalTrackHeight += MARGIN_HEIGHT;
        var rowHeight = this.state.rowHeight + MARGIN_HEIGHT;

        if (this.sizeMode !== SIZE_MODE_BOUNDED) {
          view.layout.h = Math.ceil(totalTrackHeight / rowHeight);
        }
      }

      return adjustLayoutToTrackSizes;
    }()
  }, {
    key: 'handleCloseTrack',
    value: function () {
      function handleCloseTrack(viewId, uid) {
        var tracks = this.state.views[viewId].tracks;


        this.handleUnlockValueScale(viewId, uid);

        for (var trackType in tracks) {
          var theseTracks = tracks[trackType];
          var newTracks = theseTracks.filter(function (d) {
            return d.uid !== uid;
          });

          if (newTracks.length === theseTracks.length) {
            // no whole tracks need to removed, see if any of the combined tracks
            // contain series which need to go
            var combinedTracks = newTracks.filter(function (x) {
              return x.type === 'combined';
            });

            combinedTracks.forEach(function (ct) {
              ct.contents = ct.contents.filter(function (x) {
                return x.uid !== uid;
              });
            });
          } else {
            tracks[trackType] = newTracks;
          }
        }

        this.storeTrackSizes(viewId);
        this.adjustLayoutToTrackSizes(this.state.views[viewId]);

        this.setState(function (prevState) {
          return {
            views: prevState.views
          };
        });

        return this.state.views;
      }

      return handleCloseTrack;
    }()
  }, {
    key: 'handleLockValueScale',
    value: function () {
      function handleLockValueScale(fromViewUid, fromTrackUid) {
        var _this23 = this;

        this.setState({
          chooseTrackHandler: function () {
            function chooseTrackHandler(toViewUid, toTrackUid) {
              return _this23.handleValueScaleLocked(fromViewUid, fromTrackUid, toViewUid, toTrackUid);
            }

            return chooseTrackHandler;
          }()
        });
      }

      return handleLockValueScale;
    }()
  }, {
    key: 'combineViewAndTrackUid',
    value: function () {
      function combineViewAndTrackUid(viewUid, trackUid) {
        // see if we've already created a uid for this view / track combo
        var uid = String(viewUid) + '.' + String(trackUid);

        this.combinedUidToViewTrack[uid] = { view: viewUid, track: trackUid };

        if (this.viewTrackUidsToCombinedUid[viewUid]) {
          if (this.viewTrackUidsToCombinedUid[trackUid]) {
            return this.viewTrackUidsToCombinedUid[viewUid][trackUid];
          }

          this.viewTrackUidsToCombinedUid[viewUid][trackUid] = uid;
        } else {
          this.viewTrackUidsToCombinedUid[viewUid] = {};
          this.viewTrackUidsToCombinedUid[viewUid][trackUid] = uid;
        }

        return uid;
      }

      return combineViewAndTrackUid;
    }()

    /**
     * Update all locks involving this track to use a new track uid.
     *
     * @param  {string} viewUid The view's uid
     * @param  {string} oldTrackUid The track's old uid
     * @param  {string} newTrackUid The track's new uid
     */

  }, {
    key: 'updateTrackLocks',
    value: function () {
      function updateTrackLocks(viewUid, oldTrackUid, newTrackUid) {
        // update location locks
        // update zoom locks
        // update value scale locks
        var oldLockGroupUid = this.combineViewAndTrackUid(viewUid, oldTrackUid);
        var newLockGroupUid = this.combineViewAndTrackUid(viewUid, newTrackUid);

        if (this.valueScaleLocks[oldLockGroupUid]) {
          var lockGroup = this.valueScaleLocks[oldLockGroupUid];
          this.valueScaleLocks[newLockGroupUid] = lockGroup;
          delete this.valueScaleLocks[oldLockGroupUid];
        }

        for (var lockGroupUid in this.valueScaleLocks) {
          if (this.valueScaleLocks[lockGroupUid][oldLockGroupUid]) {
            var oldEntry = this.valueScaleLocks[lockGroupUid][oldLockGroupUid];
            this.valueScaleLocks[lockGroupUid][newLockGroupUid] = oldEntry;
            oldEntry.track = newTrackUid;
            delete this.valueScaleLocks[lockGroupUid][oldLockGroupUid];
          }
        }
      }

      return updateTrackLocks;
    }()
  }, {
    key: 'handleUnlockValueScale',
    value: function () {
      function handleUnlockValueScale(viewUid, trackUid) {
        // if it's combined track, unlock each individual component
        if (this.tiledPlots[viewUid].trackRenderer.getTrackObject(trackUid).createdTracks) {
          // if the from view is a combined track, recurse and add links between its child tracks
          var childTrackUids = (0, _utils.dictKeys)(this.tiledPlots[viewUid].trackRenderer.getTrackObject(trackUid).createdTracks);
          var _iteratorNormalCompletion17 = true;
          var _didIteratorError17 = false;
          var _iteratorError17 = undefined;

          try {
            for (var _iterator17 = (0, _getIterator3['default'])(childTrackUids), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) {
              var childTrackUid = _step17.value;

              this.handleUnlock(this.combineViewAndTrackUid(viewUid, childTrackUid), this.valueScaleLocks);
            }
          } catch (err) {
            _didIteratorError17 = true;
            _iteratorError17 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion17 && _iterator17['return']) {
                _iterator17['return']();
              }
            } finally {
              if (_didIteratorError17) {
                throw _iteratorError17;
              }
            }
          }
        } else {
          this.handleUnlock(this.combineViewAndTrackUid(viewUid, trackUid), this.valueScaleLocks);
        }
      }

      return handleUnlockValueScale;
    }()
  }, {
    key: 'handleValueScaleLocked',
    value: function () {
      function handleValueScaleLocked(fromViewUid, fromTrackUid, toViewUid, toTrackUid) {
        var _this24 = this;

        if (this.tiledPlots[fromViewUid].trackRenderer.getTrackObject(fromTrackUid).createdTracks) {
          // if the from view is a combined track, recurse and add links between its child tracks
          var childTrackUids = (0, _utils.dictKeys)(this.tiledPlots[fromViewUid].trackRenderer.getTrackObject(fromTrackUid).createdTracks);
          var _iteratorNormalCompletion18 = true;
          var _didIteratorError18 = false;
          var _iteratorError18 = undefined;

          try {
            for (var _iterator18 = (0, _getIterator3['default'])(childTrackUids), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) {
              var childTrackUid = _step18.value;

              this.handleValueScaleLocked(fromViewUid, childTrackUid, toViewUid, toTrackUid);
            }
          } catch (err) {
            _didIteratorError18 = true;
            _iteratorError18 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion18 && _iterator18['return']) {
                _iterator18['return']();
              }
            } finally {
              if (_didIteratorError18) {
                throw _iteratorError18;
              }
            }
          }

          return;
        }

        if (this.tiledPlots[toViewUid].trackRenderer.getTrackObject(toTrackUid).createdTracks) {
          // if the from view is a combined track, recurse and add links between its child tracks
          var _childTrackUids = (0, _utils.dictKeys)(this.tiledPlots[toViewUid].trackRenderer.getTrackObject(toTrackUid).createdTracks);
          var _iteratorNormalCompletion19 = true;
          var _didIteratorError19 = false;
          var _iteratorError19 = undefined;

          try {
            for (var _iterator19 = (0, _getIterator3['default'])(_childTrackUids), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) {
              var _childTrackUid = _step19.value;

              this.handleValueScaleLocked(fromViewUid, fromTrackUid, toViewUid, _childTrackUid);
            }
          } catch (err) {
            _didIteratorError19 = true;
            _iteratorError19 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion19 && _iterator19['return']) {
                _iterator19['return']();
              }
            } finally {
              if (_didIteratorError19) {
                throw _iteratorError19;
              }
            }
          }

          return;
        }

        var fromUid = this.combineViewAndTrackUid(fromViewUid, fromTrackUid);
        var toUid = this.combineViewAndTrackUid(toViewUid, toTrackUid);

        this.addLock(fromUid, toUid, this.valueScaleLocks, function (uid) {
          return _this24.combinedUidToViewTrack[uid];
        });

        this.syncValueScales(fromViewUid, fromTrackUid);

        this.setState({
          chooseTrackHandler: null
        });
      }

      return handleValueScaleLocked;
    }()

    /**
     * Add callbacks for functions that need them
     *
     * Done in place.
     *
     * @param track: A view with tracks.
     */

  }, {
    key: 'addCallbacks',
    value: function () {
      function addCallbacks(viewUid, track) {
        var _this25 = this;

        var trackInfo = this.getTrackInfo(track.type);
        if (track.type === 'viewport-projection-center' || track.type === 'viewport-projection-horizontal' || track.type === 'viewport-projection-vertical' || trackInfo && trackInfo.projection) {
          var fromView = track.fromViewUid;

          track.registerViewportChanged = function (trackId, listener) {
            return _this25.addScalesChangedListener(fromView, trackId, listener);
          };
          track.removeViewportChanged = function (trackId) {
            return _this25.removeScalesChangedListener(fromView, trackId);
          };
          track.setDomainsCallback = function (xDomain, yDomain) {
            if (!fromView) {
              // If there is no `fromView`, then there must be a `projectionXDomain` instead.
              // Update the viewconfig to reflect the new `projectionXDomain` array
              // on the `viewport-projection-horizontal` track.
              if (!_this25.projectionXDomains[viewUid]) {
                _this25.projectionXDomains[viewUid] = {};
              }
              if (!_this25.projectionYDomains[viewUid]) {
                _this25.projectionYDomains[viewUid] = {};
              }
              if (track.type === 'viewport-projection-horizontal' || track.type === 'viewport-projection-center') {
                _this25.projectionXDomains[viewUid][track.uid] = xDomain;
              }
              if (track.type === 'viewport-projection-vertical' || track.type === 'viewport-projection-center') {
                _this25.projectionYDomains[viewUid][track.uid] = yDomain;
              }
              _this25.triggerViewChangeDb();
              // Return early, since the remaining code uses the `fromView` variable.
              return;
            }
            var tXScale = (0, _d3Scale.scaleLinear)().domain(xDomain).range(_this25.xScales[fromView].range());
            var tYScale = (0, _d3Scale.scaleLinear)().domain(yDomain).range(_this25.yScales[fromView].range());

            var _scalesCenterAndK25 = (0, _utils.scalesCenterAndK)(tXScale, tYScale),
                _scalesCenterAndK26 = (0, _slicedToArray3['default'])(_scalesCenterAndK25, 3),
                tx = _scalesCenterAndK26[0],
                ty = _scalesCenterAndK26[1],
                k = _scalesCenterAndK26[2];

            _this25.setCenters[fromView](tx, ty, k, false);

            var zoomLocked = false;
            var locationLocked = false;

            // if we drag the brush and this view is locked to others, we don't
            // want the movement we induce in them to come back and modify this
            // view and set up a feedback loop
            if (viewUid in _this25.zoomLocks) {
              zoomLocked = fromView in _this25.zoomLocks[viewUid];
            }
            if (zoomLocked) {
              _this25.handleUnlock(viewUid, _this25.zoomLocks);
            }

            if (viewUid in _this25.locationLocks) {
              locationLocked = fromView in _this25.locationLocks[viewUid];
            }
            if (locationLocked) {
              _this25.handleUnlock(viewUid, _this25.locationLocks);
            }

            _this25.handleScalesChanged(fromView, tXScale, tYScale, true);

            if (zoomLocked) {
              _this25.addLock(viewUid, fromView, _this25.zoomLocks, _this25.viewScalesLockData);
            }
            if (locationLocked) {
              _this25.addLock(viewUid, fromView, _this25.locationLocks, _this25.viewScalesLockData);
            }
          };
        }
      }

      return addCallbacks;
    }()
  }, {
    key: 'validateLocks',
    value: function () {
      function validateLocks(locks) {
        // locks are organized like this:
        // { v1: { v1: [0,0,0], v2: [1,1,1]}}
        // v1 marks the name of a lock group and also
        // corresponds to a view uid (a view cannot belong)
        // to more than one lock group. The numbers are the
        // zoom, xOffset, yOffset values that were present when
        // the view was created

        var toRemove = [];

        var _iteratorNormalCompletion20 = true;
        var _didIteratorError20 = false;
        var _iteratorError20 = undefined;

        try {
          for (var _iterator20 = (0, _getIterator3['default'])((0, _utils.dictKeys)(locks)), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) {
            var viewUid = _step20.value;

            if (!locks[viewUid] || !locks[viewUid][viewUid]) {
              // we need to have the starting location of the
              // lock's namesake view
              toRemove.push(viewUid);
            }
          }
        } catch (err) {
          _didIteratorError20 = true;
          _iteratorError20 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion20 && _iterator20['return']) {
              _iterator20['return']();
            }
          } finally {
            if (_didIteratorError20) {
              throw _iteratorError20;
            }
          }
        }

        var _iteratorNormalCompletion21 = true;
        var _didIteratorError21 = false;
        var _iteratorError21 = undefined;

        try {
          for (var _iterator21 = (0, _getIterator3['default'])(toRemove), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) {
            var _viewUid = _step21.value;

            if (locks[_viewUid]) {
              console.warn('View ' + String(_viewUid) + ' not present in lock group. Removing...');
              this.handleUnlock(_viewUid, locks);
              delete locks[_viewUid];
            }
          }
        } catch (err) {
          _didIteratorError21 = true;
          _iteratorError21 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion21 && _iterator21['return']) {
              _iterator21['return']();
            }
          } finally {
            if (_didIteratorError21) {
              throw _iteratorError21;
            }
          }
        }
      }

      return validateLocks;
    }()
  }, {
    key: 'deserializeLocationLocks',
    value: function () {
      function deserializeLocationLocks(viewConfig) {
        this.locationLocks = {};

        if (viewConfig.locationLocks) {
          var _iteratorNormalCompletion22 = true;
          var _didIteratorError22 = false;
          var _iteratorError22 = undefined;

          try {
            for (var _iterator22 = (0, _getIterator3['default'])((0, _utils.dictKeys)(viewConfig.locationLocks.locksByViewUid)), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) {
              var viewUid = _step22.value;

              if ((0, _typeof3['default'])(viewConfig.locationLocks.locksByViewUid[viewUid]) !== 'object') {
                this.locationLocks[viewUid] = viewConfig.locationLocks.locksDict[viewConfig.locationLocks.locksByViewUid[viewUid]];
              } else {
                // This means we need to link x and y axes separately.

                // x-axis specific locks. The x-axis of this view is linked with an axis in another view.
                if ('x' in viewConfig.locationLocks.locksByViewUid[viewUid]) {
                  var lockInfo = viewConfig.locationLocks.locksDict[viewConfig.locationLocks.locksByViewUid[viewUid].x.lock];
                  this.locationLocksAxisWise.x[viewUid] = {
                    lock: lockInfo,
                    axis: viewConfig.locationLocks.locksByViewUid[viewUid].x.axis // The axis of another view, either 'x' or 'y'
                  };
                }

                // y-axis specific locks. The y-axis of this view is linked with an axis in another view.
                if ('y' in viewConfig.locationLocks.locksByViewUid[viewUid]) {
                  var _lockInfo = viewConfig.locationLocks.locksDict[viewConfig.locationLocks.locksByViewUid[viewUid].y.lock];
                  this.locationLocksAxisWise.y[viewUid] = {
                    lock: _lockInfo,
                    axis: viewConfig.locationLocks.locksByViewUid[viewUid].y.axis // The axis of another view, either 'x' or 'y'
                  };
                }
              }
            }
          } catch (err) {
            _didIteratorError22 = true;
            _iteratorError22 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion22 && _iterator22['return']) {
                _iterator22['return']();
              }
            } finally {
              if (_didIteratorError22) {
                throw _iteratorError22;
              }
            }
          }
        }

        this.validateLocks(this.locationLocks);
      }

      return deserializeLocationLocks;
    }()
  }, {
    key: 'deserializeZoomLocks',
    value: function () {
      function deserializeZoomLocks(viewConfig) {
        this.zoomLocks = {};

        //
        if (viewConfig.zoomLocks) {
          var _iteratorNormalCompletion23 = true;
          var _didIteratorError23 = false;
          var _iteratorError23 = undefined;

          try {
            for (var _iterator23 = (0, _getIterator3['default'])((0, _utils.dictKeys)(viewConfig.zoomLocks.locksByViewUid)), _step23; !(_iteratorNormalCompletion23 = (_step23 = _iterator23.next()).done); _iteratorNormalCompletion23 = true) {
              var viewUid = _step23.value;

              this.zoomLocks[viewUid] = viewConfig.zoomLocks.locksDict[viewConfig.zoomLocks.locksByViewUid[viewUid]];
            }
          } catch (err) {
            _didIteratorError23 = true;
            _iteratorError23 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion23 && _iterator23['return']) {
                _iterator23['return']();
              }
            } finally {
              if (_didIteratorError23) {
                throw _iteratorError23;
              }
            }
          }
        }

        this.validateLocks(this.zoomLocks);
      }

      return deserializeZoomLocks;
    }()
  }, {
    key: 'deserializeValueScaleLocks',
    value: function () {
      function deserializeValueScaleLocks(viewConfig) {
        this.valueScaleLocks = {};

        if (viewConfig.valueScaleLocks) {
          var _iteratorNormalCompletion24 = true;
          var _didIteratorError24 = false;
          var _iteratorError24 = undefined;

          try {
            for (var _iterator24 = (0, _getIterator3['default'])((0, _utils.dictKeys)(viewConfig.valueScaleLocks.locksByViewUid)), _step24; !(_iteratorNormalCompletion24 = (_step24 = _iterator24.next()).done); _iteratorNormalCompletion24 = true) {
              var viewUid = _step24.value;

              this.valueScaleLocks[viewUid] = viewConfig.valueScaleLocks.locksDict[viewConfig.valueScaleLocks.locksByViewUid[viewUid]];
            }
          } catch (err) {
            _didIteratorError24 = true;
            _iteratorError24 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion24 && _iterator24['return']) {
                _iterator24['return']();
              }
            } finally {
              if (_didIteratorError24) {
                throw _iteratorError24;
              }
            }
          }
        }
      }

      return deserializeValueScaleLocks;
    }()
  }, {
    key: 'serializeLocks',
    value: function () {
      function serializeLocks(locks) {
        var locksDict = {};
        var locksByViewUid = {};

        var _iteratorNormalCompletion25 = true;
        var _didIteratorError25 = false;
        var _iteratorError25 = undefined;

        try {
          for (var _iterator25 = (0, _getIterator3['default'])((0, _utils.dictKeys)(locks)), _step25; !(_iteratorNormalCompletion25 = (_step25 = _iterator25.next()).done); _iteratorNormalCompletion25 = true) {
            var viewUid = _step25.value;

            var lockUid = locks[viewUid] && locks[viewUid].uid;

            if (!lockUid) {
              // otherwise, assign this locationLock its own uid
              lockUid = _slugid2['default'].nice();
            }
            locks[viewUid].uid = lockUid;

            // make a note that we've seen this lock
            locksDict[lockUid] = locks[viewUid];

            // note that this view has a reference to this lock
            locksByViewUid[viewUid] = locks[viewUid].uid;
          }

          // remove the uids we just added
          // for (let viewUid of dictKeys(locks)) {
          //   if (locks[viewUid].hasOwnProperty('uid')) {
          //     locks[viewUid].uid = undefined;
          //     delete locks[viewUid].uid;
          //   }
          // }
        } catch (err) {
          _didIteratorError25 = true;
          _iteratorError25 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion25 && _iterator25['return']) {
              _iterator25['return']();
            }
          } finally {
            if (_didIteratorError25) {
              throw _iteratorError25;
            }
          }
        }

        return { locksByViewUid: locksByViewUid, locksDict: locksDict };
      }

      return serializeLocks;
    }()
  }, {
    key: 'getViewsAsJson',
    value: function () {
      function getViewsAsJson() {
        var _this26 = this;

        var newJson = JSON.parse((0, _stringify2['default'])(this.state.viewConfig));
        newJson.views = (0, _values2['default'])(this.state.views).map(function (k) {
          var newView = JSON.parse((0, _stringify2['default'])(k));

          (0, _utils.visitPositionedTracks)(newView.tracks, function (track) {
            if (track.server) {
              var url = (0, _urlParse2['default'])(track.server, {});

              if (!url.hostname.length) {
                // no hostname specified in the track source servers so we'll add
                // the current URL's
                var hostString = window.location.host;
                var protocol = window.location.protocol;

                var newUrl = String(protocol) + '//' + String(hostString) + String(url.pathname);

                track.server = newUrl;
              }
            }

            if ((track.type === 'viewport-projection-center' || track.type === 'viewport-projection-horizontal') && _this26.projectionXDomains[k.uid] && _this26.projectionXDomains[k.uid][track.uid]) {
              // There is no "from" view attached to this projection track,
              // so the `projectionXDomain` field must be used.
              track.projectionXDomain = _this26.projectionXDomains[k.uid][track.uid];
            }
            if ((track.type === 'viewport-projection-center' || track.type === 'viewport-projection-vertical') && _this26.projectionYDomains[k.uid] && _this26.projectionYDomains[k.uid][track.uid]) {
              // There is no "from" view attached to this projection track,
              // so the `projectionYDomain` field must be used.
              track.projectionYDomain = _this26.projectionYDomains[k.uid][track.uid];
            }

            delete track.name;
            delete track.position;
            delete track.header;
            delete track.description;
            delete track.created;
            delete track.project;
            delete track.project_name;
            delete track.serverUidKey;
            delete track.uuid;
            delete track['private'];
            delete track.maxZoom;
            delete track.coordSystem;
            delete track.coordSystem2;
            delete track.datatype;
            delete track.maxWidth;
            delete track.datafile;
            delete track.binsPerDimension;
            delete track.resolutions;
            delete track.aggregationModes;
          });

          newView.uid = k.uid;
          newView.initialXDomain = _this26.xScales[k.uid].domain();
          newView.initialYDomain = _this26.yScales[k.uid].domain();

          delete newView.layout.i;

          return newView;
        });

        newJson.zoomLocks = this.serializeLocks(this.zoomLocks);
        newJson.locationLocks = this.serializeLocks(this.locationLocks);
        newJson.valueScaleLocks = this.serializeLocks(this.valueScaleLocks);

        return newJson;
      }

      return getViewsAsJson;
    }()
  }, {
    key: 'getViewsAsString',
    value: function () {
      function getViewsAsString() {
        return (0, _stringify2['default'])(this.getViewsAsJson(), null, 2);
      }

      return getViewsAsString;
    }()
  }, {
    key: 'handleExportViewAsJSON',
    value: function () {
      function handleExportViewAsJSON() {
        var data = this.getViewsAsString();
        // const file = new Blob([data], { type: 'text/json' });

        (0, _utils.download)('viewconf.json', data);
      }

      return handleExportViewAsJSON;
    }()
  }, {
    key: 'handleExportViewsAsLink',
    value: function () {
      function handleExportViewsAsLink() {
        var _this27 = this;

        var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.state.viewConfig.exportViewUrl;
        var fromApi = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        var parsedUrl = new URL(url, window.location.origin);

        var req = fetch(url, {
          method: 'POST',
          headers: {
            Accept: 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
          },
          body: '{"viewconf":' + String(this.getViewsAsString()) + '}',
          credentials: 'same-origin'
        }).then(function (response) {
          if (!response.ok) {
            throw response;
          }
          return response.json();
        })['catch'](function (err) {
          console.warn('err:', err);
        }).then(function (_json) {
          return {
            id: _json.uid,
            url: String(parsedUrl.origin) + '/l/?d=' + String(_json.uid)
          };
        });

        if (!fromApi) {
          req.then(function (sharedView) {
            _this27.openModal(_react2['default'].createElement(_ExportLinkDialog2['default'], {
              onDone: function () {
                function onDone() {
                  _this27.closeModalBound();
                }

                return onDone;
              }(),
              url: sharedView.url
            }));
          })['catch'](function (e) {
            return console.error('Exporting view config as link failed:', e);
          });
        }

        return req;
      }

      return handleExportViewsAsLink;
    }()

    /*
     * The initial[XY]Domain of a view has changed. Update its definition
     * and rerender.
     */

  }, {
    key: 'handleDataDomainChanged',
    value: function () {
      function handleDataDomainChanged(viewUid, newXDomain, newYDomain) {
        var views = this.state.views;


        views[viewUid].initialXDomain = newXDomain;
        views[viewUid].initialYDomain = newYDomain;

        this.xScales[viewUid] = (0, _d3Scale.scaleLinear)().domain(newXDomain);
        this.yScales[viewUid] = (0, _d3Scale.scaleLinear)().domain(newYDomain);

        if (this.zoomLocks[viewUid]) {
          var lockGroup = this.zoomLocks[viewUid];
          var lockGroupItems = (0, _utils.dictItems)(lockGroup);

          for (var i = 0; i < lockGroupItems.length; i++) {
            var _key = lockGroupItems[i][0];

            if (!(_key in this.locationLocks)) {
              // only zoom to extent if both zoom and location
              // are locked
              continue;
            }

            views[_key].initialXDomain = newXDomain;
            views[_key].initialYDomain = newYDomain;

            this.xScales[_key] = (0, _d3Scale.scaleLinear)().domain(newXDomain);
            this.yScales[_key] = (0, _d3Scale.scaleLinear)().domain(newYDomain);
          }
        }

        this.setState({ views: views });
      }

      return handleDataDomainChanged;
    }()

    /**
     * Check if we can place a view at this position
     */

  }, {
    key: 'viewPositionAvailable',
    value: function () {
      function viewPositionAvailable(pX, pY, w, h) {
        var pEndX = pX + w;
        var pEndY = pY + h;

        if (pX + w > NUM_GRID_COLUMNS) {
          // this view will go over the right edge of our grid
          return false;
        }

        var sortedViews = (0, _utils.dictValues)(this.state.views);

        // check if this position
        for (var j = 0; j < sortedViews.length; j++) {
          var svX = sortedViews[j].layout.x;
          var svY = sortedViews[j].layout.y;

          var svEndX = svX + sortedViews[j].layout.w;
          var svEndY = svY + sortedViews[j].layout.h;

          if (pX < svEndX && pEndX > svX) {
            // x range intersects
            if (pY < svEndY && pEndY > svY) {
              // y range intersects
              return false;
            }
          }
        }

        return true;
      }

      return viewPositionAvailable;
    }()

    /**
     * User clicked on the "Add View" button. We'll duplicate the last
     * view.
     */

  }, {
    key: 'handleAddView',
    value: function () {
      function handleAddView(view) {
        var _this28 = this;

        var views = (0, _utils.dictValues)(this.state.views);
        var lastView = view;

        var potentialPositions = [];

        if (view.layout.w === 12) {
          // this view is full width, we can cut it in half (#259)
          view.layout.w = 6;
        }

        for (var i = 0; i < views.length; i++) {
          var pX = views[i].layout.x + views[i].layout.w;
          var pY = views[i].layout.y;

          // can we place the new view to the right of this view?
          if (this.viewPositionAvailable(pX, pY, view.layout.w, view.layout.h)) {
            potentialPositions.push([pX, pY]);
          }

          pX = views[i].layout.x;
          pY = views[i].layout.y + views[i].layout.h;
          // can we place the new view below this view
          if (this.viewPositionAvailable(pX, pY, view.layout.w, view.layout.h)) {
            potentialPositions.push([pX, pY]);
          }
        }

        potentialPositions.sort(function (a, b) {
          var n = a[1] - b[1];

          if (n === 0) {
            return a[0] - b[0];
          }

          return n;
        });

        var jsonString = (0, _stringify2['default'])(lastView);

        var newView = JSON.parse(jsonString); // ghetto copy

        newView.initialXDomain = this.xScales[newView.uid].domain();
        newView.initialYDomain = this.yScales[newView.uid].domain();

        // place this new view below all the others

        // give it its own unique id
        var _potentialPositions$ = (0, _slicedToArray3['default'])(potentialPositions[0], 2);

        newView.layout.x = _potentialPositions$[0];
        newView.layout.y = _potentialPositions$[1];
        newView.uid = _slugid2['default'].nice();
        newView.layout.i = newView.uid;

        (0, _utils.visitPositionedTracks)(newView.tracks, function (track) {
          _this28.addCallbacks(newView.uid, track);
        });

        this.setState(function (prevState) {
          // eslint-disable-next-line no-shadow
          var views = JSON.parse((0, _stringify2['default'])(prevState.views));
          views[newView.uid] = newView;
          return { views: views };
        });
      }

      return handleAddView;
    }()
  }, {
    key: 'handleSelectedAssemblyChanged',
    value: function () {
      function handleSelectedAssemblyChanged(viewUid, newAssembly, newAutocompleteId, newServer) {
        /*
         * A new assembly was selected in the GenomePositionSearchBox.
         * Update the corresponding
         * view's entry
         *
         * Arguments
         * ---------
         *
         * viewUid: string
         *      The uid of the view this genomepositionsearchbox belongs to
         * newAssembly: string
         *      The new assembly it should display coordinates for
         *
         * Returns
         * -------
         *
         *  Nothing
         */
        var views = this.state.views;


        views[viewUid].genomePositionSearchBox.chromInfoId = newAssembly;
        views[viewUid].genomePositionSearchBox.autocompleteId = newAutocompleteId;
        views[viewUid].genomePositionSearchBox.autocompleteServer = newServer;
      }

      return handleSelectedAssemblyChanged;
    }()
  }, {
    key: 'createGenomePostionSearchBoxEntry',
    value: function () {
      function createGenomePostionSearchBoxEntry(existingGenomePositionSearchBox, suggestedAssembly) {
        /*
         * Create genomePositionSearchBox settings. If existing settings for this view exist,
         * then use those. Otherwise use defaults.
         *
         * Arguments:
         *     existingGenomePositionSearchBox:
         *          {
         *              autocompleteServer: string (e.g. higlass.io/api/v1),
         *              autocompleteId: string (e.g. Xz1f)
         *              chromInfoServer: string (e.g. higlass.io/api/v1)
         *              chromInfoId: string (e.g. hg19)
         *              visible: boolean (e.g. true)
         *           }
         *          If there's already information about which assembly and autocomplete
         *          source to use, it should be in this format.
         *
         *      suggestedAssembly:
         *          Guess which assembly should be displayed based on the tracks visible.
         *          In all meaningful scenarios, all tracks should be of the same assembly
         *          but in case they're not, suggest the most common one
         *
         * Return:
         *      A valid genomePositionSearchBox object
         *
         */
        var newGpsb = existingGenomePositionSearchBox;
        var defaultGpsb = {
          autocompleteServer: _configs.DEFAULT_SERVER,
          // "autocompleteId": "OHJakQICQD6gTD7skx4EWA",
          chromInfoServer: _configs.DEFAULT_SERVER,
          visible: false
        };

        if (!newGpsb) {
          newGpsb = JSON.parse((0, _stringify2['default'])(defaultGpsb));
        }

        if (!newGpsb.autocompleteServer) {
          newGpsb.autocompleteServer = defaultGpsb.autocompleteServer;
        }

        /*
         * If we don't have an autocompleteId, we'll try to look it up in
         * the autocomplete server
         */
        /*
            if (!newGpsb.autocompleteId)
                newGpsb.autocompleteId = defaultGpsb.autocompleteId;
            */

        if (!newGpsb.chromInfoId) {
          newGpsb.chromInfoId = suggestedAssembly;
        }

        if (!newGpsb.chromInfoServer) {
          newGpsb.chromInfoServer = defaultGpsb.chromInfoServer;
        }

        if (!newGpsb.visible) {
          newGpsb.visible = false;
        }

        return newGpsb;
      }

      return createGenomePostionSearchBoxEntry;
    }()
  }, {
    key: 'handleTogglePositionSearchBox',
    value: function () {
      function handleTogglePositionSearchBox(viewUid) {
        /*
         * Show or hide the genome position search box for a given view
         */

        var view = this.state.views[viewUid];
        view.genomePositionSearchBoxVisible = !view.genomePositionSearchBoxVisible;

        // count the number of tracks that are part of some assembly
        var assemblyCounts = {};

        (0, _utils.visitPositionedTracks)(view.tracks, function (track) {
          if (track.coordSystem) {
            if (!assemblyCounts[track.coordSystem]) {
              assemblyCounts[track.coordSystem] = 0;
            }

            assemblyCounts[track.coordSystem] += 1;
          }
        });

        var sortedAssemblyCounts = (0, _utils.dictItems)(assemblyCounts).sort(function (a, b) {
          return b[1] - a[1];
        });
        var selectedAssembly = 'hg19'; // always the default if nothing is otherwise selected

        if (sortedAssemblyCounts.length) {
          selectedAssembly = sortedAssemblyCounts[0][0];
        }

        view.genomePositionSearchBox = this.createGenomePostionSearchBoxEntry(view.genomePositionSearchBox, selectedAssembly);
        view.genomePositionSearchBox.visible = !view.genomePositionSearchBox.visible;

        this.refreshView();

        this.setState({
          configMenuUid: null
        });
      }

      return handleTogglePositionSearchBox;
    }()
  }, {
    key: 'handleTrackOptionsChanged',
    value: function () {
      function handleTrackOptionsChanged(viewUid, trackUid, newOptions) {
        // some track's options changed...
        // redraw the track  and store the changes in the config file
        var view = this.state.views[viewUid];
        var track = (0, _utils.getTrackByUid)(view.tracks, trackUid);

        if (!track) return;

        track.options = (0, _assign2['default'])(track.options, newOptions);

        if (this.mounted) {
          this.setState(function (prevState) {
            return {
              views: prevState.views
            };
          });
          this.adjustSplitHeatmapTrackOptions(track, newOptions, view.tracks, viewUid);
        }
      }

      return handleTrackOptionsChanged;
    }()

    /**
     * For convenience we adjust some options of split heatmap tracks when they are newly added.
     * This function has no effect when we get split heatmap tracks that are already correctly configured
     * (i.e. correctly set "lower-extend"/"upper-extend" options)
     * @param   {object}  track  Track whose options have changed
     * @param   {object}  options  New track options
     * @param   {list}  allTracks  All tracks
     * @param   {string}  viewUid  Related view UID
     */

  }, {
    key: 'adjustSplitHeatmapTrackOptions',
    value: function () {
      function adjustSplitHeatmapTrackOptions(track, options, allTracks, viewUid) {
        var _this29 = this;

        if (track.type === 'heatmap') {
          if (options.extent === 'upper-right' && allTracks.center[0].type === 'combined' && allTracks.center[0].contents.length > 1) {
            allTracks.center[0].contents.some(function (otherTrack) {
              if (otherTrack.type === 'heatmap' && otherTrack.uid !== track.uid && otherTrack.options.extent !== 'lower-left') {
                // Automatically change the extent of the other track to
                // `lower-left``
                var otherNewOptions = (0, _assign2['default'])({}, otherTrack.options, {
                  extent: 'lower-left',
                  labelPosition: 'bottomLeft',
                  colorbarPosition: 'bottomLeft'
                });

                // Automatically set positions of label and colorbar of the current track
                // to the opposite corner. We don't want overlapping labels.
                var originalNewOptions = (0, _assign2['default'])({}, options, {
                  labelPosition: 'topRight',
                  colorbarPosition: 'topRight'
                });

                _this29.handleTrackOptionsChanged(viewUid, otherTrack.uid, otherNewOptions);

                _this29.handleTrackOptionsChanged(viewUid, track.uid, originalNewOptions);
                return true;
              }
              return false;
            });
          }
          if (options.extent === 'lower-left') {
            if (options.extent === 'lower-left' && allTracks.center[0].type === 'combined' && allTracks.center[0].contents.length > 1) {
              allTracks.center[0].contents.some(function (otherTrack) {
                if (otherTrack.type === 'heatmap' && otherTrack.uid !== track.uid && otherTrack.options.extent !== 'upper-right') {
                  // Automatically change the extent of the other track to
                  // `upper-right``
                  var otherNewOptions = (0, _assign2['default'])({}, otherTrack.options, {
                    extent: 'upper-right',
                    labelPosition: 'topRight',
                    colorbarPosition: 'topRight'
                  });

                  // Automatically set positions of label and colorbar of the current track
                  // to the opposite corner. We don't want overlapping labels.
                  var originalNewOptions = (0, _assign2['default'])({}, options, {
                    labelPosition: 'bottomLeft',
                    colorbarPosition: 'bottomLeft'
                  });

                  _this29.handleTrackOptionsChanged(viewUid, otherTrack.uid, otherNewOptions);

                  _this29.handleTrackOptionsChanged(viewUid, track.uid, originalNewOptions);
                  return true;
                }
                return false;
              });
            }
          }
        }
      }

      return adjustSplitHeatmapTrackOptions;
    }()
  }, {
    key: 'handleViewOptionsChanged',
    value: function () {
      function handleViewOptionsChanged(viewUid, newOptions) {
        var view = this.state.views[viewUid];

        if (!view) {
          return;
        }

        view.options = (0, _assign2['default'])(view.options || {}, newOptions);

        if (this.mounted) {
          this.setState(function (prevState) {
            return {
              views: prevState.views
            };
          });
        }
      }

      return handleViewOptionsChanged;
    }()

    /**
     * Determine whether a track is valid and can be displayed.
     *
     * Tracks can be invalid due to inconsistent input such as
     * referral to views that don't exist
     *
     * @param track (object): A track definition
     * @param viewUidsPresent (Set): The view uids which are available
     */

  }, {
    key: 'isTrackValid',
    value: function () {
      function isTrackValid(track, viewUidsPresent) {
        if (track.type === 'viewport-projection-center') {
          if (!viewUidsPresent.has(track.fromViewUid)) {
            return false;
          }
        }

        return true;
      }

      return isTrackValid;
    }()

    /**
     * Remove tracks which can no longer be shown (possibly because the views they
     * refer to no longer exist
     */

  }, {
    key: 'removeInvalidTracks',
    value: function () {
      function removeInvalidTracks(viewsByUid) {
        var _this30 = this;

        var viewUidsSet = new _set2['default']((0, _utils.dictKeys)(viewsByUid));

        var _iteratorNormalCompletion26 = true;
        var _didIteratorError26 = false;
        var _iteratorError26 = undefined;

        try {
          for (var _iterator26 = (0, _getIterator3['default'])((0, _utils.dictValues)(viewsByUid)), _step26; !(_iteratorNormalCompletion26 = (_step26 = _iterator26.next()).done); _iteratorNormalCompletion26 = true) {
            var v = _step26.value;
            var _arr = ['left', 'top', 'center', 'right', 'bottom'];

            for (var _i4 = 0; _i4 < _arr.length; _i4++) {
              var trackOrientation = _arr[_i4];
              if (v.tracks && v.tracks.hasOwnProperty(trackOrientation)) {
                // filter out invalid tracks
                v.tracks[trackOrientation] = v.tracks[trackOrientation].filter(function (t) {
                  return _this30.isTrackValid(t, viewUidsSet);
                });

                // filter out invalid tracks in combined tracks
                v.tracks[trackOrientation].forEach(function (t) {
                  if (t.type === 'combined') {
                    t.contents = t.contents.filter(function (c) {
                      return _this30.isTrackValid(c, viewUidsSet);
                    });
                  }
                });
              }
            }
          }
        } catch (err) {
          _didIteratorError26 = true;
          _iteratorError26 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion26 && _iterator26['return']) {
              _iterator26['return']();
            }
          } finally {
            if (_didIteratorError26) {
              throw _iteratorError26;
            }
          }
        }

        return viewsByUid;
      }

      return removeInvalidTracks;
    }()
  }, {
    key: 'processViewConfig',
    value: function () {
      function processViewConfig(viewConfig) {
        var _this31 = this;

        var views = viewConfig.views;

        var viewsByUid = {};

        if (!viewConfig.views || viewConfig.views.length === 0) {
          console.warn('No views provided in viewConfig');
          views = [{
            editable: true,
            tracks: {}
          }];
        }

        views.forEach(function (v) {
          if (v.tracks) {
            (0, _utils.fillInMinWidths)(v.tracks);
          }

          // if a view doesn't have a uid, assign it one
          if (!v.uid) {
            v.uid = _slugid2['default'].nice();
          }

          viewsByUid[v.uid] = v;

          if (_this31.zoomToDataExtentOnInit.has(v.uid)) {
            _this31.zoomToDataExtentOnInit['delete'](v.uid);
          }

          if (!v.initialXDomain) {
            v.initialXDomain = [0, 100];

            _this31.zoomToDataExtentOnInit.add(v.uid);
          } else {
            v.initialXDomain[0] = +v.initialXDomain[0];
            v.initialXDomain[1] = +v.initialXDomain[1];
          }

          // if there's no y domain specified just use the x domain instead
          // effectively centers the view on the diagonal
          if (!v.initialYDomain) {
            v.initialYDomain = [v.initialXDomain[0], v.initialXDomain[1]];
          } else {
            v.initialXDomain[0] = +v.initialXDomain[0];
            v.initialXDomain[1] = +v.initialXDomain[1];
          }

          if (!_this31.xScales[v.uid]) {
            _this31.xScales[v.uid] = (0, _d3Scale.scaleLinear)().domain(v.initialXDomain);
          }
          if (!_this31.yScales[v.uid]) {
            _this31.yScales[v.uid] = (0, _d3Scale.scaleLinear)().domain(v.initialYDomain);
          }

          (0, _utils.visitPositionedTracks)(v.tracks, function (track) {
            if (!track.uid) track.uid = _slugid2['default'].nice();

            _this31.addCallbacks(v.uid, track);
            _this31.addDefaultTrackOptions(track);

            if (track.contents) {
              // add default options to combined tracks
              var _iteratorNormalCompletion27 = true;
              var _didIteratorError27 = false;
              var _iteratorError27 = undefined;

              try {
                for (var _iterator27 = (0, _getIterator3['default'])(track.contents), _step27; !(_iteratorNormalCompletion27 = (_step27 = _iterator27.next()).done); _iteratorNormalCompletion27 = true) {
                  var ct = _step27.value;
                  _this31.addDefaultTrackOptions(ct);
                }
              } catch (err) {
                _didIteratorError27 = true;
                _iteratorError27 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion27 && _iterator27['return']) {
                    _iterator27['return']();
                  }
                } finally {
                  if (_didIteratorError27) {
                    throw _iteratorError27;
                  }
                }
              }
            }
          });

          // make sure that the layout for this view refers to this view
          if (v.layout) {
            v.layout.i = v.uid;
          } else {
            v.layout = _this31.generateViewLayout(v);
          }
        });

        this.deserializeZoomLocks(viewConfig);
        this.deserializeLocationLocks(viewConfig);
        this.deserializeValueScaleLocks(viewConfig);

        viewsByUid = this.removeInvalidTracks(viewsByUid);

        return viewsByUid;
      }

      return processViewConfig;
    }()
  }, {
    key: 'handleWindowFocused',
    value: function () {
      function handleWindowFocused() {}
      /*
       * The window housing this view gained focus. That means the bounding boxes
       * may have changed so we need to redraw everything.
       *
       */


      /**
       * Handle range selection events.
       *
       * @description
       * Store active range selectio and forward the range selection event to the
       * API.
       *
       * @param  {Array}  range  Double array of the selected range.
       */


      return handleWindowFocused;
    }()
  }, {
    key: 'rangeSelectionHandler',
    value: function () {
      function rangeSelectionHandler(range) {
        this.rangeSelection = range;
        this.apiPublish('rangeSelection', range);
      }

      return rangeSelectionHandler;
    }()
  }, {
    key: 'offViewChange',
    value: function () {
      function offViewChange(listenerId) {
        this.viewChangeListener.splice(listenerId, 1);
      }

      return offViewChange;
    }()
  }, {
    key: 'onViewChange',
    value: function () {
      function onViewChange(callback) {
        return this.viewChangeListener.push(callback) - 1;
      }

      return onViewChange;
    }()
  }, {
    key: 'triggerViewChange',
    value: function () {
      function triggerViewChange() {
        var _this32 = this;

        this.viewChangeListener.forEach(function (callback) {
          return callback(_this32.getViewsAsString());
        });
      }

      return triggerViewChange;
    }()
  }, {
    key: 'getGenomeLocation',
    value: function () {
      function getGenomeLocation(viewId) {
        var _this33 = this;

        return _services.chromInfo.get(this.state.views[viewId].chromInfoPath).then(function (chrInfo) {
          return (0, _utils.scalesToGenomeLoci)(_this33.xScales[viewId], _this33.yScales[viewId], chrInfo);
        });
      }

      return getGenomeLocation;
    }()
  }, {
    key: 'offLocationChange',
    value: function () {
      function offLocationChange(viewId, listenerId) {
        this.removeScalesChangedListener(viewId, listenerId);
      }

      return offLocationChange;
    }()
  }, {
    key: 'zoomTo',
    value: function () {
      function zoomTo(viewUid, start1Abs, end1Abs, start2Abs, end2Abs, animateTime) {
        if (!(viewUid in this.setCenters)) {
          throw Error('Invalid viewUid. Current uuids: ' + String((0, _keys2['default'])(this.setCenters).join(',')));
        }

        if ((0, _isNan2['default'])(+start1Abs) || (0, _isNan2['default'])(+end1Abs)) {
          var coords = [start1Abs, end1Abs].join(', ');
          console.warn(['Invalid coordinates (' + String(coords) + '). All coordinates need to be numbers\n        and should represent absolute coordinates (not chromosome\n        coordinates).'].join(' '));
          return;
        }

        if ((0, _isNan2['default'])(+start2Abs) || (0, _isNan2['default'])(+end2Abs) || start2Abs === null || end2Abs === null) {
          start2Abs = start1Abs;
          end2Abs = end1Abs;
        }

        var _scalesCenterAndK27 = (0, _utils.scalesCenterAndK)(this.xScales[viewUid].copy().domain([start1Abs, end1Abs]), this.yScales[viewUid].copy().domain([start2Abs, end2Abs])),
            _scalesCenterAndK28 = (0, _slicedToArray3['default'])(_scalesCenterAndK27, 3),
            centerX = _scalesCenterAndK28[0],
            centerY = _scalesCenterAndK28[1],
            k = _scalesCenterAndK28[2];

        this.setCenters[viewUid](centerX, centerY, k, false, animateTime);
      }

      return zoomTo;
    }()
  }, {
    key: 'zoomToGene',
    value: function () {
      function zoomToGene(viewUid, geneName, padding, animateTime) {
        var _this34 = this;

        if (!(viewUid in this.setCenters)) {
          throw Error('Invalid viewUid. Current uuids: ' + String((0, _keys2['default'])(this.setCenters).join(',')));
        }

        if (!this.state.views[viewUid].genomePositionSearchBox || !this.state.views[viewUid].genomePositionSearchBox.autocompleteServer || !this.state.views[viewUid].genomePositionSearchBox.autocompleteId || !this.state.views[viewUid].chromInfoPath) {
          console.warn('Please set chromInfoPath, autocompleteServer, and autocompleteId to use the zoomToGene API');
          return;
        }

        this.suggestGene(viewUid, geneName, function (suggestions) {
          if (suggestions) {
            // extract the position of exact match
            var exactMatch = suggestions.find(function (d) {
              return d.geneName.toLowerCase() === geneName.toLowerCase();
            });

            if (exactMatch) {
              var chr = exactMatch.chr,
                  txStart = exactMatch.txStart,
                  txEnd = exactMatch.txEnd;

              // extract absolute positions

              (0, _ChromosomeInfo2['default'])(_this34.state.views[viewUid].chromInfoPath, function (loadedChromInfo) {
                // using the absolution positions, zoom to the position near a gene
                var startAbs = loadedChromInfo.chrToAbs([chr, txStart]) - padding;
                var endAbs = loadedChromInfo.chrToAbs([chr, txEnd]) + padding;

                var _scalesCenterAndK29 = (0, _utils.scalesCenterAndK)(_this34.xScales[viewUid].copy().domain([startAbs, endAbs]), _this34.yScales[viewUid].copy().domain([startAbs, endAbs])),
                    _scalesCenterAndK30 = (0, _slicedToArray3['default'])(_scalesCenterAndK29, 3),
                    centerX = _scalesCenterAndK30[0],
                    centerY = _scalesCenterAndK30[1],
                    k = _scalesCenterAndK30[2];

                _this34.setCenters[viewUid](centerX, centerY, k, false, animateTime);
              }, _this34.pubSub);
            } else {
              console.warn('Couldn\'t find the gene symbol: ' + String(geneName));
            }
          }
        });
      }

      return zoomToGene;
    }()
  }, {
    key: 'suggestGene',
    value: function () {
      function suggestGene(viewUid, keyword, callback) {
        if (!(viewUid in this.setCenters)) {
          throw Error('Invalid viewUid. Current uuids: ' + String((0, _keys2['default'])(this.setCenters).join(',')));
        }

        if (!this.state.views[viewUid].genomePositionSearchBox || !this.state.views[viewUid].genomePositionSearchBox.autocompleteServer || !this.state.views[viewUid].genomePositionSearchBox.autocompleteId) {
          console.warn('Please set autocompleteServer and autocompleteId to use the suggestGene API');
          return;
        }

        var autocompleteServer = this.state.views[viewUid].genomePositionSearchBox.autocompleteServer;
        var autocompleteId = this.state.views[viewUid].genomePositionSearchBox.autocompleteId;

        var url = String(autocompleteServer) + '/suggest/?d=' + String(autocompleteId) + '&ac=' + String(keyword.toLowerCase());

        _services.tileProxy.json(url, _utils.toVoid, this.pubSub).then(function (suggestions) {
          callback(suggestions);
        })['catch'](function (error) {
          return console.error(error);
        });
      }

      return suggestGene;
    }()
  }, {
    key: 'onLocationChange',
    value: function () {
      function onLocationChange(viewId, callback, callbackId) {
        var viewsIds = (0, _keys2['default'])(this.state.views);

        if (!viewsIds.length) {
          // HiGlass was probably initialized with an URL instead of a viewconfig
          // and that remote viewConfig is not yet loaded.
          this.unsetOnLocationChange.push({
            viewId: viewId,
            callback: callback,
            callbackId: callbackId
          });
          return null;
        }

        viewId = typeof viewId === 'undefined' && viewsIds.length === 1 ? viewsIds[0] : viewId;

        if (typeof viewId === 'undefined' || viewsIds.indexOf(viewId) === -1) {
          console.error('onLocationChange either missing a viewId or passed an invalid viewId: ', viewId);
          return null;
        }

        var view = this.state.views[viewId];

        // Convert scales into genomic locations
        var middleLayerListener = function () {
          function middleLayerListener(xScale, yScale) {
            callback({
              xDomain: xScale.domain(),
              yDomain: yScale.domain(),
              xRange: xScale.range(),
              yRange: yScale.range()
            });
          }

          return middleLayerListener;
        }();

        var newListenerId = 1;
        if (this.scalesChangedListeners[view.uid]) {
          newListenerId = (0, _keys2['default'])(this.scalesChangedListeners[view.uid]).filter(function (listenerId) {
            return listenerId.indexOf(_configs.LOCATION_LISTENER_PREFIX) === 0;
          }).map(function (listenerId) {
            return parseInt(listenerId.slice(_configs.LOCATION_LISTENER_PREFIX.length + 1), 10);
          }).reduce(function (max, value) {
            return Math.max(max, value);
          }, 0) + 1;
        }

        this.addScalesChangedListener(view.uid, String(_configs.LOCATION_LISTENER_PREFIX) + '.' + String(newListenerId), middleLayerListener);

        if (callbackId) {
          callbackId(String(_configs.LOCATION_LISTENER_PREFIX) + '.' + String(newListenerId));
        }

        return newListenerId;
      }

      return onLocationChange;
    }()

    /**
     * List all the views that are at the given position view position
     */

  }, {
    key: 'getTiledPlotAtPosition',
    value: function () {
      function getTiledPlotAtPosition(x, y) {
        var foundTiledPlot = void 0;

        var views = (0, _utils.dictValues)(this.state.views);

        for (var i = 0; i < views.length; i++) {
          var tiledPlot = this.tiledPlots[views[i].uid];

          var area = this.tiledAreasDivs[views[i].uid].getBoundingClientRect();

          var top = area.top,
              left = area.left;

          var bottom = top + area.height;
          var right = left + area.width;

          var withinX = x >= left && x <= right;
          var withinY = y >= top && y <= bottom;

          if (withinX && withinY) {
            foundTiledPlot = tiledPlot;
            break;
          }
        }

        return foundTiledPlot;
      }

      return getTiledPlotAtPosition;
    }()

    /**
     * Handle mousemove events by republishing the event using pubSub.
     *
     * @param {object}  e  Event object.
     */

  }, {
    key: 'mouseMoveHandler',
    value: function () {
      function mouseMoveHandler(e) {
        if (!this.topDiv || this.state.modal) return;

        var absX = e.clientX;
        var absY = e.clientY;
        var relPos = (0, _d3Selection.clientPoint)(this.topDiv, e);
        // We need to add the scrollTop
        relPos[1] += this.scrollTop;
        var hoveredTiledPlot = this.getTiledPlotAtPosition(absX, absY);

        var hoveredTracks = hoveredTiledPlot ? hoveredTiledPlot.listTracksAtPosition(relPos[0], relPos[1], true).map(function (track) {
          return track.originalTrack || track;
        }) : [];

        var hoveredTrack = hoveredTracks.find(function (track) {
          return !track.isAugmentationTrack;
        });

        var relTrackPos = hoveredTrack ? [relPos[0] - hoveredTrack.position[0], relPos[1] - hoveredTrack.position[1]] : relPos;

        var dataX = -1;
        var dataY = -1;

        if (hoveredTrack) {
          dataX = !hoveredTrack.flipText ? hoveredTrack._xScale.invert(relTrackPos[0]) // dataX
          : hoveredTrack._xScale.invert(relTrackPos[1]); // dataY

          dataY = hoveredTrack.is2d ? hoveredTrack._yScale.invert(relTrackPos[1]) : dataX;
        }

        var evt = {
          x: relPos[0],
          y: relPos[1],
          relTrackX: hoveredTrack && hoveredTrack.flipText ? relTrackPos[1] : relTrackPos[0],
          relTrackY: hoveredTrack && hoveredTrack.flipText ? relTrackPos[0] : relTrackPos[1],
          dataX: dataX,
          dataY: dataY,
          // See below why we need these derived boolean values
          isFrom2dTrack: !!(hoveredTrack && hoveredTrack.is2d),
          isFromVerticalTrack: !!(hoveredTrack && hoveredTrack.flipText),
          track: hoveredTrack,
          origEvt: e,
          sourceUid: this.uid,
          hoveredTracks: hoveredTracks,
          // See below why we need these derived boolean values
          noHoveredTracks: hoveredTracks.length === 0
        };

        this.pubSub.publish('app.mouseMove', evt);

        if (this.isBroadcastMousePositionGlobally) {
          // In order to broadcast information globally with the
          // Broadcast Channel API we have to remove properties that reference local
          // objects as those can't be cloned and broadcasted to another context
          // (i.e., another browser window or tab).
          // This is also the reason why created some derived boolean variables,
          // like `noHoveredTracks`.
          var eventDataOnly = (0, _extends3['default'])({}, evt);
          eventDataOnly.origEvt = undefined;
          eventDataOnly.track = undefined;
          eventDataOnly.hoveredTracks = undefined;
          delete eventDataOnly.origEvt;
          delete eventDataOnly.track;
          delete eventDataOnly.hoveredTracks;
          _pubSubEs.globalPubSub.publish('higlass.mouseMove', eventDataOnly);
        }

        this.apiPublish('cursorLocation', {
          absX: absX,
          absY: absY,
          relX: evt.x,
          relY: evt.y,
          relTrackX: evt.relTrackX,
          relTrackY: evt.relTrackY,
          dataX: evt.dataX,
          dataY: evt.dataY,
          isFrom2dTrack: evt.isFrom2dTrack,
          isFromVerticalTrack: evt.isFromVerticalTrack
        });

        this.showHoverMenu(evt);
      }

      return mouseMoveHandler;
    }()
  }, {
    key: 'getMinMaxValue',
    value: function () {
      function getMinMaxValue(viewId, trackId, ignoreOffScreenValues, ignoreFixedScale) {
        var track = (0, _utils.getTrackObjById)(this.tiledPlots, viewId, trackId);

        if (!track) {
          console.warn('Track with ID: ' + String(trackId) + ' not found!');
          return undefined;
        }

        if (!track.minVisibleValueInTiles || !track.maxVisibleValueInTiles) {
          console.warn('Track ' + String(trackId) + ' doesn\'t support the retrieval of min or max values.');
          return undefined;
        }

        if (ignoreOffScreenValues && track.getAggregatedVisibleValue) {
          return [track.getAggregatedVisibleValue('min'), track.getAggregatedVisibleValue('max')];
        }

        return [track.minVisibleValueInTiles(ignoreFixedScale), track.maxVisibleValueInTiles(ignoreFixedScale)];
      }

      return getMinMaxValue;
    }()

    /**
     * Show a menu displaying some information about the track under it
     */

  }, {
    key: 'showHoverMenu',
    value: function () {
      function showHoverMenu(evt) {
        // each track should have a function that returns an HTML representation
        // of the data at a give position
        var mouseOverHtml = evt.track && evt.track.getMouseOverHtml ? evt.track.getMouseOverHtml(evt.relTrackX, evt.relTrackY) : '';

        if (evt.track !== this.prevMouseHoverTrack) {
          if (this.prevMouseHoverTrack && this.prevMouseHoverTrack.stopHover) {
            this.prevMouseHoverTrack.stopHover();
          }
        }

        this.prevMouseHoverTrack = evt.track;

        if (this.zooming) return;

        var data = mouseOverHtml && mouseOverHtml.length ? [1] : [];

        // try to select the mouseover div
        var mouseOverDiv = (0, _d3Selection.select)('body').selectAll('.track-mouseover-menu').data(data);

        mouseOverDiv.exit().remove();

        mouseOverDiv.enter().append('div').classed('track-mouseover-menu', true).classed(_HiGlassModule2['default']['track-mouseover-menu'], true);

        mouseOverDiv = (0, _d3Selection.select)('body').selectAll('.track-mouseover-menu');
        var mousePos = (0, _d3Selection.clientPoint)((0, _d3Selection.select)('body').node(), evt.origEvt);
        var normalizedMousePos = [mousePos[0] - window.scrollX, mousePos[1] - window.scrollY];

        /*
        mouseOverDiv.selectAll('.mouseover-marker')
          .data([1])
          .enter()
          .append('div')
          .classed('.mouseover-marker', true)
        */

        mouseOverDiv.style('left', String(normalizedMousePos[0]) + 'px').style('top', String(normalizedMousePos[1]) + 'px');

        // probably not over a track so there's no mouseover rectangle
        if (!mouseOverDiv.node()) return;

        var bbox = mouseOverDiv.node().getBoundingClientRect();

        if (bbox.x + bbox.width > window.innerWidth) {
          // the overlay box is spilling outside of the track so switch
          // to showing it on the left
          mouseOverDiv.style('left', normalizedMousePos[0] - bbox.width + 'px');
        }

        if (bbox.y + bbox.height > window.innerHeight) {
          // the overlay box is spilling outside of the track so switch
          // to showing it on the left
          mouseOverDiv.style('top', normalizedMousePos[1] - bbox.height + 'px');
        }

        mouseOverDiv.html(mouseOverHtml);
      }

      return showHoverMenu;
    }()

    /**
     * Hide the hover menu when e.g. the user starts zooming
     */

  }, {
    key: 'hideHoverMenu',
    value: function () {
      function hideHoverMenu() {
        (0, _d3Selection.select)('body').selectAll('.track-mouseover-menu').remove();
      }

      return hideHoverMenu;
    }()

    /**
     * Handle internally broadcasted click events
     */

  }, {
    key: 'appClickHandler',
    value: function () {
      function appClickHandler(data) {
        this.apiPublish('click', data);
      }

      return appClickHandler;
    }()

    /**
     * Handle mousemove and zoom events.
     */

  }, {
    key: 'mouseMoveZoomHandler',
    value: function () {
      function mouseMoveZoomHandler(data) {
        this.apiPublish('mouseMoveZoom', data);
      }

      return mouseMoveZoomHandler;
    }()

    /**
     * Handle gene search events.
     */

  }, {
    key: 'geneSearchHandler',
    value: function () {
      function geneSearchHandler(data) {
        this.apiPublish('geneSearch', data);
      }

      return geneSearchHandler;
    }()

    /**
     * Handle mousedown events/
     */

  }, {
    key: 'mouseDownHandler',
    value: function () {
      function mouseDownHandler(evt) {}

      return mouseDownHandler;
    }()
  }, {
    key: 'onScrollHandler',
    value: function () {
      function onScrollHandler() {
        if (this.props.options.sizeMode !== SIZE_MODE_SCROLL) return;
        this.scrollTop = this.scrollContainer.scrollTop;
        this.pixiStage.y = -this.scrollTop;
        this.pubSub.publish('app.scroll', this.scrollTop);
        this.animate();
      }

      return onScrollHandler;
    }()
  }, {
    key: 'setTrackValueScaleLimits',
    value: function () {
      function setTrackValueScaleLimits(viewId, trackId, minValue, maxValue) {
        var track = (0, _utils.getTrackObjById)(this.tiledPlots, viewId, trackId);

        if (!track) {
          console.warn('Could\'t find track: ' + String(trackId));
          return;
        }

        if (track.setFixedValueScaleMin && track.setFixedValueScaleMax) {
          track.setFixedValueScaleMin(minValue);
          track.setFixedValueScaleMax(maxValue);

          track.rerender(track.options, true);
          track.animate();
        } else {
          console.warn("Track doesn't support fixed value scales.");
        }
      }

      return setTrackValueScaleLimits;
    }()
  }, {
    key: 'setChromInfo',
    value: function () {
      function setChromInfo(chromInfoPath, callback) {
        var _this35 = this;

        (0, _ChromosomeInfo2['default'])(chromInfoPath, function (newChromInfo) {
          _this35.chromInfo = newChromInfo;
          callback();
        }, this.pubSub);
      }

      return setChromInfo;
    }()
  }, {
    key: 'onMouseLeaveHandler',
    value: function () {
      function onMouseLeaveHandler() {
        this.pubSub.publish('app.mouseLeave');
        this.hideHoverMenu();
        this.animate();
      }

      return onMouseLeaveHandler;
    }()
  }, {
    key: 'onBlurHandler',
    value: function () {
      function onBlurHandler() {
        this.animate();
      }

      return onBlurHandler;
    }()
  }, {
    key: 'isZoomFixed',
    value: function () {
      function isZoomFixed(view) {
        return this.props.zoomFixed || this.props.options.zoomFixed || this.state.viewConfig.zoomFixed || this.props.options.sizeMode === SIZE_MODE_SCROLL || view && view.zoomFixed;
      }

      return isZoomFixed;
    }()

    /**
     * Handle trackDimensionsModified events
     * settings.viewId = id of the view
     * settings.trackId = id of the track
     * settings.height = new height of the track or undefined if current height should remain
     * settings.width = new width of the track or undefined if current width should remain
     */

  }, {
    key: 'trackDimensionsModifiedHandler',
    value: function () {
      function trackDimensionsModifiedHandler(settings) {
        var view = this.state.views[settings.viewId];

        if (!view) return;

        var track = (0, _utils.getTrackByUid)(view.tracks, settings.trackId);

        if (!track) return;

        if (settings.height !== undefined) {
          track.height = settings.height;
        }

        if (settings.width !== undefined) {
          track.width = settings.width;
        }
        this.adjustLayoutToTrackSizes(view);

        this.setState(function (prevState) {
          return {
            views: prevState.views
          };
        });
      }

      return trackDimensionsModifiedHandler;
    }()
  }, {
    key: 'wheelHandler',
    value: function () {
      function wheelHandler(evt) {
        if (this.state.modal || this.props.options.sizeMode === SIZE_MODE_SCROLL) return;

        // The event forwarder wasn't written for React's SyntheticEvent
        var nativeEvent = evt.nativeEvent || evt;

        var isTargetCanvas = evt.target === this.canvasElement;

        if (!(0, _utils.hasParent)(nativeEvent.target, this.topDiv)) {
          // ignore events that don't come from within the
          // HiGlass container
          return;
        }

        if (this.isZoomFixed()) {
          // ignore events when in zoom fixed mode
          return;
        }

        var absX = nativeEvent.clientX;
        var absY = nativeEvent.clientY;
        var hoveredTiledPlot = this.getTiledPlotAtPosition(absX, absY);

        // Find the tracks at the wheel position
        if (this.apiStack.wheel && this.apiStack.wheel.length > 0) {
          var relPos = (0, _d3Selection.clientPoint)(this.topDiv, nativeEvent);
          // We need to add the scrollTop
          relPos[1] += this.scrollTop;
          var hoveredTracks = hoveredTiledPlot ? hoveredTiledPlot.listTracksAtPosition(relPos[0], relPos[1], true).map(function (track) {
            return track.originalTrack || track;
          }) : [];
          var hoveredTrack = hoveredTracks.find(function (track) {
            return !track.isAugmentationTrack;
          });

          var relTrackPos = hoveredTrack ? [relPos[0] - hoveredTrack.position[0], relPos[1] - hoveredTrack.position[1]] : relPos;

          var evtToPublish = {
            x: relPos[0],
            y: relPos[1],
            relTrackX: hoveredTrack && hoveredTrack.flipText ? relTrackPos[1] : relTrackPos[0],
            relTrackY: hoveredTrack && hoveredTrack.flipText ? relTrackPos[0] : relTrackPos[1],
            track: hoveredTrack,
            origEvt: nativeEvent,
            sourceUid: this.uid,
            hoveredTracks: hoveredTracks,
            noHoveredTracks: hoveredTracks.length === 0
          };

          this.apiPublish('wheel', evtToPublish);
        }

        if (nativeEvent.forwarded || isTargetCanvas) {
          evt.stopPropagation();
          evt.preventDefault();

          return;
        }

        evt.preventDefault();

        // forward the wheel event back to the TrackRenderer that it should go to
        // this is so that we can zoom when there's a viewport projection present
        if (hoveredTiledPlot) {
          var trackRenderer = hoveredTiledPlot.trackRenderer;

          nativeEvent.forwarded = true;

          if (nativeEvent) {
            (0, _utils.forwardEvent)(nativeEvent, trackRenderer.eventTracker);

            nativeEvent.preventDefault();
          }
        }
      }

      return wheelHandler;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this36 = this;

        this.tiledAreasDivs = {};
        this.tiledAreas = _react2['default'].createElement('div', { className: 'HiGlass-module_tiled-area-22H1L' });

        // The component needs to be mounted in order for the initial view to have
        // the right width
        if (this.mounted) {
          this.tiledAreas = (0, _utils.dictValues)(this.state.views).map(function (view) {
            // only show the add track menu for the tiled plot it was selected for
            var addTrackPositionMenuPosition = view.uid === _this36.state.addTrackPositionMenuUid ? _this36.state.addTrackPositionMenuPosition : null;

            var overlay = null;
            if (_this36.state.chooseViewHandler) {
              var background = 'transparent';

              if (_this36.state.mouseOverOverlayUid === view.uid) background = 'green';

              overlay = _react2['default'].createElement('div', {
                className: 'tiled-plot-overlay',
                onClick: function () {
                  function onClick() {
                    return _this36.state.chooseViewHandler(view.uid);
                  }

                  return onClick;
                }(),
                onMouseEnter: function () {
                  function onMouseEnter() {
                    return _this36.handleOverlayMouseEnter(view.uid);
                  }

                  return onMouseEnter;
                }(),
                onMouseLeave: function () {
                  function onMouseLeave() {
                    return _this36.handleOverlayMouseLeave(view.uid);
                  }

                  return onMouseLeave;
                }(),
                onMouseMove: function () {
                  function onMouseMove() {
                    return _this36.handleOverlayMouseEnter(view.uid);
                  }

                  return onMouseMove;
                }(),
                style: {
                  position: 'absolute',
                  width: '100%',
                  height: '100%',
                  background: background,
                  opacity: 0.3,
                  zIndex: 1
                }
              });
            }

            var tiledPlot = _react2['default'].createElement(_TiledPlot2['default']
            // Reserved props
            , { key: 'tp' + String(view.uid),
              ref: function () {
                function ref(c) {
                  _this36.tiledPlots[view.uid] = c;
                }

                return ref;
              }()
              // Custom props
              , addTrackPosition: _this36.state.addTrackPositionView === view.uid ? _this36.state.addTrackPosition : null,
              addTrackPositionMenuPosition: addTrackPositionMenuPosition,
              canvasElement: _this36.state.canvasElement,
              chooseTrackHandler: _this36.state.chooseTrackHandler ? function (trackId) {
                return _this36.state.chooseTrackHandler(view.uid, trackId);
              } : null,
              chromInfoPath: view.chromInfoPath,
              disableTrackMenu: _this36.isTrackMenuDisabled(),
              draggingHappening: _this36.state.draggingHappening,
              editable: _this36.isEditable(),
              getLockGroupExtrema: function () {
                function getLockGroupExtrema(uid) {
                  return _this36.getLockGroupExtrema(view.uid, uid);
                }

                return getLockGroupExtrema;
              }(),
              initialXDomain: view.initialXDomain,
              initialYDomain: view.initialYDomain,
              isShowGlobalMousePosition: _this36.isShowGlobalMousePosition,
              isValueScaleLocked: function () {
                function isValueScaleLocked(uid) {
                  return _this36.isValueScaleLocked(view.uid, uid);
                }

                return isValueScaleLocked;
              }(),
              marginBottom: _this36.viewMarginBottom,
              marginLeft: _this36.viewMarginLeft,
              marginRight: _this36.viewMarginRight,
              marginTop: _this36.viewMarginTop,
              metaTracks: view.metaTracks,
              mouseTool: _this36.state.mouseTool,
              onChangeTrackData: function () {
                function onChangeTrackData(trackId, newData) {
                  return _this36.handleChangeTrackData(view.uid, trackId, newData);
                }

                return onChangeTrackData;
              }(),
              onChangeTrackType: function () {
                function onChangeTrackType(trackId, newType) {
                  return _this36.handleChangeTrackType(view.uid, trackId, newType);
                }

                return onChangeTrackType;
              }(),
              onCloseTrack: function () {
                function onCloseTrack(uid) {
                  return _this36.handleCloseTrack(view.uid, uid);
                }

                return onCloseTrack;
              }(),
              onDataDomainChanged: function () {
                function onDataDomainChanged(xDomain, yDomain) {
                  return _this36.handleDataDomainChanged(view.uid, xDomain, yDomain);
                }

                return onDataDomainChanged;
              }(),
              onLockValueScale: function () {
                function onLockValueScale(uid) {
                  return _this36.handleLockValueScale(view.uid, uid);
                }

                return onLockValueScale;
              }(),
              onMouseMoveZoom: _this36.mouseMoveZoomHandler.bind(_this36),
              onNewTilesLoaded: function () {
                function onNewTilesLoaded(trackUid) {
                  return _this36.handleNewTilesLoaded(view.uid, trackUid);
                }

                return onNewTilesLoaded;
              }(),
              onNoTrackAdded: _this36.handleNoTrackAdded.bind(_this36),
              onRangeSelection: _this36.rangeSelectionHandler.bind(_this36),
              onResizeTrack: _this36.triggerViewChangeDb,
              onScalesChanged: function () {
                function onScalesChanged(x, y) {
                  return _this36.handleScalesChanged(view.uid, x, y);
                }

                return onScalesChanged;
              }(),
              onTrackOptionsChanged: function () {
                function onTrackOptionsChanged(trackId, options) {
                  return _this36.handleTrackOptionsChanged(view.uid, trackId, options);
                }

                return onTrackOptionsChanged;
              }(),
              onTrackPositionChosen: _this36.handleTrackPositionChosen.bind(_this36),
              onTracksAdded: function () {
                function onTracksAdded(newTracks, position, host) {
                  return _this36.handleTracksAdded(view.uid, newTracks, position, host);
                }

                return onTracksAdded;
              }(),
              onUnlockValueScale: function () {
                function onUnlockValueScale(uid) {
                  return _this36.handleUnlockValueScale(view.uid, uid);
                }

                return onUnlockValueScale;
              }(),
              onValueScaleChanged: function () {
                function onValueScaleChanged(uid) {
                  return _this36.syncValueScales(view.uid, uid);
                }

                return onValueScaleChanged;
              }(),
              overlays: view.overlays,
              paddingBottom: _this36.viewPaddingBottom,
              paddingLeft: _this36.viewPaddingLeft,
              paddingRight: _this36.viewPaddingRight,
              paddingTop: _this36.viewPaddingTop,
              pixiRenderer: _this36.pixiRenderer,
              pixiStage: _this36.pixiStage,
              pluginDataFetchers: _this36.pluginDataFetchers,
              pluginTracks: _this36.pluginTracks,
              rangeSelection1dSize: _this36.state.rangeSelection1dSize,
              rangeSelectionToInt: _this36.state.rangeSelectionToInt,
              registerDraggingChangedListener: function () {
                function registerDraggingChangedListener(listener) {
                  return _this36.addDraggingChangedListener(view.uid, view.uid, listener);
                }

                return registerDraggingChangedListener;
              }(),
              removeDraggingChangedListener: function () {
                function removeDraggingChangedListener(listener) {
                  return _this36.removeDraggingChangedListener(view.uid, view.uid, listener);
                }

                return removeDraggingChangedListener;
              }(),
              setCentersFunction: function () {
                function setCentersFunction(c) {
                  _this36.setCenters[view.uid] = c;
                }

                return setCentersFunction;
              }(),
              svgElement: _this36.state.svgElement,
              tracks: view.tracks,
              trackSourceServers: _this36.state.viewConfig.trackSourceServers,
              uid: view.uid,
              verticalMargin: _this36.verticalMargin,
              viewOptions: view.options
              // dragging={this.state.dragging}
              , xDomainLimits: view.xDomainLimits,
              yDomainLimits: view.yDomainLimits,
              zoomable: !_this36.isZoomFixed(view),
              zoomLimits: _this36.calculateZoomLimits(view, view.initialXDomain),
              zoomToDataExtentOnInit: function () {
                function zoomToDataExtentOnInit() {
                  return _this36.zoomToDataExtentOnInit.has(view.uid);
                }

                return zoomToDataExtentOnInit;
              }()
            });

            var getGenomePositionSearchBox = function () {
              function getGenomePositionSearchBox(isFocused, onFocus) {
                if (!view.genomePositionSearchBox) return null;

                return _react2['default'].createElement(_GenomePositionSearchBox2['default']
                // Reserved props
                , { key: 'gpsb' + String(view.uid),
                  ref: function () {
                    function ref(c) {
                      _this36.genomePositionSearchBoxes[view.uid] = c;
                    }

                    return ref;
                  }()
                  // Custom props
                  , autocompleteId: view.genomePositionSearchBox.autocompleteId,
                  autocompleteServer: view.genomePositionSearchBox.autocompleteServer,
                  chromInfoId: view.genomePositionSearchBox.chromInfoId,
                  chromInfoPath: view.genomePositionSearchBox.chromInfoPath,
                  chromInfoServer: view.genomePositionSearchBox.chromInfoServer,
                  hideAvailableAssemblies: view.genomePositionSearchBox.hideAvailableAssemblies,
                  isFocused: isFocused
                  // the chromInfoId is either specified in the viewconfig or guessed based on
                  // the visible tracks (see createGenomePositionSearchBoxEntry)
                  , onFocus: onFocus,
                  onGeneSearch: _this36.geneSearchHandler.bind(_this36),
                  onSelectedAssemblyChanged: function () {
                    function onSelectedAssemblyChanged(x, y, server) {
                      return _this36.handleSelectedAssemblyChanged(view.uid, x, y, server);
                    }

                    return onSelectedAssemblyChanged;
                  }(),
                  registerViewportChangedListener: function () {
                    function registerViewportChangedListener(listener) {
                      return _this36.addScalesChangedListener(view.uid, view.uid, listener);
                    }

                    return registerViewportChangedListener;
                  }(),
                  removeViewportChangedListener: function () {
                    function removeViewportChangedListener() {
                      return _this36.removeScalesChangedListener(view.uid, view.uid);
                    }

                    return removeViewportChangedListener;
                  }(),
                  setCenters: function () {
                    function setCenters(centerX, centerY, k, animateTime) {
                      return _this36.setCenters[view.uid](centerX, centerY, k, false, animateTime);
                    }

                    return setCenters;
                  }(),
                  trackSourceServers: _this36.state.viewConfig.trackSourceServers,
                  twoD: true
                });
              }

              return getGenomePositionSearchBox;
            }();

            var multiTrackHeader = _this36.isEditable() && !_this36.isViewHeaderDisabled() && !_this36.state.viewConfig.hideHeader ? _react2['default'].createElement(_ViewHeader2['default'], {
              ref: function () {
                function ref(c) {
                  _this36.viewHeaders[view.uid] = c;
                }

                return ref;
              }(),
              getGenomePositionSearchBox: getGenomePositionSearchBox,
              isGenomePositionSearchBoxVisible: view.genomePositionSearchBox && view.genomePositionSearchBox.visible,
              mouseTool: _this36.state.mouseTool,
              onAddView: function () {
                function onAddView() {
                  return _this36.handleAddView(view);
                }

                return onAddView;
              }(),
              onClearView: function () {
                function onClearView() {
                  return _this36.handleClearView(view.uid);
                }

                return onClearView;
              }(),
              onCloseView: function () {
                function onCloseView() {
                  return _this36.handleCloseView(view.uid);
                }

                return onCloseView;
              }(),
              onEditViewConfig: _this36.handleEditViewConfigBound,
              onExportPNG: _this36.handleExportPNG.bind(_this36),
              onExportSVG: _this36.handleExportSVG.bind(_this36),
              onExportViewsAsJSON: _this36.handleExportViewAsJSON.bind(_this36),
              onExportViewsAsLink: _this36.handleExportViewsAsLink.bind(_this36),
              onLockLocation: function () {
                function onLockLocation(uid) {
                  return _this36.handleYankFunction(uid, _this36.handleLocationLockChosen.bind(_this36));
                }

                return onLockLocation;
              }(),
              onLockZoom: function () {
                function onLockZoom(uid) {
                  return _this36.handleYankFunction(uid, _this36.handleZoomLockChosen.bind(_this36));
                }

                return onLockZoom;
              }(),
              onLockZoomAndLocation: function () {
                function onLockZoomAndLocation(uid) {
                  return _this36.handleYankFunction(uid, function (a, b) {
                    _this36.handleZoomLockChosen(a, b);
                    _this36.handleLocationLockChosen(a, b);
                  });
                }

                return onLockZoomAndLocation;
              }(),
              onProjectViewport: _this36.handleProjectViewport.bind(_this36),
              onTakeAndLockZoomAndLocation: function () {
                function onTakeAndLockZoomAndLocation(uid) {
                  _this36.handleYankFunction(uid, function (a, b) {
                    _this36.handleZoomYanked(a, b);
                    _this36.handleLocationYanked(a, b);
                    _this36.handleZoomLockChosen(a, b);
                    _this36.handleLocationLockChosen(a, b);
                  });
                }

                return onTakeAndLockZoomAndLocation;
              }(),
              onTogglePositionSearchBox: _this36.handleTogglePositionSearchBox.bind(_this36),
              onTrackPositionChosen: function () {
                function onTrackPositionChosen(position) {
                  return _this36.handleTrackPositionChosen(view.uid, position);
                }

                return onTrackPositionChosen;
              }(),
              onUnlockLocation: function () {
                function onUnlockLocation(uid) {
                  return _this36.handleUnlock(uid, _this36.locationLocks);
                }

                return onUnlockLocation;
              }(),
              onUnlockZoom: function () {
                function onUnlockZoom(uid) {
                  return _this36.handleUnlock(uid, _this36.zoomLocks);
                }

                return onUnlockZoom;
              }(),
              onUnlockZoomAndLocation: function () {
                function onUnlockZoomAndLocation(uid) {
                  _this36.handleUnlock(uid, _this36.zoomLocks);
                  _this36.handleUnlock(uid, _this36.locationLocks);
                }

                return onUnlockZoomAndLocation;
              }(),
              onViewOptionsChanged: function () {
                function onViewOptionsChanged(newOptions) {
                  return _this36.handleViewOptionsChanged(view.uid, newOptions);
                }

                return onViewOptionsChanged;
              }(),
              onYankLocation: function () {
                function onYankLocation(uid) {
                  return _this36.handleYankFunction(uid, _this36.handleLocationYanked.bind(_this36));
                }

                return onYankLocation;
              }(),
              onYankZoom: function () {
                function onYankZoom(uid) {
                  return _this36.handleYankFunction(uid, _this36.handleZoomYanked.bind(_this36));
                }

                return onYankZoom;
              }(),
              onYankZoomAndLocation: function () {
                function onYankZoomAndLocation(uid) {
                  return _this36.handleYankFunction(uid, function (a, b) {
                    _this36.handleZoomYanked(a, b);
                    _this36.handleLocationYanked(a, b);
                  });
                }

                return onYankZoomAndLocation;
              }(),
              onZoomToData: function () {
                function onZoomToData(uid) {
                  return _this36.handleZoomToData(uid);
                }

                return onZoomToData;
              }(),
              viewUid: view.uid
            }) : null;

            return _react2['default'].createElement(
              'div',
              {
                key: view.uid,
                ref: function () {
                  function ref(c) {
                    _this36.tiledAreasDivs[view.uid] = c;
                  }

                  return ref;
                }(),
                className: 'HiGlass-module_tiled-area-22H1L'
              },
              multiTrackHeader,
              tiledPlot,
              overlay
            );
          });
        }

        var layouts = this.mounted ? (0, _values2['default'])(this.state.views).filter(function (view) {
          return view.layout;
        }).map(function (view) {
          return view.layout;
        }) : [];

        layouts = JSON.parse((0, _stringify2['default'])(layouts)); // make sure to copy the layouts

        var defaultContainerPaddingX = this.isEditable() ? _configs.DEFAULT_CONTAINER_PADDING_X : 0;
        var defaultContainerPaddingY = this.isEditable() ? _configs.DEFAULT_CONTAINER_PADDING_Y : 0;

        var containerPaddingX = +this.props.options.containerPaddingX >= 0 ? +this.props.options.containerPaddingX : defaultContainerPaddingX;
        var containerPaddingY = +this.props.options.containerPaddingY >= 0 ? +this.props.options.containerPaddingY : defaultContainerPaddingY;

        var gridLayout = _react2['default'].createElement(
          _reactGridLayout2['default']
          // Reserved props
          ,
          { ref: function () {
              function ref(c) {
                _this36.gridLayout = c;
              }

              return ref;
            }()
            // Custom props
            , cols: 12,
            containerPadding: [containerPaddingX, containerPaddingY],
            draggableHandle: '.' + String(_ViewHeaderModule2['default']['multitrack-header-grabber']),
            isDraggable: this.isEditable(),
            isResizable: this.isEditable(),
            layout: layouts,
            margin: this.isEditable() ? [10, 10] : [0, 0],
            measureBeforeMount: false,
            onBreakpointChange: this.onBreakpointChange.bind(this),
            onDragStart: this.handleDragStart.bind(this),
            onDragStop: this.handleDragStop.bind(this),
            onLayoutChange: this.handleLayoutChange.bind(this),
            onResize: this.resizeHandler.bind(this),
            rowHeight: this.state.rowHeight
            // for some reason, this becomes 40 within the react-grid component
            // (try resizing the component to see how much the height changes)
            // Programming by coincidence FTW :-/
            // WidthProvider option
            // I like to have it animate on mount. If you don't, delete
            // `useCSSTransforms` (it's default `true`)
            // and set `measureBeforeMount={true}`.
            , useCSSTransforms: this.mounted,
            verticalCompact: this.state.viewConfig.compactLayout,
            width: this.state.width
          },
          this.tiledAreas
        );

        var styleNames = 'styles.higlass';

        if (this.theme === _configs.THEME_DARK) {
          styleNames += ' styles.higlass-dark-theme';
        }

        if (this.props.options.sizeMode === SIZE_MODE_OVERFLOW || this.props.options.sizeMode === SIZE_MODE_SCROLL) {
          styleNames += ' styles.higlass-container-overflow';
        }

        var scrollStyleNames = '';
        if (this.props.options.sizeMode === SIZE_MODE_OVERFLOW) {
          scrollStyleNames = 'styles.higlass-scroll-container-overflow';
        } else if (this.props.options.sizeMode === SIZE_MODE_SCROLL) {
          scrollStyleNames = 'styles.higlass-scroll-container-scroll';
        }

        return _react2['default'].createElement(
          'div',
          {
            key: this.uid,
            ref: function () {
              function ref(c) {
                _this36.topDiv = c;
              }

              return ref;
            }(),

            onMouseLeave: this.onMouseLeaveHandlerBound,
            onMouseMove: this.mouseMoveHandlerBound,
            className: 'higlass ' + (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
          },
          _react2['default'].createElement(
            _withPubSub.Provider,
            { value: this.pubSub },
            _react2['default'].createElement(
              _withModal.Provider,
              { value: this.modal },
              _react2['default'].createElement(
                _withTheme.Provider,
                { value: this.theme },
                this.state.modal,
                _react2['default'].createElement('canvas', {
                  key: this.uid,
                  ref: function () {
                    function ref(c) {
                      _this36.canvasElement = c;
                    }

                    return ref;
                  }(),
                  className: 'HiGlass-module_higlass-canvas-_mP9r'
                }),
                _react2['default'].createElement(
                  'div',
                  {
                    ref: function () {
                      function ref(c) {
                        _this36.scrollContainer = c;
                      }

                      return ref;
                    }(),

                    onScroll: this.onScrollHandlerBound,
                    className: 'higlass-scroll-container ' + (0, _getClassName3['default'])(scrollStyleNames, _styleModuleImportMap)
                  },
                  _react2['default'].createElement(
                    'div',
                    {
                      ref: function () {
                        function ref(c) {
                          _this36.divDrawingSurface = c;
                        }

                        return ref;
                      }(),
                      className: 'higlass-drawing-surface HiGlass-module_higlass-drawing-surface-3aQQo'
                    },
                    gridLayout
                  ),
                  _react2['default'].createElement('svg', {
                    ref: function () {
                      function ref(c) {
                        _this36.svgElement = c;
                      }

                      return ref;
                    }(),
                    style: {
                      // inline the styles so they aren't overriden by other css
                      // on the web page
                      position: 'absolute',
                      width: '100%',
                      height: '100%',
                      left: 0,
                      top: 0,
                      pointerEvents: 'none'
                    },
                    className: 'HiGlass-module_higlass-svg-JJZbf'
                  })
                )
              )
            )
          )
        );
      }

      return render;
    }()
  }, {
    key: 'sizeMode',
    get: function () {
      function get() {
        // eslint-disable-next-line no-nested-ternary
        return typeof this.props.options.sizeMode === 'undefined' ? this.props.options.bounded ? 'bounded' : SIZE_MODE_DEFAULT : this.props.options.sizeMode;
      }

      return get;
    }()
  }]);
  return HiGlassComponent;
}(_react2['default'].Component);

HiGlassComponent.defaultProps = {
  options: {},
  zoomFixed: false,
  compactLayout: true
};

HiGlassComponent.propTypes = {
  getApi: _propTypes2['default'].func,
  options: _propTypes2['default'].object,
  viewConfig: _propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].object]).isRequired,
  zoomFixed: _propTypes2['default'].bool,
  compactLayout: _propTypes2['default'].bool
};

exports['default'] = HiGlassComponent;

/***/ }),
/* 233 */
/***/ (function(module, exports, __nested_webpack_require_1309094__) {

__nested_webpack_require_1309094__(234);
module.exports = __nested_webpack_require_1309094__(12).Number.isNaN;


/***/ }),
/* 234 */
/***/ (function(module, exports, __nested_webpack_require_1309254__) {

// 20.1.2.4 Number.isNaN(number)
var $export = __nested_webpack_require_1309254__(16);

$export($export.S, 'Number', {
  isNaN: function isNaN(number) {
    // eslint-disable-next-line no-self-compare
    return number != number;
  }
});


/***/ }),
/* 235 */
/***/ (function(module, exports, __nested_webpack_require_1309556__) {

__nested_webpack_require_1309556__(61);
__nested_webpack_require_1309556__(236);
module.exports = __nested_webpack_require_1309556__(12).Array.from;


/***/ }),
/* 236 */
/***/ (function(module, exports, __nested_webpack_require_1309739__) {

"use strict";

var ctx = __nested_webpack_require_1309739__(49);
var $export = __nested_webpack_require_1309739__(16);
var toObject = __nested_webpack_require_1309739__(54);
var call = __nested_webpack_require_1309739__(165);
var isArrayIter = __nested_webpack_require_1309739__(166);
var toLength = __nested_webpack_require_1309739__(88);
var createProperty = __nested_webpack_require_1309739__(237);
var getIterFn = __nested_webpack_require_1309739__(112);

$export($export.S + $export.F * !__nested_webpack_require_1309739__(167)(function (iter) { Array.from(iter); }), 'Array', {
  // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
  from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
    var O = toObject(arrayLike);
    var C = typeof this == 'function' ? this : Array;
    var aLen = arguments.length;
    var mapfn = aLen > 1 ? arguments[1] : undefined;
    var mapping = mapfn !== undefined;
    var index = 0;
    var iterFn = getIterFn(O);
    var length, result, step, iterator;
    if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
    // if object isn't iterable or it's array with default iterator - use simple case
    if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
      for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
        createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
      }
    } else {
      length = toLength(O.length);
      for (result = new C(length); length > index; index++) {
        createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
      }
    }
    result.length = index;
    return result;
  }
});


/***/ }),
/* 237 */
/***/ (function(module, exports, __nested_webpack_require_1311442__) {

"use strict";

var $defineProperty = __nested_webpack_require_1311442__(32);
var createDesc = __nested_webpack_require_1311442__(66);

module.exports = function (object, index, value) {
  if (index in object) $defineProperty.f(object, index, createDesc(0, value));
  else object[index] = value;
};


/***/ }),
/* 238 */
/***/ (function(module, exports, __nested_webpack_require_1311789__) {

var isObject = __nested_webpack_require_1311789__(33);
module.exports = function (it, TYPE) {
  if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
  return it;
};


/***/ }),
/* 239 */
/***/ (function(module, exports, __nested_webpack_require_1312068__) {

__nested_webpack_require_1312068__(240);
module.exports = -0x1fffffffffffff;


/***/ }),
/* 240 */
/***/ (function(module, exports, __nested_webpack_require_1312209__) {

// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __nested_webpack_require_1312209__(16);

$export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });


/***/ }),
/* 241 */
/***/ (function(module, exports, __nested_webpack_require_1312436__) {

__nested_webpack_require_1312436__(242);
module.exports = 0x1fffffffffffff;


/***/ }),
/* 242 */
/***/ (function(module, exports, __nested_webpack_require_1312576__) {

// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __nested_webpack_require_1312576__(16);

$export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });


/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function iota(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = i
  }
  return result
}

module.exports = iota

/***/ }),
/* 244 */
/***/ (function(module, exports) {

/*!
 * Determine if an object is a Buffer
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */

// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
  return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}

function isBuffer (obj) {
  return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}

// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
  return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}


/***/ }),
/* 245 */
/***/ (function(module, exports, __nested_webpack_require_1313788__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_1313788__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _promise = __nested_webpack_require_1313788__(62);

var _promise2 = _interopRequireDefault(_promise);

var _regenerator = __nested_webpack_require_1313788__(246);

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = __nested_webpack_require_1313788__(247);

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _stringify = __nested_webpack_require_1313788__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _classCallCheck2 = __nested_webpack_require_1313788__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1313788__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _slugid = __nested_webpack_require_1313788__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _d3Scale = __nested_webpack_require_1313788__(28);

var _utils = __nested_webpack_require_1313788__(10);

var _DenseDataExtrema1D = __nested_webpack_require_1313788__(137);

var _DenseDataExtrema1D2 = _interopRequireDefault(_DenseDataExtrema1D);

var _DenseDataExtrema2D = __nested_webpack_require_1313788__(138);

var _DenseDataExtrema2D2 = _interopRequireDefault(_DenseDataExtrema2D);

var _services = __nested_webpack_require_1313788__(24);

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

var DataFetcher = function () {
  function DataFetcher(dataConfig, pubSub) {
    (0, _classCallCheck3['default'])(this, DataFetcher);

    this.tilesetInfoLoading = true;

    if (!dataConfig) {
      console.error('No dataconfig provided');
      return;
    }

    // copy the dataConfig so that it doesn't dirty so that
    // it doesn't get modified when we make objects of its
    // children below
    this.dataConfig = JSON.parse((0, _stringify2['default'])(dataConfig));
    this.uuid = _slugid2['default'].nice();
    this.pubSub = pubSub;

    if (this.dataConfig.children) {
      // convert each child into an object
      this.dataConfig.children = dataConfig.children.map(function (c) {
        return new DataFetcher(c, pubSub);
      });
    }
  }

  /**
   * We don't a have a tilesetUid for this track. But we do have a url, filetype
   * and server. Using these, we can use the server to fullfill tile requests
   * from this dataset.
   *
   * @param {string} server The server api location (e.g. 'localhost:8000/api/v1')
   * @param {string} url The location of the data file (e.g. 'encode.org/my.file.bigwig')
   * @param {string} filetype The type of file being served (e.g. 'bigwig')
   * @param {string} coordSystem The coordinate system being served (e.g. 'hg38')
   */


  (0, _createClass3['default'])(DataFetcher, [{
    key: 'registerFileUrl',
    value: function () {
      var _ref2 = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function () {
        function _callee(_ref) {
          var server = _ref.server,
              url = _ref.url,
              filetype = _ref.filetype,
              coordSystem = _ref.coordSystem;
          var serverUrl, payload;
          return _regenerator2['default'].wrap(function () {
            function _callee$(_context) {
              while (1) {
                switch (_context.prev = _context.next) {
                  case 0:
                    serverUrl = String((0, _utils.trimTrailingSlash)(server)) + '/register_url/';
                    payload = {
                      fileurl: url,
                      filetype: filetype,
                      coordSystem: coordSystem
                    };
                    return _context.abrupt('return', fetch(serverUrl, {
                      method: 'POST',
                      body: (0, _stringify2['default'])(payload),
                      headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                      }
                    }));

                  case 3:
                  case 'end':
                    return _context.stop();
                }
              }
            }

            return _callee$;
          }(), _callee, this);
        }

        return _callee;
      }()));

      function registerFileUrl(_x) {
        return _ref2.apply(this, arguments);
      }

      return registerFileUrl;
    }()
  }, {
    key: 'tilesetInfo',
    value: function () {
      function tilesetInfo(finished) {
        var _this = this;

        // if this track has a url, server and filetype
        // then we need to register those with the server
        if (this.dataConfig.server && this.dataConfig.url && this.dataConfig.filetype) {
          return this.registerFileUrl(this.dataConfig).then(function (data) {
            return data.json();
          }).then(function (data) {
            _this.dataConfig.tilesetUid = data.uid;
            _this.tilesetInfoAfterRegister(finished);
          })['catch'](function (rejected) {
            console.error('Error registering url', rejected);
          });
        }

        return new _promise2['default'](function () {
          _this.tilesetInfoAfterRegister(finished);
        });
      }

      return tilesetInfo;
    }()

    /**
     * Obtain tileset infos for all of the tilesets listed
     *
     * If there is more than one tileset info, this function
     * should (not currently implemented) check if the tileset
     * infos have the same dimensions and then return a common
     * one.
     *
     * Paremeters
     * ----------
     * @param {function} finished A callback that will be called
     *  when all tileset infos are loaded
     */

  }, {
    key: 'tilesetInfoAfterRegister',
    value: function () {
      function tilesetInfoAfterRegister(finished /* , errorCb */) {
        var _this2 = this;

        // console.log('dataConfig', this.dataConfig);

        if (!this.dataConfig.children) {
          // this data source has no children so we just need to retrieve one tileset
          // info
          if (!this.dataConfig.server || !this.dataConfig.tilesetUid) {
            console.warn('No dataConfig children, server or tilesetUid:', this.dataConfig);
            finished(null);
          } else {
            // pass in the callback
            _services.tileProxy.trackInfo(this.dataConfig.server, this.dataConfig.tilesetUid, function (tilesetInfo) {
              // tileset infos are indxed by by tilesetUids, we can just resolve
              // that here before passing it back to the track
              _this2.dataConfig.tilesetInfo = tilesetInfo[_this2.dataConfig.tilesetUid];
              finished(tilesetInfo[_this2.dataConfig.tilesetUid], _this2.dataConfig.tilesetUid);
            }, function (error) {
              _this2.tilesetInfoLoading = false;
              finished({
                error: error
              });
            }, this.pubSub);
          }
        } else {
          // this data source has children, so we need to wait to get
          // all of their tileset infos in order to return them to the track
          var promises = this.dataConfig.children.map(function (x) {
            return new _promise2['default'](function (resolve) {
              x.tilesetInfo(resolve);
            });
          });

          _promise2['default'].all(promises).then(function (values) {
            // this is where we should check if all the children's tileset
            // infos match
            finished(values[0]);
          });
        }
      }

      return tilesetInfoAfterRegister;
    }()
  }, {
    key: 'fullTileId',
    value: function () {
      function fullTileId(tilesetUid, tileId) {
        /**
         * Convert a tilesetUid and tileId into a full tile
         * identifier
         *
         * Parameters
         * ----------
         *  tilesetUid: string
         *    Uid of the tileset on the server
         *
         *  tileId: string
         *    The tileId of the tile
         *
         *  Returns
         *  -------
         *    fullTileId: string
         *      The full tile id that the server will parse.
         *      E.g. xyxx.0.0.0.default
         */

        return String(tilesetUid) + '.' + String(tileId);
      }

      return fullTileId;
    }()
  }, {
    key: 'fetchTilesDebounced',
    value: function () {
      function fetchTilesDebounced(receivedTiles, tileIds) {
        var _this3 = this;

        /**
         * Fetch a set of tiles.
         *
         * Because the track shouldn't care about tileset ids, the tile ids
         * should just include positions and any necessary transforms.
         *
         * Parameters
         * ----------
         *  receivedTiles: callback
         *    A function to call once the tiles have been
         *    fetched
         *  tileIds: []
         *    The tile ids to fetch
         */
        if (this.dataConfig.type === 'horizontal-section') {
          this.fetchHorizontalSection(receivedTiles, tileIds);
        } else if (this.dataConfig.type === 'vertical-section') {
          this.fetchHorizontalSection(receivedTiles, tileIds, true);
        } else if (!this.dataConfig.children && this.dataConfig.tilesetUid) {
          // no children, just return the fetched tiles as is
          var promise = new _promise2['default'](function (resolve) {
            return _services.tileProxy.fetchTilesDebounced({
              id: _slugid2['default'].nice(),
              server: _this3.dataConfig.server,
              done: resolve,
              ids: tileIds.map(function (x) {
                return String(_this3.dataConfig.tilesetUid) + '.' + String(x);
              }),
              options: _this3.dataConfig.options
            }, _this3.pubSub, true);
          });

          promise.then(function (returnedTiles) {
            var tilesetUid = (0, _utils.dictValues)(returnedTiles)[0].tilesetUid;
            var newTiles = {};

            for (var i = 0; i < tileIds.length; i++) {
              var fullTileId = _this3.fullTileId(tilesetUid, tileIds[i]);

              returnedTiles[fullTileId].tilePositionId = tileIds[i];
              newTiles[tileIds[i]] = returnedTiles[fullTileId];
            }

            receivedTiles(newTiles);
          });
        } else {
          // multiple child tracks, need to wait for all of them to
          // fetch their data before returning to the parent
          var promises = this.dataConfig.children.map(function (x) {
            return new _promise2['default'](function (resolve) {
              x.fetchTilesDebounced(resolve, tileIds);
            }, _this3.pubSub, true);
          });

          _promise2['default'].all(promises).then(function (returnedTiles) {
            // if we're trying to divide two datasets,
            if (_this3.dataConfig.type === 'divided') {
              var newTiles = _this3.makeDivided(returnedTiles, tileIds);

              receivedTiles(newTiles);
            } else {
              // assume we're just returning raw tiles
              console.warn('Unimplemented dataConfig type. Returning first data source.', _this3.dataConfig);

              receivedTiles(returnedTiles[0]);
            }
          });
        }
      }

      return fetchTilesDebounced;
    }()
  }, {
    key: 'divideData',
    value: function () {
      function divideData(numeratorData, denominatorData) {
        /**
         * Return an array consisting of the division of the numerator
         * array by the denominator array
         *
         * Parameters
         * ----------
         *  numeratorData: array
         *    An array of numerical values
         *  denominatorData:
         *    An array of numerical values
         *
         * Returns
         * -------
         *  divided: array
         *    An array consisting of the division of the
         *    numerator by the denominator
         */
        var result = new Float32Array(numeratorData.length);

        for (var i = 0; i < result.length; i++) {
          if (denominatorData[i] === 0.0) result[i] = NaN;else result[i] = numeratorData[i] / denominatorData[i];
        }

        return result;
      }

      return divideData;
    }()

    /*
     * Take a horizontal slice across the returned tiles at the
     * given position.
     *
     * @param {list} returnedTiles: The tiles returned from a fetch request
     * @param {Number} sliceYPos: The y position across which to slice
     */

  }, {
    key: 'horizontalSlice',
    value: function () {
      function horizontalSlice() /* returnedTiles, sliceYPos */{
        return null;
      }

      return horizontalSlice;
    }()

    /**
     * Extract a slice from a matrix at a given position.
     *
     * @param {array} inputData: An array containing a matrix stored row-wise
     * @param {array} arrayShape: The shape of the array, should be a
     *  two element array e.g. [256,256].
     * @param {int} sliceIndex: The index across which to take the slice
     * @returns {array} an array corresponding to a slice of this matrix
     */

  }, {
    key: 'extractDataSlice',
    value: function () {
      function extractDataSlice(inputData, arrayShape, sliceIndex, axis) {
        if (!axis) {
          return inputData.slice(arrayShape[1] * sliceIndex, arrayShape[1] * (sliceIndex + 1));
        }

        var returnArray = new Array(arrayShape[1]);
        for (var i = sliceIndex; i < inputData.length; i += arrayShape[0]) {
          returnArray[Math.floor(i / arrayShape[0])] = inputData[i];
        }
        return returnArray;
      }

      return extractDataSlice;
    }()
  }, {
    key: 'fetchHorizontalSection',
    value: function () {
      function fetchHorizontalSection(receivedTiles, tileIds) {
        var _this4 = this;

        var vertical = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

        // We want to take a horizontal section of a 2D dataset
        // that means that a 1D track is requesting data from a 2D source
        // because the 1D track only requests 1D tiles, we need to calculate
        // the 2D tile from which to take the slice
        var newTileIds = [];
        var mirrored = [];

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(tileIds), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tileId = _step.value;

            var parts = tileId.split('.');
            var zoomLevel = +parts[0];
            var xTilePos = +parts[1];

            // this is a dummy scale that we'll use to fetch tile positions
            // along the y-axis of the 2D dataset (we already have the x positions
            // from the track that is querying this data)
            var scale = (0, _d3Scale.scaleLinear)().domain([this.dataConfig.slicePos, this.dataConfig.slicePos]);

            // there's two different ways of calculating tile positions
            // this needs to be consolidated into one function eventually
            var yTiles = [];

            if (this.dataConfig.tilesetInfo && this.dataConfig.tilesetInfo.resolutions) {
              var sortedResolutions = this.dataConfig.tilesetInfo.resolutions.map(function (x) {
                return +x;
              }).sort(function (a, b) {
                return b - a;
              });

              yTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[zoomLevel], scale, this.dataConfig.tilesetInfo.min_pos[vertical ? 1 : 0], this.dataConfig.tilesetInfo.max_pos[vertical ? 1 : 0]);
            } else {
              yTiles = _services.tileProxy.calculateTiles(zoomLevel, scale, this.dataConfig.tilesetInfo.min_pos[vertical ? 1 : 0], this.dataConfig.tilesetInfo.max_pos[vertical ? 1 : 0], this.dataConfig.tilesetInfo.max_zoom, this.dataConfig.tilesetInfo.max_width);
            }
            var sortedPosition = [xTilePos, yTiles[0]].sort(function (a, b) {
              return a - b;
            });

            // make note of whether we reversed the x and y tile positions
            if (sortedPosition[0] === xTilePos) {
              mirrored.push(false);
            } else {
              mirrored.push(true);
            }

            var newTileId = zoomLevel + '.' + String(sortedPosition[0]) + '.' + String(sortedPosition[1]);
            newTileIds.push(newTileId);
            // we may need to add something about the data transform
          }

          // actually fetch the new tileIds
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var promise = new _promise2['default'](function (resolve) {
          return _services.tileProxy.fetchTilesDebounced({
            id: _slugid2['default'].nice(),
            server: _this4.dataConfig.server,
            done: resolve,
            ids: newTileIds.map(function (x) {
              return String(_this4.dataConfig.tilesetUid) + '.' + String(x);
            })
          }, _this4.pubSub, true);
        });
        promise.then(function (returnedTiles) {
          // we've received some new tiles, but they're 2D
          // we need to extract the row corresponding to the data we need

          var tilesetUid = (0, _utils.dictValues)(returnedTiles)[0].tilesetUid;
          // console.log('tilesetUid:', tilesetUid);
          var newTiles = {};

          for (var i = 0; i < newTileIds.length; i++) {
            var parts = newTileIds[i].split('.');
            var zoomLevel = +parts[0];
            var xTilePos = +parts[1];
            var yTilePos = +parts[2];

            var sliceIndex = _services.tileProxy.calculateTileAndPosInTile(_this4.dataConfig.tilesetInfo, _this4.dataConfig.tilesetInfo.max_width, _this4.dataConfig.tilesetInfo.min_pos[1], zoomLevel, +_this4.dataConfig.slicePos)[1];

            var fullTileId = _this4.fullTileId(tilesetUid, newTileIds[i]);
            var tile = returnedTiles[fullTileId];

            var dataSlice = null;

            if (xTilePos === yTilePos) {
              // this is tile along the diagonal that we have to mirror
              dataSlice = _this4.extractDataSlice(tile.dense, [256, 256], sliceIndex);
              var mirroredDataSlice = _this4.extractDataSlice(tile.dense, [256, 256], sliceIndex, 1);
              for (var j = 0; j < dataSlice.length; j++) {
                dataSlice[j] += mirroredDataSlice[j];
              }
            } else if (mirrored[i]) {
              // this tile is in the upper right triangle but the data is only available for
              // the lower left so we have to mirror it
              dataSlice = _this4.extractDataSlice(tile.dense, [256, 256], sliceIndex, 1);
            } else {
              dataSlice = _this4.extractDataSlice(tile.dense, [256, 256], sliceIndex);
            }

            var newTile = {
              min_value: Math.min.apply(null, dataSlice),
              max_value: Math.max.apply(null, dataSlice),
              denseDataExtrema: new _DenseDataExtrema1D2['default'](dataSlice),
              minNonZero: (0, _utils.minNonZero)(dataSlice),
              maxNonZero: (0, _utils.maxNonZero)(dataSlice),
              dense: dataSlice,
              dtype: tile.dtype,
              server: tile.server,
              tilePos: mirrored[i] ? [yTilePos] : [xTilePos],
              tilePositionId: tileIds[i],
              tilesetUid: tilesetUid,
              zoomLevel: tile.zoomLevel
            };

            newTiles[tileIds[i]] = newTile;
          }

          receivedTiles(newTiles);
        });
      }

      return fetchHorizontalSection;
    }()
  }, {
    key: 'makeDivided',
    value: function () {
      function makeDivided(returnedTiles, tileIds) {
        if (returnedTiles.length < 2) {
          console.warn('Only one tileset specified for a divided datafetcher:', this.dataConfig);
        }

        // const numeratorTilesetUid = dictValues(returnedTiles[0])[0].tilesetUid;
        // const denominatorTilesetUid = dictValues(returnedTiles[1])[0].tilesetUid;

        var newTiles = {};

        for (var i = 0; i < tileIds.length; i++) {
          // const numeratorUid = this.fullTileId(numeratorTilesetUid, tileIds[i]);
          // const denominatorUid = this.fullTileId(denominatorTilesetUid, tileIds[i]);
          var zoomLevel = returnedTiles[0][tileIds[i]].zoomLevel;
          var tilePos = returnedTiles[0][tileIds[i]].tilePos;

          var newTile = {
            zoomLevel: zoomLevel,
            tilePos: tilePos,
            tilePositionId: tileIds[i]
          };

          if (returnedTiles[0][tileIds[i]].dense && returnedTiles[1][tileIds[i]].dense) {
            var newData = this.divideData(returnedTiles[0][tileIds[i]].dense, returnedTiles[1][tileIds[i]].dense);

            var dde = tilePos.length === 2 ? new _DenseDataExtrema2D2['default'](newData) : new _DenseDataExtrema1D2['default'](newData);

            newTile = {
              dense: newData,
              denseDataExtrema: dde,
              minNonZero: (0, _utils.minNonZero)(newData),
              maxNonZero: (0, _utils.maxNonZero)(newData),
              zoomLevel: zoomLevel,
              tilePos: tilePos,
              tilePositionId: tileIds[i]
            };
          }

          // returned ids will be indexed by the tile id and won't include the
          // tileset uid
          newTiles[tileIds[i]] = newTile;
        }

        return newTiles;
      }

      return makeDivided;
    }()
  }]);
  return DataFetcher;
}();

// Services


exports['default'] = DataFetcher;

/***/ }),
/* 246 */
/***/ (function(module, exports, __nested_webpack_require_1335829__) {

module.exports = __nested_webpack_require_1335829__(617);


/***/ }),
/* 247 */
/***/ (function(module, exports, __nested_webpack_require_1335951__) {

"use strict";


exports.__esModule = true;

var _promise = __nested_webpack_require_1335951__(62);

var _promise2 = _interopRequireDefault(_promise);

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

exports.default = function (fn) {
  return function () {
    var gen = fn.apply(this, arguments);
    return new _promise2.default(function (resolve, reject) {
      function step(key, arg) {
        try {
          var info = gen[key](arg);
          var value = info.value;
        } catch (error) {
          reject(error);
          return;
        }

        if (info.done) {
          resolve(value);
        } else {
          return _promise2.default.resolve(value).then(function (value) {
            step("next", value);
          }, function (err) {
            step("throw", err);
          });
        }
      }

      return step("next");
    });
  };
};

/***/ }),
/* 248 */
/***/ (function(module, exports, __nested_webpack_require_1336931__) {

module.exports = { "default": __nested_webpack_require_1336931__(249), __esModule: true };

/***/ }),
/* 249 */
/***/ (function(module, exports, __nested_webpack_require_1337085__) {

__nested_webpack_require_1337085__(250);
module.exports = __nested_webpack_require_1337085__(12).Math.log2;


/***/ }),
/* 250 */
/***/ (function(module, exports, __nested_webpack_require_1337242__) {

// 20.2.2.22 Math.log2(x)
var $export = __nested_webpack_require_1337242__(16);

$export($export.S, 'Math', {
  log2: function log2(x) {
    return Math.log(x) / Math.LN2;
  }
});


/***/ }),
/* 251 */
/***/ (function(module, exports, __nested_webpack_require_1337486__) {

module.exports = { "default": __nested_webpack_require_1337486__(252), __esModule: true };

/***/ }),
/* 252 */
/***/ (function(module, exports, __nested_webpack_require_1337640__) {

__nested_webpack_require_1337640__(253);
module.exports = __nested_webpack_require_1337640__(12).Number.isSafeInteger;


/***/ }),
/* 253 */
/***/ (function(module, exports, __nested_webpack_require_1337808__) {

// 20.1.2.5 Number.isSafeInteger(number)
var $export = __nested_webpack_require_1337808__(16);
var isInteger = __nested_webpack_require_1337808__(178);
var abs = Math.abs;

$export($export.S, 'Number', {
  isSafeInteger: function isSafeInteger(number) {
    return isInteger(number) && abs(number) <= 0x1fffffffffffff;
  }
});


/***/ }),
/* 254 */
/***/ (function(module, exports, __nested_webpack_require_1338184__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1338184__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1338184__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1338184__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1338184__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1338184__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _HeatmapTiledPixiTrack = __nested_webpack_require_1338184__(135);

var _HeatmapTiledPixiTrack2 = _interopRequireDefault(_HeatmapTiledPixiTrack);

var _configs = __nested_webpack_require_1338184__(11);

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

function _drawTile(tile) {
  if (!tile.graphics) {
    return;
  }

  // console.log('Id2DTiled drawTile...', tile);
  var graphics = tile.graphics;

  var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos),
      tileX = _getTilePosAndDimensi.tileX,
      tileY = _getTilePosAndDimensi.tileY,
      tileWidth = _getTilePosAndDimensi.tileWidth;

  // console.log('tileX:', tileX, 'tileY:', tileY, 'tileWidth:', tileWidth);

  // the text needs to be scaled down so that it doesn't become huge
  // when we zoom in


  tile.drawnAtScale = this._xScale.copy();

  var tSX = 1 / ((this._xScale(1) - this._xScale(0)) / (this._refXScale(1) - this._refXScale(0)));
  var tSY = 1 / ((this._yScale(1) - this._yScale(0)) / (this._refYScale(1) - this._refYScale(0)));

  tile.text.scale.x = tSX;
  tile.text.scale.y = tSY;

  var tilePixelWidth = this._xScale(tileWidth) - this._xScale(0);

  // make sure the text's size is always drawn at the same size
  tile.textGraphics.scale.x = tilePixelWidth / 256;
  tile.textGraphics.scale.y = tilePixelWidth / 256;

  graphics.clear();

  graphics.lineStyle(4 * tSX, 0x0000ff, 1);
  graphics.beginFill(0xff700b, 0.4);
  graphics.alpha = 0.5;

  // line needs to be scaled down so that it doesn't become huge

  // fun tile positioning when it's mirrored, except this is just a rectangle
  // that doesn't need to be rotated so it's easy
  if (tile.mirrored) {
    var tileScaledWidth = this._refXScale(tileY + tileWidth) - this._refXScale(tileY);
    var tileScaledHeight = this._refYScale(tileX + tileWidth) - this._refYScale(tileX);

    // add tileScaledHeight / 2 and tileScaledWidth / 2 to center the text on the tile
    tile.textGraphics.position.x = this._refXScale(tileY) + tileScaledWidth / 2;
    tile.textGraphics.position.y = this._refYScale(tileX) + tileScaledHeight / 2;

    graphics.drawRect(this._refXScale(tileY), this._refYScale(tileX), tileScaledWidth, tileScaledHeight);
  } else {
    var _tileScaledWidth = this._refXScale(tileX + tileWidth) - this._refXScale(tileX);
    var _tileScaledHeight = this._refYScale(tileY + tileWidth) - this._refYScale(tileY);

    // add tileScaledHeight / 2 and tileScaledWidth / 2 to center the text on the tile
    tile.textGraphics.position.x = this._refXScale(tileX) + _tileScaledWidth / 2;
    tile.textGraphics.position.y = this._refYScale(tileY) + _tileScaledHeight / 2;

    graphics.drawRect(this._refXScale(tileX), this._refYScale(tileY), _tileScaledWidth, _tileScaledHeight);
  }
}

// Configs
exports.drawTile = _drawTile;
function _initTile(tile) {
  var graphics = tile.graphics;
  tile.textGraphics = new _configs.GLOBALS.PIXI.Graphics();

  if (tile.mirrored) {
    // mirrored tiles have their x and y coordinates reversed
    tile.text = new _configs.GLOBALS.PIXI.Text(String(tile.tileData.zoomLevel) + '/' + String([tile.tileData.tilePos[1], tile.tileData.tilePos[0]].join('/')), {
      fontFamily: 'Arial',
      fontSize: 24,
      fill: 0xff1010,
      align: 'center'
    });
  } else {
    tile.text = new _configs.GLOBALS.PIXI.Text(String(tile.tileData.zoomLevel) + '/' + String(tile.tileData.tilePos.join('/')), {
      fontFamily: 'Arial',
      fontSize: 24,
      fill: 0xff1010,
      align: 'center'
    });
  }

  // tile.text.y = 100;
  tile.textGraphics.addChild(tile.text);

  tile.text.anchor.x = 0.5;
  tile.text.anchor.y = 0.5;

  graphics.addChild(tile.textGraphics);
}

exports.initTile = _initTile;

var Id2DTiledPixiTrack = function (_HeatmapTiledPixiTrac) {
  (0, _inherits3['default'])(Id2DTiledPixiTrack, _HeatmapTiledPixiTrac);

  function Id2DTiledPixiTrack() {
    (0, _classCallCheck3['default'])(this, Id2DTiledPixiTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (Id2DTiledPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(Id2DTiledPixiTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(Id2DTiledPixiTrack, [{
    key: 'areAllVisibleTilesLoaded',
    value: function () {
      function areAllVisibleTilesLoaded() {
        // we don't need to wait for any tiles to load before
        // drawing
        //
        return true;
      }

      return areAllVisibleTilesLoaded;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        /**
         * Create whatever is needed to draw this tile.
         */

        _initTile.bind(this)(tile);
        this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile, graphics) {}

      return destroyTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        _drawTile.bind(this)(tile);
      }

      return drawTile;
    }()
  }, {
    key: 'fetchNewTiles',
    value: function () {
      function fetchNewTiles(toFetch) {
        var _this2 = this;

        // no real fetching involved... we just need to display the data
        toFetch.forEach(function (x) {
          var key = x.remoteId;
          var keyParts = key.split('.');

          var data = {
            zoomLevel: keyParts[0],
            tilePos: keyParts.slice(1, keyParts.length).map(function (keyPart) {
              return +keyPart;
            })
          };

          _this2.fetchedTiles[x.tileId] = x;
          _this2.fetchedTiles[x.tileId].tileData = data;

          // since we're not actually fetching remote data, we can easily
          // remove these tiles from the fetching list
          if (_this2.fetching.has(x.remoteId)) {
            _this2.fetching['delete'](x.remoteId);
          }
        });

        this.synchronizeTilesAndGraphics();
      }

      return fetchNewTiles;
    }()
  }]);
  return Id2DTiledPixiTrack;
}(_HeatmapTiledPixiTrack2['default']);

exports['default'] = Id2DTiledPixiTrack;

/***/ }),
/* 255 */
/***/ (function(module, exports, __nested_webpack_require_1345108__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_1345108__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _keys = __nested_webpack_require_1345108__(18);

var _keys2 = _interopRequireDefault(_keys);

var _set = __nested_webpack_require_1345108__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1345108__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1345108__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1345108__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1345108__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get3 = __nested_webpack_require_1345108__(14);

var _get4 = _interopRequireDefault(_get3);

var _inherits2 = __nested_webpack_require_1345108__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_1345108__(28);

var _TiledPixiTrack2 = __nested_webpack_require_1345108__(79);

var _TiledPixiTrack3 = _interopRequireDefault(_TiledPixiTrack2);

var _services = __nested_webpack_require_1345108__(24);

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

var BINS_PER_TILE = 1024;

var Tiled1DPixiTrack = function (_TiledPixiTrack) {
  (0, _inherits3['default'])(Tiled1DPixiTrack, _TiledPixiTrack);

  function Tiled1DPixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, Tiled1DPixiTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Tiled1DPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(Tiled1DPixiTrack)).call(this, context, options));

    var onMouseMoveZoom = context.onMouseMoveZoom,
        isValueScaleLocked = context.isValueScaleLocked,
        getLockGroupExtrema = context.getLockGroupExtrema;


    _this.onMouseMoveZoom = onMouseMoveZoom;
    _this.isValueScaleLocked = isValueScaleLocked;
    _this.getLockGroupExtrema = getLockGroupExtrema;

    if (_this.onMouseMoveZoom) {
      _this.pubSubs.push(_this.pubSub.subscribe('app.mouseMove', _this.mouseMoveHandler.bind(_this)));
    }
    return _this;
  }

  (0, _createClass3['default'])(Tiled1DPixiTrack, [{
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        /**
         * We don't need to do anything but draw the tile.
         *
         * Child classes that rely on transforming tiles when zooming
         * and panning can override this function to draw all the elements
         * that will later be transformed.
         */
        // this.drawTile(tile);
        (0, _get4['default'])(Tiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Tiled1DPixiTrack.prototype), 'initTile', this).call(this, tile);
      }

      return initTile;
    }()
  }, {
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        /*
         * The local tile identifier
         */

        // tile contains [zoomLevel, xPos]
        return '' + String(tile.join('.'));
      }

      return tileToLocalId;
    }()
  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        /**
         * The tile identifier used on the server
         */

        // tile contains [zoomLevel, xPos]
        return '' + String(tile.join('.'));
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'relevantScale',
    value: function () {
      function relevantScale() {
        /**
         * Which scale should we use for calculating tile positions?
         *
         * Horizontal tracks should use the xScale and vertical tracks
         * should use the yScale
         *
         * This function should be overwritten by HorizontalTiled1DPixiTrack.js
         * and VerticalTiled1DPixiTrack.js
         */
        return null;
      }

      return relevantScale;
    }()
  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this2 = this;

        /**
         * Set which tiles are visible right now.
         *
         * @param tiles: A set of tiles which will be considered the currently visible
         * tile positions.
         */
        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this2.tileToLocalId(x),
            remoteId: _this2.tileToRemoteId(x)
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.tileId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        var _this3 = this;

        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        // calculate the zoom level given the scales and the data bounds
        this.zoomLevel = this.calculateZoomLevel();

        if (this.tilesetInfo.resolutions) {
          var sortedResolutions = this.tilesetInfo.resolutions.map(function (x) {
            return +x;
          }).sort(function (a, b) {
            return b - a;
          });

          var _xTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);

          var _tiles = _xTiles.map(function (x) {
            return [_this3.zoomLevel, x];
          });
          this.setVisibleTiles(_tiles);
          return;
        }

        // x doesn't necessary mean 'x' axis, it just refers to the relevant axis
        // (x if horizontal, y if vertical)
        var xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this.relevantScale(), this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        var tiles = xTiles.map(function (x) {
          return [_this3.zoomLevel, x];
        });
        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'getTilePosAndDimensions',
    value: function () {
      function getTilePosAndDimensions(zoomLevel, tilePos, binsPerTileIn) {
        /**
         * Get the tile's position in its coordinate system.
         */
        var xTilePos = tilePos[0];
        var yTilePos = tilePos[0];

        if (this.tilesetInfo.resolutions) {
          // the default bins per tile which should
          // not be used because the right value should be in the tileset info

          var binsPerTile = binsPerTileIn || BINS_PER_TILE;

          var sortedResolutions = this.tilesetInfo.resolutions.map(function (x) {
            return +x;
          }).sort(function (a, b) {
            return b - a;
          });

          var chosenResolution = sortedResolutions[zoomLevel];

          var _tileWidth = chosenResolution * binsPerTile;
          var _tileHeight = _tileWidth;

          var _tileX = chosenResolution * binsPerTile * tilePos[0];
          var _tileY = chosenResolution * binsPerTile * tilePos[1];

          return {
            tileX: _tileX,
            tileY: _tileY,
            tileWidth: _tileWidth,
            tileHeight: _tileHeight
          };
        }

        // max_width should be substitutable with 2 ** tilesetInfo.max_zoom
        var totalWidth = this.tilesetInfo.max_width;
        var totalHeight = this.tilesetInfo.max_width;

        var minX = this.tilesetInfo.min_pos[0];
        var minY = this.tilesetInfo.min_pos[1];

        var tileWidth = totalWidth / Math.pow(2, zoomLevel);
        var tileHeight = totalHeight / Math.pow(2, zoomLevel);

        var tileX = minX + xTilePos * tileWidth;
        var tileY = minY + yTilePos * tileHeight;

        return {
          tileX: tileX,
          tileY: tileY,
          tileWidth: tileWidth,
          tileHeight: tileHeight
        };
      }

      return getTilePosAndDimensions;
    }()
  }, {
    key: 'updateTile',
    value: function () {
      function updateTile(tile) {
        // no need to redraw this tile, usually
        // unless the data scale changes or something like that
      }

      return updateTile;
    }()
  }, {
    key: 'scheduleRerender',
    value: function () {
      function scheduleRerender() {
        this.backgroundTaskScheduler.enqueueTask(this.handleRerender.bind(this), null, this.uuid);
      }

      return scheduleRerender;
    }()
  }, {
    key: 'handleRerender',
    value: function () {
      function handleRerender() {
        this.rerender(this.options, false);
      }

      return handleRerender;
    }()
  }, {
    key: 'getIndicesOfVisibleDataInTile',
    value: function () {
      function getIndicesOfVisibleDataInTile(tile) {
        var visible = this._xScale.range();

        if (!this.tilesetInfo) return [null, null];

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos, this.tilesetInfo.bins_per_dimension || this.tilesetInfo.tile_size),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, this.tilesetInfo.tile_size || this.tilesetInfo.bins_per_dimension]).range([tileX, tileX + tileWidth]);

        var start = Math.max(0, Math.round(tileXScale.invert(this._xScale.invert(visible[0]))));
        var end = Math.min(tile.tileData.dense.length, Math.round(tileXScale.invert(this._xScale.invert(visible[1]))));

        return [start, end];
      }

      return getIndicesOfVisibleDataInTile;
    }()

    /**
     * Returns the minimum in the visible area (not visible tiles)
     */

  }, {
    key: 'minVisibleValue',
    value: function () {
      function minVisibleValue() {
        var _this4 = this;

        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var minimumsPerTile = visibleAndFetchedIds.map(function (x) {
          return _this4.fetchedTiles[x];
        }).map(function (tile) {
          var ind = _this4.getIndicesOfVisibleDataInTile(tile);
          return tile.tileData.denseDataExtrema.getMinNonZeroInSubset(ind);
        });

        var min = Math.min.apply(Math, (0, _toConsumableArray3['default'])(minimumsPerTile));

        if (ignoreFixedScale) return min;

        return this.valueScaleMin !== null ? this.valueScaleMin : min;
      }

      return minVisibleValue;
    }()

    /**
     * Returns the maximum in the visible area (not visible tiles)
     */

  }, {
    key: 'maxVisibleValue',
    value: function () {
      function maxVisibleValue() {
        var _this5 = this;

        var ignoreFixedScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var maximumsPerTile = visibleAndFetchedIds.map(function (x) {
          return _this5.fetchedTiles[x];
        }).map(function (tile) {
          var ind = _this5.getIndicesOfVisibleDataInTile(tile);
          return tile.tileData.denseDataExtrema.getMaxNonZeroInSubset(ind);
        });

        var max = Math.max.apply(Math, (0, _toConsumableArray3['default'])(maximumsPerTile));

        if (ignoreFixedScale) return max;

        return this.valueScaleMax !== null ? this.valueScaleMax : max;
      }

      return maxVisibleValue;
    }()

    /**
     * Return an aggregated visible value. For example, the minimum or maximum.
     *
     * @description
     *   The difference to `minVisibleValueInTiles`
     *   is that the truly visible min or max value is returned instead of the
     *   min or max value of the tile. The latter is not necessarily visible.
     *
     *   For 'min' and 'max' this is identical to minVisibleValue and maxVisibleValue
     *
     * @param  {string} aggregator Aggregation method. Currently supports `min`
     *   and `max` only.
     * @return {number} The aggregated value.
     */

  }, {
    key: 'getAggregatedVisibleValue',
    value: function () {
      function getAggregatedVisibleValue() {
        var _this6 = this;

        var aggregator = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'max';

        var aggregate = aggregator === 'min' ? Math.min : Math.max;
        var limit = aggregator === 'min' ? Infinity : -Infinity;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var visible = this._xScale.range();

        return visibleAndFetchedIds.map(function (x) {
          return _this6.fetchedTiles[x];
        }).map(function (tile) {
          if (!tile.tileData.tilePos) {
            return aggregator === 'min' ? _this6.minVisibleValue() : _this6.maxVisibleValue();
          }

          var _getTilePosAndDimensi2 = _this6.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos, _this6.tilesetInfo.bins_per_dimension || _this6.tilesetInfo.tile_size),
              tileX = _getTilePosAndDimensi2.tileX,
              tileWidth = _getTilePosAndDimensi2.tileWidth;

          var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, _this6.tilesetInfo.tile_size || _this6.tilesetInfo.bins_per_dimension]).range([tileX, tileX + tileWidth]);

          var start = Math.max(0, Math.round(tileXScale.invert(_this6._xScale.invert(visible[0]))));
          var end = Math.min(tile.tileData.dense.length, Math.round(tileXScale.invert(_this6._xScale.invert(visible[1]))));

          return tile.tileData.dense.slice(start, end);
        }).reduce(function (smallest, current) {
          return aggregate.apply(undefined, [smallest].concat((0, _toConsumableArray3['default'])(current)));
        }, limit);
      }

      return getAggregatedVisibleValue;
    }()

    /**
     * Get the data value at a relative pixel position
     * @param   {number}  relPos  Relative pixel position, where 0 indicates the
     *   start of the track
     * @return  {number}  The data value at `relPos`
     */

  }, {
    key: 'getDataAtPos',
    value: function () {
      function getDataAtPos(relPos) {
        var value = void 0;

        if (!this.tilesetInfo) return value;

        var zoomLevel = this.calculateZoomLevel();
        var tileWidth = _services.tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

        // console.log('dataPos:', this._xScale.invert(relPos));

        var tilePos = this._xScale.invert(relPos) / tileWidth;
        var tileId = this.tileToLocalId([zoomLevel, Math.floor(tilePos)]);
        var fetchedTile = this.fetchedTiles[tileId];

        if (!fetchedTile) return value;

        var posInTileX = this.tilesetInfo.tile_size * (tilePos - Math.floor(tilePos));

        if (fetchedTile.tileData.dense) {
          // gene annotation tracks, for example, don't have dense
          // data
          return fetchedTile.tileData.dense[Math.floor(posInTileX)];
        }

        return null;
      }

      return getDataAtPos;
    }()
  }, {
    key: 'mouseMoveHandler',
    value: function () {
      function mouseMoveHandler() {
        var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            x = _ref.x,
            y = _ref.y;

        if (!this.isWithin(x, y)) return;

        this.mouseX = x;
        this.mouseY = y;

        this.mouseMoveZoomHandler();
      }

      return mouseMoveHandler;
    }()
  }, {
    key: 'mouseMoveZoomHandler',
    value: function () {
      function mouseMoveZoomHandler() {
        // Implemented in the horizontal and vertical sub-classes
      }

      return mouseMoveZoomHandler;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed() {
        var _get2;

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

        (_get2 = (0, _get4['default'])(Tiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Tiled1DPixiTrack.prototype), 'zoomed', this)).call.apply(_get2, [this].concat(args));
        this.mouseMoveZoomHandler();
      }

      return zoomed;
    }()
  }]);
  return Tiled1DPixiTrack;
}(_TiledPixiTrack3['default']);

exports['default'] = Tiled1DPixiTrack;

/***/ }),
/* 256 */
/***/ (function(module, exports, __nested_webpack_require_1362076__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_1362076__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _toConsumableArray2 = __nested_webpack_require_1362076__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _keys = __nested_webpack_require_1362076__(18);

var _keys2 = _interopRequireDefault(_keys);

var _set = __nested_webpack_require_1362076__(38);

var _set2 = _interopRequireDefault(_set);

var _classCallCheck2 = __nested_webpack_require_1362076__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1362076__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _slugid = __nested_webpack_require_1362076__(26);

var _slugid2 = _interopRequireDefault(_slugid);

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

var CombinedTrack = function () {
  function CombinedTrack(_ref) {
    var _this = this;

    var tracks = _ref.tracks,
        createTrackObject = _ref.createTrackObject;
    (0, _classCallCheck3['default'])(this, CombinedTrack);

    this.childTracks = tracks.map(createTrackObject);
    this.createdTracks = {};
    this.uid = _slugid2['default'].nice();

    this.childTracks.forEach(function (ct, i) {
      _this.createdTracks[tracks[i].uid] = ct;
    });

    for (var i = 0; i < this.childTracks.length; i++) {
      if (!this.childTracks[i]) {
        console.error('Empty child track in CombinedTrack:', this);
      }
    }
  }

  (0, _createClass3['default'])(CombinedTrack, [{
    key: 'updateContents',
    value: function () {
      function updateContents(newContents, trackCreator) {
        var _this2 = this;

        var newTracks = [];
        var currentTracks = new _set2['default']();

        // go through the new track list and create tracks which we don't
        // already have
        newContents.forEach(function (nc) {
          currentTracks.add(nc.uid);

          if (nc.uid in _this2.createdTracks) {
            newTracks.push(_this2.createdTracks[nc.uid]);
          } else {
            var newTrack = trackCreator(nc);
            newTrack.setPosition(_this2.position);
            newTrack.setDimensions(_this2.dimensions);
            newTracks.push(newTrack);

            newTrack.zoomed(_this2._xScale, _this2._yScale);

            _this2.createdTracks[nc.uid] = newTrack;
          }
        });

        this.childTracks = newTracks;

        // remove the ones that were previously, but no longer, present
        var knownTracks = new _set2['default']((0, _keys2['default'])(this.createdTracks));
        var exitTracks = new _set2['default']([].concat((0, _toConsumableArray3['default'])(knownTracks)).filter(function (x) {
          return !currentTracks.has(x);
        }));
        [].concat((0, _toConsumableArray3['default'])(exitTracks)).forEach(function (trackUid) {
          _this2.createdTracks[trackUid].remove();
          delete _this2.createdTracks[trackUid];
        });

        return this;
      }

      return updateContents;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        /**
         * Setting the position of this track simply means setting the positions
         * of its children.
         */
        this.position = newPosition;

        for (var i = 0; i < this.childTracks.length; i++) {
          this.childTracks[i].setPosition(newPosition);
        }
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        this.dimensions = newDimensions;

        for (var i = 0; i < this.childTracks.length; i++) {
          this.childTracks[i].setDimensions(newDimensions);
        }
      }

      return setDimensions;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, x, y, xPositionOffset, yPositionOffset) {
        this._xScale = newXScale;
        this._yScale = newYScale;

        for (var i = 0; i < this.childTracks.length; i++) {
          // console.log('childTracks.zoomed', this.childTracks[i].zoomed);
          this.childTracks[i].zoomed(newXScale, newYScale, k, x, y, xPositionOffset, yPositionOffset);
        }
      }

      return zoomed;
    }()

    // refXScale(xScale) {
    //   for (let i = 0; i < this.childTracks.length; i++) {
    //     this.childTracks[i].refXScale(xScale);
    //   }
    // }

    // refYScale(yScale) {
    //   for (let i = 0; i < this.childTracks.length; i++) {
    //     this.childTracks[i].refYScale(yScale);
    //   }
    // }

  }, {
    key: 'draw',
    value: function () {
      function draw() {}
      // for (let i = 0; i < this.childTracks.length; i++) {
      //   this.childTracks[i].draw();
      // }


      // xScale(xScale) {
      //   this._xScale = xScale;

      //   for (let i = 0; i < this.childTracks.length; i++) {
      //     this.childTracks[i].xScale(xScale);
      //   }
      // }

      // yScale(xScale) {
      //   this._yScale = yScale;

      //   for (let i = 0; i < this.childTracks.length; i++) {
      //     this.childTracks[i].yScale(yScale);
      //   }
      // }

      return draw;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        for (var i = 0; i < this.childTracks.length; i++) {
          this.childTracks[i].refScalesChanged(refXScale, refYScale);
        }
      }

      return refScalesChanged;
    }()
  }, {
    key: 'remove',
    value: function () {
      function remove() {
        for (var i = 0; i < this.childTracks.length; i++) {
          this.childTracks[i].remove();
        }
      }

      return remove;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var svg = document.createElement('g');

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(this.childTracks), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var childTrack = _step.value;

            if (childTrack.exportSVG) {
              // exportSVG returns a tuple containing the base element
              // and the element onto which to draw extra features
              // in our case, we only need the complete svg
              svg.appendChild(childTrack.exportSVG()[0]);
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        return [svg, svg];
      }

      return exportSVG;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options) {
        // console.log('COMBINED TRACK rerender...');
      }

      return rerender;
    }()
  }, {
    key: 'minValue',
    value: function () {
      function minValue(_) {
        if (arguments.length === 0) {
          var minValues = this.childTracks.filter(function (x) {
            return x.minValue;
          }) // filter for tracks which have the minValue function
          .map(function (x) {
            return x.minValue();
          }) // get the minValue for each track
          .filter(function (x) {
            return x;
          }); // filter out undefineds

          return Math.min.apply(Math, (0, _toConsumableArray3['default'])(minValues));
        }
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])(this.childTracks), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var childTrack = _step2.value;

            if (childTrack.minValue) {
              childTrack.minValue(_);
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        return undefined;
      }

      return minValue;
    }()
  }, {
    key: 'maxValue',
    value: function () {
      function maxValue(_) {
        if (arguments.length === 0) {
          var maxValues = this.childTracks.filter(function (x) {
            return x.maxValue;
          }) // filter for tracks which have the minValue function
          .map(function (x) {
            return x.maxValue();
          }) // get the minValue for each track
          .filter(function (x) {
            return x;
          }); // filter out undefineds

          return Math.max.apply(Math, (0, _toConsumableArray3['default'])(maxValues));
        }
        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = undefined;

        try {
          for (var _iterator3 = (0, _getIterator3['default'])(this.childTracks), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
            var childTrack = _step3.value;

            if (childTrack.maxValue) {
              childTrack.maxValue(_);
            }
          }
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3['return']) {
              _iterator3['return']();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }

        return undefined;
      }

      return maxValue;
    }()
  }, {
    key: 'respondsToPosition',
    value: function () {
      function respondsToPosition(x, y) {
        return x >= this.position[0] && x <= this.dimensions[0] + this.position[0] && y >= this.position[1] && y <= this.dimensions[1] + this.position[1];
      }

      return respondsToPosition;
    }()
  }, {
    key: 'stopHover',
    value: function () {
      function stopHover() {
        var _iteratorNormalCompletion4 = true;
        var _didIteratorError4 = false;
        var _iteratorError4 = undefined;

        try {
          for (var _iterator4 = (0, _getIterator3['default'])(this.childTracks), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
            var childTrack = _step4.value;

            if (childTrack.stopHover) childTrack.stopHover();
          }
        } catch (err) {
          _didIteratorError4 = true;
          _iteratorError4 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion4 && _iterator4['return']) {
              _iterator4['return']();
            }
          } finally {
            if (_didIteratorError4) {
              throw _iteratorError4;
            }
          }
        }
      }

      return stopHover;
    }()
  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX, trackY) {
        var mouseOverHtml = '';

        var _iteratorNormalCompletion5 = true;
        var _didIteratorError5 = false;
        var _iteratorError5 = undefined;

        try {
          for (var _iterator5 = (0, _getIterator3['default'])(this.childTracks), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
            var childTrack = _step5.value;

            if (childTrack.getMouseOverHtml) {
              var trackHtml = childTrack.getMouseOverHtml(trackX, trackY);

              if (trackHtml && trackHtml.length) {
                mouseOverHtml += trackHtml;
                mouseOverHtml += '<br/>';
              }
            }
          }
        } catch (err) {
          _didIteratorError5 = true;
          _iteratorError5 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion5 && _iterator5['return']) {
              _iterator5['return']();
            }
          } finally {
            if (_didIteratorError5) {
              throw _iteratorError5;
            }
          }
        }

        return mouseOverHtml;
      }

      return getMouseOverHtml;
    }()
  }]);
  return CombinedTrack;
}();

exports['default'] = CombinedTrack;

/***/ }),
/* 257 */
/***/ (function(module, exports, __nested_webpack_require_1375091__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global, Buffer) {

var bits = __nested_webpack_require_1375091__(258)
var dup = __nested_webpack_require_1375091__(620)

//Legacy pool support
if(!global.__TYPEDARRAY_POOL) {
  global.__TYPEDARRAY_POOL = {
      UINT8   : dup([32, 0])
    , UINT16  : dup([32, 0])
    , UINT32  : dup([32, 0])
    , INT8    : dup([32, 0])
    , INT16   : dup([32, 0])
    , INT32   : dup([32, 0])
    , FLOAT   : dup([32, 0])
    , DOUBLE  : dup([32, 0])
    , DATA    : dup([32, 0])
    , UINT8C  : dup([32, 0])
    , BUFFER  : dup([32, 0])
  }
}

var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined'
var POOL = global.__TYPEDARRAY_POOL

//Upgrade pool
if(!POOL.UINT8C) {
  POOL.UINT8C = dup([32, 0])
}
if(!POOL.BUFFER) {
  POOL.BUFFER = dup([32, 0])
}

//New technique: Only allocate from ArrayBufferView and Buffer
var DATA    = POOL.DATA
  , BUFFER  = POOL.BUFFER

exports.free = function free(array) {
  if(Buffer.isBuffer(array)) {
    BUFFER[bits.log2(array.length)].push(array)
  } else {
    if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') {
      array = array.buffer
    }
    if(!array) {
      return
    }
    var n = array.length || array.byteLength
    var log_n = bits.log2(n)|0
    DATA[log_n].push(array)
  }
}

function freeArrayBuffer(buffer) {
  if(!buffer) {
    return
  }
  var n = buffer.length || buffer.byteLength
  var log_n = bits.log2(n)
  DATA[log_n].push(buffer)
}

function freeTypedArray(array) {
  freeArrayBuffer(array.buffer)
}

exports.freeUint8 =
exports.freeUint16 =
exports.freeUint32 =
exports.freeInt8 =
exports.freeInt16 =
exports.freeInt32 =
exports.freeFloat32 = 
exports.freeFloat =
exports.freeFloat64 = 
exports.freeDouble = 
exports.freeUint8Clamped = 
exports.freeDataView = freeTypedArray

exports.freeArrayBuffer = freeArrayBuffer

exports.freeBuffer = function freeBuffer(array) {
  BUFFER[bits.log2(array.length)].push(array)
}

exports.malloc = function malloc(n, dtype) {
  if(dtype === undefined || dtype === 'arraybuffer') {
    return mallocArrayBuffer(n)
  } else {
    switch(dtype) {
      case 'uint8':
        return mallocUint8(n)
      case 'uint16':
        return mallocUint16(n)
      case 'uint32':
        return mallocUint32(n)
      case 'int8':
        return mallocInt8(n)
      case 'int16':
        return mallocInt16(n)
      case 'int32':
        return mallocInt32(n)
      case 'float':
      case 'float32':
        return mallocFloat(n)
      case 'double':
      case 'float64':
        return mallocDouble(n)
      case 'uint8_clamped':
        return mallocUint8Clamped(n)
      case 'buffer':
        return mallocBuffer(n)
      case 'data':
      case 'dataview':
        return mallocDataView(n)

      default:
        return null
    }
  }
  return null
}

function mallocArrayBuffer(n) {
  var n = bits.nextPow2(n)
  var log_n = bits.log2(n)
  var d = DATA[log_n]
  if(d.length > 0) {
    return d.pop()
  }
  return new ArrayBuffer(n)
}
exports.mallocArrayBuffer = mallocArrayBuffer

function mallocUint8(n) {
  return new Uint8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocUint8 = mallocUint8

function mallocUint16(n) {
  return new Uint16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocUint16 = mallocUint16

function mallocUint32(n) {
  return new Uint32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocUint32 = mallocUint32

function mallocInt8(n) {
  return new Int8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocInt8 = mallocInt8

function mallocInt16(n) {
  return new Int16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocInt16 = mallocInt16

function mallocInt32(n) {
  return new Int32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocInt32 = mallocInt32

function mallocFloat(n) {
  return new Float32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocFloat32 = exports.mallocFloat = mallocFloat

function mallocDouble(n) {
  return new Float64Array(mallocArrayBuffer(8*n), 0, n)
}
exports.mallocFloat64 = exports.mallocDouble = mallocDouble

function mallocUint8Clamped(n) {
  if(hasUint8C) {
    return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n)
  } else {
    return mallocUint8(n)
  }
}
exports.mallocUint8Clamped = mallocUint8Clamped

function mallocDataView(n) {
  return new DataView(mallocArrayBuffer(n), 0, n)
}
exports.mallocDataView = mallocDataView

function mallocBuffer(n) {
  n = bits.nextPow2(n)
  var log_n = bits.log2(n)
  var cache = BUFFER[log_n]
  if(cache.length > 0) {
    return cache.pop()
  }
  return new Buffer(n)
}
exports.mallocBuffer = mallocBuffer

exports.clearCache = function clearCache() {
  for(var i=0; i<32; ++i) {
    POOL.UINT8[i].length = 0
    POOL.UINT16[i].length = 0
    POOL.UINT32[i].length = 0
    POOL.INT8[i].length = 0
    POOL.INT16[i].length = 0
    POOL.INT32[i].length = 0
    POOL.FLOAT[i].length = 0
    POOL.DOUBLE[i].length = 0
    POOL.UINT8C[i].length = 0
    DATA[i].length = 0
    BUFFER[i].length = 0
  }
}
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1375091__(27), __nested_webpack_require_1375091__(113).Buffer))

/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Bit twiddling hacks for JavaScript.
 *
 * Author: Mikola Lysenko
 *
 * Ported from Stanford bit twiddling hack library:
 *    http://graphics.stanford.edu/~seander/bithacks.html
 */

 "use restrict";

//Number of bits in an integer
var INT_BITS = 32;

//Constants
exports.INT_BITS  = INT_BITS;
exports.INT_MAX   =  0x7fffffff;
exports.INT_MIN   = -1<<(INT_BITS-1);

//Returns -1, 0, +1 depending on sign of x
exports.sign = function(v) {
  return (v > 0) - (v < 0);
}

//Computes absolute value of integer
exports.abs = function(v) {
  var mask = v >> (INT_BITS-1);
  return (v ^ mask) - mask;
}

//Computes minimum of integers x and y
exports.min = function(x, y) {
  return y ^ ((x ^ y) & -(x < y));
}

//Computes maximum of integers x and y
exports.max = function(x, y) {
  return x ^ ((x ^ y) & -(x < y));
}

//Checks if a number is a power of two
exports.isPow2 = function(v) {
  return !(v & (v-1)) && (!!v);
}

//Computes log base 2 of v
exports.log2 = function(v) {
  var r, shift;
  r =     (v > 0xFFFF) << 4; v >>>= r;
  shift = (v > 0xFF  ) << 3; v >>>= shift; r |= shift;
  shift = (v > 0xF   ) << 2; v >>>= shift; r |= shift;
  shift = (v > 0x3   ) << 1; v >>>= shift; r |= shift;
  return r | (v >> 1);
}

//Computes log base 10 of v
exports.log10 = function(v) {
  return  (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
          (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
          (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
}

//Counts number of bits
exports.popCount = function(v) {
  v = v - ((v >>> 1) & 0x55555555);
  v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
  return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
}

//Counts number of trailing zeros
function countTrailingZeros(v) {
  var c = 32;
  v &= -v;
  if (v) c--;
  if (v & 0x0000FFFF) c -= 16;
  if (v & 0x00FF00FF) c -= 8;
  if (v & 0x0F0F0F0F) c -= 4;
  if (v & 0x33333333) c -= 2;
  if (v & 0x55555555) c -= 1;
  return c;
}
exports.countTrailingZeros = countTrailingZeros;

//Rounds to next power of 2
exports.nextPow2 = function(v) {
  v += v === 0;
  --v;
  v |= v >>> 1;
  v |= v >>> 2;
  v |= v >>> 4;
  v |= v >>> 8;
  v |= v >>> 16;
  return v + 1;
}

//Rounds down to previous power of 2
exports.prevPow2 = function(v) {
  v |= v >>> 1;
  v |= v >>> 2;
  v |= v >>> 4;
  v |= v >>> 8;
  v |= v >>> 16;
  return v - (v>>>1);
}

//Computes parity of word
exports.parity = function(v) {
  v ^= v >>> 16;
  v ^= v >>> 8;
  v ^= v >>> 4;
  v &= 0xf;
  return (0x6996 >>> v) & 1;
}

var REVERSE_TABLE = new Array(256);

(function(tab) {
  for(var i=0; i<256; ++i) {
    var v = i, r = i, s = 7;
    for (v >>>= 1; v; v >>>= 1) {
      r <<= 1;
      r |= v & 1;
      --s;
    }
    tab[i] = (r << s) & 0xff;
  }
})(REVERSE_TABLE);

//Reverse bits in a 32 bit word
exports.reverse = function(v) {
  return  (REVERSE_TABLE[ v         & 0xff] << 24) |
          (REVERSE_TABLE[(v >>> 8)  & 0xff] << 16) |
          (REVERSE_TABLE[(v >>> 16) & 0xff] << 8)  |
           REVERSE_TABLE[(v >>> 24) & 0xff];
}

//Interleave bits of 2 coordinates with 16 bits.  Useful for fast quadtree codes
exports.interleave2 = function(x, y) {
  x &= 0xFFFF;
  x = (x | (x << 8)) & 0x00FF00FF;
  x = (x | (x << 4)) & 0x0F0F0F0F;
  x = (x | (x << 2)) & 0x33333333;
  x = (x | (x << 1)) & 0x55555555;

  y &= 0xFFFF;
  y = (y | (y << 8)) & 0x00FF00FF;
  y = (y | (y << 4)) & 0x0F0F0F0F;
  y = (y | (y << 2)) & 0x33333333;
  y = (y | (y << 1)) & 0x55555555;

  return x | (y << 1);
}

//Extracts the nth interleaved component
exports.deinterleave2 = function(v, n) {
  v = (v >>> n) & 0x55555555;
  v = (v | (v >>> 1))  & 0x33333333;
  v = (v | (v >>> 2))  & 0x0F0F0F0F;
  v = (v | (v >>> 4))  & 0x00FF00FF;
  v = (v | (v >>> 16)) & 0x000FFFF;
  return (v << 16) >> 16;
}


//Interleave bits of 3 coordinates, each with 10 bits.  Useful for fast octree codes
exports.interleave3 = function(x, y, z) {
  x &= 0x3FF;
  x  = (x | (x<<16)) & 4278190335;
  x  = (x | (x<<8))  & 251719695;
  x  = (x | (x<<4))  & 3272356035;
  x  = (x | (x<<2))  & 1227133513;

  y &= 0x3FF;
  y  = (y | (y<<16)) & 4278190335;
  y  = (y | (y<<8))  & 251719695;
  y  = (y | (y<<4))  & 3272356035;
  y  = (y | (y<<2))  & 1227133513;
  x |= (y << 1);
  
  z &= 0x3FF;
  z  = (z | (z<<16)) & 4278190335;
  z  = (z | (z<<8))  & 251719695;
  z  = (z | (z<<4))  & 3272356035;
  z  = (z | (z<<2))  & 1227133513;
  
  return x | (z << 2);
}

//Extracts nth interleaved component of a 3-tuple
exports.deinterleave3 = function(v, n) {
  v = (v >>> n)       & 1227133513;
  v = (v | (v>>>2))   & 3272356035;
  v = (v | (v>>>4))   & 251719695;
  v = (v | (v>>>8))   & 4278190335;
  v = (v | (v>>>16))  & 0x3FF;
  return (v<<22)>>22;
}

//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
exports.nextCombination = function(v) {
  var t = v | (v - 1);
  return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));
}



/***/ }),
/* 259 */
/***/ (function(module, exports, __nested_webpack_require_1385297__) {

"use strict";


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

var _values = __nested_webpack_require_1385297__(37);

var _values2 = _interopRequireDefault(_values);

var _isNan = __nested_webpack_require_1385297__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _slicedToArray2 = __nested_webpack_require_1385297__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_1385297__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1385297__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1385297__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1385297__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1385297__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1385297__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_1385297__(28);

var _d3Zoom = __nested_webpack_require_1385297__(157);

var _HorizontalLine1DPixiTrack = __nested_webpack_require_1385297__(116);

var _HorizontalLine1DPixiTrack2 = _interopRequireDefault(_HorizontalLine1DPixiTrack);

var _configs = __nested_webpack_require_1385297__(11);

var _utils = __nested_webpack_require_1385297__(10);

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

// Configs
var HEX_WHITE = (0, _utils.colorToHex)('#FFFFFF');

// Utils

var BarTrack = function (_HorizontalLine1DPixi) {
  (0, _inherits3['default'])(BarTrack, _HorizontalLine1DPixi);

  function BarTrack() {
    var _ref;

    (0, _classCallCheck3['default'])(this, BarTrack);

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

    var _this = (0, _possibleConstructorReturn3['default'])(this, (_ref = BarTrack.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack)).call.apply(_ref, [this].concat(args)));

    _this.zeroLine = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMain.addChild(_this.zeroLine);
    _this.valueScaleTransform = _d3Zoom.zoomIdentity;

    if (_this.options && _this.options.colorRange) {
      if (_this.options.colorRangeGradient) {
        _this.setColorGradient(_this.options.colorRange);
      } else {
        _this.setColorScale(_this.options.colorRange);
      }
    }

    _this.initialized = true;
    return _this;
  }

  (0, _createClass3['default'])(BarTrack, [{
    key: 'setColorScale',
    value: function () {
      function setColorScale(colorRange) {
        if (!colorRange) return;

        this.colorScale = (0, _utils.colorDomainToRgbaArray)(colorRange);

        // Normalize colormap upfront to save 3 divisions per data point during the
        // rendering.
        this.colorScale = this.colorScale.map(function (rgb) {
          return rgb.map(function (channel) {
            return channel / 255.0;
          });
        });
      }

      return setColorScale;
    }()
  }, {
    key: 'setColorGradient',
    value: function () {
      function setColorGradient(colorGradient) {
        if (!colorGradient) return;

        var N = colorGradient.length - 1;

        this.colorGradientColors = this.options.align === 'bottom' ? colorGradient.slice().reverse().map(function (color, i) {
          return { from: i / N, color: color };
        }) : colorGradient.map(function (color, i) {
          return { from: i / N, color: color };
        });
      }

      return setColorGradient;
    }()

    /**
     * Create whatever is needed to draw this tile.
     */

  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        if (!this.initialized) return;
        (0, _get3['default'])(BarTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack.prototype), 'initTile', this).call(this, tile);
      }

      return initTile;
    }()
  }, {
    key: 'updateTile',
    value: function () {
      function updateTile(tile) {
        if (!tile.valueScale || !this.scale || this.scale.minValue !== tile.scale.minValue || this.scale.maxValue !== tile.scale.maxValue) {
          // not rendered using the current scale, so we need to rerender
          this.renderTile(tile);
        }
      }

      return updateTile;
    }()
  }, {
    key: 'renderTile',
    value: function () {
      function renderTile(tile) {
        if (!this.initialized) return;
        (0, _get3['default'])(BarTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack.prototype), 'renderTile', this).call(this, tile);
      }

      return renderTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        if (!tile.graphics) return;

        if (!tile.tileData || !tile.tileData.dense) {
          return;
        }

        var graphics = tile.graphics;

        // Reset svg data to avoid overplotting

        tile.svgData = undefined;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos, this.tilesetInfo.bins_per_dimension || this.tilesetInfo.tile_size),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileValues = tile.tileData.dense;

        if (tileValues.length === 0) return;

        var _makeValueScale = this.makeValueScale(this.minValue(), this.medianVisibleValue, this.maxValue(), 0),
            _makeValueScale2 = (0, _slicedToArray3['default'])(_makeValueScale, 2),
            valueScale = _makeValueScale2[0],
            pseudocount = _makeValueScale2[1];

        // Important when when using `options.valueScaleMin` or
        // `options.valueScaleMax` such that the y position later on doesn't become
        // negative


        valueScale.clamp(true);

        this.valueScale = valueScale;

        var colorScale = valueScale.copy();
        colorScale.range([254, 0]).clamp(true);

        graphics.clear();

        this.drawAxis(this.valueScale);

        if (this.options.valueScaling === 'log' && this.valueScale.domain()[1] < 0) {
          console.warn('Negative values present when using a log scale', this.valueScale.domain());
          return;
        }

        var stroke = (0, _utils.colorToHex)(this.options.lineStrokeColor || 'blue');

        // this scale should go from an index in the data array to
        // a position in the genome coordinates
        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, this.tilesetInfo.tile_size || this.tilesetInfo.bins_per_dimension]).range([tileX, tileX + tileWidth]);

        var strokeWidth = 0;
        graphics.lineStyle(strokeWidth, stroke, 1);

        var color = this.options.barFillColor || 'grey';
        var colorHex = (0, _utils.colorToHex)(color);

        var opacity = 'barOpacity' in this.options ? this.options.barOpacity : 1;

        graphics.beginFill(colorHex, opacity);

        tile.drawnAtScale = this._xScale.copy();

        var isTopAligned = this.options.align === 'top';

        var xPos = void 0;
        var width = void 0;
        var yPos = void 0;
        var height = void 0;

        var barMask = void 0;
        var barSprite = void 0;
        if (this.colorGradientColors) {
          barMask = new _configs.GLOBALS.PIXI.Graphics();
          barMask.beginFill(HEX_WHITE, 1);

          var canvas = (0, _utils.gradient)(this.colorGradientColors, 1, this.dimensions[1], // width, height
          0, 0, 0, this.dimensions[1] // fromX, fromY, toX, toY
          );

          barSprite = new _configs.GLOBALS.PIXI.Sprite(_configs.GLOBALS.PIXI.Texture.fromCanvas(canvas, _configs.GLOBALS.PIXI.SCALE_MODES.NEAREST));

          barSprite.x = this._xScale(tileX);
          barSprite.width = this._xScale(tileX + tileWidth) - barSprite.x;
        }

        for (var i = 0; i < tileValues.length; i++) {
          xPos = this._xScale(tileXScale(i));
          yPos = this.valueScale(tileValues[i] + pseudocount);
          width = this._xScale(tileXScale(i + 1)) - xPos;
          height = this.dimensions[1] - yPos;

          if (isTopAligned) yPos = 0;

          if ((0, _isNan2['default'])(height) || height < 0 || yPos < 0) continue;
          this.addSVGInfo(tile, xPos, yPos, width, height, color);

          // this data is in the last tile and extends beyond the length
          // of the coordinate system
          if (tileXScale(i) > this.tilesetInfo.max_pos[0]) break;

          if (this.colorScale && !this.options.colorRangeGradient) {
            var rgbIdx = Math.round(colorScale(tileValues[i] + pseudocount));
            var rgb = this.colorScale[rgbIdx];
            var hex = _configs.GLOBALS.PIXI.utils.rgb2hex(rgb);
            graphics.beginFill(hex, opacity);
          }

          (barMask || graphics).drawRect(xPos, yPos, width, height);
        }

        if (this.colorGradientColors) {
          barSprite.mask = barMask;

          graphics.removeChildren();
          graphics.addChild(barSprite, barMask);
        }
      }

      return drawTile;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        if (options && options.colorRange) {
          if (options.colorRangeGradient) {
            this.setColorGradient(options.colorRange);
          } else {
            this.setColorScale(options.colorRange);
          }
        }

        (0, _get3['default'])(BarTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack.prototype), 'rerender', this).call(this, options, force);
      }

      return rerender;
    }()
  }, {
    key: 'drawZeroLine',
    value: function () {
      function drawZeroLine() {
        this.zeroLine.clear();

        var color = (0, _utils.colorToHex)(this.options.barFillColor || 'grey');
        var opacity = +this.options.barOpacity || 1;

        var demarcationColor = this.options.zeroLineColor ? (0, _utils.colorToHex)(this.options.zeroLineColor) : color;

        var demarcationOpacity = (0, _isNan2['default'])(+this.options.zeroLineOpacity) ? opacity : +this.options.zeroLineOpacity;

        this.zeroLine.beginFill(demarcationColor, demarcationOpacity);

        this.zeroLine.drawRect(0, this.dimensions[1] - 1, this.dimensions[0], 1);
      }

      return drawZeroLine;
    }()
  }, {
    key: 'drawZeroLineSvg',
    value: function () {
      function drawZeroLineSvg(output) {
        var zeroLine = document.createElement('rect');
        zeroLine.setAttribute('id', 'zero-line');

        zeroLine.setAttribute('x', 0);
        zeroLine.setAttribute('y', this.dimensions[1] - 1);
        zeroLine.setAttribute('height', 1);
        zeroLine.setAttribute('width', this.dimensions[0]);

        zeroLine.setAttribute('fill', this.options.zeroLineColor || this.options.barFillColor);
        zeroLine.setAttribute('fill-opacity', this.options.zeroLineOpacity || this.options.barOpacity);

        output.appendChild(zeroLine);
      }

      return drawZeroLineSvg;
    }()
  }, {
    key: 'getXScaleAndOffset',
    value: function () {
      function getXScaleAndOffset(drawnAtScale) {
        var dA = drawnAtScale.domain();
        var dB = this._xScale.domain();

        // scaling between tiles
        var tileK = (dA[1] - dA[0]) / (dB[1] - dB[0]);

        var newRange = this._xScale.domain().map(drawnAtScale);

        var posOffset = newRange[0];

        return [tileK, -posOffset * tileK];
      }

      return getXScaleAndOffset;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var _this2 = this;

        if (!this.initialized) return;

        // we don't want to call HorizontalLine1DPixiTrack's draw function
        // but rather its parent's
        (0, _get3['default'])(BarTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack.prototype), 'draw', this).call(this);

        if (this.options.zeroLineVisible) this.drawZeroLine();else this.zeroLine.clear();

        (0, _values2['default'])(this.fetchedTiles).forEach(function (tile) {
          var _getXScaleAndOffset = _this2.getXScaleAndOffset(tile.drawnAtScale),
              _getXScaleAndOffset2 = (0, _slicedToArray3['default'])(_getXScaleAndOffset, 2),
              graphicsXScale = _getXScaleAndOffset2[0],
              graphicsXPos = _getXScaleAndOffset2[1];

          tile.graphics.scale.x = graphicsXScale;
          tile.graphics.position.x = graphicsXPos;
        });
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        (0, _get3['default'])(BarTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);
      }

      return zoomed;
    }()
  }, {
    key: 'movedY',
    value: function () {
      function movedY(dY) {
        // // see the reasoning behind why the code in
        // // zoomedY is commented out.
        // Object.values(this.fetchedTiles).forEach((tile) => {
        //   const vst = this.valueScaleTransform;
        //   const { y, k } = vst;
        //   const height = this.dimensions[1];
        //   // clamp at the bottom and top
        //   if (
        //     y + dY / k > -(k - 1) * height
        //     && y + dY / k < 0
        //   ) {
        //     this.valueScaleTransform = vst.translate(
        //       0, dY / k
        //     );
        //   }
        //   tile.graphics.position.y = this.valueScaleTransform.y;
        // });
        // this.animate();
      }

      return movedY;
    }()
  }, {
    key: 'zoomedY',
    value: function () {
      function zoomedY(yPos, kMultiplier) {}
      // // this is commented out to serve as an example
      // // of how valueScale zooming works
      // // dont' want to support it just yet though
      // const k0 = this.valueScaleTransform.k;
      // const t0 = this.valueScaleTransform.y;
      // const dp = (yPos - t0) / k0;
      // const k1 = Math.max(k0 / kMultiplier, 1.0);
      // let t1 = k0 * dp + t0 - k1 * dp;
      // const height = this.dimensions[1];
      // // clamp at the bottom
      // t1 = Math.max(t1, -(k1 - 1) * height);
      // // clamp at the top
      // t1 = Math.min(t1, 0);
      // // right now, the point at position 162 is at position 0
      // // 0 = 1 * 162 - 162
      // //
      // // we want that when k = 2, that point is still at position
      // // 0 = 2 * 162 - t1
      // //  ypos = k0 * dp + t0
      // //  dp = (ypos - t0) / k0
      // //  nypos = k1 * dp + t1
      // //  k1 * dp + t1 = k0 * dp + t0
      // //  t1 = k0 * dp +t0 - k1 * dp
      // // we're only interested in scaling along one axis so we
      // // leave the translation of the other axis blank
      // this.valueScaleTransform = zoomIdentity.translate(0, t1).scale(k1);
      // this.zoomedValueScale = this.valueScaleTransform.rescaleY(
      //   this.valueScale.clamp(false)
      // );
      // // this.pMain.scale.y = k1;
      // // this.pMain.position.y = t1;
      // Object.values(this.fetchedTiles).forEach((tile) => {
      //   tile.graphics.scale.y = k1;
      //   tile.graphics.position.y = t1;
      //   this.drawAxis(this.zoomedValueScale);
      // });
      // this.animate();


      /**
       * Adds information to recreate the track in SVG to the tile
       *
       * @param tile
       * @param x x value of bar
       * @param y y value of bar
       * @param width width of bar
       * @param height height of bar
       * @param color color of bar (not converted to hex)
       */


      return zoomedY;
    }()
  }, {
    key: 'addSVGInfo',
    value: function () {
      function addSVGInfo(tile, x, y, width, height, color) {
        if (tile.svgData) {
          tile.svgData.barXValues.push(x);
          tile.svgData.barYValues.push(y);
          tile.svgData.barWidths.push(width);
          tile.svgData.barHeights.push(height);
          tile.svgData.barColors.push(color);
        } else {
          tile.svgData = {
            barXValues: [x],
            barYValues: [y],
            barWidths: [width],
            barHeights: [height],
            barColors: [color]
          };
        }
      }

      return addSVGInfo;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        var _get$call = (0, _get3['default'])(BarTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BarTrack.prototype), 'superSVG', this).call(this);

        var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

        base = _get$call2[0];
        track = _get$call2[1];


        base.setAttribute('class', 'exported-line-track');
        var output = document.createElement('g');

        track.appendChild(output);
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        if (this.options.zeroLine) this.drawZeroLineSvg(output);

        this.visibleAndFetchedTiles().filter(function (tile) {
          return tile.svgData && tile.svgData.barXValues;
        }).forEach(function (tile) {
          // const [xScale, xPos] = this.getXScaleAndOffset(tile.drawnAtScale);
          var data = tile.svgData;

          for (var i = 0; i < data.barXValues.length; i++) {
            var rect = document.createElement('rect');
            rect.setAttribute('fill', data.barColors[i]);
            rect.setAttribute('stroke', data.barColors[i]);

            // rect.setAttribute('x', (data.barXValues[i] + xPos) * xScale);
            rect.setAttribute('x', data.barXValues[i]);
            rect.setAttribute('y', data.barYValues[i]);
            rect.setAttribute('height', data.barHeights[i]);
            rect.setAttribute('width', data.barWidths[i]);
            if (tile.barBorders) {
              rect.setAttribute('stroke-width', '0.1');
              rect.setAttribute('stroke', 'black');
            }

            output.appendChild(rect);
          }
        });

        var gAxis = document.createElement('g');
        gAxis.setAttribute('id', 'axis');

        // append the axis to base so that it's not clipped
        base.appendChild(gAxis);
        gAxis.setAttribute('transform', 'translate(' + String(this.axis.pAxis.position.x) + ', ' + String(this.axis.pAxis.position.y) + ')');

        // add the axis to the export
        if (this.options.axisPositionHorizontal === 'left' || this.options.axisPositionVertical === 'top') {
          // left axis are shown at the beginning of the plot
          var gDrawnAxis = this.axis.exportAxisLeftSVG(this.valueScale, this.dimensions[1]);
          gAxis.appendChild(gDrawnAxis);
        } else if (this.options.axisPositionHorizontal === 'right' || this.options.axisPositionVertical === 'bottom') {
          var _gDrawnAxis = this.axis.exportAxisRightSVG(this.valueScale, this.dimensions[1]);
          gAxis.appendChild(_gDrawnAxis);
        }

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return BarTrack;
}(_HorizontalLine1DPixiTrack2['default']);

exports['default'] = BarTrack;

/***/ }),
/* 260 */
/***/ (function(module, exports, __nested_webpack_require_1404891__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_1404891__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _values = __nested_webpack_require_1404891__(37);

var _values2 = _interopRequireDefault(_values);

var _getIterator2 = __nested_webpack_require_1404891__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _stringify = __nested_webpack_require_1404891__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = __nested_webpack_require_1404891__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1404891__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1404891__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1404891__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1404891__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1404891__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _boxIntersect = __nested_webpack_require_1404891__(180);

var _boxIntersect2 = _interopRequireDefault(_boxIntersect);

var _robustPointInPolygon = __nested_webpack_require_1404891__(355);

var _robustPointInPolygon2 = _interopRequireDefault(_robustPointInPolygon);

var _configs = __nested_webpack_require_1404891__(11);

var _HorizontalTiled1DPixiTrack = __nested_webpack_require_1404891__(115);

var _HorizontalTiled1DPixiTrack2 = _interopRequireDefault(_HorizontalTiled1DPixiTrack);

var _services = __nested_webpack_require_1404891__(24);

var _utils = __nested_webpack_require_1404891__(10);

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

// these are default values that are overwritten by the track's options


// Services


// Configs
var FONT_SIZE = 11;

// Utils


// Components

var FONT_FAMILY = 'Arial';
var GENE_LABEL_POS = 'outside';
var GENE_RECT_HEIGHT = 10;
var GENE_STRAND_SPACING = 4;
var MAX_TEXTS = 20;
var WHITE_HEX = (0, _utils.colorToHex)('#ffffff');
var EXON_LINE_HEIGHT = 2;
var EXON_HEIGHT = 2 * GENE_RECT_HEIGHT / 3;
var GENE_MINI_TRIANGLE_HEIGHT = 2 * EXON_HEIGHT / 3;
var MAX_GENE_ENTRIES = 50;
var MAX_FILLER_ENTRIES = 5000;
var DEFAULT_PLUS_STRAND_COLOR = 'blue';
var DEFAULT_MINUS_STRAND_COLOR = 'red';

/**
 * Event handler for when gene annotations are clicked on.
 */
var geneClickFunc = function geneClickFunc(event, track, payload) {
  // fill rectangles are just indicators and are not meant to be
  // clicked on
  if (payload.type === 'filler') return;

  track.pubSub.publish('app.click', {
    type: 'gene-annotation',
    event: event,
    payload: payload
  });
};

/**
 * Fillers are annotations indicating that the region they cover
 * contains hidden [gene] annotations. If a filler overlaps a gene
 * then it's not necessary because we already see the gene.
 *
 * This function goes through a set of genes and fillers and flags
 * the fillers that are completely contained within a gene so that
 * we don't display them.
 *
 * @param  {array} genes   A list of gene annotations
 * @param  {array} fillers A list of filler annotations
 */
var flagOverlappingFillers = function flagOverlappingFillers(genes, fillers) {
  var regions = genes.concat(fillers);
  var boxes = regions.map(function (x) {
    return [x.xStart, 1, x.xEnd, 1];
  });
  (0, _boxIntersect2['default'])(boxes, function (i, j) {
    var filler = null;
    var gene = null;

    if (regions[i].type === 'filler') {
      filler = regions[i];
    } else {
      gene = regions[i];
    }

    if (regions[j].type === 'filler') {
      if (filler) return; // two fillers, don't care if they overlap
      filler = regions[j];
    } else {
      if (!filler) return;
      gene = regions[j];
    }

    if (filler.xStart >= gene.xStart && filler.xEnd <= gene.xEnd) {
      filler.hide = true;
    }
  });
};

/**
 * Initialize a tile. Pulled out from the track so that it
 * can be modified without having to modify the track
 * object (e.g. in an Observable notebooke)
 *
 * @param  {HorizontalGeneAnnotationsTrack} track   The track object
 * @param  {Object} tile    The tile to render
 * @param  {Object} options The track's options
 */
function externalInitTile(track, tile, options) {
  var flipText = options.flipText,
      fontSize = options.fontSize,
      fontFamily = options.fontFamily,
      plusStrandColor = options.plusStrandColor,
      minusStrandColor = options.minusStrandColor,
      maxGeneEntries = options.maxGeneEntries,
      maxFillerEntries = options.maxFillerEntries,
      maxTexts = options.maxTexts;
  // create texts

  tile.texts = {};

  tile.rectGraphics = new _configs.GLOBALS.PIXI.Graphics();
  tile.textBgGraphics = new _configs.GLOBALS.PIXI.Graphics();
  tile.textGraphics = new _configs.GLOBALS.PIXI.Graphics();
  tile.rectMaskGraphics = new _configs.GLOBALS.PIXI.Graphics();

  tile.graphics.addChild(tile.rectGraphics);
  tile.graphics.addChild(tile.textBgGraphics);
  tile.graphics.addChild(tile.textGraphics);
  tile.graphics.addChild(tile.rectMaskGraphics);

  tile.rectGraphics.mask = tile.rectMaskGraphics;

  if (!tile.tileData.sort) return;

  tile.tileData.sort(function (a, b) {
    return b.importance - a.importance;
  });

  var geneEntries = tile.tileData.filter(function (td) {
    return td.type !== 'filler';
  }).slice(0, maxGeneEntries);
  var fillerEntries = tile.tileData.filter(function (td) {
    return td.type === 'filler';
  }).slice(0, maxFillerEntries);

  tile.tileData = geneEntries.concat(fillerEntries);

  tile.tileData.forEach(function (td, i) {
    if (td.type === 'filler') {
      return;
    }

    var geneInfo = td.fields;
    var geneName = geneInfo[3];
    var geneId = track.geneId(geneInfo, td.type);
    var strand = td.strand || geneInfo[5];

    var fill = plusStrandColor || DEFAULT_PLUS_STRAND_COLOR;

    if (strand === '-') {
      fill = minusStrandColor || DEFAULT_MINUS_STRAND_COLOR;
    }
    tile.textWidths = {};
    tile.textHeights = {};

    // don't draw texts for the latter entries in the tile
    if (i >= maxTexts) return;

    var text = new _configs.GLOBALS.PIXI.Text(geneName, {
      fontSize: String(fontSize) + 'px',
      fontFamily: fontFamily,
      fill: (0, _utils.colorToHex)(fill)
    });
    text.interactive = true;

    if (flipText) text.scale.x = -1;

    text.anchor.x = 0.5;
    text.anchor.y = 1;

    tile.texts[geneId] = text; // index by geneName
    tile.texts[geneId].strand = strand;
    tile.textGraphics.addChild(text);
  });

  tile.initialized = true;
}

/** Draw generic rectangles... currently used for filler annotations */
function renderRects(rects, track, tile, someGraphics, // unused in this function
xScale, color, alpha, centerY, height) {
  var topY = centerY - height / 2;
  var FILLER_PADDING = 0;

  rects.forEach(function (td) {
    var graphics = new _configs.GLOBALS.PIXI.Graphics();

    tile.rectGraphics.addChild(graphics);

    graphics.beginFill(color, 0.1);
    graphics.lineStyle(0, color);

    var poly = [xScale(td.xStart) - FILLER_PADDING, topY, xScale(td.xEnd) + FILLER_PADDING, topY, xScale(td.xEnd) + FILLER_PADDING, topY + height, xScale(td.xStart) - FILLER_PADDING, topY + height, xScale(td.xStart) - FILLER_PADDING, topY];

    graphics.interactive = true;
    graphics.buttonMode = true;

    graphics.mouseup = function (event) {
      return geneClickFunc(event, track, td);
    };
    graphics.drawPolygon(poly);
    tile.allRects.push([poly, td.strand, td]);
  });
}

/** Draw the exons within a gene */
function drawExons(track, graphics, txStart, txEnd, exonStarts, exonEnds, chrOffset, centerY, height, strand) {
  var topY = centerY - height / 2;

  var exonOffsetStarts = exonStarts.split(',').map(function (x) {
    return +x + chrOffset;
  });
  var exonOffsetEnds = exonEnds.split(',').map(function (x) {
    return +x + chrOffset;
  });

  var xStartPos = track._xScale(txStart);
  var xEndPos = track._xScale(txEnd);

  var width = xEndPos - xStartPos;
  var yMiddle = centerY;

  var polys = [];

  // draw the middle line
  var poly = [xStartPos, yMiddle - EXON_LINE_HEIGHT / 2, xStartPos + width, yMiddle - EXON_LINE_HEIGHT / 2, xStartPos + width, yMiddle + EXON_LINE_HEIGHT / 2, xStartPos, yMiddle + EXON_LINE_HEIGHT / 2];
  graphics.drawPolygon(poly);
  polys.push(poly);

  // the distance between the mini-triangles
  var triangleInterval = 2 * height;

  // the first triangle (arrowhead) will be drawn in renderGeneSymbols
  for (var j = Math.max(track.position[0], xStartPos) + triangleInterval; j < Math.min(track.position[0] + track.dimensions[0], xStartPos + width); j += triangleInterval) {
    if (strand === '+') {
      poly = [j, yMiddle - GENE_MINI_TRIANGLE_HEIGHT / 2, j + GENE_MINI_TRIANGLE_HEIGHT / 2, yMiddle, j, yMiddle + GENE_MINI_TRIANGLE_HEIGHT / 2];
    } else {
      poly = [j, yMiddle - GENE_MINI_TRIANGLE_HEIGHT / 2, j - GENE_MINI_TRIANGLE_HEIGHT / 2, yMiddle, j, yMiddle + GENE_MINI_TRIANGLE_HEIGHT / 2];
    }

    polys.push(poly);
    graphics.drawPolygon(poly);
  }

  // draw the actual exons
  for (var _j = 0; _j < exonOffsetStarts.length; _j++) {
    var exonStart = exonOffsetStarts[_j];
    var exonEnd = exonOffsetEnds[_j];

    var xStart = track._xScale(exonStart);
    var localWidth = Math.max(1, track._xScale(exonEnd) - track._xScale(exonStart));

    // we're not going to draw rectangles over the arrowhead
    // at the start of the gene
    var minX = xStartPos;
    var maxX = xEndPos;
    var pointerWidth = track.geneRectHeight / 2;
    var localPoly = null;

    if (strand === '+') {
      maxX = xEndPos - pointerWidth;
      localPoly = [Math.min(xStart, maxX), topY, Math.min(xStart + localWidth, maxX), topY, Math.min(xStart + localWidth, maxX), topY + height, Math.min(xStart, maxX), topY + height, Math.min(xStart, maxX), topY];
    } else {
      minX = xStartPos + pointerWidth;
      localPoly = [Math.max(xStart, minX), topY, Math.max(xStart + localWidth, minX), topY, Math.max(xStart + localWidth, minX), topY + height, Math.max(xStart, minX), topY + height, Math.max(xStart, minX), topY];
    }

    polys.push(localPoly);
    graphics.drawPolygon(localPoly);
  }

  return polys;
}

/** Draw the arrowheads at the ends of genes */
function renderGeneSymbols(genes, track, tile, oldGraphics, xScale, color, alpha, centerY, height) {
  var topY = centerY - height / 2;

  genes.forEach(function (gene) {
    var xStart = track._xScale(gene.xStart);
    var xEnd = track._xScale(gene.xEnd);

    var graphics = new _configs.GLOBALS.PIXI.Graphics();
    tile.rectGraphics.addChild(graphics);

    graphics.beginFill(color, alpha);
    graphics.interactive = true;
    graphics.buttonMode = true;
    graphics.mouseup = function (evt) {
      return geneClickFunc(evt, track, gene);
    };

    var pointerWidth = track.geneRectHeight / 2;

    var poly = [];
    if (gene.strand === '+' || gene.fields[5] === '+') {
      var pointerStart = Math.max(xStart, xEnd - pointerWidth);
      var pointerEnd = pointerStart + pointerWidth;

      poly = [pointerStart, topY, pointerEnd, topY + track.geneRectHeight / 2, pointerStart, topY + track.geneRectHeight];
    } else {
      var _pointerStart = Math.min(xEnd, xStart + pointerWidth);
      var _pointerEnd = _pointerStart - pointerWidth;

      poly = [_pointerStart, topY, _pointerEnd, topY + track.geneRectHeight / 2, _pointerStart, topY + track.geneRectHeight];
    }

    graphics.drawPolygon(poly);
    tile.allRects.push([poly, gene.strand, gene]);
  });
}

function renderGeneExons(genes, track, tile, rectGraphics, xScale, color, alpha, centerY, height) {
  genes.forEach(function (gene) {
    var geneInfo = gene.fields;
    var chrOffset = +gene.chrOffset;

    var exonStarts = geneInfo[12];
    var exonEnds = geneInfo[13];
    var graphics = new _configs.GLOBALS.PIXI.Graphics();
    tile.rectGraphics.addChild(graphics);

    graphics.beginFill(color, alpha);
    graphics.interactive = true;
    graphics.buttonMode = true;
    graphics.mouseup = function (evt) {
      return geneClickFunc(evt, track, gene);
    };

    tile.allRects = tile.allRects.concat(drawExons(track, graphics, gene.xStart, gene.xEnd, exonStarts, exonEnds, chrOffset, // not used for now because we have just one chromosome
    centerY, height, gene.strand || gene.fields[5]).map(function (x) {
      return [x, gene.strand, gene];
    }));
  });
}

function renderGenes(genes, track, tile, graphics, xScale, color, alpha, centerY, height) {
  renderGeneSymbols(genes, track, tile, graphics, xScale, color, alpha, centerY, height);
  renderGeneExons(genes, track, tile, graphics, xScale, color, alpha, centerY, height);
}

/** Create a preventing this track from drawing outside of its
 * visible area
 */
function renderMask(track, tile) {
  var _trackUtils$getTilePo = _utils.trackUtils.getTilePosAndDimensions(track.tilesetInfo, tile.tileId),
      tileX = _trackUtils$getTilePo.tileX,
      tileWidth = _trackUtils$getTilePo.tileWidth;

  tile.rectMaskGraphics.clear();

  var randomColor = Math.floor(Math.random() * Math.pow(16, 6));
  tile.rectMaskGraphics.beginFill(randomColor, 0.3);

  var x = track._xScale(tileX);
  var y = 0;
  var width = track._xScale(tileX + tileWidth) - track._xScale(tileX);
  var height = track.dimensions[1];
  tile.rectMaskGraphics.drawRect(x, y, width, height);
}

var HorizontalGeneAnnotationsTrack = function (_HorizontalTiled1DPix) {
  (0, _inherits3['default'])(HorizontalGeneAnnotationsTrack, _HorizontalTiled1DPix);

  /**
   * Create a new track for Gene Annotations
   *
   * Arguments:
   * ----------
   * context: Object related to the environment of this track
   *   (e.g. renderer object, pubSubs)
   * options: Options from the viewconf
   */
  function HorizontalGeneAnnotationsTrack(context, options) {
    (0, _classCallCheck3['default'])(this, HorizontalGeneAnnotationsTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HorizontalGeneAnnotationsTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack)).call(this, context, options));

    var animate = context.animate;


    _this.animate = animate;
    _this.options = options;

    _this.fontSize = +_this.options.fontSize || FONT_SIZE;
    _this.geneLabelPos = _this.options.geneLabelPosition || GENE_LABEL_POS;
    _this.geneRectHeight = +_this.options.geneAnnotationHeight || GENE_RECT_HEIGHT;

    // Don't ask me why but rectangles and triangles seem to be drawn 2px larger
    // than they should be
    _this.geneRectHeight -= 2;

    _this.geneStrandSpacing = +_this.options.geneStrandSpacing || GENE_STRAND_SPACING;
    _this.geneStrandHSpacing = _this.geneStrandSpacing / 2;
    _this.geneRectHHeight = _this.geneRectHeight / 2;
    return _this;
  }

  (0, _createClass3['default'])(HorizontalGeneAnnotationsTrack, [{
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        externalInitTile(this, tile, {
          flipText: this.flipText,
          fontSize: this.fontSize,
          fontFamily: FONT_FAMILY,
          plusStrandColor: this.options.plusStrandColor,
          minusStrandColor: this.options.minusStrandColor,
          maxGeneEntries: MAX_GENE_ENTRIES,
          maxFillerEntries: MAX_FILLER_ENTRIES,
          maxTexts: MAX_TEXTS
        });

        this.renderTile(tile);
      }

      return initTile;
    }()

    /** cleanup */

  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile) {
        tile.rectGraphics.destroy();
        tile.rectMaskGraphics.destroy();
        tile.textGraphics.destroy();
        tile.textBgGraphics.destroy();
        tile.graphics.destroy();
      }

      return destroyTile;
    }()

    /*
     * Redraw the track because the options
     * changed
     */

  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        var _this2 = this;

        var strOptions = (0, _stringify2['default'])(options);
        if (!force && strOptions === this.prevOptions) return;

        (0, _get3['default'])(HorizontalGeneAnnotationsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack.prototype), 'rerender', this).call(this, options, force);

        this.fontSize = +this.options.fontSize || FONT_SIZE;
        this.geneLabelPos = this.options.geneLabelPosition || GENE_LABEL_POS;
        this.geneRectHeight = +this.options.geneAnnotationHeight || GENE_RECT_HEIGHT;
        this.geneStrandHSpacing = this.geneStrandSpacing / 2;
        this.geneRectHHeight = this.geneRectHeight / 2;

        this.prevOptions = strOptions;

        this.visibleAndFetchedTiles().forEach(function (tile) {
          _this2.renderTile(tile);
        });
      }

      return rerender;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile() {}

      return drawTile;
    }()
  }, {
    key: 'geneId',
    value: function () {
      function geneId(geneInfo, type) {
        return String(type) + '_' + String(geneInfo[0]) + '_' + String(geneInfo[1]) + '_' + String(geneInfo[2]) + '_' + String(geneInfo[3]);
      }

      return geneId;
    }()
  }, {
    key: 'renderTile',
    value: function () {
      function renderTile(tile) {
        if (!tile.initialized) return;

        tile.allRects = [];
        // store the scale at while the tile was drawn at so that
        // we only resize it when redrawing
        tile.drawnAtScale = this._xScale.copy();
        tile.rectGraphics.removeChildren();
        tile.rectGraphics.clear();
        tile.textBgGraphics.clear();

        var fill = {};
        var FILLER_RECT_ALPHA = 0.3;
        var GENE_ALPHA = 0.3;

        fill['+'] = (0, _utils.colorToHex)(this.options.plusStrandColor || DEFAULT_PLUS_STRAND_COLOR);
        fill['-'] = (0, _utils.colorToHex)(this.options.minusStrandColor || DEFAULT_MINUS_STRAND_COLOR);

        var plusFillerRects = tile.tileData.filter(function (td) {
          return td.type === 'filler' && td.strand === '+';
        });
        var minusFillerRects = tile.tileData.filter(function (td) {
          return td.type === 'filler' && td.strand === '-';
        });

        var plusGenes = tile.tileData.filter(function (td) {
          return td.type !== 'filler' && (td.strand === '+' || td.fields[5] === '+');
        });
        var minusGenes = tile.tileData.filter(function (td) {
          return td.type !== 'filler' && (td.strand === '-' || td.fields[5] === '-');
        });

        flagOverlappingFillers(plusGenes, plusFillerRects);
        flagOverlappingFillers(minusGenes, minusFillerRects);

        // remove the fillers that are contained within a gene
        plusFillerRects = plusFillerRects.filter(function (x) {
          return !x.hide;
        });
        minusFillerRects = minusFillerRects.filter(function (x) {
          return !x.hide;
        });

        var yMiddle = this.dimensions[1] / 2;

        // const fillerGeneSpacing = (this.options.fillerHeight - this.geneRectHeight) / 2;
        var plusStrandCenterY = yMiddle - this.geneRectHeight / 2 - this.geneStrandSpacing / 2;
        var minusStrandCenterY = yMiddle + this.geneRectHeight / 2 + this.geneStrandSpacing / 2;

        var plusRenderContext = [this, tile, tile.rectGraphics, this._xScale, fill['+'], FILLER_RECT_ALPHA, plusStrandCenterY, this.geneRectHeight];
        var minusRenderContext = [this, tile, tile.rectGraphics, this._xScale, fill['-'], FILLER_RECT_ALPHA, minusStrandCenterY, this.geneRectHeight];

        renderRects.apply(undefined, [plusFillerRects].concat(plusRenderContext));
        renderRects.apply(undefined, [minusFillerRects].concat(minusRenderContext));

        plusRenderContext[5] = GENE_ALPHA;
        minusRenderContext[5] = GENE_ALPHA;

        renderGenes.apply(undefined, [plusGenes].concat(plusRenderContext));
        renderGenes.apply(undefined, [minusGenes].concat(minusRenderContext));

        renderMask(this, tile);

        _utils.trackUtils.stretchRects(this, [function (x) {
          return x.rectGraphics;
        }, function (x) {
          return x.rectMaskGraphics;
        }]);

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])((0, _values2['default'])(tile.texts)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var text = _step.value;

            text.style = {
              fontSize: String(this.fontSize) + 'px',
              FONT_FAMILY: FONT_FAMILY,
              fill: (0, _utils.colorToHex)(text.strand === '-' ? this.options.minusStrandColor || DEFAULT_MINUS_STRAND_COLOR : this.options.plusStrandColor || DEFAULT_PLUS_STRAND_COLOR)
            };
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return renderTile;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        // offset by 2 because 1D tiles are more dense than 2D tiles
        // 1024 points per tile vs 256 for 2D tiles
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);

        var zoomLevel = Math.min(xZoomLevel, this.maxZoom);
        zoomLevel = Math.max(zoomLevel, 0);

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var _this3 = this;

        (0, _get3['default'])(HorizontalGeneAnnotationsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack.prototype), 'draw', this).call(this);

        this.allTexts = [];
        this.allBoxes = [];
        var allTiles = [];

        this.geneAreaHeight = this.geneRectHeight;
        var fontSizeHalf = this.fontSize / 2;

        _utils.trackUtils.stretchRects(this, [function (x) {
          return x.rectGraphics;
        }, function (x) {
          return x.rectMaskGraphics;
        }]);

        (0, _values2['default'])(this.fetchedTiles)
        // tile hasn't been drawn properly because we likely got some
        // bogus data from the server
        .filter(function (tile) {
          return tile.drawnAtScale;
        }).forEach(function (tile) {
          tile.textBgGraphics.clear();
          tile.textBgGraphics.beginFill(typeof _this3.options.labelBackgroundColor !== 'undefined' ? (0, _utils.colorToHex)(_this3.options.labelBackgroundColor) : WHITE_HEX);

          // move the texts
          var parentInFetched = _this3.parentInFetched(tile);

          if (!tile.initialized) return;

          tile.tileData.forEach(function (td) {
            // tile probably hasn't been initialized yet
            if (!tile.texts) return;
            if (td.type === 'filler') return;

            var geneInfo = td.fields;
            var geneName = geneInfo[3];

            var geneId = _this3.geneId(geneInfo, td.type);

            var text = tile.texts[geneId];

            if (!text) return;

            var chrOffset = +td.chrOffset;
            var txStart = +geneInfo[1] + chrOffset;
            var txEnd = +geneInfo[2] + chrOffset;
            var txMiddle = (txStart + txEnd) / 2;
            var textYMiddle = _this3.dimensions[1] / 2;

            var fontRectPadding = (_this3.geneAreaHeight - _this3.fontSize) / 2;

            if (geneInfo[5] === '+') {
              // genes on the + strand drawn above and in a user-specified color or the
              // default blue textYMiddle -= 10;
              textYMiddle -= _this3.geneLabelPos === 'inside' ? fontRectPadding + _this3.geneStrandSpacing - 2 : _this3.fontSize / 2 + _this3.geneAreaHeight - 2;
            } else {
              // genes on the - strand drawn below and in a user-specified color or the
              // default red
              textYMiddle += _this3.geneLabelPos === 'inside' ? _this3.fontSize + _this3.geneStrandSpacing / 2 + fontRectPadding + 1 : 1.5 * _this3.fontSize + _this3.geneAreaHeight + 2;
            }

            text.position.x = _this3._xScale(txMiddle);
            text.position.y = textYMiddle;

            if (!tile.textWidths[geneId]) {
              // if we haven't measured the text's width in renderTile, do it now
              // this can occur if the same gene is in more than one tile, so its
              // dimensions are measured for the first tile and not for the second
              var textWidth = text.getBounds().width;
              var textHeight = text.getBounds().height;

              tile.textHeights[geneId] = textHeight;
              tile.textWidths[geneId] = textWidth;
            }

            if (!parentInFetched) {
              text.visible = true;

              var TEXT_MARGIN = 2;

              if (_this3.flipText) {
                // when flipText is set, that means that the track is being displayed
                // vertically so we need to use the stored text height rather than width
                _this3.allBoxes.push([text.position.x - tile.textHeights[geneId] / 2 - TEXT_MARGIN, textYMiddle - fontSizeHalf - 1, text.position.x + tile.textHeights[geneId] / 2 + TEXT_MARGIN, textYMiddle + fontSizeHalf - 1, geneName]);
              } else {
                _this3.allBoxes.push([text.position.x - tile.textWidths[geneId] / 2 - TEXT_MARGIN, textYMiddle - fontSizeHalf - 1, text.position.x + tile.textWidths[geneId] / 2 + TEXT_MARGIN, textYMiddle + fontSizeHalf - 1, geneName]);
              }

              _this3.allTexts.push({
                importance: +geneInfo[4],
                text: text,
                caption: geneName,
                strand: geneInfo[5]
              });

              allTiles.push(tile.textBgGraphics);
            } else {
              text.visible = false;
            }
          });
        });

        this.hideOverlaps(this.allBoxes, this.allTexts);
        this.renderTextBg(this.allBoxes, this.allTexts, allTiles);
      }

      return draw;
    }()
  }, {
    key: 'renderTextBg',
    value: function () {
      function renderTextBg(allBoxes, allTexts, allTiles) {
        allTexts.forEach(function (text, i) {
          if (text.text.visible && allBoxes[i] && allTiles[i]) {
            var _allBoxes$i = (0, _slicedToArray3['default'])(allBoxes[i], 4),
                minX = _allBoxes$i[0],
                minY = _allBoxes$i[1],
                maxX = _allBoxes$i[2],
                maxY = _allBoxes$i[3];

            var width = maxX - minX;
            var height = maxY - minY;

            allTiles[i].drawRect(minX - width / 2, minY - height / 2, width, height);
          }
        });
      }

      return renderTextBg;
    }()
  }, {
    key: 'hideOverlaps',
    value: function () {
      function hideOverlaps(allBoxes, allTexts) {
        (0, _boxIntersect2['default'])(allBoxes, function (i, j) {
          if (allTexts[i].importance > allTexts[j].importance) {
            allTexts[j].text.visible = false;
          } else {
            allTexts[i].text.visible = false;
          }
        });
      }

      return hideOverlaps;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(HorizontalGeneAnnotationsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack.prototype), 'setPosition', this).call(this, newPosition);

        var _position = (0, _slicedToArray3['default'])(this.position, 2);

        this.pMain.position.x = _position[0];
        this.pMain.position.y = _position[1];
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        var _this4 = this;

        (0, _get3['default'])(HorizontalGeneAnnotationsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        this.halfRectHHeight = this.dimensions[1] / 2;

        // redraw the contents
        this.visibleAndFetchedTiles().forEach(function (tile) {
          _this4.renderTile(tile);
        });
      }

      return setDimensions;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTiles();

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX, trackY) {
        if (!this.tilesetInfo) {
          return '';
        }

        var point = [trackX, trackY];

        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var tile = _step2.value;

            for (var i = 0; i < tile.allRects.length; i++) {
              // copy the visible rects array
              if (tile.allRects[i][2].type === 'filler') {
                continue;
              }
              var rect = tile.allRects[i][0].slice(0);

              var newArr = [];
              while (rect.length) {
                var newPoint = rect.splice(0, 2);
                newPoint[0] = newPoint[0] * tile.rectGraphics.scale.x + tile.rectGraphics.position.x;
                newPoint[1] = newPoint[1] * tile.rectGraphics.scale.y + tile.rectGraphics.position.y;

                newArr.push(newPoint);
              }

              var pc = (0, _robustPointInPolygon2['default'])(newArr, point);

              if (pc === -1) {
                var gene = tile.allRects[i][2];

                return '\n            <div>\n              <b>' + String(gene.fields[3]) + '</b><br>\n              <b>Position:</b> ' + String(gene.fields[0]) + ':' + String(gene.fields[1]) + '-' + String(gene.fields[2]) + '<br>\n              <b>Strand:</b> ' + String(gene.fields[5]) + '\n            </div>\n          ';
              }
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        return '';
      }

      return getMouseOverHtml;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var _this5 = this;

        var track = null;
        var base = null;

        if ((0, _get3['default'])(HorizontalGeneAnnotationsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(HorizontalGeneAnnotationsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalGeneAnnotationsTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);

        this.visibleAndFetchedTiles().filter(function (tile) {
          return tile.allRects;
        }).forEach(function (tile) {
          var gTile = document.createElement('g');
          gTile.setAttribute('transform', 'translate(' + String(tile.rectGraphics.position.x) + ',\n          ' + String(tile.rectGraphics.position.y) + ')\n          scale(' + String(tile.rectGraphics.scale.x) + ',\n          ' + String(tile.rectGraphics.scale.y) + ')');

          tile.allRects.forEach(function (rect) {
            var r = document.createElement('path');

            var poly = rect[0];

            var d = 'M ' + String(poly[0]) + ' ' + String(poly[1]);

            for (var i = 2; i < poly.length; i += 2) {
              d += ' L ' + String(poly[i]) + ' ' + String(poly[i + 1]);
            }

            r.setAttribute('d', d);

            if (rect[1] === '+') {
              r.setAttribute('fill', _this5.options.plusStrandColor);
            } else {
              r.setAttribute('fill', _this5.options.minusStrandColor);
            }
            r.setAttribute('opacity', '0.3');

            gTile.appendChild(r);
          });

          output.appendChild(gTile);
        });

        this.allTexts.filter(function (text) {
          return text.text.visible;
        }).forEach(function (text) {
          var g = document.createElement('g');
          var t = document.createElement('text');
          t.setAttribute('text-anchor', 'middle');
          t.setAttribute('font-family', FONT_FAMILY);
          t.setAttribute('font-size', String(_this5.fontSize) + 'px');

          // this small adjustment of .2em is to place the text better
          // in relation to the rectangles used for the genes and exons
          t.setAttribute('dy', '-.2em');
          g.setAttribute('transform', 'scale(' + String(text.text.scale.x) + ',1)');

          if (text.strand === '+') {
            // t.setAttribute('stroke', this.options.plusStrandColor);
            t.setAttribute('fill', _this5.options.plusStrandColor);
          } else {
            // t.setAttribute('stroke', this.options.minusStrandColor);
            t.setAttribute('fill', _this5.options.minusStrandColor);
          }

          t.innerHTML = text.text.text;

          g.appendChild(t);
          g.setAttribute('transform', 'translate(' + String(text.text.x) + ',' + String(text.text.y) + ')scale(' + String(text.text.scale.x) + ',1)');
          output.appendChild(g);
        });

        return [base, base];
      }

      return exportSVG;
    }()
  }]);
  return HorizontalGeneAnnotationsTrack;
}(_HorizontalTiled1DPixiTrack2['default']);

exports['default'] = HorizontalGeneAnnotationsTrack;

/***/ }),
/* 261 */
/***/ (function(module, exports, __nested_webpack_require_1439895__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1439895__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1439895__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1439895__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1439895__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1439895__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1439895__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _mixwith = __nested_webpack_require_1439895__(81);

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

var RuleMixin = (0, _mixwith.Mixin)(function (superclass) {
  return function (_superclass) {
    (0, _inherits3['default'])(_class, _superclass);

    function _class(context, options) {
      (0, _classCallCheck3['default'])(this, _class);

      var _this = (0, _possibleConstructorReturn3['default'])(this, (_class.__proto__ || (0, _getPrototypeOf2['default'])(_class)).call(this, context, options));

      var animate = context.animate;


      _this.highlighted = false;
      _this.animate = animate;

      _this.MOUSEOVER_RADIUS = 4;

      _this.pubSub = context.pubSub;

      _this.pubSubs.push(_this.pubSub.subscribe('app.mouseMove', _this.mouseMoveHandler.bind(_this)));
      return _this;
    }

    (0, _createClass3['default'])(_class, [{
      key: 'setPosition',
      value: function () {
        function setPosition(newPosition) {
          (0, _get3['default'])(_class.prototype.__proto__ || (0, _getPrototypeOf2['default'])(_class.prototype), 'setPosition', this).call(this, newPosition);

          // console.log('position', this.position);
          this.pMain.position.x = this.position[0];
          this.pMain.position.y = this.position[1];
        }

        return setPosition;
      }()
    }, {
      key: 'zoomed',
      value: function () {
        function zoomed(newXScale, newYScale) {
          (0, _get3['default'])(_class.prototype.__proto__ || (0, _getPrototypeOf2['default'])(_class.prototype), 'zoomed', this).call(this, newXScale, newYScale);

          this.draw();
        }

        return zoomed;
      }()
    }, {
      key: 'respondsToPosition',
      value: function () {
        function respondsToPosition() {
          return this.highlighted;
        }

        return respondsToPosition;
      }()
    }]);
    return _class;
  }(superclass);
});

exports['default'] = RuleMixin;

/***/ }),
/* 262 */
/***/ (function(module, exports, __nested_webpack_require_1442692__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_1442692__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _get2 = __nested_webpack_require_1442692__(14);

var _get3 = _interopRequireDefault(_get2);

var _getPrototypeOf = __nested_webpack_require_1442692__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1442692__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1442692__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1442692__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1442692__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _mixwith = __nested_webpack_require_1442692__(81);

var _PixiTrack = __nested_webpack_require_1442692__(40);

var _PixiTrack2 = _interopRequireDefault(_PixiTrack);

var _RuleMixin = __nested_webpack_require_1442692__(261);

var _RuleMixin2 = _interopRequireDefault(_RuleMixin);

var _utils = __nested_webpack_require_1442692__(10);

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

var VerticalRuleMixin = exports.VerticalRuleMixin = (0, _mixwith.Mixin)(function (superclass) {
  return function (_superclass) {
    (0, _inherits3['default'])(_class, _superclass);

    function _class() {
      (0, _classCallCheck3['default'])(this, _class);
      return (0, _possibleConstructorReturn3['default'])(this, (_class.__proto__ || (0, _getPrototypeOf2['default'])(_class)).apply(this, arguments));
    }

    (0, _createClass3['default'])(_class, [{
      key: 'drawVerticalRule',
      value: function () {
        function drawVerticalRule(graphics) {
          var stroke = (0, _utils.colorToHex)(this.options.color || 'black');

          if (this.highlighted) {
            stroke = (0, _utils.colorToHex)('red');
          }

          graphics.lineStyle(this.strokeWidth, stroke, this.strokeOpacity);

          var pos = 0;

          // console.log('this.position', this.position);
          // console.log('this._xScale.range()', this._xScale.range());

          while (pos < this.dimensions[1]) {
            graphics.moveTo(this._xScale(this.xPosition), pos);
            graphics.lineTo(this._xScale(this.xPosition), pos + this.dashLength);

            pos += this.dashLength + this.dashGap;
          }
        }

        return drawVerticalRule;
      }()
    }, {
      key: 'isMouseOverVerticalLine',
      value: function () {
        function isMouseOverVerticalLine(mousePos) {
          return Math.abs(mousePos.x - this.position[0] - this._xScale(this.xPosition)) < this.MOUSEOVER_RADIUS;
        }

        return isMouseOverVerticalLine;
      }()
    }]);
    return _class;
  }(superclass);
});

var VerticalRule = function (_mix$with) {
  (0, _inherits3['default'])(VerticalRule, _mix$with);

  function VerticalRule(context, options) {
    (0, _classCallCheck3['default'])(this, VerticalRule);

    var _this2 = (0, _possibleConstructorReturn3['default'])(this, (VerticalRule.__proto__ || (0, _getPrototypeOf2['default'])(VerticalRule)).call(this, context, options));

    _this2.xPosition = context.xPosition;

    _this2.strokeWidth = 2;
    _this2.strokeOpacity = 1;
    _this2.dashLength = 5;
    _this2.dashGap = 3;
    return _this2;
  }

  (0, _createClass3['default'])(VerticalRule, [{
    key: 'draw',
    value: function () {
      function draw() {
        var graphics = this.pMain;
        graphics.clear();

        this.drawVerticalRule(graphics);
        this.animate();
      }

      return draw;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(VerticalRule.prototype.__proto__ || (0, _getPrototypeOf2['default'])(VerticalRule.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(VerticalRule.prototype.__proto__ || (0, _getPrototypeOf2['default'])(VerticalRule.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        output.setAttribute('class', 'vertical-rule');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);

        var stroke = this.options.color || 'black';

        var line = document.createElement('line');
        line.setAttribute('stroke', stroke);
        line.setAttribute('stroke-width', this.strokeWidth);
        line.setAttribute('stroke-dasharray', String(this.dashLength) + ' ' + String(this.dashGap));
        line.setAttribute('x1', this._xScale(this.xPosition));
        line.setAttribute('y1', 0);
        line.setAttribute('x2', this._xScale(this.xPosition));
        line.setAttribute('y2', this.dimensions[1]);

        output.appendChild(line);

        return [base, track];
      }

      return exportSVG;
    }()
  }, {
    key: 'mouseMoveHandler',
    value: function () {
      function mouseMoveHandler(mousePos) {
        this.highlighted = this.isWithin(mousePos.x, mousePos.y) && this.isMouseOverVerticalLine(mousePos);

        this.draw();
      }

      return mouseMoveHandler;
    }()
  }]);
  return VerticalRule;
}((0, _mixwith.mix)(_PixiTrack2['default'])['with'](_RuleMixin2['default'], VerticalRuleMixin));

exports['default'] = VerticalRule;

/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

module.exports = {
  2:      'need dictionary',     /* Z_NEED_DICT       2  */
  1:      'stream end',          /* Z_STREAM_END      1  */
  0:      '',                    /* Z_OK              0  */
  '-1':   'file error',          /* Z_ERRNO         (-1) */
  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
};


/***/ }),
/* 264 */
/***/ (function(module, exports, __nested_webpack_require_1450455__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1450455__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1450455__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1450455__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1450455__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1450455__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_1450455__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_1450455__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_1450455__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _utils = __nested_webpack_require_1450455__(10);

var _utils2 = _interopRequireDefault(_utils);

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

var PopupMenu = function (_React$Component) {
  (0, _inherits3['default'])(PopupMenu, _React$Component);

  function PopupMenu(props) {
    (0, _classCallCheck3['default'])(this, PopupMenu);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (PopupMenu.__proto__ || (0, _getPrototypeOf2['default'])(PopupMenu)).call(this, props));

    _this.clickHandlerBound = _this.clickHandler.bind(_this);
    _this.contextMenuHandlerBound = _this.contextMenuHandler.bind(_this);
    _this.resizeHandlerBound = _this.resizeHandler.bind(_this);
    return _this;
  }

  (0, _createClass3['default'])(PopupMenu, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        this.popup = document.createElement('div');
        document.body.appendChild(this.popup);

        this.popup.style.zIndex = 99;
        this.popup.style.position = 'absolute';
        this.popup.className = 'hg-popup';

        document.addEventListener('click', this.clickHandlerBound, true);
        document.addEventListener('contextmenu', this.contextMenuHandlerBound, true);
        window.addEventListener('resize', this.resizeHandlerBound, true);

        this._renderLayer();
      }

      return componentDidMount;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate() {
        this._renderLayer();
      }

      return componentDidUpdate;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        document.removeEventListener('click', this.clickHandlerBound, true);
        document.removeEventListener('contextmenu', this.contextMenuHandlerBound, true);
        window.removeEventListener('resize', this.resizeHandlerBound, true);
        _reactDom2['default'].unmountComponentAtNode(this.popup);
        document.body.removeChild(this.popup);
      }

      return componentWillUnmount;
    }()
  }, {
    key: '_renderLayer',
    value: function () {
      function _renderLayer() {
        _reactDom2['default'].render(this.props.children, this.popup);
      }

      return _renderLayer;
    }()
  }, {
    key: 'clickHandler',
    value: function () {
      function clickHandler(event) {
        if (!this.popup.contains(event.target)) {
          if (this.props.onMenuClosed) this.props.onMenuClosed(event);
        }
      }

      return clickHandler;
    }()
  }, {
    key: 'contextMenuHandler',
    value: function () {
      function contextMenuHandler(event) {
        if (event.altKey) return;
        event.preventDefault();
        this.clickHandler(event);
      }

      return contextMenuHandler;
    }()
  }, {
    key: 'resizeHandler',
    value: function () {
      function resizeHandler() {
        this.props.onMenuClosed(null);
      }

      return resizeHandler;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        // Render a placeholder
        return _react2['default'].createElement('div', null);
      }

      return render;
    }()
  }]);
  return PopupMenu;
}(_react2['default'].Component);

PopupMenu.defaultProps = {
  onMenuClosed: _utils2['default']
};

PopupMenu.propTypes = {
  children: _propTypes2['default'].node.isRequired,
  onMenuClosed: _propTypes2['default'].func
};

exports['default'] = PopupMenu;

/***/ }),
/* 265 */
/***/ (function(module, exports, __nested_webpack_require_1454992__) {

"use strict";


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

var _set = __nested_webpack_require_1454992__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1454992__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1454992__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1454992__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1454992__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1454992__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_1454992__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_1454992__(1);

var _react2 = _interopRequireDefault(_react);

var _DraggableDiv = __nested_webpack_require_1454992__(668);

var _DraggableDiv2 = _interopRequireDefault(_DraggableDiv);

var _TrackArea2 = __nested_webpack_require_1454992__(670);

var _TrackArea3 = _interopRequireDefault(_TrackArea2);

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

// See commented out block in "render()".
//
// const checkMousePosVsEl = (x, y, el) => {
//   const bBox = el.getBoundingClientRect();
//   return isWithin(
//     x, y, bBox.left, bBox.left + bBox.width, bBox.top, bBox.top + bBox.height
//   );
// };

var MoveableTrack = function (_TrackArea) {
  (0, _inherits3['default'])(MoveableTrack, _TrackArea);

  function MoveableTrack(props) {
    (0, _classCallCheck3['default'])(this, MoveableTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (MoveableTrack.__proto__ || (0, _getPrototypeOf2['default'])(MoveableTrack)).call(this, props));

    _this.moveable = true;
    return _this;
  }

  (0, _createClass3['default'])(MoveableTrack, [{
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(r) {
                _this2.el = r;
              }

              return ref;
            }(),
            className: this.props.className,
            onMouseEnter: this.handleMouseEnter.bind(this),
            onMouseLeave: function () {
              function onMouseLeave() /* e */{
                // This let to https://github.com/higlass/higlass/issues/263
                // Therefore I disabled it.
                // if (checkMousePosVsEl(
                //   e.nativeEvent.clientX, e.nativeEvent.clientY, this.el
                // )) {
                //   return;
                // }
                _this2.handleMouseLeave();
              }

              return onMouseLeave;
            }(),
            style: {
              height: this.props.height,
              width: this.props.width
            }
          },
          _react2['default'].createElement(_DraggableDiv2['default'], {
            key: this.props.uid,
            height: this.props.height,
            resizeHandles: this.props.editable ? this.props.resizeHandles : new _set2['default'](),
            sizeChanged: function () {
              function sizeChanged(stuff) {
                return _this2.props.handleResizeTrack(_this2.props.uid, stuff.width, stuff.height);
              }

              return sizeChanged;
            }(),
            style: { background: 'transparent' },
            uid: this.props.uid,
            width: this.props.width
          }),
          this.props.editable && this.getControls(this.state.controlsVisible || this.props.item.configMenuVisible)
        );
      }

      return render;
    }()
  }]);
  return MoveableTrack;
}(_TrackArea3['default']);

MoveableTrack.propTypes = {
  className: _propTypes2['default'].string,
  uid: _propTypes2['default'].string,
  item: _propTypes2['default'].object,
  height: _propTypes2['default'].number,
  width: _propTypes2['default'].number
};

exports['default'] = MoveableTrack;

/***/ }),
/* 266 */
/***/ (function(module, exports, __nested_webpack_require_1459203__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.svgArrowheadDomainsIcon = exports.svgVertical1DTilesIcon = exports.svg1DTilesIcon = exports.svgGeneAnnotationsIcon = exports.svgVertical1DAxisIcon = exports.svg1DAxisIcon = exports.svg2DHeatmapIcon = exports.svg2DTilesIcon = exports.svgHorizontalLineIcon = exports.svgHorizontal1dHeatmap = exports.svgGeoMapIcon = exports.all = exports.FOLDER_OPEN_O = exports.FOLDER_O = exports.CHEVRON_DOWN = exports.CHEVRON_RIGHT = exports.FILE_O = exports.SQUARE_O = exports.CHECK_SQUARE_O = exports.SELECT = exports.TRACK_LINE = exports.CONTENT_COPY = exports.PLUS = exports.PLAY = exports.MOVE = exports.MINUS = exports.ENLARGE = exports.CROSS = exports.COG = undefined;
exports.SearchIcon = SearchIcon;

var _getClassName2 = __nested_webpack_require_1459203__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_1459203__(1);

var _react2 = _interopRequireDefault(_react);

var _d3Selection = __nested_webpack_require_1459203__(0);

__nested_webpack_require_1459203__(267);

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

var _styleModuleImportMap = {
  '../styles/ViewHeader.module.scss': {
    'multitrack-header': 'ViewHeader-module_multitrack-header-3XnZx',
    'multitrack-header-focus': 'ViewHeader-module_multitrack-header-focus-3akkN',
    'multitrack-header-squeazed': 'ViewHeader-module_multitrack-header-squeazed-GHIVd',
    'multitrack-header-dark': 'ViewHeader-module_multitrack-header-dark-97tZt',
    'multitrack-header-id': 'ViewHeader-module_multitrack-header-id-3YURk',
    'multitrack-header-left': 'ViewHeader-module_multitrack-header-left-Qj9Sm',
    'multitrack-header-grabber': 'ViewHeader-module_multitrack-header-grabber-3jrIz',
    'multitrack-header-grabber-squeazed': 'ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z',
    'multitrack-header-search': 'ViewHeader-module_multitrack-header-search-1X_3_',
    'multitrack-header-nav-list': 'ViewHeader-module_multitrack-header-nav-list-2nvcu',
    'multitrack-header-icon': 'ViewHeader-module_multitrack-header-icon-16QKZ',
    'multitrack-header-icon-squeazed': 'ViewHeader-module_multitrack-header-icon-squeazed-25lkF',
    'mouse-tool-selection': 'ViewHeader-module_mouse-tool-selection-1pg2m'
  }
};
var COG = exports.COG = {
  id: 'cog',
  paths: ['M466.895 305.125c-26.863-46.527-10.708-106.152 36.076-133.244l-50.313-87.146c-14.375 8.427-31.088 13.259-48.923 13.259-53.768 0-97.354-43.873-97.354-97.995h-100.629c0.133 16.705-4.037 33.641-12.979 49.126-26.862 46.528-86.578 62.351-133.431 35.379l-50.312 87.146c14.485 8.236 27.025 20.294 35.943 35.739 26.819 46.454 10.756 105.96-35.854 133.112l50.313 87.146c14.325-8.348 30.958-13.127 48.7-13.127 53.598 0 97.072 43.596 97.35 97.479h100.627c-0.043-16.537 4.136-33.285 12.983-48.609 26.818-46.453 86.388-62.297 133.207-35.506l50.313-87.145c-14.39-8.233-26.846-20.249-35.717-35.614zM256 359.666c-57.254 0-103.668-46.412-103.668-103.667 0-57.254 46.413-103.667 103.668-103.667s103.666 46.413 103.666 103.667c-0.001 57.255-46.412 103.667-103.666 103.667z'],
  viewBox: '0 0 512 512'
};

var CROSS = exports.CROSS = {
  id: 'cross',
  paths: ['M507.331 411.33c-0.002-0.002-0.004-0.004-0.006-0.005l-155.322-155.325 155.322-155.325c0.002-0.002 0.004-0.003 0.006-0.005 1.672-1.673 2.881-3.627 3.656-5.708 2.123-5.688 0.912-12.341-3.662-16.915l-73.373-73.373c-4.574-4.573-11.225-5.783-16.914-3.66-2.080 0.775-4.035 1.984-5.709 3.655 0 0.002-0.002 0.003-0.004 0.005l-155.324 155.326-155.324-155.325c-0.002-0.002-0.003-0.003-0.005-0.005-1.673-1.671-3.627-2.88-5.707-3.655-5.69-2.124-12.341-0.913-16.915 3.66l-73.374 73.374c-4.574 4.574-5.784 11.226-3.661 16.914 0.776 2.080 1.985 4.036 3.656 5.708 0.002 0.001 0.003 0.003 0.005 0.005l155.325 155.324-155.325 155.326c-0.001 0.002-0.003 0.003-0.004 0.005-1.671 1.673-2.88 3.627-3.657 5.707-2.124 5.688-0.913 12.341 3.661 16.915l73.374 73.373c4.575 4.574 11.226 5.784 16.915 3.661 2.080-0.776 4.035-1.985 5.708-3.656 0.001-0.002 0.003-0.003 0.005-0.005l155.324-155.325 155.324 155.325c0.002 0.001 0.004 0.003 0.006 0.004 1.674 1.672 3.627 2.881 5.707 3.657 5.689 2.123 12.342 0.913 16.914-3.661l73.373-73.374c4.574-4.574 5.785-11.227 3.662-16.915-0.776-2.080-1.985-4.034-3.657-5.707z'],
  viewBox: '0 0 512 512'
};

var ENLARGE = exports.ENLARGE = {
  id: 'enlarge',
  paths: ['M512 0h-208l80 80-96 96 48 48 96-96 80 80z', 'M512 512v-208l-80 80-96-96-48 48 96 96-80 80z', 'M0 512h208l-80-80 96-96-48-48-96 96-80-80z', 'M0 0v208l80-80 96 96 48-48-96-96 80-80z'],
  viewBox: '0 0 512 512'
};

var MINUS = exports.MINUS = {
  id: 'minus',
  paths: ['M0 208v96c0 8.836 7.164 16 16 16h480c8.836 0 16-7.164 16-16v-96c0-8.836-7.164-16-16-16h-480c-8.836 0-16 7.164-16 16z'],
  viewBox: '0 0 512 512'
};

var MOVE = exports.MOVE = {
  id: 'move',
  paths: ['M512,260.096L405.5,161.79v49.155H301.061v-104.45h49.149L251.904,0L160.77,106.495h49.15v104.45H106.495V161.79L0,260.096l106.495,91.135v-49.149h104.45v104.45H161.79L251.904,512l98.306-106.5h-49.149V301.061H405.5v49.149L512,260.096z'],
  viewBox: '0 0 512 512'
};

var PLAY = exports.PLAY = {
  id: 'play',
  paths: ['M96 64l320 192-320 192z'],
  viewBox: '0 0 512 512'
};

var PLUS = exports.PLUS = {
  id: 'plus',
  paths: ['M496 192h-176v-176c0-8.836-7.164-16-16-16h-96c-8.836 0-16 7.164-16 16v176h-176c-8.836 0-16 7.164-16 16v96c0 8.836 7.164 16 16 16h176v176c0 8.836 7.164 16 16 16h96c8.836 0 16-7.164 16-16v-176h176c8.836 0 16-7.164 16-16v-96c0-8.836-7.164-16-16-16z'],
  viewBox: '0 0 512 512'
};

var CONTENT_COPY = exports.CONTENT_COPY = {
  id: 'copy',
  paths: ['M607.5 672v-448.5h-351v448.5h351zM607.5 160.5c34.5 0 64.5 28.5 64.5 63v448.5c0 34.5-30 64.5-64.5 64.5h-351c-34.5 0-64.5-30-64.5-64.5v-448.5c0-34.5 30-63 64.5-63h351zM511.5 31.5v64.5h-384v448.5h-63v-448.5c0-34.5 28.5-64.5 63-64.5h384z'],
  viewBox: '0 0 712 712'
};

var TRACK_LINE = exports.TRACK_LINE = {
  id: 'trackLine',
  paths: ['M60 20 L50 52 L40 26 L34 46 L24 30 L14 50 L4 12'],
  viewBox: '0 0 60 60'
};

var SELECT = exports.SELECT = {
  id: 'select',
  viewBox: '0 0 16 16',
  paths: ['M2 14h2v1H1v-3h1v2zm8 1H6v-1h4v1zm5 0h-3v-1h2v-2h1v3zm0-5h-1V6h1v4zM2 10H1V6h1v4zm13-6h-1V2h-2V1h3v3zM4 2H2v2H1V1h3v1zm6 0H6V1h4.03L10 2z']
};

var CHECK_SQUARE_O = exports.CHECK_SQUARE_O = {
  id: 'check_square_o',
  viewBox: '0 0 1792 1792',
  paths: ['M1472 930v318q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q63 0 117 25 15 7 18 23 3 17-9 29l-49 49q-10 10-23 10-3 0-9-2-23-6-45-6h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-254q0-13 9-22l64-64q10-10 23-10 6 0 12 3 20 8 20 29zm231-489l-814 814q-24 24-57 24t-57-24l-430-430q-24-24-24-57t24-57l110-110q24-24 57-24t57 24l263 263 647-647q24-24 57-24t57 24l110 110q24 24 24 57t-24 57z']
};

var SQUARE_O = exports.SQUARE_O = {
  id: 'square_o',
  viewBox: '0 0 1792 1792',
  paths: ['M1312 256h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-832q0-66-47-113t-113-47zm288 160v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z']
};

var FILE_O = exports.FILE_O = {
  id: 'file_o',
  viewBox: '0 0 1792 1792',
  paths: ['M1596 380q28 28 48 76t20 88v1152q0 40-28 68t-68 28h-1344q-40 0-68-28t-28-68v-1600q0-40 28-68t68-28h896q40 0 88 20t76 48zm-444-244v376h376q-10-29-22-41l-313-313q-12-12-41-22zm384 1528v-1024h-416q-40 0-68-28t-28-68v-416h-768v1536h1280z']
};

var CHEVRON_RIGHT = exports.CHEVRON_RIGHT = {
  id: 'chevron_right',
  viewBox: '0 0 1792 1792',
  paths: ['M1363 877l-742 742q-19 19-45 19t-45-19l-166-166q-19-19-19-45t19-45l531-531-531-531q-19-19-19-45t19-45l166-166q19-19 45-19t45 19l742 742q19 19 19 45t-19 45z']
};

var CHEVRON_DOWN = exports.CHEVRON_DOWN = {
  id: 'chevron_down',
  viewBox: '0 0 1792 1792',
  paths: ['M1683 808l-742 741q-19 19-45 19t-45-19l-742-741q-19-19-19-45.5t19-45.5l166-165q19-19 45-19t45 19l531 531 531-531q19-19 45-19t45 19l166 165q19 19 19 45.5t-19 45.5z']
};

var FOLDER_O = exports.FOLDER_O = {
  id: 'folder_o',
  viewBox: '0 0 1792 1792',
  paths: ['M1600 1312v-704q0-40-28-68t-68-28h-704q-40 0-68-28t-28-68v-64q0-40-28-68t-68-28h-320q-40 0-68 28t-28 68v960q0 40 28 68t68 28h1216q40 0 68-28t28-68zm128-704v704q0 92-66 158t-158 66h-1216q-92 0-158-66t-66-158v-960q0-92 66-158t158-66h320q92 0 158 66t66 158v32h672q92 0 158 66t66 158z']
};

var FOLDER_OPEN_O = exports.FOLDER_OPEN_O = {
  id: 'folder_open_o',
  viewBox: '0 0 1792 1792',
  paths: ['M1845 931q0-35-53-35h-1088q-40 0-85.5 21.5t-71.5 52.5l-294 363q-18 24-18 40 0 35 53 35h1088q40 0 86-22t71-53l294-363q18-22 18-39zm-1141-163h768v-160q0-40-28-68t-68-28h-576q-40 0-68-28t-28-68v-64q0-40-28-68t-68-28h-320q-40 0-68 28t-28 68v853l256-315q44-53 116-87.5t140-34.5zm1269 163q0 62-46 120l-295 363q-43 53-116 87.5t-140 34.5h-1088q-92 0-158-66t-66-158v-960q0-92 66-158t158-66h320q92 0 158 66t66 158v32h544q92 0 158 66t66 158v160h192q54 0 99 24.5t67 70.5q15 32 15 68z']
};

var all = exports.all = [COG, CROSS, ENLARGE, MINUS, MOVE, PLAY, PLUS, CONTENT_COPY, SELECT, CHECK_SQUARE_O, SQUARE_O, FILE_O, FOLDER_O, FOLDER_OPEN_O, CHEVRON_RIGHT, CHEVRON_DOWN];

var parser = new DOMParser();

var svgGeoMapStr = '<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="1.5"><path d="M4 2.1L.5 3.5v12l5-2 5 2 5-2v-12l-5 2-3.17-1.268M10.5 3.5v12" fill="none" stroke="currentColor"/><path d="M5.5 13.5v-7" fill="none" stroke="currentColor" stroke-width=".9969299999999999"/><path d="M5.494 0c-1.803 0-3.26 1.496-3.26 3.35 0 .427.124.97.264 1.343L5.5 11l3.003-6.306c.142-.375.263-.916.263-1.342C8.766 1.496 7.3 0 5.494 0zM5.5 4.64c-.76 0-1.375-.616-1.375-1.374 0-.76.616-1.376 1.375-1.376.76 0 1.374.616 1.374 1.376 0 .758-.614 1.375-1.374 1.375z" fill="currentColor"/></svg>';
var svgGeoMapIcon = exports.svgGeoMapIcon = parser.parseFromString(svgGeoMapStr, 'text/xml').documentElement;

var horizontal1dHeatmap = '\n<svg width="20px" height="20px" viewBox="0 0 20 20">\n  <rect x="0" y="3" width="4" height="14" fill="#637993"/>\n  <rect x="4" y="3" width="2" height="14" fill="#c7d1de"/>\n  <rect x="6" y="3" width="5" height="14" fill="#3c5068"/>\n  <rect x="11" y="3" width="3" height="14" fill="#92a3ba"/>\n  <rect x="14" y="3" width="2" height="14" fill="#000000"/>\n  <rect x="16" y="3" width="4" height="14" fill="#637993"/>\n</svg>\n';
var svgHorizontal1dHeatmap = exports.svgHorizontal1dHeatmap = parser.parseFromString(horizontal1dHeatmap, 'text/xml').documentElement;

var horizontalLineStr = '\n<svg width="20px" height="20px" viewBox="0 0 135 85" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <title>line</title>\n    <defs></defs>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n        <polyline id="Path" stroke="#4990E2" stroke-width="8" points="2 45.5625 20.7460938 6.3359375 36.828125 86.6484375 59.8945312 17.5742188 79.0390625 70.703125 99.9335938 27 112.769531 81.1601562 132.078125 3"></polyline>\n    </g>\n</svg>\n';

var svgHorizontalLineIcon = exports.svgHorizontalLineIcon = parser.parseFromString(horizontalLineStr, 'text/xml').documentElement;

var tiles2DIconStr = '\n<svg width="20px" height="20px" viewBox="0 0 60 60" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <!-- Generator: Sketch 41 (35326) - http://www.bohemiancoding.com/sketch -->\n    <title>2d-tiles-icon</title>\n    <desc>Created with Sketch.</desc>\n    <defs>\n        <rect id="tiles2DIconStr-path-1" x="0" y="0" width="30" height="30"></rect>\n        <mask id="tiles2DIconStr-mask-2" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="30" height="30" fill="white">\n            <use xlink:href="#tiles2DIconStr-path-1"></use>\n        </mask>\n        <rect id="tiles2DIconStr-path-3" x="0" y="30" width="30" height="30"></rect>\n        <mask id="tiles2DIconStr-mask-4" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="30" height="30" fill="white">\n            <use xlink:href="#tiles2DIconStr-path-3"></use>\n        </mask>\n        <rect id="tiles2DIconStr-path-5" x="30" y="0" width="30" height="30"></rect>\n        <mask id="tiles2DIconStr-mask-6" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="30" height="30" fill="white">\n            <use xlink:href="#tiles2DIconStr-path-5"></use>\n        </mask>\n        <rect id="tiles2DIconStr-path-7" x="30" y="30" width="30" height="30"></rect>\n        <mask id="tiles2DIconStr-mask-8" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="30" height="30" fill="white">\n            <use xlink:href="#tiles2DIconStr-path-7"></use>\n        </mask>\n    </defs>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n        <use id="Rectangle" stroke="#979797" mask="url(#tiles2DIconStr-mask-2)" stroke-width="6" fill="#EEE0E0" xlink:href="#tiles2DIconStr-path-1"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#tiles2DIconStr-mask-4)" stroke-width="6" fill="#EEE0E0" xlink:href="#tiles2DIconStr-path-3"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#tiles2DIconStr-mask-6)" stroke-width="6" fill="#EEE0E0" xlink:href="#tiles2DIconStr-path-5"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#tiles2DIconStr-mask-8)" stroke-width="6" fill="#EEE0E0" xlink:href="#tiles2DIconStr-path-7"></use>\n    </g>\n</svg>\n';

var svg2DTilesIcon = exports.svg2DTilesIcon = parser.parseFromString(tiles2DIconStr, 'text/xml').documentElement;

var heatmap2DStr = '\n<svg width="20px" height="20px" viewBox="0 0 90 90" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <!-- Generator: Sketch 41 (35326) - http://www.bohemiancoding.com/sketch -->\n    <title>2d-heatmap</title>\n    <desc>Created with Sketch.</desc>\n    <defs>\n        <rect id="heatmap2DStr-path-1" x="0" y="0" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-2" x="30" y="0" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-3" x="60" y="0" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-4" x="0" y="30" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-5" x="30" y="30" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-6" x="60" y="30" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-7" x="0" y="60" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-8" x="30" y="60" width="30" height="30"></rect>\n        <rect id="heatmap2DStr-path-9" x="60" y="60" width="30" height="30"></rect>\n    </defs>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n        <use id="Rectangle" fill="#858372" xlink:href="#heatmap2DStr-path-1"></use>\n        <use id="Rectangle" fill="#BBBAA4" xlink:href="#heatmap2DStr-path-2"></use>\n        <use id="Rectangle" fill="#ECECD5" xlink:href="#heatmap2DStr-path-3"></use>\n        <use id="Rectangle" fill="#BCBD9E" xlink:href="#heatmap2DStr-path-4"></use>\n        <use id="Rectangle" fill="#817C7C" xlink:href="#heatmap2DStr-path-5"></use>\n        <use id="Rectangle" fill="#BBBAA4" xlink:href="#heatmap2DStr-path-6"></use>\n        <use id="Rectangle" fill="#ECECD5" xlink:href="#heatmap2DStr-path-7"></use>\n        <use id="Rectangle" fill="#BBBAA4" xlink:href="#heatmap2DStr-path-8"></use>\n        <use id="Rectangle" fill="#7B7777" xlink:href="#heatmap2DStr-path-9"></use>\n    </g>\n</svg>\n';

var svg2DHeatmapIcon = exports.svg2DHeatmapIcon = parser.parseFromString(heatmap2DStr, 'text/xml').documentElement;

var axis1D = '\n<svg width="20px" height="20px" viewBox="0 0 77 33" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <!-- Generator: Sketch 41 (35326) - http://www.bohemiancoding.com/sketch -->\n    <title>axis-1d</title>\n    <desc>Created with Sketch.</desc>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n        <polyline id="Path" stroke="#979797" stroke-width="8" transform="translate(38.258485, 27.557860) scale(1, -1) translate(-38.258485, -27.557860) " points="4 27.05786 36.7512307 27.05786 72.5169695 27.05786"></polyline>\n        <path d="M38,24.484375 L38,3" id="Path-2" stroke="#979797" stroke-width="4"></path>\n    </g>\n</svg>\n';

var svg1DAxisIcon = exports.svg1DAxisIcon = parser.parseFromString(axis1D, 'text/xml').documentElement;
var svgVertical1DAxisIcon = exports.svgVertical1DAxisIcon = (0, _d3Selection.select)(parser.parseFromString(axis1D, 'text/xml').documentElement).style('transform', 'rotate(90deg)').node();

var geneAnnotations = '\n<svg width="20px" height="20px" viewBox="0 0 171 116" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <!-- Generator: Sketch 41 (35326) - http://www.bohemiancoding.com/sketch -->\n    <title>gene-annotations</title>\n    <desc>Created with Sketch.</desc>\n    <defs>\n        <rect id="geneAnnotations-path-1" x="34" y="0" width="24" height="116"></rect>\n        <mask id="geneAnnotations-mask-2" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="24" height="116" fill="white">\n            <use xlink:href="#geneAnnotations-path-1"></use>\n        </mask>\n        <rect id="geneAnnotations-path-3" x="80" y="0" width="56" height="116"></rect>\n        <mask id="geneAnnotations-mask-4" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="56" height="116" fill="white">\n            <use xlink:href="#geneAnnotations-path-3"></use>\n        </mask>\n        <rect id="geneAnnotations-path-5" x="147" y="40" width="24" height="35"></rect>\n        <mask id="geneAnnotations-mask-6" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="24" height="35" fill="white">\n            <use xlink:href="#geneAnnotations-path-5"></use>\n        </mask>\n    </defs>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n        <path d="M12.71875,58 L147.10172,58" id="Path" stroke="#979797" stroke-width="8"></path>\n        <use id="Rectangle" stroke="#979797" mask="url(#geneAnnotations-mask-2)" stroke-width="4" fill="#DDDD66" xlink:href="#geneAnnotations-path-1"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#geneAnnotations-mask-4)" stroke-width="4" fill="#DDDD66" xlink:href="#geneAnnotations-path-3"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#geneAnnotations-mask-6)" stroke-width="4" fill="#DDDD66" xlink:href="#geneAnnotations-path-5"></use>\n        <polygon id="Triangle" stroke="#979797" fill="#D8D8D8" points="25 57.5 1 75 1 40"></polygon>\n    </g>\n</svg>\n';

var svgGeneAnnotationsIcon = exports.svgGeneAnnotationsIcon = parser.parseFromString(geneAnnotations, 'text/xml').documentElement;

var tiles1DIconStr = '\n<svg width="20px" height="20px" viewBox="0 0 180 90" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <!-- Generator: Sketch 42 (36781) - http://www.bohemiancoding.com/sketch -->\n    <title>1d-tiles-icon</title>\n    <desc>Created with Sketch.</desc>\n    <defs>\n        <rect id="tiles1DIconStr-path-1" x="0" y="0" width="90" height="90"></rect>\n        <mask id="tiles1DIconStr-mask-2" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="90" height="90" fill="white">\n            <use xlink:href="#tiles1DIconStr-path-1"></use>\n        </mask>\n        <rect id="tiles1DIconStr-path-3" x="90" y="0" width="90" height="90"></rect>\n        <mask id="tiles1DIconStr-mask-4" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="90" height="90" fill="white">\n            <use xlink:href="#tiles1DIconStr-path-3"></use>\n        </mask>\n    </defs>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\n        <use id="Rectangle" stroke="#979797" mask="url(#tiles1DIconStr-mask-2)" stroke-width="12" fill="#E6D5D5" xlink:href="#tiles1DIconStr-path-1"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#tiles1DIconStr-mask-4)" stroke-width="12" fill="#E6D5D5" xlink:href="#tiles1DIconStr-path-3"></use>\n    </g>\n</svg>\n';

var svg1DTilesIcon = exports.svg1DTilesIcon = parser.parseFromString(tiles1DIconStr, 'text/xml').documentElement;
var svgVertical1DTilesIcon = exports.svgVertical1DTilesIcon = (0, _d3Selection.select)(parser.parseFromString(tiles1DIconStr, 'text/xml').documentElement).style('transform', 'rotate(90deg)').node();

var arrowHeadDomainsStr = '\n<svg width="20px" height="20px" viewBox="0 0 111 111" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\n    <!-- Generator: Sketch 42 (36781) - http://www.bohemiancoding.com/sketch -->\n    <title>arrowhead-domains</title>\n    <desc>Created with Sketch.</desc>\n    <defs>\n        <rect id="arrowHeadDomainsStr-path-1" x="0" y="0" width="90" height="90"></rect>\n        <mask id="arrowHeadDomainsStr-mask-2" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="90" height="90" fill="white">\n            <use xlink:href="#arrowHeadDomainsStr-path-1"></use>\n        </mask>\n        <rect id="arrowHeadDomainsStr-path-3" x="52" y="52" width="59" height="59"></rect>\n        <mask id="arrowHeadDomainsStr-mask-4" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="59" height="59" fill="white">\n            <use xlink:href="#arrowHeadDomainsStr-path-3"></use>\n        </mask>\n    </defs>\n    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" fill-opacity="0">\n        <use id="Rectangle" stroke="#979797" mask="url(#arrowHeadDomainsStr-mask-2)" stroke-width="22" fill="#D8D8D8" xlink:href="#arrowHeadDomainsStr-path-1"></use>\n        <use id="Rectangle" stroke="#979797" mask="url(#arrowHeadDomainsStr-mask-4)" stroke-width="22" fill="#D8D8D8" xlink:href="#arrowHeadDomainsStr-path-3"></use>\n    </g>\n</svg>\n';

var svgArrowheadDomainsIcon = exports.svgArrowheadDomainsIcon = parser.parseFromString(arrowHeadDomainsStr, 'text/xml').documentElement;

function SearchIcon(_ref) {
  var theStyle = _ref.theStyle;

  return _react2['default'].createElement(
    'svg',
    {
      viewBox: '0 0 12 13',
      xmlns: 'http://www.w3.org/2000/svg',
      className: (0, _getClassName3['default'])(theStyle, _styleModuleImportMap)
    },
    _react2['default'].createElement(
      'g',
      { fill: 'none', stroke: '#6c6c6c', strokeWidth: '2' },
      _react2['default'].createElement('path', { d: 'M11.29 11.71l-4-4' }),
      _react2['default'].createElement('circle', { cx: '5', cy: '5', r: '4' })
    )
  );
}

/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"multitrack-header":"ViewHeader-module_multitrack-header-3XnZx","multitrack-header-focus":"ViewHeader-module_multitrack-header-focus-3akkN","multitrack-header-squeazed":"ViewHeader-module_multitrack-header-squeazed-GHIVd","multitrack-header-dark":"ViewHeader-module_multitrack-header-dark-97tZt","multitrack-header-id":"ViewHeader-module_multitrack-header-id-3YURk","multitrack-header-left":"ViewHeader-module_multitrack-header-left-Qj9Sm","multitrack-header-grabber":"ViewHeader-module_multitrack-header-grabber-3jrIz","multitrack-header-grabber-squeazed":"ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z","multitrack-header-search":"ViewHeader-module_multitrack-header-search-1X_3_","multitrack-header-nav-list":"ViewHeader-module_multitrack-header-nav-list-2nvcu","multitrack-header-icon":"ViewHeader-module_multitrack-header-icon-16QKZ","multitrack-header-icon-squeazed":"ViewHeader-module_multitrack-header-icon-squeazed-25lkF","mouse-tool-selection":"ViewHeader-module_mouse-tool-selection-1pg2m"};

/***/ }),
/* 268 */
/***/ (function(module, exports, __nested_webpack_require_1483497__) {

"use strict";


var URI = __nested_webpack_require_1483497__(693)
  , equal = __nested_webpack_require_1483497__(269)
  , util = __nested_webpack_require_1483497__(117)
  , SchemaObject = __nested_webpack_require_1483497__(398)
  , traverse = __nested_webpack_require_1483497__(695);

module.exports = resolve;

resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;

/**
 * [resolve and compile the references ($ref)]
 * @this   Ajv
 * @param  {Function} compile reference to schema compilation funciton (localCompile)
 * @param  {Object} root object with information about the root schema for the current schema
 * @param  {String} ref reference to resolve
 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
 */
function resolve(compile, root, ref) {
  /* jshint validthis: true */
  var refVal = this._refs[ref];
  if (typeof refVal == 'string') {
    if (this._refs[refVal]) refVal = this._refs[refVal];
    else return resolve.call(this, compile, root, refVal);
  }

  refVal = refVal || this._schemas[ref];
  if (refVal instanceof SchemaObject) {
    return inlineRef(refVal.schema, this._opts.inlineRefs)
            ? refVal.schema
            : refVal.validate || this._compile(refVal);
  }

  var res = resolveSchema.call(this, root, ref);
  var schema, v, baseId;
  if (res) {
    schema = res.schema;
    root = res.root;
    baseId = res.baseId;
  }

  if (schema instanceof SchemaObject) {
    v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
  } else if (schema !== undefined) {
    v = inlineRef(schema, this._opts.inlineRefs)
        ? schema
        : compile.call(this, schema, root, undefined, baseId);
  }

  return v;
}


/**
 * Resolve schema, its root and baseId
 * @this Ajv
 * @param  {Object} root root object with properties schema, refVal, refs
 * @param  {String} ref  reference to resolve
 * @return {Object} object with properties schema, root, baseId
 */
function resolveSchema(root, ref) {
  /* jshint validthis: true */
  var p = URI.parse(ref)
    , refPath = _getFullPath(p)
    , baseId = getFullPath(this._getId(root.schema));
  if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == 'string') {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject) {
      if (!refVal.validate) this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        if (id == normalizeId(ref))
          return { schema: refVal, root: root, baseId: baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema) return;
    baseId = getFullPath(this._getId(root.schema));
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}


/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
  /* jshint validthis: true */
  var res = resolveSchema.call(this, root, ref);
  if (res) {
    var schema = res.schema;
    var baseId = res.baseId;
    root = res.root;
    var id = this._getId(schema);
    if (id) baseId = resolveUrl(baseId, id);
    return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  }
}


var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
  /* jshint validthis: true */
  parsedRef.fragment = parsedRef.fragment || '';
  if (parsedRef.fragment.slice(0,1) != '/') return;
  var parts = parsedRef.fragment.split('/');

  for (var i = 1; i < parts.length; i++) {
    var part = parts[i];
    if (part) {
      part = util.unescapeFragment(part);
      schema = schema[part];
      if (schema === undefined) break;
      var id;
      if (!PREVENT_SCOPE_CHANGE[part]) {
        id = this._getId(schema);
        if (id) baseId = resolveUrl(baseId, id);
        if (schema.$ref) {
          var $ref = resolveUrl(baseId, schema.$ref);
          var res = resolveSchema.call(this, root, $ref);
          if (res) {
            schema = res.schema;
            root = res.root;
            baseId = res.baseId;
          }
        }
      }
    }
  }
  if (schema !== undefined && schema !== root.schema)
    return { schema: schema, root: root, baseId: baseId };
}


var SIMPLE_INLINED = util.toHash([
  'type', 'format', 'pattern',
  'maxLength', 'minLength',
  'maxProperties', 'minProperties',
  'maxItems', 'minItems',
  'maximum', 'minimum',
  'uniqueItems', 'multipleOf',
  'required', 'enum'
]);
function inlineRef(schema, limit) {
  if (limit === false) return false;
  if (limit === undefined || limit === true) return checkNoRef(schema);
  else if (limit) return countKeys(schema) <= limit;
}


function checkNoRef(schema) {
  var item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return false;
      item = schema[key];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  }
  return true;
}


function countKeys(schema) {
  var count = 0, item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object') count += countKeys(item);
      if (count == Infinity) return Infinity;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return Infinity;
      if (SIMPLE_INLINED[key]) {
        count++;
      } else {
        item = schema[key];
        if (typeof item == 'object') count += countKeys(item) + 1;
        if (count == Infinity) return Infinity;
      }
    }
  }
  return count;
}


function getFullPath(id, normalize) {
  if (normalize !== false) id = normalizeId(id);
  var p = URI.parse(id);
  return _getFullPath(p);
}


function _getFullPath(p) {
  return URI.serialize(p).split('#')[0] + '#';
}


var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
  return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}


function resolveUrl(baseId, id) {
  id = normalizeId(id);
  return URI.resolve(baseId, id);
}


/* @this Ajv */
function resolveIds(schema) {
  var schemaId = normalizeId(this._getId(schema));
  var baseIds = {'': schemaId};
  var fullPaths = {'': getFullPath(schemaId, false)};
  var localRefs = {};
  var self = this;

  traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
    if (jsonPtr === '') return;
    var id = self._getId(sch);
    var baseId = baseIds[parentJsonPtr];
    var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
    if (keyIndex !== undefined)
      fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));

    if (typeof id == 'string') {
      id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);

      var refVal = self._refs[id];
      if (typeof refVal == 'string') refVal = self._refs[refVal];
      if (refVal && refVal.schema) {
        if (!equal(sch, refVal.schema))
          throw new Error('id "' + id + '" resolves to more than one schema');
      } else if (id != normalizeId(fullPath)) {
        if (id[0] == '#') {
          if (localRefs[id] && !equal(sch, localRefs[id]))
            throw new Error('id "' + id + '" resolves to more than one schema');
          localRefs[id] = sch;
        } else {
          self._refs[id] = fullPath;
        }
      }
    }
    baseIds[jsonPtr] = baseId;
    fullPaths[jsonPtr] = fullPath;
  });

  return localRefs;
}


/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var isArray = Array.isArray;
var keyList = Object.keys;
var hasProp = Object.prototype.hasOwnProperty;

module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    var arrA = isArray(a)
      , arrB = isArray(b)
      , i
      , length
      , key;

    if (arrA && arrB) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }

    if (arrA != arrB) return false;

    var dateA = a instanceof Date
      , dateB = b instanceof Date;
    if (dateA != dateB) return false;
    if (dateA && dateB) return a.getTime() == b.getTime();

    var regexpA = a instanceof RegExp
      , regexpB = b instanceof RegExp;
    if (regexpA != regexpB) return false;
    if (regexpA && regexpB) return a.toString() == b.toString();

    var keys = keyList(a);
    length = keys.length;

    if (length !== keyList(b).length)
      return false;

    for (i = length; i-- !== 0;)
      if (!hasProp.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      key = keys[i];
      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  return a!==a && b!==b;
};


/***/ }),
/* 270 */
/***/ (function(module, exports, __nested_webpack_require_1492801__) {

"use strict";


var resolve = __nested_webpack_require_1492801__(268);

module.exports = {
  Validation: errorSubclass(ValidationError),
  MissingRef: errorSubclass(MissingRefError)
};


function ValidationError(errors) {
  this.message = 'validation failed';
  this.errors = errors;
  this.ajv = this.validation = true;
}


MissingRefError.message = function (baseId, ref) {
  return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
};


function MissingRefError(baseId, ref, message) {
  this.message = message || MissingRefError.message(baseId, ref);
  this.missingRef = resolve.url(baseId, ref);
  this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
}


function errorSubclass(Subclass) {
  Subclass.prototype = Object.create(Error.prototype);
  Subclass.prototype.constructor = Subclass;
  return Subclass;
}


/***/ }),
/* 271 */
/***/ (function(module) {

module.exports = {"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://higlass.io/#viewconf","title":"HiGlass viewconf","type":"object","additionalProperties":false,"required":[],"properties":{"editable":{"type":"boolean","default":true},"viewEditable":{"type":"boolean","default":true},"tracksEditable":{"type":"boolean","default":true},"zoomFixed":{"type":"boolean"},"compactLayout":{"type":"boolean"},"exportViewUrl":{"type":"string"},"trackSourceServers":{"type":"array","items":{"type":"string"},"minLength":1},"zoomLocks":{"$ref":"#/definitions/locks/zoomLocks"},"locationLocks":{"$ref":"#/definitions/locks/locationLocks"},"valueScaleLocks":{"$ref":"#/definitions/locks/valueScaleLocks"},"views":{"type":"array","items":{"$ref":"#/definitions/view"},"minLength":1},"chromInfoPath":{"type":"string"}},"definitions":{"data":{"type":"object","properties":{"url":{"type":"string"},"server":{"type":"string"},"filetype":{"type":"string"},"type":{"type":"string"},"tilesetInfo":{"type":"object"},"children":{"type":"array"},"tiles":{"type":"object"}}},"locks":{"slug":{"type":"string"},"locksByViewUid":{"type":"object","additionalProperties":false,"patternProperties":{".":{"$ref":"#/definitions/locks/slug"}}},"axisSpecificLocks":{"additionalProperties":false,"properties":{"axis":{"enum":["x","y"],"type":"string"},"lock":{"type":"string"}},"required":["lock","axis"],"type":"object"},"locationLocksByViewUid":{"type":"object","additionalProperties":false,"patternProperties":{".":{"anyOf":[{"type":"string"},{"additionalProperties":false,"properties":{"x":{"$ref":"#/definitions/locks/axisSpecificLocks"},"y":{"$ref":"#/definitions/locks/axisSpecificLocks"}},"type":"object"}]}}},"zoomLocks":{"type":"object","additionalProperties":false,"required":[],"properties":{"locksByViewUid":{"$ref":"#/definitions/locks/locksByViewUid"},"locksDict":{"type":"object","additionalProperties":false,"patternProperties":{".":{"type":"object","additionalProperties":false,"properties":{"uid":{"$ref":"#/definitions/locks/slug"}},"patternProperties":{"^(?!uid).":{"type":"array","minLength":3,"maxLength":3,"items":{"type":"number"}}}}}}}},"locationLocks":{"type":"object","additionalProperties":false,"required":[],"properties":{"locksByViewUid":{"$ref":"#/definitions/locks/locationLocksByViewUid"},"locksDict":{"type":"object","additionalProperties":false,"patternProperties":{".":{"type":"object","additionalProperties":false,"properties":{"uid":{"$ref":"#/definitions/locks/slug"}},"patternProperties":{"^(?!uid).":{"type":"array","minLength":3,"maxLength":3,"items":{"type":"number"}}}}}}}},"valueScaleLocks":{"type":"object","additionalProperties":false,"required":["locksByViewUid","locksDict"],"properties":{"locksByViewUid":{"$ref":"#/definitions/locks/locksByViewUid"},"locksDict":{"type":"object","additionalProperties":false,"patternProperties":{".":{"type":"object","additionalProperties":false,"properties":{"uid":{"$ref":"#/definitions/locks/slug"},"ignoreOffScreenValues":{"type":"boolean"}},"patternProperties":{"^(?!(uid|ignoreOffScreenValues)).":{"type":"object","additionalProperties":false,"required":["view","track"],"properties":{"view":{"type":"string"},"track":{"$ref":"#/definitions/locks/slug"}}}}}}}}}},"view":{"type":"object","additionalProperties":false,"required":["tracks","layout"],"properties":{"autocompleteSource":{"type":"string"},"chromInfoPath":{"type":"string"},"genomePositionSearchBox":{"$ref":"#/definitions/viewProperties/genomePositionSearchBox"},"genomePositionSearchBoxVisible":{"type":"boolean"},"initialXDomain":{"$ref":"#/definitions/viewProperties/domain"},"initialYDomain":{"$ref":"#/definitions/viewProperties/domain"},"layout":{"$ref":"#/definitions/viewProperties/layout"},"overlays":{"type":"array","items":{"$ref":"#/definitions/viewProperties/overlay"}},"selectionView":{"type":"boolean"},"tracks":{"$ref":"#/definitions/viewProperties/tracks_object"},"uid":{"type":"string"},"zoomFixed":{"type":"boolean"},"zoomLimits":{"type":"array","minLength":2,"maxLength":2,"default":[1,null]}}},"viewProperties":{"genomePositionSearchBox":{"type":"object","title":"The Genome Position Search Box Schema","required":["chromInfoServer","chromInfoId"],"properties":{"autocompleteServer":{"type":"string","title":"The Autocomplete Server URL","default":"","examples":["//higlass.io/api/v1"],"pattern":"^(.*)$"},"autocompleteId":{"type":"string","title":"The Autocomplete ID","default":"","examples":["OHJakQICQD6gTD7skx4EWA"],"pattern":"^(.*)$"},"chromInfoServer":{"type":"string","title":"The Chrominfo Server URL","default":"","examples":["//higlass.io/api/v1"],"pattern":"^(.*)$"},"chromInfoId":{"type":"string","title":"The Chromosome Info ID","default":"","examples":["hg19"],"pattern":"^(.*)$"},"visible":{"type":"boolean","title":"The Visible Schema","default":false}}},"overlay":{"type":"object","additionalProperties":false,"properties":{"chromInfoPath":{"type":"string"},"includes":{"type":"array"},"options":{"type":"object","properties":{"extent":{"type":"array"},"minWidth":{"type":"number"},"fill":{"type":"string"},"fillOpacity":{"type":"number"},"stroke":{"type":"string"},"strokeOpacity":{"type":"number"},"strokeWidth":{"type":"number"},"strokePos":{"type":["string","array"]},"outline":{"type":"string"},"outlineOpacity":{"type":"number"},"outlineWidth":{"type":"number"},"outlinePos":{"type":["string","array"]}}},"type":{"type":"string"},"uid":{"type":"string"}}},"layout":{"type":"object","additionalProperties":false,"required":["w","h","x","y"],"properties":{"x":{"type":"integer","title":"The X Position","default":0},"y":{"type":"integer","title":"The Y Position","default":0},"w":{"type":"integer","title":"Width","default":12},"h":{"type":"integer","title":"Height","default":12},"moved":{"type":"boolean"},"static":{"type":"boolean"}}},"tracks_object":{"type":"object","additionalProperties":false,"properties":{"left":{"$ref":"#/definitions/viewProperties/tracks_array"},"right":{"$ref":"#/definitions/viewProperties/tracks_array"},"top":{"$ref":"#/definitions/viewProperties/tracks_array"},"bottom":{"$ref":"#/definitions/viewProperties/tracks_array"},"center":{"$ref":"#/definitions/viewProperties/tracks_array"},"whole":{"$ref":"#/definitions/viewProperties/tracks_array"},"gallery":{"$ref":"#/definitions/viewProperties/tracks_array"}}},"tracks_array":{"type":"array","items":{"oneOf":[{"$ref":"#/definitions/tracks/enum_track"},{"$ref":"#/definitions/tracks/combined_track"},{"$ref":"#/definitions/tracks/heatmap_track"},{"$ref":"#/definitions/tracks/independent_viewport_projection_track"}]}},"domain":{"type":"array","items":{"type":"number"},"maxItems":2,"minItems":2}},"tracks":{"heatmap_track":{"type":"object","additionalProperties":false,"required":[],"properties":{"uid":{"type":"string"},"type":{"const":"heatmap"},"data":{"$ref":"#/definitions/data"},"height":{"type":"number"},"options":{"type":"object"},"position":{"type":"string"},"server":{"type":"string"},"tilesetUid":{"type":"string"},"width":{"type":"number"},"transforms":{"type":"array"}}},"combined_track":{"type":"object","additionalProperties":false,"required":["contents"],"properties":{"contents":{"$ref":"#/definitions/viewProperties/tracks_array"},"height":{"type":"number"},"options":{},"position":{"type":"string"},"type":{"const":"combined"},"uid":{"type":"string"},"width":{"type":"number"}}},"enum_track":{"type":"object","additionalProperties":false,"required":["type"],"properties":{"server":{"type":"string"},"tilesetUid":{"type":"string"},"data":{"$ref":"#/definitions/data"},"uid":{"type":"string"},"type":{"enum":["multivec","1d-heatmap","line","point","bar","divergent-bar","stacked-interval","gene-annotations","linear-2d-rectangle-domains","chromosome-labels","linear-heatmap","1d-value-interval","2d-annotations","2d-chromosome-annotations","2d-chromosome-grid","2d-chromosome-labels","2d-rectangle-domains","2d-tiles","arrowhead-domains","bedlike","cross-rule","dummy","horizontal-1d-annotations","horizontal-1d-heatmap","horizontal-1d-tiles","horizontal-1d-value-interval","horizontal-2d-rectangle-domains","horizontal-bar","horizontal-chromosome-grid","horizontal-chromosome-labels","horizontal-divergent-bar","horizontal-gene-annotations","horizontal-heatmap","horizontal-line","horizontal-multivec","horizontal-point","horizontal-rule","horizontal-vector-heatmap","image-tiles","left-axis","left-stacked-interval","mapbox-tiles","osm-2d-tile-ids","osm-tiles","raster-tiles","simple-svg","square-markers","top-axis","top-stacked-interval","vertical-1d-annotations","vertical-1d-heatmap","vertical-1d-tiles","vertical-1d-value-interval","vertical-2d-rectangle-domains","vertical-bar","vertical-bedlike","vertical-chromosome-grid","vertical-chromosome-labels","vertical-gene-annotations","vertical-heatmap","vertical-line","vertical-multivec","vertical-point","vertical-rule","vertical-vector-heatmap","viewport-projection-center","viewport-projection-horizontal","viewport-projection-vertical"]},"chromInfoPath":{"type":"string"},"fromViewUid":{"type":"string"},"height":{"type":"number"},"options":{"type":"object"},"width":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}}},"independent_viewport_projection_track":{"type":"object","additionalProperties":false,"properties":{"uid":{"type":"string"},"type":{"enum":["viewport-projection-horizontal","viewport-projection-vertical","viewport-projection-center"]},"fromViewUid":{"type":"null"},"projectionXDomain":{"$ref":"#/definitions/viewProperties/domain"},"projectionYDomain":{"$ref":"#/definitions/viewProperties/domain"},"options":{"type":"object"},"transforms":{"type":"array"},"width":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}}}}}};

/***/ }),
/* 272 */
/***/ (function(module, exports, __nested_webpack_require_1503464__) {

var baseForOwn = __nested_webpack_require_1503464__(407),
    castFunction = __nested_webpack_require_1503464__(411);

/**
 * Iterates over own enumerable string keyed properties of an object and
 * invokes `iteratee` for each property. The iteratee is invoked with three
 * arguments: (value, key, object). Iteratee functions may exit iteration
 * early by explicitly returning `false`.
 *
 * @static
 * @memberOf _
 * @since 0.3.0
 * @category Object
 * @param {Object} object The object to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Object} Returns `object`.
 * @see _.forOwnRight
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.forOwn(new Foo, function(value, key) {
 *   console.log(key);
 * });
 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
 */
function forOwn(object, iteratee) {
  return object && baseForOwn(object, castFunction(iteratee));
}

module.exports = forOwn;


/***/ }),
/* 273 */
/***/ (function(module, exports, __nested_webpack_require_1504533__) {

var baseIsTypedArray = __nested_webpack_require_1504533__(741),
    baseUnary = __nested_webpack_require_1504533__(275),
    nodeUtil = __nested_webpack_require_1504533__(276);

/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;

/**
 * Checks if `value` is classified as a typed array.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 * @example
 *
 * _.isTypedArray(new Uint8Array);
 * // => true
 *
 * _.isTypedArray([]);
 * // => false
 */
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;

module.exports = isTypedArray;


/***/ }),
/* 274 */
/***/ (function(module, exports) {

/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

module.exports = isLength;


/***/ }),
/* 275 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.unary` without support for storing metadata.
 *
 * @private
 * @param {Function} func The function to cap arguments for.
 * @returns {Function} Returns the new capped function.
 */
function baseUnary(func) {
  return function(value) {
    return func(value);
  };
}

module.exports = baseUnary;


/***/ }),
/* 276 */
/***/ (function(module, exports, __nested_webpack_require_1506554__) {

/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __nested_webpack_require_1506554__(406);

/** Detect free variable `exports`. */
var freeExports =   true && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;

/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
  try {
    // Use `util.types` for Node.js 10+.
    var types = freeModule && freeModule.require && freeModule.require('util').types;

    if (types) {
      return types;
    }

    // Legacy `process.binding('util')` for Node.js < 10.
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}());

module.exports = nodeUtil;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1506554__(173)(module)))

/***/ }),
/* 277 */
/***/ (function(module, exports, __nested_webpack_require_1507728__) {

var baseGetTag = __nested_webpack_require_1507728__(97),
    isObject = __nested_webpack_require_1507728__(45);

/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    proxyTag = '[object Proxy]';

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  if (!isObject(value)) {
    return false;
  }
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 9 which returns 'object' for typed arrays and other constructors.
  var tag = baseGetTag(value);
  return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}

module.exports = isFunction;


/***/ }),
/* 278 */
/***/ (function(module, exports, __nested_webpack_require_1508801__) {

var overArg = __nested_webpack_require_1508801__(410);

/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);

module.exports = getPrototype;


/***/ }),
/* 279 */
/***/ (function(module, exports, __nested_webpack_require_1509046__) {

var getNative = __nested_webpack_require_1509046__(99),
    root = __nested_webpack_require_1509046__(41);

/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');

module.exports = Map;


/***/ }),
/* 280 */
/***/ (function(module, exports, __nested_webpack_require_1509325__) {

var mapCacheClear = __nested_webpack_require_1509325__(760),
    mapCacheDelete = __nested_webpack_require_1509325__(767),
    mapCacheGet = __nested_webpack_require_1509325__(769),
    mapCacheHas = __nested_webpack_require_1509325__(770),
    mapCacheSet = __nested_webpack_require_1509325__(771);

/**
 * Creates a map cache object to store key-value pairs.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function MapCache(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;

module.exports = MapCache;


/***/ }),
/* 281 */
/***/ (function(module, exports) {

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

module.exports = arrayPush;


/***/ }),
/* 282 */
/***/ (function(module, exports, __nested_webpack_require_1510758__) {

var arrayFilter = __nested_webpack_require_1510758__(283),
    stubArray = __nested_webpack_require_1510758__(421);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
  if (object == null) {
    return [];
  }
  object = Object(object);
  return arrayFilter(nativeGetSymbols(object), function(symbol) {
    return propertyIsEnumerable.call(object, symbol);
  });
};

module.exports = getSymbols;


/***/ }),
/* 283 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.filter` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function arrayFilter(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length,
      resIndex = 0,
      result = [];

  while (++index < length) {
    var value = array[index];
    if (predicate(value, index, array)) {
      result[resIndex++] = value;
    }
  }
  return result;
}

module.exports = arrayFilter;


/***/ }),
/* 284 */
/***/ (function(module, exports, __nested_webpack_require_1512414__) {

var castPath = __nested_webpack_require_1512414__(193),
    toKey = __nested_webpack_require_1512414__(145);

/**
 * The base implementation of `_.get` without support for default values.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @returns {*} Returns the resolved value.
 */
function baseGet(object, path) {
  path = castPath(path, object);

  var index = 0,
      length = path.length;

  while (object != null && index < length) {
    object = object[toKey(path[index++])];
  }
  return (index && index == length) ? object : undefined;
}

module.exports = baseGet;


/***/ }),
/* 285 */
/***/ (function(module, exports, __nested_webpack_require_1513116__) {

var isArray = __nested_webpack_require_1513116__(31),
    isSymbol = __nested_webpack_require_1513116__(194);

/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
    reIsPlainProp = /^\w*$/;

/**
 * Checks if `value` is a property name and not a property path.
 *
 * @private
 * @param {*} value The value to check.
 * @param {Object} [object] The object to query keys on.
 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
 */
function isKey(value, object) {
  if (isArray(value)) {
    return false;
  }
  var type = typeof value;
  if (type == 'number' || type == 'symbol' || type == 'boolean' ||
      value == null || isSymbol(value)) {
    return true;
  }
  return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
    (object != null && value in Object(object));
}

module.exports = isKey;


/***/ }),
/* 286 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.forEach` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns `array`.
 */
function arrayEach(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}

module.exports = arrayEach;


/***/ }),
/* 287 */
/***/ (function(module, exports, __nested_webpack_require_1514676__) {

var defineProperty = __nested_webpack_require_1514676__(426);

/**
 * The base implementation of `assignValue` and `assignMergeValue` without
 * value checks.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function baseAssignValue(object, key, value) {
  if (key == '__proto__' && defineProperty) {
    defineProperty(object, key, {
      'configurable': true,
      'enumerable': true,
      'value': value,
      'writable': true
    });
  } else {
    object[key] = value;
  }
}

module.exports = baseAssignValue;


/***/ }),
/* 288 */
/***/ (function(module, exports, __nested_webpack_require_1515376__) {

var Uint8Array = __nested_webpack_require_1515376__(418);

/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */
function cloneArrayBuffer(arrayBuffer) {
  var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  return result;
}

module.exports = cloneArrayBuffer;


/***/ }),
/* 289 */
/***/ (function(module, exports, __nested_webpack_require_1515904__) {

"use strict";


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

var _react = __nested_webpack_require_1515904__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_1515904__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _checkboard = __nested_webpack_require_1515904__(826);

var checkboard = _interopRequireWildcard(_checkboard);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

var Checkboard = exports.Checkboard = function Checkboard(_ref) {
  var white = _ref.white,
      grey = _ref.grey,
      size = _ref.size,
      renderers = _ref.renderers,
      borderRadius = _ref.borderRadius,
      boxShadow = _ref.boxShadow;

  var styles = (0, _reactcss2.default)({
    'default': {
      grid: {
        borderRadius: borderRadius,
        boxShadow: boxShadow,
        absolute: '0px 0px 0px 0px',
        background: 'url(' + checkboard.get(white, grey, size, renderers.canvas) + ') center left'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.grid });
};

Checkboard.defaultProps = {
  size: 8,
  white: 'transparent',
  grey: 'rgba(0,0,0,.08)',
  renderers: {}
};

exports.default = Checkboard;

/***/ }),
/* 290 */
/***/ (function(module, exports, __nested_webpack_require_1517504__) {

var baseRest = __nested_webpack_require_1517504__(291),
    isIterateeCall = __nested_webpack_require_1517504__(294);

/**
 * Creates a function like `_.assign`.
 *
 * @private
 * @param {Function} assigner The function to assign values.
 * @returns {Function} Returns the new assigner function.
 */
function createAssigner(assigner) {
  return baseRest(function(object, sources) {
    var index = -1,
        length = sources.length,
        customizer = length > 1 ? sources[length - 1] : undefined,
        guard = length > 2 ? sources[2] : undefined;

    customizer = (assigner.length > 3 && typeof customizer == 'function')
      ? (length--, customizer)
      : undefined;

    if (guard && isIterateeCall(sources[0], sources[1], guard)) {
      customizer = length < 3 ? undefined : customizer;
      length = 1;
    }
    object = Object(object);
    while (++index < length) {
      var source = sources[index];
      if (source) {
        assigner(object, source, index, customizer);
      }
    }
    return object;
  });
}

module.exports = createAssigner;


/***/ }),
/* 291 */
/***/ (function(module, exports, __nested_webpack_require_1518623__) {

var identity = __nested_webpack_require_1518623__(143),
    overRest = __nested_webpack_require_1518623__(433),
    setToString = __nested_webpack_require_1518623__(293);

/**
 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @returns {Function} Returns the new function.
 */
function baseRest(func, start) {
  return setToString(overRest(func, start, identity), func + '');
}

module.exports = baseRest;


/***/ }),
/* 292 */
/***/ (function(module, exports) {

/**
 * A faster alternative to `Function#apply`, this function invokes `func`
 * with the `this` binding of `thisArg` and the arguments of `args`.
 *
 * @private
 * @param {Function} func The function to invoke.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} args The arguments to invoke `func` with.
 * @returns {*} Returns the result of `func`.
 */
function apply(func, thisArg, args) {
  switch (args.length) {
    case 0: return func.call(thisArg);
    case 1: return func.call(thisArg, args[0]);
    case 2: return func.call(thisArg, args[0], args[1]);
    case 3: return func.call(thisArg, args[0], args[1], args[2]);
  }
  return func.apply(thisArg, args);
}

module.exports = apply;


/***/ }),
/* 293 */
/***/ (function(module, exports, __nested_webpack_require_1520037__) {

var baseSetToString = __nested_webpack_require_1520037__(835),
    shortOut = __nested_webpack_require_1520037__(434);

/**
 * Sets the `toString` method of `func` to return `string`.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var setToString = shortOut(baseSetToString);

module.exports = setToString;


/***/ }),
/* 294 */
/***/ (function(module, exports, __nested_webpack_require_1520505__) {

var eq = __nested_webpack_require_1520505__(120),
    isArrayLike = __nested_webpack_require_1520505__(98),
    isIndex = __nested_webpack_require_1520505__(142),
    isObject = __nested_webpack_require_1520505__(45);

/**
 * Checks if the given arguments are from an iteratee call.
 *
 * @private
 * @param {*} value The potential iteratee value argument.
 * @param {*} index The potential iteratee index or key argument.
 * @param {*} object The potential iteratee object argument.
 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
 *  else `false`.
 */
function isIterateeCall(value, index, object) {
  if (!isObject(object)) {
    return false;
  }
  var type = typeof index;
  if (type == 'number'
        ? (isArrayLike(object) && isIndex(index, object.length))
        : (type == 'string' && index in object)
      ) {
    return eq(object[index], value);
  }
  return false;
}

module.exports = isIterateeCall;


/***/ }),
/* 295 */
/***/ (function(module, exports, __nested_webpack_require_1521474__) {

"use strict";


var slice = Array.prototype.slice;
var isArgs = __nested_webpack_require_1521474__(450);

var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __nested_webpack_require_1521474__(953);

var originalKeys = Object.keys;

keysShim.shim = function shimObjectKeys() {
	if (Object.keys) {
		var keysWorksWithArguments = (function () {
			// Safari 5.0 bug
			var args = Object.keys(arguments);
			return args && args.length === arguments.length;
		}(1, 2));
		if (!keysWorksWithArguments) {
			Object.keys = function keys(object) { // eslint-disable-line func-name-matching
				if (isArgs(object)) {
					return originalKeys(slice.call(object));
				}
				return originalKeys(object);
			};
		}
	} else {
		Object.keys = keysShim;
	}
	return Object.keys || keysShim;
};

module.exports = keysShim;


/***/ }),
/* 296 */
/***/ (function(module, exports, __nested_webpack_require_1522374__) {

/**
 * Export cheerio (with )
 */

exports = module.exports = __nested_webpack_require_1522374__(454);

/*
  Export the version
*/

exports.version = __nested_webpack_require_1522374__(1047).version;


/***/ }),
/* 297 */
/***/ (function(module) {

module.exports = {"Aacute":"Á","aacute":"á","Abreve":"Ă","abreve":"ă","ac":"∾","acd":"∿","acE":"∾̳","Acirc":"Â","acirc":"â","acute":"´","Acy":"А","acy":"а","AElig":"Æ","aelig":"æ","af":"⁡","Afr":"𝔄","afr":"𝔞","Agrave":"À","agrave":"à","alefsym":"ℵ","aleph":"ℵ","Alpha":"Α","alpha":"α","Amacr":"Ā","amacr":"ā","amalg":"⨿","amp":"&","AMP":"&","andand":"⩕","And":"⩓","and":"∧","andd":"⩜","andslope":"⩘","andv":"⩚","ang":"∠","ange":"⦤","angle":"∠","angmsdaa":"⦨","angmsdab":"⦩","angmsdac":"⦪","angmsdad":"⦫","angmsdae":"⦬","angmsdaf":"⦭","angmsdag":"⦮","angmsdah":"⦯","angmsd":"∡","angrt":"∟","angrtvb":"⊾","angrtvbd":"⦝","angsph":"∢","angst":"Å","angzarr":"⍼","Aogon":"Ą","aogon":"ą","Aopf":"𝔸","aopf":"𝕒","apacir":"⩯","ap":"≈","apE":"⩰","ape":"≊","apid":"≋","apos":"'","ApplyFunction":"⁡","approx":"≈","approxeq":"≊","Aring":"Å","aring":"å","Ascr":"𝒜","ascr":"𝒶","Assign":"≔","ast":"*","asymp":"≈","asympeq":"≍","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","awconint":"∳","awint":"⨑","backcong":"≌","backepsilon":"϶","backprime":"‵","backsim":"∽","backsimeq":"⋍","Backslash":"∖","Barv":"⫧","barvee":"⊽","barwed":"⌅","Barwed":"⌆","barwedge":"⌅","bbrk":"⎵","bbrktbrk":"⎶","bcong":"≌","Bcy":"Б","bcy":"б","bdquo":"„","becaus":"∵","because":"∵","Because":"∵","bemptyv":"⦰","bepsi":"϶","bernou":"ℬ","Bernoullis":"ℬ","Beta":"Β","beta":"β","beth":"ℶ","between":"≬","Bfr":"𝔅","bfr":"𝔟","bigcap":"⋂","bigcirc":"◯","bigcup":"⋃","bigodot":"⨀","bigoplus":"⨁","bigotimes":"⨂","bigsqcup":"⨆","bigstar":"★","bigtriangledown":"▽","bigtriangleup":"△","biguplus":"⨄","bigvee":"⋁","bigwedge":"⋀","bkarow":"⤍","blacklozenge":"⧫","blacksquare":"▪","blacktriangle":"▴","blacktriangledown":"▾","blacktriangleleft":"◂","blacktriangleright":"▸","blank":"␣","blk12":"▒","blk14":"░","blk34":"▓","block":"█","bne":"=⃥","bnequiv":"≡⃥","bNot":"⫭","bnot":"⌐","Bopf":"𝔹","bopf":"𝕓","bot":"⊥","bottom":"⊥","bowtie":"⋈","boxbox":"⧉","boxdl":"┐","boxdL":"╕","boxDl":"╖","boxDL":"╗","boxdr":"┌","boxdR":"╒","boxDr":"╓","boxDR":"╔","boxh":"─","boxH":"═","boxhd":"┬","boxHd":"╤","boxhD":"╥","boxHD":"╦","boxhu":"┴","boxHu":"╧","boxhU":"╨","boxHU":"╩","boxminus":"⊟","boxplus":"⊞","boxtimes":"⊠","boxul":"┘","boxuL":"╛","boxUl":"╜","boxUL":"╝","boxur":"└","boxuR":"╘","boxUr":"╙","boxUR":"╚","boxv":"│","boxV":"║","boxvh":"┼","boxvH":"╪","boxVh":"╫","boxVH":"╬","boxvl":"┤","boxvL":"╡","boxVl":"╢","boxVL":"╣","boxvr":"├","boxvR":"╞","boxVr":"╟","boxVR":"╠","bprime":"‵","breve":"˘","Breve":"˘","brvbar":"¦","bscr":"𝒷","Bscr":"ℬ","bsemi":"⁏","bsim":"∽","bsime":"⋍","bsolb":"⧅","bsol":"\\","bsolhsub":"⟈","bull":"•","bullet":"•","bump":"≎","bumpE":"⪮","bumpe":"≏","Bumpeq":"≎","bumpeq":"≏","Cacute":"Ć","cacute":"ć","capand":"⩄","capbrcup":"⩉","capcap":"⩋","cap":"∩","Cap":"⋒","capcup":"⩇","capdot":"⩀","CapitalDifferentialD":"ⅅ","caps":"∩︀","caret":"⁁","caron":"ˇ","Cayleys":"ℭ","ccaps":"⩍","Ccaron":"Č","ccaron":"č","Ccedil":"Ç","ccedil":"ç","Ccirc":"Ĉ","ccirc":"ĉ","Cconint":"∰","ccups":"⩌","ccupssm":"⩐","Cdot":"Ċ","cdot":"ċ","cedil":"¸","Cedilla":"¸","cemptyv":"⦲","cent":"¢","centerdot":"·","CenterDot":"·","cfr":"𝔠","Cfr":"ℭ","CHcy":"Ч","chcy":"ч","check":"✓","checkmark":"✓","Chi":"Χ","chi":"χ","circ":"ˆ","circeq":"≗","circlearrowleft":"↺","circlearrowright":"↻","circledast":"⊛","circledcirc":"⊚","circleddash":"⊝","CircleDot":"⊙","circledR":"®","circledS":"Ⓢ","CircleMinus":"⊖","CirclePlus":"⊕","CircleTimes":"⊗","cir":"○","cirE":"⧃","cire":"≗","cirfnint":"⨐","cirmid":"⫯","cirscir":"⧂","ClockwiseContourIntegral":"∲","CloseCurlyDoubleQuote":"”","CloseCurlyQuote":"’","clubs":"♣","clubsuit":"♣","colon":":","Colon":"∷","Colone":"⩴","colone":"≔","coloneq":"≔","comma":",","commat":"@","comp":"∁","compfn":"∘","complement":"∁","complexes":"ℂ","cong":"≅","congdot":"⩭","Congruent":"≡","conint":"∮","Conint":"∯","ContourIntegral":"∮","copf":"𝕔","Copf":"ℂ","coprod":"∐","Coproduct":"∐","copy":"©","COPY":"©","copysr":"℗","CounterClockwiseContourIntegral":"∳","crarr":"↵","cross":"✗","Cross":"⨯","Cscr":"𝒞","cscr":"𝒸","csub":"⫏","csube":"⫑","csup":"⫐","csupe":"⫒","ctdot":"⋯","cudarrl":"⤸","cudarrr":"⤵","cuepr":"⋞","cuesc":"⋟","cularr":"↶","cularrp":"⤽","cupbrcap":"⩈","cupcap":"⩆","CupCap":"≍","cup":"∪","Cup":"⋓","cupcup":"⩊","cupdot":"⊍","cupor":"⩅","cups":"∪︀","curarr":"↷","curarrm":"⤼","curlyeqprec":"⋞","curlyeqsucc":"⋟","curlyvee":"⋎","curlywedge":"⋏","curren":"¤","curvearrowleft":"↶","curvearrowright":"↷","cuvee":"⋎","cuwed":"⋏","cwconint":"∲","cwint":"∱","cylcty":"⌭","dagger":"†","Dagger":"‡","daleth":"ℸ","darr":"↓","Darr":"↡","dArr":"⇓","dash":"‐","Dashv":"⫤","dashv":"⊣","dbkarow":"⤏","dblac":"˝","Dcaron":"Ď","dcaron":"ď","Dcy":"Д","dcy":"д","ddagger":"‡","ddarr":"⇊","DD":"ⅅ","dd":"ⅆ","DDotrahd":"⤑","ddotseq":"⩷","deg":"°","Del":"∇","Delta":"Δ","delta":"δ","demptyv":"⦱","dfisht":"⥿","Dfr":"𝔇","dfr":"𝔡","dHar":"⥥","dharl":"⇃","dharr":"⇂","DiacriticalAcute":"´","DiacriticalDot":"˙","DiacriticalDoubleAcute":"˝","DiacriticalGrave":"`","DiacriticalTilde":"˜","diam":"⋄","diamond":"⋄","Diamond":"⋄","diamondsuit":"♦","diams":"♦","die":"¨","DifferentialD":"ⅆ","digamma":"ϝ","disin":"⋲","div":"÷","divide":"÷","divideontimes":"⋇","divonx":"⋇","DJcy":"Ђ","djcy":"ђ","dlcorn":"⌞","dlcrop":"⌍","dollar":"$","Dopf":"𝔻","dopf":"𝕕","Dot":"¨","dot":"˙","DotDot":"⃜","doteq":"≐","doteqdot":"≑","DotEqual":"≐","dotminus":"∸","dotplus":"∔","dotsquare":"⊡","doublebarwedge":"⌆","DoubleContourIntegral":"∯","DoubleDot":"¨","DoubleDownArrow":"⇓","DoubleLeftArrow":"⇐","DoubleLeftRightArrow":"⇔","DoubleLeftTee":"⫤","DoubleLongLeftArrow":"⟸","DoubleLongLeftRightArrow":"⟺","DoubleLongRightArrow":"⟹","DoubleRightArrow":"⇒","DoubleRightTee":"⊨","DoubleUpArrow":"⇑","DoubleUpDownArrow":"⇕","DoubleVerticalBar":"∥","DownArrowBar":"⤓","downarrow":"↓","DownArrow":"↓","Downarrow":"⇓","DownArrowUpArrow":"⇵","DownBreve":"̑","downdownarrows":"⇊","downharpoonleft":"⇃","downharpoonright":"⇂","DownLeftRightVector":"⥐","DownLeftTeeVector":"⥞","DownLeftVectorBar":"⥖","DownLeftVector":"↽","DownRightTeeVector":"⥟","DownRightVectorBar":"⥗","DownRightVector":"⇁","DownTeeArrow":"↧","DownTee":"⊤","drbkarow":"⤐","drcorn":"⌟","drcrop":"⌌","Dscr":"𝒟","dscr":"𝒹","DScy":"Ѕ","dscy":"ѕ","dsol":"⧶","Dstrok":"Đ","dstrok":"đ","dtdot":"⋱","dtri":"▿","dtrif":"▾","duarr":"⇵","duhar":"⥯","dwangle":"⦦","DZcy":"Џ","dzcy":"џ","dzigrarr":"⟿","Eacute":"É","eacute":"é","easter":"⩮","Ecaron":"Ě","ecaron":"ě","Ecirc":"Ê","ecirc":"ê","ecir":"≖","ecolon":"≕","Ecy":"Э","ecy":"э","eDDot":"⩷","Edot":"Ė","edot":"ė","eDot":"≑","ee":"ⅇ","efDot":"≒","Efr":"𝔈","efr":"𝔢","eg":"⪚","Egrave":"È","egrave":"è","egs":"⪖","egsdot":"⪘","el":"⪙","Element":"∈","elinters":"⏧","ell":"ℓ","els":"⪕","elsdot":"⪗","Emacr":"Ē","emacr":"ē","empty":"∅","emptyset":"∅","EmptySmallSquare":"◻","emptyv":"∅","EmptyVerySmallSquare":"▫","emsp13":" ","emsp14":" ","emsp":" ","ENG":"Ŋ","eng":"ŋ","ensp":" ","Eogon":"Ę","eogon":"ę","Eopf":"𝔼","eopf":"𝕖","epar":"⋕","eparsl":"⧣","eplus":"⩱","epsi":"ε","Epsilon":"Ε","epsilon":"ε","epsiv":"ϵ","eqcirc":"≖","eqcolon":"≕","eqsim":"≂","eqslantgtr":"⪖","eqslantless":"⪕","Equal":"⩵","equals":"=","EqualTilde":"≂","equest":"≟","Equilibrium":"⇌","equiv":"≡","equivDD":"⩸","eqvparsl":"⧥","erarr":"⥱","erDot":"≓","escr":"ℯ","Escr":"ℰ","esdot":"≐","Esim":"⩳","esim":"≂","Eta":"Η","eta":"η","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","euro":"€","excl":"!","exist":"∃","Exists":"∃","expectation":"ℰ","exponentiale":"ⅇ","ExponentialE":"ⅇ","fallingdotseq":"≒","Fcy":"Ф","fcy":"ф","female":"♀","ffilig":"ﬃ","fflig":"ﬀ","ffllig":"ﬄ","Ffr":"𝔉","ffr":"𝔣","filig":"ﬁ","FilledSmallSquare":"◼","FilledVerySmallSquare":"▪","fjlig":"fj","flat":"♭","fllig":"ﬂ","fltns":"▱","fnof":"ƒ","Fopf":"𝔽","fopf":"𝕗","forall":"∀","ForAll":"∀","fork":"⋔","forkv":"⫙","Fouriertrf":"ℱ","fpartint":"⨍","frac12":"½","frac13":"⅓","frac14":"¼","frac15":"⅕","frac16":"⅙","frac18":"⅛","frac23":"⅔","frac25":"⅖","frac34":"¾","frac35":"⅗","frac38":"⅜","frac45":"⅘","frac56":"⅚","frac58":"⅝","frac78":"⅞","frasl":"⁄","frown":"⌢","fscr":"𝒻","Fscr":"ℱ","gacute":"ǵ","Gamma":"Γ","gamma":"γ","Gammad":"Ϝ","gammad":"ϝ","gap":"⪆","Gbreve":"Ğ","gbreve":"ğ","Gcedil":"Ģ","Gcirc":"Ĝ","gcirc":"ĝ","Gcy":"Г","gcy":"г","Gdot":"Ġ","gdot":"ġ","ge":"≥","gE":"≧","gEl":"⪌","gel":"⋛","geq":"≥","geqq":"≧","geqslant":"⩾","gescc":"⪩","ges":"⩾","gesdot":"⪀","gesdoto":"⪂","gesdotol":"⪄","gesl":"⋛︀","gesles":"⪔","Gfr":"𝔊","gfr":"𝔤","gg":"≫","Gg":"⋙","ggg":"⋙","gimel":"ℷ","GJcy":"Ѓ","gjcy":"ѓ","gla":"⪥","gl":"≷","glE":"⪒","glj":"⪤","gnap":"⪊","gnapprox":"⪊","gne":"⪈","gnE":"≩","gneq":"⪈","gneqq":"≩","gnsim":"⋧","Gopf":"𝔾","gopf":"𝕘","grave":"`","GreaterEqual":"≥","GreaterEqualLess":"⋛","GreaterFullEqual":"≧","GreaterGreater":"⪢","GreaterLess":"≷","GreaterSlantEqual":"⩾","GreaterTilde":"≳","Gscr":"𝒢","gscr":"ℊ","gsim":"≳","gsime":"⪎","gsiml":"⪐","gtcc":"⪧","gtcir":"⩺","gt":">","GT":">","Gt":"≫","gtdot":"⋗","gtlPar":"⦕","gtquest":"⩼","gtrapprox":"⪆","gtrarr":"⥸","gtrdot":"⋗","gtreqless":"⋛","gtreqqless":"⪌","gtrless":"≷","gtrsim":"≳","gvertneqq":"≩︀","gvnE":"≩︀","Hacek":"ˇ","hairsp":" ","half":"½","hamilt":"ℋ","HARDcy":"Ъ","hardcy":"ъ","harrcir":"⥈","harr":"↔","hArr":"⇔","harrw":"↭","Hat":"^","hbar":"ℏ","Hcirc":"Ĥ","hcirc":"ĥ","hearts":"♥","heartsuit":"♥","hellip":"…","hercon":"⊹","hfr":"𝔥","Hfr":"ℌ","HilbertSpace":"ℋ","hksearow":"⤥","hkswarow":"⤦","hoarr":"⇿","homtht":"∻","hookleftarrow":"↩","hookrightarrow":"↪","hopf":"𝕙","Hopf":"ℍ","horbar":"―","HorizontalLine":"─","hscr":"𝒽","Hscr":"ℋ","hslash":"ℏ","Hstrok":"Ħ","hstrok":"ħ","HumpDownHump":"≎","HumpEqual":"≏","hybull":"⁃","hyphen":"‐","Iacute":"Í","iacute":"í","ic":"⁣","Icirc":"Î","icirc":"î","Icy":"И","icy":"и","Idot":"İ","IEcy":"Е","iecy":"е","iexcl":"¡","iff":"⇔","ifr":"𝔦","Ifr":"ℑ","Igrave":"Ì","igrave":"ì","ii":"ⅈ","iiiint":"⨌","iiint":"∭","iinfin":"⧜","iiota":"℩","IJlig":"Ĳ","ijlig":"ĳ","Imacr":"Ī","imacr":"ī","image":"ℑ","ImaginaryI":"ⅈ","imagline":"ℐ","imagpart":"ℑ","imath":"ı","Im":"ℑ","imof":"⊷","imped":"Ƶ","Implies":"⇒","incare":"℅","in":"∈","infin":"∞","infintie":"⧝","inodot":"ı","intcal":"⊺","int":"∫","Int":"∬","integers":"ℤ","Integral":"∫","intercal":"⊺","Intersection":"⋂","intlarhk":"⨗","intprod":"⨼","InvisibleComma":"⁣","InvisibleTimes":"⁢","IOcy":"Ё","iocy":"ё","Iogon":"Į","iogon":"į","Iopf":"𝕀","iopf":"𝕚","Iota":"Ι","iota":"ι","iprod":"⨼","iquest":"¿","iscr":"𝒾","Iscr":"ℐ","isin":"∈","isindot":"⋵","isinE":"⋹","isins":"⋴","isinsv":"⋳","isinv":"∈","it":"⁢","Itilde":"Ĩ","itilde":"ĩ","Iukcy":"І","iukcy":"і","Iuml":"Ï","iuml":"ï","Jcirc":"Ĵ","jcirc":"ĵ","Jcy":"Й","jcy":"й","Jfr":"𝔍","jfr":"𝔧","jmath":"ȷ","Jopf":"𝕁","jopf":"𝕛","Jscr":"𝒥","jscr":"𝒿","Jsercy":"Ј","jsercy":"ј","Jukcy":"Є","jukcy":"є","Kappa":"Κ","kappa":"κ","kappav":"ϰ","Kcedil":"Ķ","kcedil":"ķ","Kcy":"К","kcy":"к","Kfr":"𝔎","kfr":"𝔨","kgreen":"ĸ","KHcy":"Х","khcy":"х","KJcy":"Ќ","kjcy":"ќ","Kopf":"𝕂","kopf":"𝕜","Kscr":"𝒦","kscr":"𝓀","lAarr":"⇚","Lacute":"Ĺ","lacute":"ĺ","laemptyv":"⦴","lagran":"ℒ","Lambda":"Λ","lambda":"λ","lang":"⟨","Lang":"⟪","langd":"⦑","langle":"⟨","lap":"⪅","Laplacetrf":"ℒ","laquo":"«","larrb":"⇤","larrbfs":"⤟","larr":"←","Larr":"↞","lArr":"⇐","larrfs":"⤝","larrhk":"↩","larrlp":"↫","larrpl":"⤹","larrsim":"⥳","larrtl":"↢","latail":"⤙","lAtail":"⤛","lat":"⪫","late":"⪭","lates":"⪭︀","lbarr":"⤌","lBarr":"⤎","lbbrk":"❲","lbrace":"{","lbrack":"[","lbrke":"⦋","lbrksld":"⦏","lbrkslu":"⦍","Lcaron":"Ľ","lcaron":"ľ","Lcedil":"Ļ","lcedil":"ļ","lceil":"⌈","lcub":"{","Lcy":"Л","lcy":"л","ldca":"⤶","ldquo":"“","ldquor":"„","ldrdhar":"⥧","ldrushar":"⥋","ldsh":"↲","le":"≤","lE":"≦","LeftAngleBracket":"⟨","LeftArrowBar":"⇤","leftarrow":"←","LeftArrow":"←","Leftarrow":"⇐","LeftArrowRightArrow":"⇆","leftarrowtail":"↢","LeftCeiling":"⌈","LeftDoubleBracket":"⟦","LeftDownTeeVector":"⥡","LeftDownVectorBar":"⥙","LeftDownVector":"⇃","LeftFloor":"⌊","leftharpoondown":"↽","leftharpoonup":"↼","leftleftarrows":"⇇","leftrightarrow":"↔","LeftRightArrow":"↔","Leftrightarrow":"⇔","leftrightarrows":"⇆","leftrightharpoons":"⇋","leftrightsquigarrow":"↭","LeftRightVector":"⥎","LeftTeeArrow":"↤","LeftTee":"⊣","LeftTeeVector":"⥚","leftthreetimes":"⋋","LeftTriangleBar":"⧏","LeftTriangle":"⊲","LeftTriangleEqual":"⊴","LeftUpDownVector":"⥑","LeftUpTeeVector":"⥠","LeftUpVectorBar":"⥘","LeftUpVector":"↿","LeftVectorBar":"⥒","LeftVector":"↼","lEg":"⪋","leg":"⋚","leq":"≤","leqq":"≦","leqslant":"⩽","lescc":"⪨","les":"⩽","lesdot":"⩿","lesdoto":"⪁","lesdotor":"⪃","lesg":"⋚︀","lesges":"⪓","lessapprox":"⪅","lessdot":"⋖","lesseqgtr":"⋚","lesseqqgtr":"⪋","LessEqualGreater":"⋚","LessFullEqual":"≦","LessGreater":"≶","lessgtr":"≶","LessLess":"⪡","lesssim":"≲","LessSlantEqual":"⩽","LessTilde":"≲","lfisht":"⥼","lfloor":"⌊","Lfr":"𝔏","lfr":"𝔩","lg":"≶","lgE":"⪑","lHar":"⥢","lhard":"↽","lharu":"↼","lharul":"⥪","lhblk":"▄","LJcy":"Љ","ljcy":"љ","llarr":"⇇","ll":"≪","Ll":"⋘","llcorner":"⌞","Lleftarrow":"⇚","llhard":"⥫","lltri":"◺","Lmidot":"Ŀ","lmidot":"ŀ","lmoustache":"⎰","lmoust":"⎰","lnap":"⪉","lnapprox":"⪉","lne":"⪇","lnE":"≨","lneq":"⪇","lneqq":"≨","lnsim":"⋦","loang":"⟬","loarr":"⇽","lobrk":"⟦","longleftarrow":"⟵","LongLeftArrow":"⟵","Longleftarrow":"⟸","longleftrightarrow":"⟷","LongLeftRightArrow":"⟷","Longleftrightarrow":"⟺","longmapsto":"⟼","longrightarrow":"⟶","LongRightArrow":"⟶","Longrightarrow":"⟹","looparrowleft":"↫","looparrowright":"↬","lopar":"⦅","Lopf":"𝕃","lopf":"𝕝","loplus":"⨭","lotimes":"⨴","lowast":"∗","lowbar":"_","LowerLeftArrow":"↙","LowerRightArrow":"↘","loz":"◊","lozenge":"◊","lozf":"⧫","lpar":"(","lparlt":"⦓","lrarr":"⇆","lrcorner":"⌟","lrhar":"⇋","lrhard":"⥭","lrm":"‎","lrtri":"⊿","lsaquo":"‹","lscr":"𝓁","Lscr":"ℒ","lsh":"↰","Lsh":"↰","lsim":"≲","lsime":"⪍","lsimg":"⪏","lsqb":"[","lsquo":"‘","lsquor":"‚","Lstrok":"Ł","lstrok":"ł","ltcc":"⪦","ltcir":"⩹","lt":"<","LT":"<","Lt":"≪","ltdot":"⋖","lthree":"⋋","ltimes":"⋉","ltlarr":"⥶","ltquest":"⩻","ltri":"◃","ltrie":"⊴","ltrif":"◂","ltrPar":"⦖","lurdshar":"⥊","luruhar":"⥦","lvertneqq":"≨︀","lvnE":"≨︀","macr":"¯","male":"♂","malt":"✠","maltese":"✠","Map":"⤅","map":"↦","mapsto":"↦","mapstodown":"↧","mapstoleft":"↤","mapstoup":"↥","marker":"▮","mcomma":"⨩","Mcy":"М","mcy":"м","mdash":"—","mDDot":"∺","measuredangle":"∡","MediumSpace":" ","Mellintrf":"ℳ","Mfr":"𝔐","mfr":"𝔪","mho":"℧","micro":"µ","midast":"*","midcir":"⫰","mid":"∣","middot":"·","minusb":"⊟","minus":"−","minusd":"∸","minusdu":"⨪","MinusPlus":"∓","mlcp":"⫛","mldr":"…","mnplus":"∓","models":"⊧","Mopf":"𝕄","mopf":"𝕞","mp":"∓","mscr":"𝓂","Mscr":"ℳ","mstpos":"∾","Mu":"Μ","mu":"μ","multimap":"⊸","mumap":"⊸","nabla":"∇","Nacute":"Ń","nacute":"ń","nang":"∠⃒","nap":"≉","napE":"⩰̸","napid":"≋̸","napos":"ŉ","napprox":"≉","natural":"♮","naturals":"ℕ","natur":"♮","nbsp":" ","nbump":"≎̸","nbumpe":"≏̸","ncap":"⩃","Ncaron":"Ň","ncaron":"ň","Ncedil":"Ņ","ncedil":"ņ","ncong":"≇","ncongdot":"⩭̸","ncup":"⩂","Ncy":"Н","ncy":"н","ndash":"–","nearhk":"⤤","nearr":"↗","neArr":"⇗","nearrow":"↗","ne":"≠","nedot":"≐̸","NegativeMediumSpace":"​","NegativeThickSpace":"​","NegativeThinSpace":"​","NegativeVeryThinSpace":"​","nequiv":"≢","nesear":"⤨","nesim":"≂̸","NestedGreaterGreater":"≫","NestedLessLess":"≪","NewLine":"\n","nexist":"∄","nexists":"∄","Nfr":"𝔑","nfr":"𝔫","ngE":"≧̸","nge":"≱","ngeq":"≱","ngeqq":"≧̸","ngeqslant":"⩾̸","nges":"⩾̸","nGg":"⋙̸","ngsim":"≵","nGt":"≫⃒","ngt":"≯","ngtr":"≯","nGtv":"≫̸","nharr":"↮","nhArr":"⇎","nhpar":"⫲","ni":"∋","nis":"⋼","nisd":"⋺","niv":"∋","NJcy":"Њ","njcy":"њ","nlarr":"↚","nlArr":"⇍","nldr":"‥","nlE":"≦̸","nle":"≰","nleftarrow":"↚","nLeftarrow":"⇍","nleftrightarrow":"↮","nLeftrightarrow":"⇎","nleq":"≰","nleqq":"≦̸","nleqslant":"⩽̸","nles":"⩽̸","nless":"≮","nLl":"⋘̸","nlsim":"≴","nLt":"≪⃒","nlt":"≮","nltri":"⋪","nltrie":"⋬","nLtv":"≪̸","nmid":"∤","NoBreak":"⁠","NonBreakingSpace":" ","nopf":"𝕟","Nopf":"ℕ","Not":"⫬","not":"¬","NotCongruent":"≢","NotCupCap":"≭","NotDoubleVerticalBar":"∦","NotElement":"∉","NotEqual":"≠","NotEqualTilde":"≂̸","NotExists":"∄","NotGreater":"≯","NotGreaterEqual":"≱","NotGreaterFullEqual":"≧̸","NotGreaterGreater":"≫̸","NotGreaterLess":"≹","NotGreaterSlantEqual":"⩾̸","NotGreaterTilde":"≵","NotHumpDownHump":"≎̸","NotHumpEqual":"≏̸","notin":"∉","notindot":"⋵̸","notinE":"⋹̸","notinva":"∉","notinvb":"⋷","notinvc":"⋶","NotLeftTriangleBar":"⧏̸","NotLeftTriangle":"⋪","NotLeftTriangleEqual":"⋬","NotLess":"≮","NotLessEqual":"≰","NotLessGreater":"≸","NotLessLess":"≪̸","NotLessSlantEqual":"⩽̸","NotLessTilde":"≴","NotNestedGreaterGreater":"⪢̸","NotNestedLessLess":"⪡̸","notni":"∌","notniva":"∌","notnivb":"⋾","notnivc":"⋽","NotPrecedes":"⊀","NotPrecedesEqual":"⪯̸","NotPrecedesSlantEqual":"⋠","NotReverseElement":"∌","NotRightTriangleBar":"⧐̸","NotRightTriangle":"⋫","NotRightTriangleEqual":"⋭","NotSquareSubset":"⊏̸","NotSquareSubsetEqual":"⋢","NotSquareSuperset":"⊐̸","NotSquareSupersetEqual":"⋣","NotSubset":"⊂⃒","NotSubsetEqual":"⊈","NotSucceeds":"⊁","NotSucceedsEqual":"⪰̸","NotSucceedsSlantEqual":"⋡","NotSucceedsTilde":"≿̸","NotSuperset":"⊃⃒","NotSupersetEqual":"⊉","NotTilde":"≁","NotTildeEqual":"≄","NotTildeFullEqual":"≇","NotTildeTilde":"≉","NotVerticalBar":"∤","nparallel":"∦","npar":"∦","nparsl":"⫽⃥","npart":"∂̸","npolint":"⨔","npr":"⊀","nprcue":"⋠","nprec":"⊀","npreceq":"⪯̸","npre":"⪯̸","nrarrc":"⤳̸","nrarr":"↛","nrArr":"⇏","nrarrw":"↝̸","nrightarrow":"↛","nRightarrow":"⇏","nrtri":"⋫","nrtrie":"⋭","nsc":"⊁","nsccue":"⋡","nsce":"⪰̸","Nscr":"𝒩","nscr":"𝓃","nshortmid":"∤","nshortparallel":"∦","nsim":"≁","nsime":"≄","nsimeq":"≄","nsmid":"∤","nspar":"∦","nsqsube":"⋢","nsqsupe":"⋣","nsub":"⊄","nsubE":"⫅̸","nsube":"⊈","nsubset":"⊂⃒","nsubseteq":"⊈","nsubseteqq":"⫅̸","nsucc":"⊁","nsucceq":"⪰̸","nsup":"⊅","nsupE":"⫆̸","nsupe":"⊉","nsupset":"⊃⃒","nsupseteq":"⊉","nsupseteqq":"⫆̸","ntgl":"≹","Ntilde":"Ñ","ntilde":"ñ","ntlg":"≸","ntriangleleft":"⋪","ntrianglelefteq":"⋬","ntriangleright":"⋫","ntrianglerighteq":"⋭","Nu":"Ν","nu":"ν","num":"#","numero":"№","numsp":" ","nvap":"≍⃒","nvdash":"⊬","nvDash":"⊭","nVdash":"⊮","nVDash":"⊯","nvge":"≥⃒","nvgt":">⃒","nvHarr":"⤄","nvinfin":"⧞","nvlArr":"⤂","nvle":"≤⃒","nvlt":"<⃒","nvltrie":"⊴⃒","nvrArr":"⤃","nvrtrie":"⊵⃒","nvsim":"∼⃒","nwarhk":"⤣","nwarr":"↖","nwArr":"⇖","nwarrow":"↖","nwnear":"⤧","Oacute":"Ó","oacute":"ó","oast":"⊛","Ocirc":"Ô","ocirc":"ô","ocir":"⊚","Ocy":"О","ocy":"о","odash":"⊝","Odblac":"Ő","odblac":"ő","odiv":"⨸","odot":"⊙","odsold":"⦼","OElig":"Œ","oelig":"œ","ofcir":"⦿","Ofr":"𝔒","ofr":"𝔬","ogon":"˛","Ograve":"Ò","ograve":"ò","ogt":"⧁","ohbar":"⦵","ohm":"Ω","oint":"∮","olarr":"↺","olcir":"⦾","olcross":"⦻","oline":"‾","olt":"⧀","Omacr":"Ō","omacr":"ō","Omega":"Ω","omega":"ω","Omicron":"Ο","omicron":"ο","omid":"⦶","ominus":"⊖","Oopf":"𝕆","oopf":"𝕠","opar":"⦷","OpenCurlyDoubleQuote":"“","OpenCurlyQuote":"‘","operp":"⦹","oplus":"⊕","orarr":"↻","Or":"⩔","or":"∨","ord":"⩝","order":"ℴ","orderof":"ℴ","ordf":"ª","ordm":"º","origof":"⊶","oror":"⩖","orslope":"⩗","orv":"⩛","oS":"Ⓢ","Oscr":"𝒪","oscr":"ℴ","Oslash":"Ø","oslash":"ø","osol":"⊘","Otilde":"Õ","otilde":"õ","otimesas":"⨶","Otimes":"⨷","otimes":"⊗","Ouml":"Ö","ouml":"ö","ovbar":"⌽","OverBar":"‾","OverBrace":"⏞","OverBracket":"⎴","OverParenthesis":"⏜","para":"¶","parallel":"∥","par":"∥","parsim":"⫳","parsl":"⫽","part":"∂","PartialD":"∂","Pcy":"П","pcy":"п","percnt":"%","period":".","permil":"‰","perp":"⊥","pertenk":"‱","Pfr":"𝔓","pfr":"𝔭","Phi":"Φ","phi":"φ","phiv":"ϕ","phmmat":"ℳ","phone":"☎","Pi":"Π","pi":"π","pitchfork":"⋔","piv":"ϖ","planck":"ℏ","planckh":"ℎ","plankv":"ℏ","plusacir":"⨣","plusb":"⊞","pluscir":"⨢","plus":"+","plusdo":"∔","plusdu":"⨥","pluse":"⩲","PlusMinus":"±","plusmn":"±","plussim":"⨦","plustwo":"⨧","pm":"±","Poincareplane":"ℌ","pointint":"⨕","popf":"𝕡","Popf":"ℙ","pound":"£","prap":"⪷","Pr":"⪻","pr":"≺","prcue":"≼","precapprox":"⪷","prec":"≺","preccurlyeq":"≼","Precedes":"≺","PrecedesEqual":"⪯","PrecedesSlantEqual":"≼","PrecedesTilde":"≾","preceq":"⪯","precnapprox":"⪹","precneqq":"⪵","precnsim":"⋨","pre":"⪯","prE":"⪳","precsim":"≾","prime":"′","Prime":"″","primes":"ℙ","prnap":"⪹","prnE":"⪵","prnsim":"⋨","prod":"∏","Product":"∏","profalar":"⌮","profline":"⌒","profsurf":"⌓","prop":"∝","Proportional":"∝","Proportion":"∷","propto":"∝","prsim":"≾","prurel":"⊰","Pscr":"𝒫","pscr":"𝓅","Psi":"Ψ","psi":"ψ","puncsp":" ","Qfr":"𝔔","qfr":"𝔮","qint":"⨌","qopf":"𝕢","Qopf":"ℚ","qprime":"⁗","Qscr":"𝒬","qscr":"𝓆","quaternions":"ℍ","quatint":"⨖","quest":"?","questeq":"≟","quot":"\"","QUOT":"\"","rAarr":"⇛","race":"∽̱","Racute":"Ŕ","racute":"ŕ","radic":"√","raemptyv":"⦳","rang":"⟩","Rang":"⟫","rangd":"⦒","range":"⦥","rangle":"⟩","raquo":"»","rarrap":"⥵","rarrb":"⇥","rarrbfs":"⤠","rarrc":"⤳","rarr":"→","Rarr":"↠","rArr":"⇒","rarrfs":"⤞","rarrhk":"↪","rarrlp":"↬","rarrpl":"⥅","rarrsim":"⥴","Rarrtl":"⤖","rarrtl":"↣","rarrw":"↝","ratail":"⤚","rAtail":"⤜","ratio":"∶","rationals":"ℚ","rbarr":"⤍","rBarr":"⤏","RBarr":"⤐","rbbrk":"❳","rbrace":"}","rbrack":"]","rbrke":"⦌","rbrksld":"⦎","rbrkslu":"⦐","Rcaron":"Ř","rcaron":"ř","Rcedil":"Ŗ","rcedil":"ŗ","rceil":"⌉","rcub":"}","Rcy":"Р","rcy":"р","rdca":"⤷","rdldhar":"⥩","rdquo":"”","rdquor":"”","rdsh":"↳","real":"ℜ","realine":"ℛ","realpart":"ℜ","reals":"ℝ","Re":"ℜ","rect":"▭","reg":"®","REG":"®","ReverseElement":"∋","ReverseEquilibrium":"⇋","ReverseUpEquilibrium":"⥯","rfisht":"⥽","rfloor":"⌋","rfr":"𝔯","Rfr":"ℜ","rHar":"⥤","rhard":"⇁","rharu":"⇀","rharul":"⥬","Rho":"Ρ","rho":"ρ","rhov":"ϱ","RightAngleBracket":"⟩","RightArrowBar":"⇥","rightarrow":"→","RightArrow":"→","Rightarrow":"⇒","RightArrowLeftArrow":"⇄","rightarrowtail":"↣","RightCeiling":"⌉","RightDoubleBracket":"⟧","RightDownTeeVector":"⥝","RightDownVectorBar":"⥕","RightDownVector":"⇂","RightFloor":"⌋","rightharpoondown":"⇁","rightharpoonup":"⇀","rightleftarrows":"⇄","rightleftharpoons":"⇌","rightrightarrows":"⇉","rightsquigarrow":"↝","RightTeeArrow":"↦","RightTee":"⊢","RightTeeVector":"⥛","rightthreetimes":"⋌","RightTriangleBar":"⧐","RightTriangle":"⊳","RightTriangleEqual":"⊵","RightUpDownVector":"⥏","RightUpTeeVector":"⥜","RightUpVectorBar":"⥔","RightUpVector":"↾","RightVectorBar":"⥓","RightVector":"⇀","ring":"˚","risingdotseq":"≓","rlarr":"⇄","rlhar":"⇌","rlm":"‏","rmoustache":"⎱","rmoust":"⎱","rnmid":"⫮","roang":"⟭","roarr":"⇾","robrk":"⟧","ropar":"⦆","ropf":"𝕣","Ropf":"ℝ","roplus":"⨮","rotimes":"⨵","RoundImplies":"⥰","rpar":")","rpargt":"⦔","rppolint":"⨒","rrarr":"⇉","Rrightarrow":"⇛","rsaquo":"›","rscr":"𝓇","Rscr":"ℛ","rsh":"↱","Rsh":"↱","rsqb":"]","rsquo":"’","rsquor":"’","rthree":"⋌","rtimes":"⋊","rtri":"▹","rtrie":"⊵","rtrif":"▸","rtriltri":"⧎","RuleDelayed":"⧴","ruluhar":"⥨","rx":"℞","Sacute":"Ś","sacute":"ś","sbquo":"‚","scap":"⪸","Scaron":"Š","scaron":"š","Sc":"⪼","sc":"≻","sccue":"≽","sce":"⪰","scE":"⪴","Scedil":"Ş","scedil":"ş","Scirc":"Ŝ","scirc":"ŝ","scnap":"⪺","scnE":"⪶","scnsim":"⋩","scpolint":"⨓","scsim":"≿","Scy":"С","scy":"с","sdotb":"⊡","sdot":"⋅","sdote":"⩦","searhk":"⤥","searr":"↘","seArr":"⇘","searrow":"↘","sect":"§","semi":";","seswar":"⤩","setminus":"∖","setmn":"∖","sext":"✶","Sfr":"𝔖","sfr":"𝔰","sfrown":"⌢","sharp":"♯","SHCHcy":"Щ","shchcy":"щ","SHcy":"Ш","shcy":"ш","ShortDownArrow":"↓","ShortLeftArrow":"←","shortmid":"∣","shortparallel":"∥","ShortRightArrow":"→","ShortUpArrow":"↑","shy":"­","Sigma":"Σ","sigma":"σ","sigmaf":"ς","sigmav":"ς","sim":"∼","simdot":"⩪","sime":"≃","simeq":"≃","simg":"⪞","simgE":"⪠","siml":"⪝","simlE":"⪟","simne":"≆","simplus":"⨤","simrarr":"⥲","slarr":"←","SmallCircle":"∘","smallsetminus":"∖","smashp":"⨳","smeparsl":"⧤","smid":"∣","smile":"⌣","smt":"⪪","smte":"⪬","smtes":"⪬︀","SOFTcy":"Ь","softcy":"ь","solbar":"⌿","solb":"⧄","sol":"/","Sopf":"𝕊","sopf":"𝕤","spades":"♠","spadesuit":"♠","spar":"∥","sqcap":"⊓","sqcaps":"⊓︀","sqcup":"⊔","sqcups":"⊔︀","Sqrt":"√","sqsub":"⊏","sqsube":"⊑","sqsubset":"⊏","sqsubseteq":"⊑","sqsup":"⊐","sqsupe":"⊒","sqsupset":"⊐","sqsupseteq":"⊒","square":"□","Square":"□","SquareIntersection":"⊓","SquareSubset":"⊏","SquareSubsetEqual":"⊑","SquareSuperset":"⊐","SquareSupersetEqual":"⊒","SquareUnion":"⊔","squarf":"▪","squ":"□","squf":"▪","srarr":"→","Sscr":"𝒮","sscr":"𝓈","ssetmn":"∖","ssmile":"⌣","sstarf":"⋆","Star":"⋆","star":"☆","starf":"★","straightepsilon":"ϵ","straightphi":"ϕ","strns":"¯","sub":"⊂","Sub":"⋐","subdot":"⪽","subE":"⫅","sube":"⊆","subedot":"⫃","submult":"⫁","subnE":"⫋","subne":"⊊","subplus":"⪿","subrarr":"⥹","subset":"⊂","Subset":"⋐","subseteq":"⊆","subseteqq":"⫅","SubsetEqual":"⊆","subsetneq":"⊊","subsetneqq":"⫋","subsim":"⫇","subsub":"⫕","subsup":"⫓","succapprox":"⪸","succ":"≻","succcurlyeq":"≽","Succeeds":"≻","SucceedsEqual":"⪰","SucceedsSlantEqual":"≽","SucceedsTilde":"≿","succeq":"⪰","succnapprox":"⪺","succneqq":"⪶","succnsim":"⋩","succsim":"≿","SuchThat":"∋","sum":"∑","Sum":"∑","sung":"♪","sup1":"¹","sup2":"²","sup3":"³","sup":"⊃","Sup":"⋑","supdot":"⪾","supdsub":"⫘","supE":"⫆","supe":"⊇","supedot":"⫄","Superset":"⊃","SupersetEqual":"⊇","suphsol":"⟉","suphsub":"⫗","suplarr":"⥻","supmult":"⫂","supnE":"⫌","supne":"⊋","supplus":"⫀","supset":"⊃","Supset":"⋑","supseteq":"⊇","supseteqq":"⫆","supsetneq":"⊋","supsetneqq":"⫌","supsim":"⫈","supsub":"⫔","supsup":"⫖","swarhk":"⤦","swarr":"↙","swArr":"⇙","swarrow":"↙","swnwar":"⤪","szlig":"ß","Tab":"\t","target":"⌖","Tau":"Τ","tau":"τ","tbrk":"⎴","Tcaron":"Ť","tcaron":"ť","Tcedil":"Ţ","tcedil":"ţ","Tcy":"Т","tcy":"т","tdot":"⃛","telrec":"⌕","Tfr":"𝔗","tfr":"𝔱","there4":"∴","therefore":"∴","Therefore":"∴","Theta":"Θ","theta":"θ","thetasym":"ϑ","thetav":"ϑ","thickapprox":"≈","thicksim":"∼","ThickSpace":"  ","ThinSpace":" ","thinsp":" ","thkap":"≈","thksim":"∼","THORN":"Þ","thorn":"þ","tilde":"˜","Tilde":"∼","TildeEqual":"≃","TildeFullEqual":"≅","TildeTilde":"≈","timesbar":"⨱","timesb":"⊠","times":"×","timesd":"⨰","tint":"∭","toea":"⤨","topbot":"⌶","topcir":"⫱","top":"⊤","Topf":"𝕋","topf":"𝕥","topfork":"⫚","tosa":"⤩","tprime":"‴","trade":"™","TRADE":"™","triangle":"▵","triangledown":"▿","triangleleft":"◃","trianglelefteq":"⊴","triangleq":"≜","triangleright":"▹","trianglerighteq":"⊵","tridot":"◬","trie":"≜","triminus":"⨺","TripleDot":"⃛","triplus":"⨹","trisb":"⧍","tritime":"⨻","trpezium":"⏢","Tscr":"𝒯","tscr":"𝓉","TScy":"Ц","tscy":"ц","TSHcy":"Ћ","tshcy":"ћ","Tstrok":"Ŧ","tstrok":"ŧ","twixt":"≬","twoheadleftarrow":"↞","twoheadrightarrow":"↠","Uacute":"Ú","uacute":"ú","uarr":"↑","Uarr":"↟","uArr":"⇑","Uarrocir":"⥉","Ubrcy":"Ў","ubrcy":"ў","Ubreve":"Ŭ","ubreve":"ŭ","Ucirc":"Û","ucirc":"û","Ucy":"У","ucy":"у","udarr":"⇅","Udblac":"Ű","udblac":"ű","udhar":"⥮","ufisht":"⥾","Ufr":"𝔘","ufr":"𝔲","Ugrave":"Ù","ugrave":"ù","uHar":"⥣","uharl":"↿","uharr":"↾","uhblk":"▀","ulcorn":"⌜","ulcorner":"⌜","ulcrop":"⌏","ultri":"◸","Umacr":"Ū","umacr":"ū","uml":"¨","UnderBar":"_","UnderBrace":"⏟","UnderBracket":"⎵","UnderParenthesis":"⏝","Union":"⋃","UnionPlus":"⊎","Uogon":"Ų","uogon":"ų","Uopf":"𝕌","uopf":"𝕦","UpArrowBar":"⤒","uparrow":"↑","UpArrow":"↑","Uparrow":"⇑","UpArrowDownArrow":"⇅","updownarrow":"↕","UpDownArrow":"↕","Updownarrow":"⇕","UpEquilibrium":"⥮","upharpoonleft":"↿","upharpoonright":"↾","uplus":"⊎","UpperLeftArrow":"↖","UpperRightArrow":"↗","upsi":"υ","Upsi":"ϒ","upsih":"ϒ","Upsilon":"Υ","upsilon":"υ","UpTeeArrow":"↥","UpTee":"⊥","upuparrows":"⇈","urcorn":"⌝","urcorner":"⌝","urcrop":"⌎","Uring":"Ů","uring":"ů","urtri":"◹","Uscr":"𝒰","uscr":"𝓊","utdot":"⋰","Utilde":"Ũ","utilde":"ũ","utri":"▵","utrif":"▴","uuarr":"⇈","Uuml":"Ü","uuml":"ü","uwangle":"⦧","vangrt":"⦜","varepsilon":"ϵ","varkappa":"ϰ","varnothing":"∅","varphi":"ϕ","varpi":"ϖ","varpropto":"∝","varr":"↕","vArr":"⇕","varrho":"ϱ","varsigma":"ς","varsubsetneq":"⊊︀","varsubsetneqq":"⫋︀","varsupsetneq":"⊋︀","varsupsetneqq":"⫌︀","vartheta":"ϑ","vartriangleleft":"⊲","vartriangleright":"⊳","vBar":"⫨","Vbar":"⫫","vBarv":"⫩","Vcy":"В","vcy":"в","vdash":"⊢","vDash":"⊨","Vdash":"⊩","VDash":"⊫","Vdashl":"⫦","veebar":"⊻","vee":"∨","Vee":"⋁","veeeq":"≚","vellip":"⋮","verbar":"|","Verbar":"‖","vert":"|","Vert":"‖","VerticalBar":"∣","VerticalLine":"|","VerticalSeparator":"❘","VerticalTilde":"≀","VeryThinSpace":" ","Vfr":"𝔙","vfr":"𝔳","vltri":"⊲","vnsub":"⊂⃒","vnsup":"⊃⃒","Vopf":"𝕍","vopf":"𝕧","vprop":"∝","vrtri":"⊳","Vscr":"𝒱","vscr":"𝓋","vsubnE":"⫋︀","vsubne":"⊊︀","vsupnE":"⫌︀","vsupne":"⊋︀","Vvdash":"⊪","vzigzag":"⦚","Wcirc":"Ŵ","wcirc":"ŵ","wedbar":"⩟","wedge":"∧","Wedge":"⋀","wedgeq":"≙","weierp":"℘","Wfr":"𝔚","wfr":"𝔴","Wopf":"𝕎","wopf":"𝕨","wp":"℘","wr":"≀","wreath":"≀","Wscr":"𝒲","wscr":"𝓌","xcap":"⋂","xcirc":"◯","xcup":"⋃","xdtri":"▽","Xfr":"𝔛","xfr":"𝔵","xharr":"⟷","xhArr":"⟺","Xi":"Ξ","xi":"ξ","xlarr":"⟵","xlArr":"⟸","xmap":"⟼","xnis":"⋻","xodot":"⨀","Xopf":"𝕏","xopf":"𝕩","xoplus":"⨁","xotime":"⨂","xrarr":"⟶","xrArr":"⟹","Xscr":"𝒳","xscr":"𝓍","xsqcup":"⨆","xuplus":"⨄","xutri":"△","xvee":"⋁","xwedge":"⋀","Yacute":"Ý","yacute":"ý","YAcy":"Я","yacy":"я","Ycirc":"Ŷ","ycirc":"ŷ","Ycy":"Ы","ycy":"ы","yen":"¥","Yfr":"𝔜","yfr":"𝔶","YIcy":"Ї","yicy":"ї","Yopf":"𝕐","yopf":"𝕪","Yscr":"𝒴","yscr":"𝓎","YUcy":"Ю","yucy":"ю","yuml":"ÿ","Yuml":"Ÿ","Zacute":"Ź","zacute":"ź","Zcaron":"Ž","zcaron":"ž","Zcy":"З","zcy":"з","Zdot":"Ż","zdot":"ż","zeetrf":"ℨ","ZeroWidthSpace":"​","Zeta":"Ζ","zeta":"ζ","zfr":"𝔷","Zfr":"ℨ","ZHcy":"Ж","zhcy":"ж","zigrarr":"⇝","zopf":"𝕫","Zopf":"ℤ","Zscr":"𝒵","zscr":"𝓏","zwj":"‍","zwnj":"‌"};

/***/ }),
/* 298 */
/***/ (function(module) {

module.exports = {"amp":"&","apos":"'","gt":">","lt":"<","quot":"\""};

/***/ }),
/* 299 */
/***/ (function(module, exports, __nested_webpack_require_1551920__) {

/*
  Module dependencies
*/
var ElementType = __nested_webpack_require_1551920__(123);
var entities = __nested_webpack_require_1551920__(960);

var unencodedElements = {
  __proto__: null,
  style: true,
  script: true,
  xmp: true,
  iframe: true,
  noembed: true,
  noframes: true,
  plaintext: true,
  noscript: true
};

/*
  Format attributes
*/
function formatAttrs(attributes, opts) {
  if (!attributes) return;

  var output = '',
      value;

  // Loop through the attributes
  for (var key in attributes) {
    value = attributes[key];
    if (output) {
      output += ' ';
    }

    output += key;
    if ((value !== null && value !== '') || opts.xmlMode) {
        output += '="' + (opts.decodeEntities ? entities.encodeXML(value) : value) + '"';
    }
  }

  return output;
}

/*
  Self-enclosing tags (stolen from node-htmlparser)
*/
var singleTag = {
  __proto__: null,
  area: true,
  base: true,
  basefont: true,
  br: true,
  col: true,
  command: true,
  embed: true,
  frame: true,
  hr: true,
  img: true,
  input: true,
  isindex: true,
  keygen: true,
  link: true,
  meta: true,
  param: true,
  source: true,
  track: true,
  wbr: true,
};


var render = module.exports = function(dom, opts) {
  if (!Array.isArray(dom) && !dom.cheerio) dom = [dom];
  opts = opts || {};

  var output = '';

  for(var i = 0; i < dom.length; i++){
    var elem = dom[i];

    if (elem.type === 'root')
      output += render(elem.children, opts);
    else if (ElementType.isTag(elem))
      output += renderTag(elem, opts);
    else if (elem.type === ElementType.Directive)
      output += renderDirective(elem);
    else if (elem.type === ElementType.Comment)
      output += renderComment(elem);
    else if (elem.type === ElementType.CDATA)
      output += renderCdata(elem);
    else
      output += renderText(elem, opts);
  }

  return output;
};

function renderTag(elem, opts) {
  // Handle SVG
  if (elem.name === "svg") opts = {decodeEntities: opts.decodeEntities, xmlMode: true};

  var tag = '<' + elem.name,
      attribs = formatAttrs(elem.attribs, opts);

  if (attribs) {
    tag += ' ' + attribs;
  }

  if (
    opts.xmlMode
    && (!elem.children || elem.children.length === 0)
  ) {
    tag += '/>';
  } else {
    tag += '>';
    if (elem.children) {
      tag += render(elem.children, opts);
    }

    if (!singleTag[elem.name] || opts.xmlMode) {
      tag += '</' + elem.name + '>';
    }
  }

  return tag;
}

function renderDirective(elem) {
  return '<' + elem.data + '>';
}

function renderText(elem, opts) {
  var data = elem.data || '';

  // if entities weren't decoded, no need to encode them back
  if (opts.decodeEntities && !(elem.parent && elem.parent.name in unencodedElements)) {
    data = entities.encodeXML(data);
  }

  return data;
}

function renderCdata(elem) {
  return '<![CDATA[' + elem.children[0].data + ']]>';
}

function renderComment(elem) {
  return '<!--' + elem.data + '-->';
}


/***/ }),
/* 300 */
/***/ (function(module, exports, __nested_webpack_require_1554914__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



/*<replacement>*/

var Buffer = __nested_webpack_require_1554914__(200).Buffer;
/*</replacement>*/

var isEncoding = Buffer.isEncoding || function (encoding) {
  encoding = '' + encoding;
  switch (encoding && encoding.toLowerCase()) {
    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
      return true;
    default:
      return false;
  }
};

function _normalizeEncoding(enc) {
  if (!enc) return 'utf8';
  var retried;
  while (true) {
    switch (enc) {
      case 'utf8':
      case 'utf-8':
        return 'utf8';
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return 'utf16le';
      case 'latin1':
      case 'binary':
        return 'latin1';
      case 'base64':
      case 'ascii':
      case 'hex':
        return enc;
      default:
        if (retried) return; // undefined
        enc = ('' + enc).toLowerCase();
        retried = true;
    }
  }
};

// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
  var nenc = _normalizeEncoding(enc);
  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  return nenc || enc;
}

// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
  this.encoding = normalizeEncoding(encoding);
  var nb;
  switch (this.encoding) {
    case 'utf16le':
      this.text = utf16Text;
      this.end = utf16End;
      nb = 4;
      break;
    case 'utf8':
      this.fillLast = utf8FillLast;
      nb = 4;
      break;
    case 'base64':
      this.text = base64Text;
      this.end = base64End;
      nb = 3;
      break;
    default:
      this.write = simpleWrite;
      this.end = simpleEnd;
      return;
  }
  this.lastNeed = 0;
  this.lastTotal = 0;
  this.lastChar = Buffer.allocUnsafe(nb);
}

StringDecoder.prototype.write = function (buf) {
  if (buf.length === 0) return '';
  var r;
  var i;
  if (this.lastNeed) {
    r = this.fillLast(buf);
    if (r === undefined) return '';
    i = this.lastNeed;
    this.lastNeed = 0;
  } else {
    i = 0;
  }
  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  return r || '';
};

StringDecoder.prototype.end = utf8End;

// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;

// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  this.lastNeed -= buf.length;
};

// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  return byte >> 6 === 0x02 ? -1 : -2;
}

// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i || nb === -2) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}

// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
  if ((buf[0] & 0xC0) !== 0x80) {
    self.lastNeed = 0;
    return '\ufffd';
  }
  if (self.lastNeed > 1 && buf.length > 1) {
    if ((buf[1] & 0xC0) !== 0x80) {
      self.lastNeed = 1;
      return '\ufffd';
    }
    if (self.lastNeed > 2 && buf.length > 2) {
      if ((buf[2] & 0xC0) !== 0x80) {
        self.lastNeed = 2;
        return '\ufffd';
      }
    }
  }
}

// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
  var p = this.lastTotal - this.lastNeed;
  var r = utf8CheckExtraBytes(this, buf, p);
  if (r !== undefined) return r;
  if (this.lastNeed <= buf.length) {
    buf.copy(this.lastChar, p, 0, this.lastNeed);
    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  }
  buf.copy(this.lastChar, p, 0, buf.length);
  this.lastNeed -= buf.length;
}

// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
  var total = utf8CheckIncomplete(this, buf, i);
  if (!this.lastNeed) return buf.toString('utf8', i);
  this.lastTotal = total;
  var end = buf.length - (total - this.lastNeed);
  buf.copy(this.lastChar, 0, end);
  return buf.toString('utf8', i, end);
}

// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd';
  return r;
}

// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
  if ((buf.length - i) % 2 === 0) {
    var r = buf.toString('utf16le', i);
    if (r) {
      var c = r.charCodeAt(r.length - 1);
      if (c >= 0xD800 && c <= 0xDBFF) {
        this.lastNeed = 2;
        this.lastTotal = 4;
        this.lastChar[0] = buf[buf.length - 2];
        this.lastChar[1] = buf[buf.length - 1];
        return r.slice(0, -1);
      }
    }
    return r;
  }
  this.lastNeed = 1;
  this.lastTotal = 2;
  this.lastChar[0] = buf[buf.length - 1];
  return buf.toString('utf16le', i, buf.length - 1);
}

// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) {
    var end = this.lastTotal - this.lastNeed;
    return r + this.lastChar.toString('utf16le', 0, end);
  }
  return r;
}

function base64Text(buf, i) {
  var n = (buf.length - i) % 3;
  if (n === 0) return buf.toString('base64', i);
  this.lastNeed = 3 - n;
  this.lastTotal = 3;
  if (n === 1) {
    this.lastChar[0] = buf[buf.length - 1];
  } else {
    this.lastChar[0] = buf[buf.length - 2];
    this.lastChar[1] = buf[buf.length - 1];
  }
  return buf.toString('base64', i, buf.length - n);
}

function base64End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  return r;
}

// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
  return buf.toString(this.encoding);
}

function simpleEnd(buf) {
  return buf && buf.length ? this.write(buf) : '';
}

/***/ }),
/* 301 */
/***/ (function(module, exports, __nested_webpack_require_1564461__) {

"use strict";


var DOCUMENT_MODE = __nested_webpack_require_1564461__(64).DOCUMENT_MODE;

//Node construction
exports.createDocument = function () {
    return {
        nodeName: '#document',
        mode: DOCUMENT_MODE.NO_QUIRKS,
        childNodes: []
    };
};

exports.createDocumentFragment = function () {
    return {
        nodeName: '#document-fragment',
        childNodes: []
    };
};

exports.createElement = function (tagName, namespaceURI, attrs) {
    return {
        nodeName: tagName,
        tagName: tagName,
        attrs: attrs,
        namespaceURI: namespaceURI,
        childNodes: [],
        parentNode: null
    };
};

exports.createCommentNode = function (data) {
    return {
        nodeName: '#comment',
        data: data,
        parentNode: null
    };
};

var createTextNode = function (value) {
    return {
        nodeName: '#text',
        value: value,
        parentNode: null
    };
};


//Tree mutation
var appendChild = exports.appendChild = function (parentNode, newNode) {
    parentNode.childNodes.push(newNode);
    newNode.parentNode = parentNode;
};

var insertBefore = exports.insertBefore = function (parentNode, newNode, referenceNode) {
    var insertionIdx = parentNode.childNodes.indexOf(referenceNode);

    parentNode.childNodes.splice(insertionIdx, 0, newNode);
    newNode.parentNode = parentNode;
};

exports.setTemplateContent = function (templateElement, contentElement) {
    templateElement.content = contentElement;
};

exports.getTemplateContent = function (templateElement) {
    return templateElement.content;
};

exports.setDocumentType = function (document, name, publicId, systemId) {
    var doctypeNode = null;

    for (var i = 0; i < document.childNodes.length; i++) {
        if (document.childNodes[i].nodeName === '#documentType') {
            doctypeNode = document.childNodes[i];
            break;
        }
    }

    if (doctypeNode) {
        doctypeNode.name = name;
        doctypeNode.publicId = publicId;
        doctypeNode.systemId = systemId;
    }

    else {
        appendChild(document, {
            nodeName: '#documentType',
            name: name,
            publicId: publicId,
            systemId: systemId
        });
    }
};

exports.setDocumentMode = function (document, mode) {
    document.mode = mode;
};

exports.getDocumentMode = function (document) {
    return document.mode;
};

exports.detachNode = function (node) {
    if (node.parentNode) {
        var idx = node.parentNode.childNodes.indexOf(node);

        node.parentNode.childNodes.splice(idx, 1);
        node.parentNode = null;
    }
};

exports.insertText = function (parentNode, text) {
    if (parentNode.childNodes.length) {
        var prevNode = parentNode.childNodes[parentNode.childNodes.length - 1];

        if (prevNode.nodeName === '#text') {
            prevNode.value += text;
            return;
        }
    }

    appendChild(parentNode, createTextNode(text));
};

exports.insertTextBefore = function (parentNode, text, referenceNode) {
    var prevNode = parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode) - 1];

    if (prevNode && prevNode.nodeName === '#text')
        prevNode.value += text;
    else
        insertBefore(parentNode, createTextNode(text), referenceNode);
};

exports.adoptAttributes = function (recipient, attrs) {
    var recipientAttrsMap = [];

    for (var i = 0; i < recipient.attrs.length; i++)
        recipientAttrsMap.push(recipient.attrs[i].name);

    for (var j = 0; j < attrs.length; j++) {
        if (recipientAttrsMap.indexOf(attrs[j].name) === -1)
            recipient.attrs.push(attrs[j]);
    }
};


//Tree traversing
exports.getFirstChild = function (node) {
    return node.childNodes[0];
};

exports.getChildNodes = function (node) {
    return node.childNodes;
};

exports.getParentNode = function (node) {
    return node.parentNode;
};

exports.getAttrList = function (element) {
    return element.attrs;
};

//Node data
exports.getTagName = function (element) {
    return element.tagName;
};

exports.getNamespaceURI = function (element) {
    return element.namespaceURI;
};

exports.getTextNodeContent = function (textNode) {
    return textNode.value;
};

exports.getCommentNodeContent = function (commentNode) {
    return commentNode.data;
};

exports.getDocumentTypeNodeName = function (doctypeNode) {
    return doctypeNode.name;
};

exports.getDocumentTypeNodePublicId = function (doctypeNode) {
    return doctypeNode.publicId;
};

exports.getDocumentTypeNodeSystemId = function (doctypeNode) {
    return doctypeNode.systemId;
};

//Node types
exports.isTextNode = function (node) {
    return node.nodeName === '#text';
};

exports.isCommentNode = function (node) {
    return node.nodeName === '#comment';
};

exports.isDocumentTypeNode = function (node) {
    return node.nodeName === '#documentType';
};

exports.isElementNode = function (node) {
    return !!node.tagName;
};


/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = function mergeOptions(defaults, options) {
    options = options || Object.create(null);

    return [defaults, options].reduce(function (merged, optObj) {
        Object.keys(optObj).forEach(function (key) {
            merged[key] = optObj[key];
        });

        return merged;
    }, Object.create(null));
};


/***/ }),
/* 303 */
/***/ (function(module, exports, __nested_webpack_require_1569913__) {

"use strict";


var DOCUMENT_MODE = __nested_webpack_require_1569913__(64).DOCUMENT_MODE;

//Const
var VALID_DOCTYPE_NAME = 'html',
    QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd',
    QUIRKS_MODE_PUBLIC_ID_PREFIXES = [
        '+//silmaril//dtd html pro v0r11 19970101//en',
        '-//advasoft ltd//dtd html 3.0 aswedit + extensions//en',
        '-//as//dtd html 3.0 aswedit + extensions//en',
        '-//ietf//dtd html 2.0 level 1//en',
        '-//ietf//dtd html 2.0 level 2//en',
        '-//ietf//dtd html 2.0 strict level 1//en',
        '-//ietf//dtd html 2.0 strict level 2//en',
        '-//ietf//dtd html 2.0 strict//en',
        '-//ietf//dtd html 2.0//en',
        '-//ietf//dtd html 2.1e//en',
        '-//ietf//dtd html 3.0//en',
        '-//ietf//dtd html 3.0//en//',
        '-//ietf//dtd html 3.2 final//en',
        '-//ietf//dtd html 3.2//en',
        '-//ietf//dtd html 3//en',
        '-//ietf//dtd html level 0//en',
        '-//ietf//dtd html level 0//en//2.0',
        '-//ietf//dtd html level 1//en',
        '-//ietf//dtd html level 1//en//2.0',
        '-//ietf//dtd html level 2//en',
        '-//ietf//dtd html level 2//en//2.0',
        '-//ietf//dtd html level 3//en',
        '-//ietf//dtd html level 3//en//3.0',
        '-//ietf//dtd html strict level 0//en',
        '-//ietf//dtd html strict level 0//en//2.0',
        '-//ietf//dtd html strict level 1//en',
        '-//ietf//dtd html strict level 1//en//2.0',
        '-//ietf//dtd html strict level 2//en',
        '-//ietf//dtd html strict level 2//en//2.0',
        '-//ietf//dtd html strict level 3//en',
        '-//ietf//dtd html strict level 3//en//3.0',
        '-//ietf//dtd html strict//en',
        '-//ietf//dtd html strict//en//2.0',
        '-//ietf//dtd html strict//en//3.0',
        '-//ietf//dtd html//en',
        '-//ietf//dtd html//en//2.0',
        '-//ietf//dtd html//en//3.0',
        '-//metrius//dtd metrius presentational//en',
        '-//microsoft//dtd internet explorer 2.0 html strict//en',
        '-//microsoft//dtd internet explorer 2.0 html//en',
        '-//microsoft//dtd internet explorer 2.0 tables//en',
        '-//microsoft//dtd internet explorer 3.0 html strict//en',
        '-//microsoft//dtd internet explorer 3.0 html//en',
        '-//microsoft//dtd internet explorer 3.0 tables//en',
        '-//netscape comm. corp.//dtd html//en',
        '-//netscape comm. corp.//dtd strict html//en',
        '-//o\'reilly and associates//dtd html 2.0//en',
        '-//o\'reilly and associates//dtd html extended 1.0//en',
        '-//spyglass//dtd html 2.0 extended//en',
        '-//sq//dtd html 2.0 hotmetal + extensions//en',
        '-//sun microsystems corp.//dtd hotjava html//en',
        '-//sun microsystems corp.//dtd hotjava strict html//en',
        '-//w3c//dtd html 3 1995-03-24//en',
        '-//w3c//dtd html 3.2 draft//en',
        '-//w3c//dtd html 3.2 final//en',
        '-//w3c//dtd html 3.2//en',
        '-//w3c//dtd html 3.2s draft//en',
        '-//w3c//dtd html 4.0 frameset//en',
        '-//w3c//dtd html 4.0 transitional//en',
        '-//w3c//dtd html experimental 19960712//en',
        '-//w3c//dtd html experimental 970421//en',
        '-//w3c//dtd w3 html//en',
        '-//w3o//dtd w3 html 3.0//en',
        '-//w3o//dtd w3 html 3.0//en//',
        '-//webtechs//dtd mozilla html 2.0//en',
        '-//webtechs//dtd mozilla html//en'
    ],
    QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([
        '-//w3c//dtd html 4.01 frameset//',
        '-//w3c//dtd html 4.01 transitional//'
    ]),
    QUIRKS_MODE_PUBLIC_IDS = [
        '-//w3o//dtd w3 html strict 3.0//en//',
        '-/w3c/dtd html 4.0 transitional/en',
        'html'
    ],
    LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = [
        '-//W3C//DTD XHTML 1.0 Frameset//',
        '-//W3C//DTD XHTML 1.0 Transitional//'
    ],
    LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([
        '-//W3C//DTD HTML 4.01 Frameset//',
        '-//W3C//DTD HTML 4.01 Transitional//'
    ]);


//Utils
function enquoteDoctypeId(id) {
    var quote = id.indexOf('"') !== -1 ? '\'' : '"';

    return quote + id + quote;
}

function hasPrefix(publicId, prefixes) {
    for (var i = 0; i < prefixes.length; i++) {
        if (publicId.indexOf(prefixes[i]) === 0)
            return true;
    }

    return false;
}


//API
exports.getDocumentMode = function (name, publicId, systemId) {
    if (name !== VALID_DOCTYPE_NAME)
        return DOCUMENT_MODE.QUIRKS;

    if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID)
        return DOCUMENT_MODE.QUIRKS;

    if (publicId !== null) {
        publicId = publicId.toLowerCase();

        if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1)
            return DOCUMENT_MODE.QUIRKS;

        var prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES;

        if (hasPrefix(publicId, prefixes))
            return DOCUMENT_MODE.QUIRKS;

        prefixes = systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;

        if (hasPrefix(publicId, prefixes))
            return DOCUMENT_MODE.LIMITED_QUIRKS;
    }

    return DOCUMENT_MODE.NO_QUIRKS;
};

exports.serializeContent = function (name, publicId, systemId) {
    var str = '!DOCTYPE ';

    if (name)
        str += name;

    if (publicId !== null)
        str += ' PUBLIC ' + enquoteDoctypeId(publicId);

    else if (systemId !== null)
        str += ' SYSTEM';

    if (systemId !== null)
        str += ' ' + enquoteDoctypeId(systemId);

    return str;
};


/***/ }),
/* 304 */
/***/ (function(module, exports, __nested_webpack_require_1575688__) {

exports = module.exports = __nested_webpack_require_1575688__(468);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __nested_webpack_require_1575688__(305);
exports.Duplex = __nested_webpack_require_1575688__(102);
exports.Transform = __nested_webpack_require_1575688__(471);
exports.PassThrough = __nested_webpack_require_1575688__(987);


/***/ }),
/* 305 */
/***/ (function(module, exports, __nested_webpack_require_1576056__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.



/*<replacement>*/

var pna = __nested_webpack_require_1576056__(203);
/*</replacement>*/

module.exports = Writable;

/* <replacement> */
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
  this.next = null;
}

// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
  var _this = this;

  this.next = null;
  this.entry = null;
  this.finish = function () {
    onCorkedFinish(_this, state);
  };
}
/* </replacement> */

/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/

/*<replacement>*/
var Duplex;
/*</replacement>*/

Writable.WritableState = WritableState;

/*<replacement>*/
var util = __nested_webpack_require_1576056__(151);
util.inherits = __nested_webpack_require_1576056__(58);
/*</replacement>*/

/*<replacement>*/
var internalUtil = {
  deprecate: __nested_webpack_require_1576056__(986)
};
/*</replacement>*/

/*<replacement>*/
var Stream = __nested_webpack_require_1576056__(469);
/*</replacement>*/

/*<replacement>*/

var Buffer = __nested_webpack_require_1576056__(200).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*</replacement>*/

var destroyImpl = __nested_webpack_require_1576056__(470);

util.inherits(Writable, Stream);

function nop() {}

function WritableState(options, stream) {
  Duplex = Duplex || __nested_webpack_require_1576056__(102);

  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  var isDuplex = stream instanceof Duplex;

  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;

  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;

  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  var writableHwm = options.writableHighWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;

  // cast to ints.
  this.highWaterMark = Math.floor(this.highWaterMark);

  // if _final has been called
  this.finalCalled = false;

  // drain event flag.
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;

  // has it been destroyed
  this.destroyed = false;

  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;

  // a flag to see when we're in the middle of a write.
  this.writing = false;

  // when true all writes will be buffered until .uncork() call
  this.corked = 0;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;

  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function (er) {
    onwrite(stream, er);
  };

  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;

  // the amount that is being written when _write is called.
  this.writelen = 0;

  this.bufferedRequest = null;
  this.lastBufferedRequest = null;

  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;

  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;

  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;

  // count buffered requests
  this.bufferedRequestCount = 0;

  // allocate the first CorkedRequest, there is always
  // one allocated and free to use, and we maintain at most two
  this.corkedRequestsFree = new CorkedRequest(this);
}

WritableState.prototype.getBuffer = function getBuffer() {
  var current = this.bufferedRequest;
  var out = [];
  while (current) {
    out.push(current);
    current = current.next;
  }
  return out;
};

(function () {
  try {
    Object.defineProperty(WritableState.prototype, 'buffer', {
      get: internalUtil.deprecate(function () {
        return this.getBuffer();
      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
    });
  } catch (_) {}
})();

// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  realHasInstance = Function.prototype[Symbol.hasInstance];
  Object.defineProperty(Writable, Symbol.hasInstance, {
    value: function (object) {
      if (realHasInstance.call(this, object)) return true;
      if (this !== Writable) return false;

      return object && object._writableState instanceof WritableState;
    }
  });
} else {
  realHasInstance = function (object) {
    return object instanceof this;
  };
}

function Writable(options) {
  Duplex = Duplex || __nested_webpack_require_1576056__(102);

  // Writable ctor is applied to Duplexes, too.
  // `realHasInstance` is necessary because using plain `instanceof`
  // would return false, as no `_writableState` property is attached.

  // Trying to use the custom `instanceof` for Writable here will also break the
  // Node.js LazyTransform implementation, which has a non-trivial getter for
  // `_writableState` that would lead to infinite recursion.
  if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
    return new Writable(options);
  }

  this._writableState = new WritableState(options, this);

  // legacy.
  this.writable = true;

  if (options) {
    if (typeof options.write === 'function') this._write = options.write;

    if (typeof options.writev === 'function') this._writev = options.writev;

    if (typeof options.destroy === 'function') this._destroy = options.destroy;

    if (typeof options.final === 'function') this._final = options.final;
  }

  Stream.call(this);
}

// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
  this.emit('error', new Error('Cannot pipe, not readable'));
};

function writeAfterEnd(stream, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  pna.nextTick(cb, er);
}

// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  var er = false;

  if (chunk === null) {
    er = new TypeError('May not write null values to stream');
  } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  if (er) {
    stream.emit('error', er);
    pna.nextTick(cb, er);
    valid = false;
  }
  return valid;
}

Writable.prototype.write = function (chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
  var isBuf = !state.objectMode && _isUint8Array(chunk);

  if (isBuf && !Buffer.isBuffer(chunk)) {
    chunk = _uint8ArrayToBuffer(chunk);
  }

  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;

  if (typeof cb !== 'function') cb = nop;

  if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  }

  return ret;
};

Writable.prototype.cork = function () {
  var state = this._writableState;

  state.corked++;
};

Writable.prototype.uncork = function () {
  var state = this._writableState;

  if (state.corked) {
    state.corked--;

    if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  }
};

Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  // node::ParseEncoding() requires lower case.
  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  this._writableState.defaultEncoding = encoding;
  return this;
};

function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
    chunk = Buffer.from(chunk, encoding);
  }
  return chunk;
}

Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._writableState.highWaterMark;
  }
});

// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  if (!isBuf) {
    var newChunk = decodeChunk(state, chunk, encoding);
    if (chunk !== newChunk) {
      isBuf = true;
      encoding = 'buffer';
      chunk = newChunk;
    }
  }
  var len = state.objectMode ? 1 : chunk.length;

  state.length += len;

  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret) state.needDrain = true;

  if (state.writing || state.corked) {
    var last = state.lastBufferedRequest;
    state.lastBufferedRequest = {
      chunk: chunk,
      encoding: encoding,
      isBuf: isBuf,
      callback: cb,
      next: null
    };
    if (last) {
      last.next = state.lastBufferedRequest;
    } else {
      state.bufferedRequest = state.lastBufferedRequest;
    }
    state.bufferedRequestCount += 1;
  } else {
    doWrite(stream, state, false, len, chunk, encoding, cb);
  }

  return ret;
}

function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}

function onwriteError(stream, state, sync, er, cb) {
  --state.pendingcb;

  if (sync) {
    // defer the callback if we are being called synchronously
    // to avoid piling up things on the stack
    pna.nextTick(cb, er);
    // this can emit finish, and it will always happen
    // after error
    pna.nextTick(finishMaybe, stream, state);
    stream._writableState.errorEmitted = true;
    stream.emit('error', er);
  } else {
    // the caller expect this to happen before if
    // it is async
    cb(er);
    stream._writableState.errorEmitted = true;
    stream.emit('error', er);
    // this can emit finish, but finish must
    // always follow error
    finishMaybe(stream, state);
  }
}

function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}

function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;

  onwriteStateUpdate(state);

  if (er) onwriteError(stream, state, sync, er, cb);else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(state);

    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
      clearBuffer(stream, state);
    }

    if (sync) {
      /*<replacement>*/
      asyncWrite(afterWrite, stream, state, finished, cb);
      /*</replacement>*/
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}

function afterWrite(stream, state, finished, cb) {
  if (!finished) onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}

// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}

// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
  var entry = state.bufferedRequest;

  if (stream._writev && entry && entry.next) {
    // Fast case, write everything using _writev()
    var l = state.bufferedRequestCount;
    var buffer = new Array(l);
    var holder = state.corkedRequestsFree;
    holder.entry = entry;

    var count = 0;
    var allBuffers = true;
    while (entry) {
      buffer[count] = entry;
      if (!entry.isBuf) allBuffers = false;
      entry = entry.next;
      count += 1;
    }
    buffer.allBuffers = allBuffers;

    doWrite(stream, state, true, state.length, buffer, '', holder.finish);

    // doWrite is almost always async, defer these to save a bit of time
    // as the hot path ends with doWrite
    state.pendingcb++;
    state.lastBufferedRequest = null;
    if (holder.next) {
      state.corkedRequestsFree = holder.next;
      holder.next = null;
    } else {
      state.corkedRequestsFree = new CorkedRequest(state);
    }
    state.bufferedRequestCount = 0;
  } else {
    // Slow case, write chunks one-by-one
    while (entry) {
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;

      doWrite(stream, state, false, len, chunk, encoding, cb);
      entry = entry.next;
      state.bufferedRequestCount--;
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        break;
      }
    }

    if (entry === null) state.lastBufferedRequest = null;
  }

  state.bufferedRequest = entry;
  state.bufferProcessing = false;
}

Writable.prototype._write = function (chunk, encoding, cb) {
  cb(new Error('_write() is not implemented'));
};

Writable.prototype._writev = null;

Writable.prototype.end = function (chunk, encoding, cb) {
  var state = this._writableState;

  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }

  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);

  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }

  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished) endWritable(this, state, cb);
};

function needFinish(state) {
  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
  stream._final(function (err) {
    state.pendingcb--;
    if (err) {
      stream.emit('error', err);
    }
    state.prefinished = true;
    stream.emit('prefinish');
    finishMaybe(stream, state);
  });
}
function prefinish(stream, state) {
  if (!state.prefinished && !state.finalCalled) {
    if (typeof stream._final === 'function') {
      state.pendingcb++;
      state.finalCalled = true;
      pna.nextTick(callFinal, stream, state);
    } else {
      state.prefinished = true;
      stream.emit('prefinish');
    }
  }
}

function finishMaybe(stream, state) {
  var need = needFinish(state);
  if (need) {
    prefinish(stream, state);
    if (state.pendingcb === 0) {
      state.finished = true;
      stream.emit('finish');
    }
  }
  return need;
}

function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  }
  state.ended = true;
  stream.writable = false;
}

function onCorkedFinish(corkReq, state, err) {
  var entry = corkReq.entry;
  corkReq.entry = null;
  while (entry) {
    var cb = entry.callback;
    state.pendingcb--;
    cb(err);
    entry = entry.next;
  }
  if (state.corkedRequestsFree) {
    state.corkedRequestsFree.next = corkReq;
  } else {
    state.corkedRequestsFree = corkReq;
  }
}

Object.defineProperty(Writable.prototype, 'destroyed', {
  get: function () {
    if (this._writableState === undefined) {
      return false;
    }
    return this._writableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._writableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._writableState.destroyed = value;
  }
});

Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
  this.end();
  cb(err);
};
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1576056__(150), __nested_webpack_require_1576056__(984).setImmediate, __nested_webpack_require_1576056__(27)))

/***/ }),
/* 306 */
/***/ (function(module, exports, __nested_webpack_require_1596606__) {

var baseRest = __nested_webpack_require_1596606__(291),
    createWrap = __nested_webpack_require_1596606__(997),
    getHolder = __nested_webpack_require_1596606__(309),
    replaceHolders = __nested_webpack_require_1596606__(206);

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
    WRAP_PARTIAL_FLAG = 32;

/**
 * Creates a function that invokes `func` with the `this` binding of `thisArg`
 * and `partials` prepended to the arguments it receives.
 *
 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
 * may be used as a placeholder for partially applied arguments.
 *
 * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
 * property of bound functions.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to bind.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {...*} [partials] The arguments to be partially applied.
 * @returns {Function} Returns the new bound function.
 * @example
 *
 * function greet(greeting, punctuation) {
 *   return greeting + ' ' + this.user + punctuation;
 * }
 *
 * var object = { 'user': 'fred' };
 *
 * var bound = _.bind(greet, object, 'hi');
 * bound('!');
 * // => 'hi fred!'
 *
 * // Bound with placeholders.
 * var bound = _.bind(greet, object, _, '!');
 * bound('hi');
 * // => 'hi fred!'
 */
var bind = baseRest(function(func, thisArg, partials) {
  var bitmask = WRAP_BIND_FLAG;
  if (partials.length) {
    var holders = replaceHolders(partials, getHolder(bind));
    bitmask |= WRAP_PARTIAL_FLAG;
  }
  return createWrap(func, bitmask, thisArg, partials, holders);
});

// Assign default placeholders.
bind.placeholder = {};

module.exports = bind;


/***/ }),
/* 307 */
/***/ (function(module, exports, __nested_webpack_require_1598378__) {

var baseCreate = __nested_webpack_require_1598378__(197),
    baseLodash = __nested_webpack_require_1598378__(308);

/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;

/**
 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
 *
 * @private
 * @constructor
 * @param {*} value The value to wrap.
 */
function LazyWrapper(value) {
  this.__wrapped__ = value;
  this.__actions__ = [];
  this.__dir__ = 1;
  this.__filtered__ = false;
  this.__iteratees__ = [];
  this.__takeCount__ = MAX_ARRAY_LENGTH;
  this.__views__ = [];
}

// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;

module.exports = LazyWrapper;


/***/ }),
/* 308 */
/***/ (function(module, exports) {

/**
 * The function whose prototype chain sequence wrappers inherit from.
 *
 * @private
 */
function baseLodash() {
  // No operation performed.
}

module.exports = baseLodash;


/***/ }),
/* 309 */
/***/ (function(module, exports) {

/**
 * Gets the argument placeholder value for `func`.
 *
 * @private
 * @param {Function} func The function to inspect.
 * @returns {*} Returns the placeholder value.
 */
function getHolder(func) {
  var object = func;
  return object.placeholder;
}

module.exports = getHolder;


/***/ }),
/* 310 */
/***/ (function(module, exports, __nested_webpack_require_1599804__) {

/**
 * Module dependencies
 */

var serialize = __nested_webpack_require_1599804__(299),
    defaultOptions = __nested_webpack_require_1599804__(204).default,
    flattenOptions = __nested_webpack_require_1599804__(204).flatten,
    select = __nested_webpack_require_1599804__(485),
    parse = __nested_webpack_require_1599804__(198),
    _ = {
      merge: __nested_webpack_require_1599804__(46),
      defaults: __nested_webpack_require_1599804__(484)
    };

/**
 * $.load(str)
 */

exports.load = function(content, options, isDocument) {
  var Cheerio = __nested_webpack_require_1599804__(454);

  options = _.defaults(flattenOptions(options || {}), defaultOptions);

  if (isDocument === void 0)
    isDocument = true;

  var root = parse(content, options, isDocument);

  var initialize = function(selector, context, r, opts) {
    if (!(this instanceof initialize)) {
      return new initialize(selector, context, r, opts);
    }
    opts = _.defaults(opts || {}, options);
    return Cheerio.call(this, selector, context, r || root, opts);
  };

  // Ensure that selections created by the "loaded" `initialize` function are
  // true Cheerio instances.
  initialize.prototype = Object.create(Cheerio.prototype);
  initialize.prototype.constructor = initialize;

  // Mimic jQuery's prototype alias for plugin authors.
  initialize.fn = initialize.prototype;

  // Keep a reference to the top-level scope so we can chain methods that implicitly
  // resolve selectors; e.g. $("<span>").(".bar"), which otherwise loses ._root
  initialize.prototype._originalRoot = root;

  // Add in the static methods
  _.merge(initialize, exports);

  // Add in the root
  initialize._root = root;
  // store options
  initialize._options = options;

  return initialize;
};

/*
* Helper function
*/

function render(that, dom, options) {
  if (!dom) {
    if (that._root && that._root.children) {
      dom = that._root.children;
    } else {
      return '';
    }
  } else if (typeof dom === 'string') {
    dom = select(dom, that._root, options);
  }

  return serialize(dom, options);
}

/**
 * $.html([selector | dom], [options])
 */

exports.html = function(dom, options) {
  // be flexible about parameters, sometimes we call html(),
  // with options as only parameter
  // check dom argument for dom element specific properties
  // assume there is no 'length' or 'type' properties in the options object
  if (Object.prototype.toString.call(dom) === '[object Object]' && !options && !('length' in dom) && !('type' in dom))
  {
    options = dom;
    dom = undefined;
  }

  // sometimes $.html() used without preloading html
  // so fallback non existing options to the default ones
  options = _.defaults(flattenOptions(options || {}), this._options, defaultOptions);

  return render(this, dom, options);
};

/**
 * $.xml([selector | dom])
 */

exports.xml = function(dom) {
  var options = _.defaults({xml: true}, this._options);

  return render(this, dom, options);
};

/**
 * $.text(dom)
 */

exports.text = function(elems) {
  if (!elems) {
    elems = this.root();
  }

  var ret = '',
      len = elems.length,
      elem;

  for (var i = 0; i < len; i++) {
    elem = elems[i];
    if (elem.type === 'text') ret += elem.data;
    else if (elem.children && elem.type !== 'comment' && elem.tagName !== 'script' && elem.tagName !== 'style') {
      ret += exports.text(elem.children);
    }
  }

  return ret;
};

/**
 * $.parseHTML(data [, context ] [, keepScripts ])
 * Parses a string into an array of DOM nodes. The `context` argument has no
 * meaning for Cheerio, but it is maintained for API compatibility with jQuery.
 */
exports.parseHTML = function(data, context, keepScripts) {
  var parsed;

  if (!data || typeof data !== 'string') {
    return null;
  }

  if (typeof context === 'boolean') {
    keepScripts = context;
  }

  parsed = this.load(data, defaultOptions, false);
  if (!keepScripts) {
    parsed('script').remove();
  }

  // The `children` array is used by Cheerio internally to group elements that
  // share the same parents. When nodes created through `parseHTML` are
  // inserted into previously-existing DOM structures, they will be removed
  // from the `children` array. The results of `parseHTML` should remain
  // constant across these operations, so a shallow copy should be returned.
  return parsed.root()[0].children.slice();
};

/**
 * $.root()
 */
exports.root = function() {
  return this(this._root);
};

/**
 * $.contains()
 */
exports.contains = function(container, contained) {

  // According to the jQuery API, an element does not "contain" itself
  if (contained === container) {
    return false;
  }

  // Step up the descendants, stopping when the root element is reached
  // (signaled by `.parent` returning a reference to the same object)
  while (contained && contained !== contained.parent) {
    contained = contained.parent;
    if (contained === container) {
      return true;
    }
  }

  return false;
};

/**
 * $.merge()
 */

exports.merge = function(arr1, arr2) {
  if(!(isArrayLike(arr1) && isArrayLike(arr2))){
    return;
  }
  var newLength = arr1.length + arr2.length;
  var i = 0;
  while(i < arr2.length){
    arr1[i + arr1.length] = arr2[i];
    i++;
  }
  arr1.length = newLength;
  return arr1;
};

function isArrayLike(item){
  if(Array.isArray(item)){
    return true;
  }
  if(typeof item !== 'object'){
    return false;
  }
  if(!item.hasOwnProperty('length')){
    return false;
  }
  if(typeof item.length !== 'number') {
    return false;
  }
  if(item.length < 0){
    return false;
  }
  var i = 0;
  while(i < item.length){
    if(!(i in item)){
      return false;
    }
    i++;
  }
  return true;
}


/***/ }),
/* 311 */
/***/ (function(module, exports, __nested_webpack_require_1605467__) {

/*
	pseudo selectors

	---

	they are available in two forms:
	* filters called when the selector
	  is compiled and return a function
	  that needs to return next()
	* pseudos get called on execution
	  they need to return a boolean
*/

var DomUtils    = __nested_webpack_require_1605467__(101),
    isTag       = DomUtils.isTag,
    getText     = DomUtils.getText,
    getParent   = DomUtils.getParent,
    getChildren = DomUtils.getChildren,
    getSiblings = DomUtils.getSiblings,
    hasAttrib   = DomUtils.hasAttrib,
    getName     = DomUtils.getName,
    getAttribute= DomUtils.getAttributeValue,
    getNCheck   = __nested_webpack_require_1605467__(1021),
    checkAttrib = __nested_webpack_require_1605467__(486).rules.equals,
    BaseFuncs   = __nested_webpack_require_1605467__(153),
    trueFunc    = BaseFuncs.trueFunc,
    falseFunc   = BaseFuncs.falseFunc;

//helper methods
function getFirstElement(elems){
	for(var i = 0; elems && i < elems.length; i++){
		if(isTag(elems[i])) return elems[i];
	}
}

function getAttribFunc(name, value){
	var data = {name: name, value: value};
	return function attribFunc(next){
		return checkAttrib(next, data);
	};
}

function getChildFunc(next){
	return function(elem){
		return !!getParent(elem) && next(elem);
	};
}

var filters = {
	contains: function(next, text){
		return function contains(elem){
			return next(elem) && getText(elem).indexOf(text) >= 0;
		};
	},
	icontains: function(next, text){
		var itext = text.toLowerCase();
		return function icontains(elem){
			return next(elem) &&
				getText(elem).toLowerCase().indexOf(itext) >= 0;
		};
	},

	//location specific methods
	"nth-child": function(next, rule){
		var func = getNCheck(rule);

		if(func === falseFunc) return func;
		if(func === trueFunc)  return getChildFunc(next);

		return function nthChild(elem){
			var siblings = getSiblings(elem);

			for(var i = 0, pos = 0; i < siblings.length; i++){
				if(isTag(siblings[i])){
					if(siblings[i] === elem) break;
					else pos++;
				}
			}

			return func(pos) && next(elem);
		};
	},
	"nth-last-child": function(next, rule){
		var func = getNCheck(rule);

		if(func === falseFunc) return func;
		if(func === trueFunc)  return getChildFunc(next);

		return function nthLastChild(elem){
			var siblings = getSiblings(elem);

			for(var pos = 0, i = siblings.length - 1; i >= 0; i--){
				if(isTag(siblings[i])){
					if(siblings[i] === elem) break;
					else pos++;
				}
			}

			return func(pos) && next(elem);
		};
	},
	"nth-of-type": function(next, rule){
		var func = getNCheck(rule);

		if(func === falseFunc) return func;
		if(func === trueFunc)  return getChildFunc(next);

		return function nthOfType(elem){
			var siblings = getSiblings(elem);

			for(var pos = 0, i = 0; i < siblings.length; i++){
				if(isTag(siblings[i])){
					if(siblings[i] === elem) break;
					if(getName(siblings[i]) === getName(elem)) pos++;
				}
			}

			return func(pos) && next(elem);
		};
	},
	"nth-last-of-type": function(next, rule){
		var func = getNCheck(rule);

		if(func === falseFunc) return func;
		if(func === trueFunc)  return getChildFunc(next);

		return function nthLastOfType(elem){
			var siblings = getSiblings(elem);

			for(var pos = 0, i = siblings.length - 1; i >= 0; i--){
				if(isTag(siblings[i])){
					if(siblings[i] === elem) break;
					if(getName(siblings[i]) === getName(elem)) pos++;
				}
			}

			return func(pos) && next(elem);
		};
	},

    //TODO determine the actual root element
    root: function(next){
        return function(elem){
            return !getParent(elem) && next(elem);
        };
    },

    scope: function(next, rule, options, context){
        if(!context || context.length === 0){
            //equivalent to :root
            return filters.root(next);
        }

        if(context.length === 1){
            //NOTE: can't be unpacked, as :has uses this for side-effects
            return function(elem){
                return context[0] === elem && next(elem);
            };
        }

        return function(elem){
            return context.indexOf(elem) >= 0 && next(elem);
        };
    },

	//jQuery extensions (others follow as pseudos)
	checkbox: getAttribFunc("type", "checkbox"),
	file: getAttribFunc("type", "file"),
	password: getAttribFunc("type", "password"),
	radio: getAttribFunc("type", "radio"),
	reset: getAttribFunc("type", "reset"),
	image: getAttribFunc("type", "image"),
	submit: getAttribFunc("type", "submit")
};

//while filters are precompiled, pseudos get called when they are needed
var pseudos = {
	empty: function(elem){
		return !getChildren(elem).some(function(elem){
			return isTag(elem) || elem.type === "text";
		});
	},

	"first-child": function(elem){
		return getFirstElement(getSiblings(elem)) === elem;
	},
	"last-child": function(elem){
		var siblings = getSiblings(elem);

		for(var i = siblings.length - 1; i >= 0; i--){
			if(siblings[i] === elem) return true;
			if(isTag(siblings[i])) break;
		}

		return false;
	},
	"first-of-type": function(elem){
		var siblings = getSiblings(elem);

		for(var i = 0; i < siblings.length; i++){
			if(isTag(siblings[i])){
				if(siblings[i] === elem) return true;
				if(getName(siblings[i]) === getName(elem)) break;
			}
		}

		return false;
	},
	"last-of-type": function(elem){
		var siblings = getSiblings(elem);

		for(var i = siblings.length-1; i >= 0; i--){
			if(isTag(siblings[i])){
				if(siblings[i] === elem) return true;
				if(getName(siblings[i]) === getName(elem)) break;
			}
		}

		return false;
	},
	"only-of-type": function(elem){
		var siblings = getSiblings(elem);

		for(var i = 0, j = siblings.length; i < j; i++){
			if(isTag(siblings[i])){
				if(siblings[i] === elem) continue;
				if(getName(siblings[i]) === getName(elem)) return false;
			}
		}

		return true;
	},
	"only-child": function(elem){
		var siblings = getSiblings(elem);

		for(var i = 0; i < siblings.length; i++){
			if(isTag(siblings[i]) && siblings[i] !== elem) return false;
		}

		return true;
	},

	//:matches(a, area, link)[href]
	link: function(elem){
		return hasAttrib(elem, "href");
	},
	visited: falseFunc, //seems to be a valid implementation
	//TODO: :any-link once the name is finalized (as an alias of :link)

	//forms
	//to consider: :target

	//:matches([selected], select:not([multiple]):not(> option[selected]) > option:first-of-type)
	selected: function(elem){
		if(hasAttrib(elem, "selected")) return true;
		else if(getName(elem) !== "option") return false;

		//the first <option> in a <select> is also selected
		var parent = getParent(elem);

		if(
			!parent ||
			getName(parent) !== "select" ||
			hasAttrib(parent, "multiple")
		) return false;

		var siblings = getChildren(parent),
			sawElem  = false;

		for(var i = 0; i < siblings.length; i++){
			if(isTag(siblings[i])){
				if(siblings[i] === elem){
					sawElem = true;
				} else if(!sawElem){
					return false;
				} else if(hasAttrib(siblings[i], "selected")){
					return false;
				}
			}
		}

		return sawElem;
	},
	//https://html.spec.whatwg.org/multipage/scripting.html#disabled-elements
	//:matches(
	//  :matches(button, input, select, textarea, menuitem, optgroup, option)[disabled],
	//  optgroup[disabled] > option),
	// fieldset[disabled] * //TODO not child of first <legend>
	//)
	disabled: function(elem){
		return hasAttrib(elem, "disabled");
	},
	enabled: function(elem){
		return !hasAttrib(elem, "disabled");
	},
	//:matches(:matches(:radio, :checkbox)[checked], :selected) (TODO menuitem)
	checked: function(elem){
		return hasAttrib(elem, "checked") || pseudos.selected(elem);
	},
	//:matches(input, select, textarea)[required]
	required: function(elem){
		return hasAttrib(elem, "required");
	},
	//:matches(input, select, textarea):not([required])
	optional: function(elem){
		return !hasAttrib(elem, "required");
	},

	//jQuery extensions

	//:not(:empty)
	parent: function(elem){
		return !pseudos.empty(elem);
	},
	//:matches(h1, h2, h3, h4, h5, h6)
	header: function(elem){
		var name = getName(elem);
		return name === "h1" ||
		       name === "h2" ||
		       name === "h3" ||
		       name === "h4" ||
		       name === "h5" ||
		       name === "h6";
	},

	//:matches(button, input[type=button])
	button: function(elem){
		var name = getName(elem);
		return name === "button" ||
		       name === "input" &&
		       getAttribute(elem, "type") === "button";
	},
	//:matches(input, textarea, select, button)
	input: function(elem){
		var name = getName(elem);
		return name === "input" ||
		       name === "textarea" ||
		       name === "select" ||
		       name === "button";
	},
	//input:matches(:not([type!='']), [type='text' i])
	text: function(elem){
		var attr;
		return getName(elem) === "input" && (
			!(attr = getAttribute(elem, "type")) ||
			attr.toLowerCase() === "text"
		);
	}
};

function verifyArgs(func, name, subselect){
	if(subselect === null){
		if(func.length > 1 && name !== "scope"){
			throw new SyntaxError("pseudo-selector :" + name + " requires an argument");
		}
	} else {
		if(func.length === 1){
			throw new SyntaxError("pseudo-selector :" + name + " doesn't have any arguments");
		}
	}
}

//FIXME this feels hacky
var re_CSS3 = /^(?:(?:nth|last|first|only)-(?:child|of-type)|root|empty|(?:en|dis)abled|checked|not)$/;

module.exports = {
	compile: function(next, data, options, context){
		var name = data.name,
			subselect = data.data;

		if(options && options.strict && !re_CSS3.test(name)){
			throw SyntaxError(":" + name + " isn't part of CSS3");
		}

		if(typeof filters[name] === "function"){
			verifyArgs(filters[name], name,  subselect);
			return filters[name](next, subselect, options, context);
		} else if(typeof pseudos[name] === "function"){
			var func = pseudos[name];
			verifyArgs(func, name, subselect);

			if(next === trueFunc) return func;

			return function pseudoArgs(elem){
				return func(elem, subselect) && next(elem);
			};
		} else {
			throw new SyntaxError("unmatched pseudo-class :" + name);
		}
	},
	filters: filters,
	pseudos: pseudos
};


/***/ }),
/* 312 */
/***/ (function(module, exports, __nested_webpack_require_1615533__) {

var bind = __nested_webpack_require_1615533__(53);
var has = bind.call(Function.call, Object.prototype.hasOwnProperty);

var $assign = Object.assign;

module.exports = function assign(target, source) {
	if ($assign) {
		return $assign(target, source);
	}

	for (var key in source) {
		if (has(source, key)) {
			target[key] = source[key];
		}
	}
	return target;
};


/***/ }),
/* 313 */
/***/ (function(module, exports, __nested_webpack_require_1615962__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

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

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; };

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.getAdapter = getAdapter;
exports.makeOptions = makeOptions;
exports.isCustomComponentElement = isCustomComponentElement;
exports.propsOfNode = propsOfNode;
exports.typeOfNode = typeOfNode;
exports.nodeHasType = nodeHasType;
exports.nodeMatches = nodeMatches;
exports.nodeEqual = nodeEqual;
exports.containsChildrenSubArray = containsChildrenSubArray;
exports.childrenToSimplifiedArray = childrenToSimplifiedArray;
exports.isReactElementAlike = isReactElementAlike;
exports.withSetStateAllowed = withSetStateAllowed;
exports.AND = AND;
exports.displayNameOfNode = displayNameOfNode;
exports.sym = sym;
exports.privateSet = privateSet;
exports.cloneElement = cloneElement;
exports.spyMethod = spyMethod;
exports.shallowEqual = shallowEqual;
exports.isEmptyValue = isEmptyValue;
exports.renderedDive = renderedDive;

var _object = __nested_webpack_require_1615962__(122);

var _object2 = _interopRequireDefault(_object);

var _lodash = __nested_webpack_require_1615962__(172);

var _lodash2 = _interopRequireDefault(_lodash);

var _objectIs = __nested_webpack_require_1615962__(501);

var _objectIs2 = _interopRequireDefault(_objectIs);

var _object3 = __nested_webpack_require_1615962__(502);

var _object4 = _interopRequireDefault(_object3);

var _functionPrototype = __nested_webpack_require_1615962__(314);

var _functionPrototype2 = _interopRequireDefault(_functionPrototype);

var _has = __nested_webpack_require_1615962__(59);

var _has2 = _interopRequireDefault(_has);

var _arrayPrototype = __nested_webpack_require_1615962__(154);

var _arrayPrototype2 = _interopRequireDefault(_arrayPrototype);

var _stringPrototype = __nested_webpack_require_1615962__(1061);

var _stringPrototype2 = _interopRequireDefault(_stringPrototype);

var _configuration = __nested_webpack_require_1615962__(315);

var _RSTTraversal = __nested_webpack_require_1615962__(156);

var _getAdapter = __nested_webpack_require_1615962__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /* eslint no-use-before-define: 0 */


var ITERATOR_SYMBOL = exports.ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;

function getAdapter() {
  var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  console.warn('getAdapter from Utils is deprecated; please use ./getAdapter instead');
  return (0, _getAdapter2['default'])(options);
}

function validateMountOptions(attachTo, hydrateIn) {
  if (attachTo && hydrateIn && attachTo !== hydrateIn) {
    throw new TypeError('If both the `attachTo` and `hydrateIn` options are provided, they must be === (for backwards compatibility)');
  }
}

function makeOptions(options) {
  var _get = (0, _configuration.get)(),
      configAttachTo = _get.attachTo,
      configHydrateIn = _get.hydrateIn,
      config = _objectWithoutProperties(_get, ['attachTo', 'hydrateIn']);

  validateMountOptions(configAttachTo, configHydrateIn);

  var attachTo = options.attachTo,
      hydrateIn = options.hydrateIn;

  validateMountOptions(attachTo, hydrateIn);

  // neither present: both undefined
  // only attachTo present: attachTo set, hydrateIn undefined
  // only hydrateIn present: both set to hydrateIn
  // both present (and ===, per above): both set to hydrateIn
  var finalAttachTo = hydrateIn || configHydrateIn || configAttachTo || attachTo || undefined;
  var finalHydrateIn = hydrateIn || configHydrateIn || undefined;
  var mountTargets = (0, _object2['default'])({}, finalAttachTo && { attachTo: finalAttachTo }, finalHydrateIn && { hydrateIn: finalHydrateIn });

  return (0, _object2['default'])({}, config, options, mountTargets);
}

function isCustomComponentElement(inst, adapter) {
  if (adapter.isCustomComponentElement) {
    return !!adapter.isCustomComponentElement(inst);
  }
  return !!inst && adapter.isValidElement(inst) && typeof inst.type === 'function';
}

function propsOfNode(node) {
  return (0, _object4['default'])(node && node.props || {}).filter(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        value = _ref2[1];

    return typeof value !== 'undefined';
  }).reduce(function (acc, _ref3) {
    var _ref4 = _slicedToArray(_ref3, 2),
        key = _ref4[0],
        value = _ref4[1];

    return (0, _object2['default'])(acc, _defineProperty({}, key, value));
  }, {});
}

function typeOfNode(node) {
  return node ? node.type : null;
}

function nodeHasType(node, type) {
  if (!type || !node) return false;

  var adapter = (0, _getAdapter2['default'])();
  if (adapter.displayNameOfNode) {
    var displayName = adapter.displayNameOfNode(node);
    return displayName === type;
  }

  if (!node.type) return false;
  if (typeof node.type === 'string') return node.type === type;
  return (typeof node.type === 'function' ? (0, _functionPrototype2['default'])(node.type) === type : node.type.name === type) || node.type.displayName === type;
}

function internalChildrenCompare(a, b, lenComp, isLoose) {
  var nodeCompare = isLoose ? nodeMatches : nodeEqual;

  if (a === b) return true;
  if (!Array.isArray(a) && !Array.isArray(b)) {
    return nodeCompare(a, b, lenComp);
  }
  var flatA = (0, _arrayPrototype2['default'])(a, Infinity);
  var flatB = (0, _arrayPrototype2['default'])(b, Infinity);
  if (flatA.length !== flatB.length) return false;
  if (flatA.length === 0 && flatB.length === 0) return true;
  for (var i = 0; i < flatA.length; i += 1) {
    if (!nodeCompare(flatA[i], flatB[i], lenComp)) return false;
  }
  return true;
}

function childrenMatch(a, b, lenComp) {
  return internalChildrenCompare(a, b, lenComp, true);
}

function childrenEqual(a, b, lenComp) {
  return internalChildrenCompare(a, b, lenComp, false);
}

function removeNullaryReducer(acc, _ref5) {
  var _ref6 = _slicedToArray(_ref5, 2),
      key = _ref6[0],
      value = _ref6[1];

  var addition = value == null ? {} : _defineProperty({}, key, value);
  return (0, _object2['default'])({}, acc, addition);
}

function internalNodeCompare(a, b, lenComp, isLoose) {
  if (a === b) return true;
  if (!a || !b) return false;
  if (a.type !== b.type) return false;

  var left = propsOfNode(a);
  var right = propsOfNode(b);
  if (isLoose) {
    left = (0, _object4['default'])(left).reduce(removeNullaryReducer, {});
    right = (0, _object4['default'])(right).reduce(removeNullaryReducer, {});
  }

  var leftKeys = Object.keys(left);
  for (var i = 0; i < leftKeys.length; i += 1) {
    var prop = leftKeys[i];
    // we will check children later
    if (prop === 'children') {
      // continue;
    } else if (!(prop in right)) {
      return false;
    } else if (right[prop] === left[prop]) {
      // continue;
    } else if (_typeof(right[prop]) === _typeof(left[prop]) && _typeof(left[prop]) === 'object') {
      if (!(0, _lodash2['default'])(left[prop], right[prop])) return false;
    } else {
      return false;
    }
  }

  var leftHasChildren = 'children' in left;
  var rightHasChildren = 'children' in right;
  var childCompare = isLoose ? childrenMatch : childrenEqual;
  if (leftHasChildren || rightHasChildren) {
    if (!childCompare(childrenToSimplifiedArray(left.children, isLoose), childrenToSimplifiedArray(right.children, isLoose), lenComp)) {
      return false;
    }
  }

  if (!isTextualNode(a)) {
    var rightKeys = Object.keys(right);
    return lenComp(leftKeys.length - leftHasChildren, rightKeys.length - rightHasChildren);
  }

  return false;
}

function nodeMatches(a, b) {
  var lenComp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _objectIs2['default'];

  return internalNodeCompare(a, b, lenComp, true);
}

function nodeEqual(a, b) {
  var lenComp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _objectIs2['default'];

  return internalNodeCompare(a, b, lenComp, false);
}

function containsChildrenSubArray(match, node, subArray) {
  var children = (0, _RSTTraversal.childrenOfNode)(node);
  var checker = function checker(_, i) {
    return arraysEqual(match, children.slice(i, i + subArray.length), subArray);
  };
  return children.some(checker);
}

function arraysEqual(match, left, right) {
  return left.length === right.length && left.every(function (el, i) {
    return match(el, right[i]);
  });
}

function childrenToArray(children) {
  var result = [];

  var push = function push(el) {
    if (el === null || el === false || typeof el === 'undefined') return;
    result.push(el);
  };

  if (Array.isArray(children)) {
    children.forEach(push);
  } else {
    push(children);
  }
  return result;
}

function childrenToSimplifiedArray(nodeChildren) {
  var isLoose = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

  var childrenArray = childrenToArray(nodeChildren);
  var simplifiedArray = [];

  for (var i = 0; i < childrenArray.length; i += 1) {
    var child = childrenArray[i];
    var previousChild = simplifiedArray.pop();

    if (typeof previousChild === 'undefined') {
      simplifiedArray.push(child);
    } else if (isTextualNode(child) && isTextualNode(previousChild)) {
      simplifiedArray.push(previousChild + child);
    } else {
      simplifiedArray.push(previousChild);
      simplifiedArray.push(child);
    }
  }

  if (isLoose) {
    return simplifiedArray.map(function (x) {
      return typeof x === 'string' ? (0, _stringPrototype2['default'])(x) : x;
    });
  }

  return simplifiedArray;
}

function isTextualNode(node) {
  return typeof node === 'string' || typeof node === 'number';
}

function isReactElementAlike(arg, adapter) {
  return adapter.isValidElement(arg) || isTextualNode(arg) || Array.isArray(arg);
}

// TODO(lmr): can we get rid of this outside of the adapter?
function withSetStateAllowed(fn) {
  // NOTE(lmr):
  // this is currently here to circumvent a React bug where `setState()` is
  // not allowed without global being defined.
  var cleanup = false;
  if (typeof global.document === 'undefined') {
    cleanup = true;
    global.document = {};
  }
  fn();
  if (cleanup) {
    // This works around a bug in node/jest in that developers aren't able to
    // delete things from global when running in a node vm.
    global.document = undefined;
    delete global.document;
  }
}

function AND(fns) {
  var fnsReversed = fns.slice().reverse();
  return function (x) {
    return fnsReversed.every(function (fn) {
      return fn(x);
    });
  };
}

function displayNameOfNode(node) {
  if (!node) return null;

  var type = node.type;


  if (!type) return null;

  return type.displayName || (typeof type === 'function' ? (0, _functionPrototype2['default'])(type) : type.name || type);
}

function sym(s) {
  return typeof Symbol === 'function' ? Symbol['for']('enzyme.' + String(s)) : s;
}

function privateSet(obj, prop, value) {
  Object.defineProperty(obj, prop, {
    value: value,
    enumerable: false,
    writable: true
  });
}

function cloneElement(adapter, el, props) {
  return adapter.createElement(el.type, (0, _object2['default'])({}, el.props, props));
}

function spyMethod(instance, methodName) {
  var lastReturnValue = void 0;
  var originalMethod = instance[methodName];
  var hasOwn = (0, _has2['default'])(instance, methodName);
  var descriptor = void 0;
  if (hasOwn) {
    descriptor = Object.getOwnPropertyDescriptor(instance, methodName);
  }
  Object.defineProperty(instance, methodName, {
    configurable: true,
    enumerable: !descriptor || !!descriptor.enumerable,
    value: function () {
      function value() {
        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        var result = originalMethod.apply(this, args);
        lastReturnValue = result;
        return result;
      }

      return value;
    }()
  });
  return {
    restore: function () {
      function restore() {
        if (hasOwn) {
          if (descriptor) {
            Object.defineProperty(instance, methodName, descriptor);
          } else {
            /* eslint-disable no-param-reassign */
            instance[methodName] = originalMethod;
            /* eslint-enable no-param-reassign */
          }
        } else {
          /* eslint-disable no-param-reassign */
          delete instance[methodName];
          /* eslint-enable no-param-reassign */
        }
      }

      return restore;
    }(),
    getLastReturnValue: function () {
      function getLastReturnValue() {
        return lastReturnValue;
      }

      return getLastReturnValue;
    }()
  };
}

// adapted from https://github.com/facebook/react/blob/144328fe81719e916b946e22660479e31561bb0b/packages/shared/shallowEqual.js#L36-L68
function shallowEqual(objA, objB) {
  if ((0, _objectIs2['default'])(objA, objB)) {
    return true;
  }

  if (!objA || !objB || (typeof objA === 'undefined' ? 'undefined' : _typeof(objA)) !== 'object' || (typeof objB === 'undefined' ? 'undefined' : _typeof(objB)) !== 'object') {
    return false;
  }

  var keysA = Object.keys(objA);
  var keysB = Object.keys(objB);

  if (keysA.length !== keysB.length) {
    return false;
  }

  keysA.sort();
  keysB.sort();

  // Test for A's keys different from B.
  for (var i = 0; i < keysA.length; i += 1) {
    if (!(0, _has2['default'])(objB, keysA[i]) || !(0, _objectIs2['default'])(objA[keysA[i]], objB[keysA[i]])) {
      return false;
    }
  }

  return true;
}

function isEmptyValue(renderedValue) {
  return renderedValue === null || renderedValue === false;
}

function renderedDive(nodes) {
  if (isEmptyValue(nodes)) {
    return true;
  }

  return [].concat(nodes).every(function (n) {
    if (n) {
      var rendered = n.rendered;

      return isEmptyValue(rendered) || renderedDive(rendered);
    }

    return isEmptyValue(n);
  });
}
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_1615962__(27)))

/***/ }),
/* 314 */
/***/ (function(module, exports, __nested_webpack_require_1631311__) {

"use strict";


var define = __nested_webpack_require_1631311__(52);
var bind = __nested_webpack_require_1631311__(53);

var implementation = __nested_webpack_require_1631311__(506);
var getPolyfill = __nested_webpack_require_1631311__(508);
var shim = __nested_webpack_require_1631311__(1060);

var bound = bind.call(Function.call, implementation);

define(bound, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = bound;


/***/ }),
/* 315 */
/***/ (function(module, exports, __nested_webpack_require_1631783__) {

"use strict";


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

var _object = __nested_webpack_require_1631783__(122);

var _object2 = _interopRequireDefault(_object);

var _validateAdapter = __nested_webpack_require_1631783__(511);

var _validateAdapter2 = _interopRequireDefault(_validateAdapter);

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

var configuration = {};

function get() {
  return (0, _object2['default'])({}, configuration);
}

function merge(extra) {
  if (extra.adapter) {
    (0, _validateAdapter2['default'])(extra.adapter);
  }
  (0, _object2['default'])(configuration, extra);
}

function reset() {
  var replacementConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  configuration = {};
  merge(replacementConfig);
}

/***/ }),
/* 316 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_1632753__) {

"use strict";
__nested_webpack_require_1632753__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-axis/src/array.js
var slice = Array.prototype.slice;

// CONCATENATED MODULE: ../node_modules/d3-axis/src/identity.js
/* harmony default export */ var identity = (function(x) {
  return x;
});

// CONCATENATED MODULE: ../node_modules/d3-axis/src/axis.js



var axis_top = 1,
    right = 2,
    bottom = 3,
    left = 4,
    epsilon = 1e-6;

function translateX(x) {
  return "translate(" + (x + 0.5) + ",0)";
}

function translateY(y) {
  return "translate(0," + (y + 0.5) + ")";
}

function number(scale) {
  return function(d) {
    return +scale(d);
  };
}

function center(scale) {
  var offset = Math.max(0, scale.bandwidth() - 1) / 2; // Adjust for 0.5px offset.
  if (scale.round()) offset = Math.round(offset);
  return function(d) {
    return +scale(d) + offset;
  };
}

function entering() {
  return !this.__axis;
}

function axis_axis(orient, scale) {
  var tickArguments = [],
      tickValues = null,
      tickFormat = null,
      tickSizeInner = 6,
      tickSizeOuter = 6,
      tickPadding = 3,
      k = orient === axis_top || orient === left ? -1 : 1,
      x = orient === left || orient === right ? "x" : "y",
      transform = orient === axis_top || orient === bottom ? translateX : translateY;

  function axis(context) {
    var values = tickValues == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : tickValues,
        format = tickFormat == null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity) : tickFormat,
        spacing = Math.max(tickSizeInner, 0) + tickPadding,
        range = scale.range(),
        range0 = +range[0] + 0.5,
        range1 = +range[range.length - 1] + 0.5,
        position = (scale.bandwidth ? center : number)(scale.copy()),
        selection = context.selection ? context.selection() : context,
        path = selection.selectAll(".domain").data([null]),
        tick = selection.selectAll(".tick").data(values, scale).order(),
        tickExit = tick.exit(),
        tickEnter = tick.enter().append("g").attr("class", "tick"),
        line = tick.select("line"),
        text = tick.select("text");

    path = path.merge(path.enter().insert("path", ".tick")
        .attr("class", "domain")
        .attr("stroke", "currentColor"));

    tick = tick.merge(tickEnter);

    line = line.merge(tickEnter.append("line")
        .attr("stroke", "currentColor")
        .attr(x + "2", k * tickSizeInner));

    text = text.merge(tickEnter.append("text")
        .attr("fill", "currentColor")
        .attr(x, k * spacing)
        .attr("dy", orient === axis_top ? "0em" : orient === bottom ? "0.71em" : "0.32em"));

    if (context !== selection) {
      path = path.transition(context);
      tick = tick.transition(context);
      line = line.transition(context);
      text = text.transition(context);

      tickExit = tickExit.transition(context)
          .attr("opacity", epsilon)
          .attr("transform", function(d) { return isFinite(d = position(d)) ? transform(d) : this.getAttribute("transform"); });

      tickEnter
          .attr("opacity", epsilon)
          .attr("transform", function(d) { var p = this.parentNode.__axis; return transform(p && isFinite(p = p(d)) ? p : position(d)); });
    }

    tickExit.remove();

    path
        .attr("d", orient === left || orient == right
            ? (tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H0.5V" + range1 + "H" + k * tickSizeOuter : "M0.5," + range0 + "V" + range1)
            : (tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V0.5H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + ",0.5H" + range1));

    tick
        .attr("opacity", 1)
        .attr("transform", function(d) { return transform(position(d)); });

    line
        .attr(x + "2", k * tickSizeInner);

    text
        .attr(x, k * spacing)
        .text(format);

    selection.filter(entering)
        .attr("fill", "none")
        .attr("font-size", 10)
        .attr("font-family", "sans-serif")
        .attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");

    selection
        .each(function() { this.__axis = position; });
  }

  axis.scale = function(_) {
    return arguments.length ? (scale = _, axis) : scale;
  };

  axis.ticks = function() {
    return tickArguments = slice.call(arguments), axis;
  };

  axis.tickArguments = function(_) {
    return arguments.length ? (tickArguments = _ == null ? [] : slice.call(_), axis) : tickArguments.slice();
  };

  axis.tickValues = function(_) {
    return arguments.length ? (tickValues = _ == null ? null : slice.call(_), axis) : tickValues && tickValues.slice();
  };

  axis.tickFormat = function(_) {
    return arguments.length ? (tickFormat = _, axis) : tickFormat;
  };

  axis.tickSize = function(_) {
    return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis) : tickSizeInner;
  };

  axis.tickSizeInner = function(_) {
    return arguments.length ? (tickSizeInner = +_, axis) : tickSizeInner;
  };

  axis.tickSizeOuter = function(_) {
    return arguments.length ? (tickSizeOuter = +_, axis) : tickSizeOuter;
  };

  axis.tickPadding = function(_) {
    return arguments.length ? (tickPadding = +_, axis) : tickPadding;
  };

  return axis;
}

function axisTop(scale) {
  return axis_axis(axis_top, scale);
}

function axisRight(scale) {
  return axis_axis(right, scale);
}

function axisBottom(scale) {
  return axis_axis(bottom, scale);
}

function axisLeft(scale) {
  return axis_axis(left, scale);
}

// CONCATENATED MODULE: ../node_modules/d3-axis/src/index.js
/* concated harmony reexport axisTop */__nested_webpack_require_1632753__.d(__webpack_exports__, "axisTop", function() { return axisTop; });
/* concated harmony reexport axisRight */__nested_webpack_require_1632753__.d(__webpack_exports__, "axisRight", function() { return axisRight; });
/* concated harmony reexport axisBottom */__nested_webpack_require_1632753__.d(__webpack_exports__, "axisBottom", function() { return axisBottom; });
/* concated harmony reexport axisLeft */__nested_webpack_require_1632753__.d(__webpack_exports__, "axisLeft", function() { return axisLeft; });



/***/ }),
/* 317 */
/***/ (function(module, exports, __nested_webpack_require_1639030__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.viewer = exports.version = exports.getTrackObjectFromHGC = exports.mountHGComponent = exports.waitForTransitionsFinished = exports.waitForTilesLoaded = exports.waitForJsonComplete = exports.schema = exports.tracks = exports.trackViewer = exports.HiGlassTrackComponent = exports.HiGlassComponent = exports.ChromosomeInfo = undefined;

var _ChromosomeInfo = __nested_webpack_require_1639030__(73);

Object.defineProperty(exports, 'ChromosomeInfo', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_ChromosomeInfo)['default'];
    }

    return get;
  }()
});

var _HiGlassComponent = __nested_webpack_require_1639030__(232);

Object.defineProperty(exports, 'HiGlassComponent', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_HiGlassComponent)['default'];
    }

    return get;
  }()
});

var _HiGlassTrackComponent = __nested_webpack_require_1639030__(1086);

Object.defineProperty(exports, 'HiGlassTrackComponent', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_HiGlassTrackComponent)['default'];
    }

    return get;
  }()
});
Object.defineProperty(exports, 'trackViewer', {
  enumerable: true,
  get: function () {
    function get() {
      return _HiGlassTrackComponent.trackViewer;
    }

    return get;
  }()
});

var _schema = __nested_webpack_require_1639030__(271);

Object.defineProperty(exports, 'schema', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_schema)['default'];
    }

    return get;
  }()
});

var _utils = __nested_webpack_require_1639030__(10);

Object.defineProperty(exports, 'waitForJsonComplete', {
  enumerable: true,
  get: function () {
    function get() {
      return _utils.waitForJsonComplete;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'waitForTilesLoaded', {
  enumerable: true,
  get: function () {
    function get() {
      return _utils.waitForTilesLoaded;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'waitForTransitionsFinished', {
  enumerable: true,
  get: function () {
    function get() {
      return _utils.waitForTransitionsFinished;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'mountHGComponent', {
  enumerable: true,
  get: function () {
    function get() {
      return _utils.mountHGComponent;
    }

    return get;
  }()
});
Object.defineProperty(exports, 'getTrackObjectFromHGC', {
  enumerable: true,
  get: function () {
    function get() {
      return _utils.getTrackObjectFromHGC;
    }

    return get;
  }()
});

var _react = __nested_webpack_require_1639030__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_1639030__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _HiGlassComponent2 = _interopRequireDefault(_HiGlassComponent);

var _SVGTrack = __nested_webpack_require_1639030__(80);

var _SVGTrack2 = _interopRequireDefault(_SVGTrack);

var _TiledPixiTrack = __nested_webpack_require_1639030__(79);

var _TiledPixiTrack2 = _interopRequireDefault(_TiledPixiTrack);

var _HorizontalGeneAnnotationsTrack = __nested_webpack_require_1639030__(260);

var _HorizontalGeneAnnotationsTrack2 = _interopRequireDefault(_HorizontalGeneAnnotationsTrack);

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

var tracks = exports.tracks = {
  SVGTrack: _SVGTrack2['default'],
  TiledPixiTrack: _TiledPixiTrack2['default'],
  HorizontalGeneAnnotationsTrack: _HorizontalGeneAnnotationsTrack2['default']
};

var version = exports.version = "1.11.9";

var launch = function launch(element, config, options) {
  /**
   * The instance's public API will be passed into the callback
   *
   * @param {DOMElement} element The element to attach the HiGlass component to
   *  E.g. ``document.getElementById('two-heatmaps')``
   *
   * @param {Object} config The viewconfig to load. If this parameter is a string
   * it will be interpreted as a url from which to retrieve the viewconf.
   *
   * @param {Object} options Options that affect how the component is drawn and
   * and behaves.
   *
   * @return  {Object} The instance's public API
   */
  var ref = _react2['default'].createRef();
  _reactDom2['default'].render(_react2['default'].createElement(_HiGlassComponent2['default'], { ref: ref, options: options || {}, viewConfig: config }), element);
  return ref.current;
};

/**
 * Create a HiGlass component.
 *
 * In addition to the parameters below, a number of extra options can be passed
 * using the **options** parameter:
 *
 * * **authToken** *(string)* - An auth token to be included with every tile request
  (e.g. ``JWT xyz``)
 * * **bounded** *(bool)* - A boolean specifying whether the component should be sized
  to fit within the enclosing div [default=false]. If it is false, then the component
  will grow as needed to fit the tracks within it.
 * * **editable** *(bool)* - Can the layout be changed? If false, the view headers will
  be hidden. This can also be specified in the viewconfig using the ``editable`` option.
  The value passed here overrides the value in the viewconf. [default=true]
 * * **defaultTrackOptions** *(dict)* - Specify a set of default options that will be used for
 *  newly added tracks. These can be broken down into two types: `all` - affecting all
 *  all track types and `trackSpecific` which will affect only some track types. See the
 *  example below for a concrete demonstration.
 * @param  {Object}  element  DOM element the HiGlass component should be
 *   attached to.
 * @param  {Object|String}  viewConfig  The viewconfig to load. If this parameter is a string
 * it will be interpreted as a url from which to retrieve the viewconf. If it is a dictionary
 * it will be loaded as is.
 * @param  {Object}  options  Dictionary of public options. See the description above for a list
   of available values.
 * @example
 *
 * const hgv = hglib.viewer(
 *  document.getElementById('development-demo'),
 *  testViewConfig,
 *  { bounded: true,
 *   defaultTrackOptions: {
 *     all: {
 *       showTooltip: true,
 *     },
 *     trackSpecific: {
 *      'heatmap': {
 *        showTooltip: false,
 *      }
 *     }
 *   }
 * });
 *
 * @return  {Object}  Newly created HiGlass component.
 */
var viewer = exports.viewer = function viewer(element, viewConfig, options) {
  /**
   * Available options:
   *
   *  bounded: [true/false]
   *      Fit the container to the bounds of the element
   */
  var hg = launch(element, viewConfig, options);
  return hg.api;
};

/***/ }),
/* 318 */
/***/ (function(module, exports, __nested_webpack_require_1645707__) {

// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __nested_webpack_require_1645707__(39);
var aFunction = __nested_webpack_require_1645707__(92);
var SPECIES = __nested_webpack_require_1645707__(21)('species');
module.exports = function (O, D) {
  var C = anObject(O).constructor;
  var S;
  return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};


/***/ }),
/* 319 */
/***/ (function(module, exports, __nested_webpack_require_1646139__) {

var ctx = __nested_webpack_require_1646139__(49);
var invoke = __nested_webpack_require_1646139__(524);
var html = __nested_webpack_require_1646139__(163);
var cel = __nested_webpack_require_1646139__(108);
var global = __nested_webpack_require_1646139__(23);
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
  var id = +this;
  // eslint-disable-next-line no-prototype-builtins
  if (queue.hasOwnProperty(id)) {
    var fn = queue[id];
    delete queue[id];
    fn();
  }
};
var listener = function (event) {
  run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
  setTask = function setImmediate(fn) {
    var args = [];
    var i = 1;
    while (arguments.length > i) args.push(arguments[i++]);
    queue[++counter] = function () {
      // eslint-disable-next-line no-new-func
      invoke(typeof fn == 'function' ? fn : Function(fn), args);
    };
    defer(counter);
    return counter;
  };
  clearTask = function clearImmediate(id) {
    delete queue[id];
  };
  // Node.js 0.8-
  if (__nested_webpack_require_1646139__(74)(process) == 'process') {
    defer = function (id) {
      process.nextTick(ctx(run, id, 1));
    };
  // Sphere (JS game engine) Dispatch API
  } else if (Dispatch && Dispatch.now) {
    defer = function (id) {
      Dispatch.now(ctx(run, id, 1));
    };
  // Browsers with MessageChannel, includes WebWorkers
  } else if (MessageChannel) {
    channel = new MessageChannel();
    port = channel.port2;
    channel.port1.onmessage = listener;
    defer = ctx(port.postMessage, port, 1);
  // Browsers with postMessage, skip WebWorkers
  // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
  } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
    defer = function (id) {
      global.postMessage(id + '', '*');
    };
    global.addEventListener('message', listener, false);
  // IE8-
  } else if (ONREADYSTATECHANGE in cel('script')) {
    defer = function (id) {
      html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
        html.removeChild(this);
        run.call(id);
      };
    };
  // Rest old browsers
  } else {
    defer = function (id) {
      setTimeout(ctx(run, id, 1), 0);
    };
  }
}
module.exports = {
  set: setTask,
  clear: clearTask
};


/***/ }),
/* 320 */
/***/ (function(module, exports) {

module.exports = function (exec) {
  try {
    return { e: false, v: exec() };
  } catch (e) {
    return { e: true, v: e };
  }
};


/***/ }),
/* 321 */
/***/ (function(module, exports, __nested_webpack_require_1648917__) {

var anObject = __nested_webpack_require_1648917__(39);
var isObject = __nested_webpack_require_1648917__(33);
var newPromiseCapability = __nested_webpack_require_1648917__(219);

module.exports = function (C, x) {
  anObject(C);
  if (isObject(x) && x.constructor === C) return x;
  var promiseCapability = newPromiseCapability.f(C);
  var resolve = promiseCapability.resolve;
  resolve(x);
  return promiseCapability.promise;
};


/***/ }),
/* 322 */
/***/ (function(module, exports, __nested_webpack_require_1649381__) {

"use strict";

var global = __nested_webpack_require_1649381__(23);
var core = __nested_webpack_require_1649381__(12);
var dP = __nested_webpack_require_1649381__(32);
var DESCRIPTORS = __nested_webpack_require_1649381__(36);
var SPECIES = __nested_webpack_require_1649381__(21)('species');

module.exports = function (KEY) {
  var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
  if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
    configurable: true,
    get: function () { return this; }
  });
};


/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Clone an event by invoking the source event's constructor and passing in
 *   the source event.
 * @param   {object}  event  Source event to be cloned.
 * @return  {object}  Cloned event
 */
var cloneEvent = function cloneEvent(event) {
  var newEvent = new event.constructor(event.type, event);
  newEvent.sourceUid = event.sourceUid;
  newEvent.forwarded = event.forwarded;

  return newEvent;
};

exports["default"] = cloneEvent;

/***/ }),
/* 324 */
/***/ (function(module, exports, __nested_webpack_require_1650507__) {

"use strict";


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

var _pixi = __nested_webpack_require_1650507__(325);

var PIXI = _interopRequireWildcard(_pixi);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

var GLOBALS = {
  PIXI: PIXI
};

exports['default'] = GLOBALS;

/***/ }),
/* 325 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE__325__;

/***/ }),
/* 326 */
/***/ (function(module, exports, __nested_webpack_require_1651195__) {

"use strict";


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

var _ = __nested_webpack_require_1651195__(10);

var dataToGenomicLoci = function dataToGenomicLoci(x0, x1, chromInfo) {
  var gX0 = (0, _.absToChr)(x0, chromInfo);
  var gX1 = (0, _.absToChr)(x1, chromInfo);

  return [gX0[0], Math.round(gX0[1]), gX1[0], Math.round(gX1[1])];
};

exports['default'] = dataToGenomicLoci;

/***/ }),
/* 327 */
/***/ (function(module, exports, __nested_webpack_require_1651661__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.THEME_DEFAULT = exports.THEME_DARK = exports.THEME_LIGHT = undefined;

var _symbol = __nested_webpack_require_1651661__(225);

var _symbol2 = _interopRequireDefault(_symbol);

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

var THEME_LIGHT = exports.THEME_LIGHT = (0, _symbol2['default'])('Light theme');

var THEME_DARK = exports.THEME_DARK = (0, _symbol2['default'])('Dark theme');

var THEME_DEFAULT = exports.THEME_DEFAULT = THEME_LIGHT;

/***/ }),
/* 328 */
/***/ (function(module, exports, __nested_webpack_require_1652306__) {

// 7.2.2 IsArray(argument)
var cof = __nested_webpack_require_1652306__(74);
module.exports = Array.isArray || function isArray(arg) {
  return cof(arg) == 'Array';
};


/***/ }),
/* 329 */
/***/ (function(module, exports, __nested_webpack_require_1652538__) {

// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __nested_webpack_require_1652538__(158);
var hiddenKeys = __nested_webpack_require_1652538__(107).concat('length', 'prototype');

exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  return $keys(O, hiddenKeys);
};


/***/ }),
/* 330 */
/***/ (function(module, exports, __nested_webpack_require_1652892__) {

var getKeys = __nested_webpack_require_1652892__(60);
var toIObject = __nested_webpack_require_1652892__(48);
var isEnum = __nested_webpack_require_1652892__(93).f;
module.exports = function (isEntries) {
  return function (it) {
    var O = toIObject(it);
    var keys = getKeys(O);
    var length = keys.length;
    var i = 0;
    var result = [];
    var key;
    while (length > i) if (isEnum.call(O, key = keys[i++])) {
      result.push(isEntries ? [key, O[key]] : O[key]);
    } return result;
  };
};


/***/ }),
/* 331 */
/***/ (function(module, exports, __nested_webpack_require_1653435__) {

module.exports = { "default": __nested_webpack_require_1653435__(564), __esModule: true };

/***/ }),
/* 332 */
/***/ (function(module, exports, __nested_webpack_require_1653589__) {

"use strict";


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

var _react = __nested_webpack_require_1653589__(1);

var _react2 = _interopRequireDefault(_react);

__nested_webpack_require_1653589__(573);

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

var Cross = function Cross() {
  return _react2['default'].createElement('div', { className: 'Cross-module_cross-3WYME' });
};

exports['default'] = Cross;

/***/ }),
/* 333 */
/***/ (function(module, exports, __nested_webpack_require_1654116__) {

"use strict";

var dP = __nested_webpack_require_1654116__(32).f;
var create = __nested_webpack_require_1654116__(110);
var redefineAll = __nested_webpack_require_1654116__(220);
var ctx = __nested_webpack_require_1654116__(49);
var anInstance = __nested_webpack_require_1654116__(218);
var forOf = __nested_webpack_require_1654116__(129);
var $iterDefine = __nested_webpack_require_1654116__(109);
var step = __nested_webpack_require_1654116__(160);
var setSpecies = __nested_webpack_require_1654116__(322);
var DESCRIPTORS = __nested_webpack_require_1654116__(36);
var fastKey = __nested_webpack_require_1654116__(226).fastKey;
var validate = __nested_webpack_require_1654116__(238);
var SIZE = DESCRIPTORS ? '_s' : 'size';

var getEntry = function (that, key) {
  // fast case
  var index = fastKey(key);
  var entry;
  if (index !== 'F') return that._i[index];
  // frozen object case
  for (entry = that._f; entry; entry = entry.n) {
    if (entry.k == key) return entry;
  }
};

module.exports = {
  getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
    var C = wrapper(function (that, iterable) {
      anInstance(that, C, NAME, '_i');
      that._t = NAME;         // collection type
      that._i = create(null); // index
      that._f = undefined;    // first entry
      that._l = undefined;    // last entry
      that[SIZE] = 0;         // size
      if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
    });
    redefineAll(C.prototype, {
      // 23.1.3.1 Map.prototype.clear()
      // 23.2.3.2 Set.prototype.clear()
      clear: function clear() {
        for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
          entry.r = true;
          if (entry.p) entry.p = entry.p.n = undefined;
          delete data[entry.i];
        }
        that._f = that._l = undefined;
        that[SIZE] = 0;
      },
      // 23.1.3.3 Map.prototype.delete(key)
      // 23.2.3.4 Set.prototype.delete(value)
      'delete': function (key) {
        var that = validate(this, NAME);
        var entry = getEntry(that, key);
        if (entry) {
          var next = entry.n;
          var prev = entry.p;
          delete that._i[entry.i];
          entry.r = true;
          if (prev) prev.n = next;
          if (next) next.p = prev;
          if (that._f == entry) that._f = next;
          if (that._l == entry) that._l = prev;
          that[SIZE]--;
        } return !!entry;
      },
      // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
      // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
      forEach: function forEach(callbackfn /* , that = undefined */) {
        validate(this, NAME);
        var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
        var entry;
        while (entry = entry ? entry.n : this._f) {
          f(entry.v, entry.k, this);
          // revert to the last existing entry
          while (entry && entry.r) entry = entry.p;
        }
      },
      // 23.1.3.7 Map.prototype.has(key)
      // 23.2.3.7 Set.prototype.has(value)
      has: function has(key) {
        return !!getEntry(validate(this, NAME), key);
      }
    });
    if (DESCRIPTORS) dP(C.prototype, 'size', {
      get: function () {
        return validate(this, NAME)[SIZE];
      }
    });
    return C;
  },
  def: function (that, key, value) {
    var entry = getEntry(that, key);
    var prev, index;
    // change existing entry
    if (entry) {
      entry.v = value;
    // create new entry
    } else {
      that._l = entry = {
        i: index = fastKey(key, true), // <- index
        k: key,                        // <- key
        v: value,                      // <- value
        p: prev = that._l,             // <- previous entry
        n: undefined,                  // <- next entry
        r: false                       // <- removed
      };
      if (!that._f) that._f = entry;
      if (prev) prev.n = entry;
      that[SIZE]++;
      // add to index
      if (index !== 'F') that._i[index] = entry;
    } return that;
  },
  getEntry: getEntry,
  setStrong: function (C, NAME, IS_MAP) {
    // add .keys, .values, .entries, [@@iterator]
    // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
    $iterDefine(C, NAME, function (iterated, kind) {
      this._t = validate(iterated, NAME); // target
      this._k = kind;                     // kind
      this._l = undefined;                // previous
    }, function () {
      var that = this;
      var kind = that._k;
      var entry = that._l;
      // revert to the last existing entry
      while (entry && entry.r) entry = entry.p;
      // get next entry
      if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
        // or finish the iteration
        that._t = undefined;
        return step(1);
      }
      // return step by kind
      if (kind == 'keys') return step(0, entry.k);
      if (kind == 'values') return step(0, entry.v);
      return step(0, [entry.k, entry.v]);
    }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);

    // add [@@species], 23.1.2.2, 23.2.2.2
    setSpecies(NAME);
  }
};


/***/ }),
/* 334 */
/***/ (function(module, exports, __nested_webpack_require_1659213__) {

"use strict";

var global = __nested_webpack_require_1659213__(23);
var $export = __nested_webpack_require_1659213__(16);
var meta = __nested_webpack_require_1659213__(226);
var fails = __nested_webpack_require_1659213__(50);
var hide = __nested_webpack_require_1659213__(43);
var redefineAll = __nested_webpack_require_1659213__(220);
var forOf = __nested_webpack_require_1659213__(129);
var anInstance = __nested_webpack_require_1659213__(218);
var isObject = __nested_webpack_require_1659213__(33);
var setToStringTag = __nested_webpack_require_1659213__(77);
var dP = __nested_webpack_require_1659213__(32).f;
var each = __nested_webpack_require_1659213__(582)(0);
var DESCRIPTORS = __nested_webpack_require_1659213__(36);

module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
  var Base = global[NAME];
  var C = Base;
  var ADDER = IS_MAP ? 'set' : 'add';
  var proto = C && C.prototype;
  var O = {};
  if (!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
    new C().entries().next();
  }))) {
    // create collection constructor
    C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
    redefineAll(C.prototype, methods);
    meta.NEED = true;
  } else {
    C = wrapper(function (target, iterable) {
      anInstance(target, C, NAME, '_c');
      target._c = new Base();
      if (iterable != undefined) forOf(iterable, IS_MAP, target[ADDER], target);
    });
    each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','), function (KEY) {
      var IS_ADDER = KEY == 'add' || KEY == 'set';
      if (KEY in proto && !(IS_WEAK && KEY == 'clear')) hide(C.prototype, KEY, function (a, b) {
        anInstance(this, C, KEY);
        if (!IS_ADDER && IS_WEAK && !isObject(a)) return KEY == 'get' ? undefined : false;
        var result = this._c[KEY](a === 0 ? 0 : a, b);
        return IS_ADDER ? this : result;
      });
    });
    IS_WEAK || dP(C.prototype, 'size', {
      get: function () {
        return this._c.size;
      }
    });
  }

  setToStringTag(C, NAME);

  O[NAME] = C;
  $export($export.G + $export.W + $export.F, O);

  if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);

  return C;
};


/***/ }),
/* 335 */
/***/ (function(module, exports, __nested_webpack_require_1661311__) {

// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __nested_webpack_require_1661311__(111);
var from = __nested_webpack_require_1661311__(586);
module.exports = function (NAME) {
  return function toJSON() {
    if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
    return from(this);
  };
};


/***/ }),
/* 336 */
/***/ (function(module, exports, __nested_webpack_require_1661701__) {

"use strict";

// https://tc39.github.io/proposal-setmap-offrom/
var $export = __nested_webpack_require_1661701__(16);

module.exports = function (COLLECTION) {
  $export($export.S, COLLECTION, { of: function of() {
    var length = arguments.length;
    var A = new Array(length);
    while (length--) A[length] = arguments[length];
    return new this(A);
  } });
};


/***/ }),
/* 337 */
/***/ (function(module, exports, __nested_webpack_require_1662134__) {

"use strict";

// https://tc39.github.io/proposal-setmap-offrom/
var $export = __nested_webpack_require_1662134__(16);
var aFunction = __nested_webpack_require_1662134__(92);
var ctx = __nested_webpack_require_1662134__(49);
var forOf = __nested_webpack_require_1662134__(129);

module.exports = function (COLLECTION) {
  $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
    var mapFn = arguments[1];
    var mapping, A, n, cb;
    aFunction(this);
    mapping = mapFn !== undefined;
    if (mapping) aFunction(mapFn);
    if (source == undefined) return new this();
    A = [];
    if (mapping) {
      n = 0;
      cb = ctx(mapFn, arguments[2], 2);
      forOf(source, false, function (nextItem) {
        A.push(cb(nextItem, n++));
      });
    } else {
      forOf(source, false, A.push, A);
    }
    return new this(A);
  } });
};


/***/ }),
/* 338 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),
/* 339 */
/***/ (function(module, exports, __nested_webpack_require_1663218__) {

"use strict";


exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_1663218__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_1663218__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lodash = __nested_webpack_require_1663218__(172);

var _lodash2 = _interopRequireDefault(_lodash);

var _classnames = __nested_webpack_require_1663218__(340);

var _classnames2 = _interopRequireDefault(_classnames);

var _utils = __nested_webpack_require_1663218__(133);

var _GridItem = __nested_webpack_require_1663218__(595);

var _GridItem2 = _interopRequireDefault(_GridItem);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// End Types

/**
 * A reactive, fluid grid layout with draggable, resizable components.
 */

// Types
var ReactGridLayout = function (_React$Component) {
  _inherits(ReactGridLayout, _React$Component);

  // TODO publish internal ReactClass displayName transform
  function ReactGridLayout(props, context) {
    _classCallCheck(this, ReactGridLayout);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));

    _initialiseProps.call(_this);

    (0, _utils.autoBindHandlers)(_this, ["onDragStart", "onDrag", "onDragStop", "onResizeStart", "onResize", "onResizeStop"]);
    return _this;
  }

  ReactGridLayout.prototype.componentDidMount = function componentDidMount() {
    this.setState({ mounted: true });
    // Possibly call back with layout on mount. This should be done after correcting the layout width
    // to ensure we don't rerender with the wrong width.
    this.onLayoutMaybeChanged(this.state.layout, this.props.layout);
  };

  ReactGridLayout.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    var newLayoutBase = void 0;
    // Legacy support for compactType
    // Allow parent to set layout directly.
    if (!(0, _lodash2.default)(nextProps.layout, this.props.layout) || nextProps.compactType !== this.props.compactType) {
      newLayoutBase = nextProps.layout;
    } else if (!(0, _utils.childrenEqual)(this.props.children, nextProps.children)) {
      // If children change, also regenerate the layout. Use our state
      // as the base in case because it may be more up to date than
      // what is in props.
      newLayoutBase = this.state.layout;
    }

    // We need to regenerate the layout.
    if (newLayoutBase) {
      var newLayout = (0, _utils.synchronizeLayoutWithChildren)(newLayoutBase, nextProps.children, nextProps.cols, this.compactType(nextProps));
      var _oldLayout = this.state.layout;
      this.setState({ layout: newLayout });
      this.onLayoutMaybeChanged(newLayout, _oldLayout);
    }
  };

  /**
   * Calculates a pixel value for the container.
   * @return {String} Container height in pixels.
   */


  ReactGridLayout.prototype.containerHeight = function containerHeight() {
    if (!this.props.autoSize) return;
    var nbRow = (0, _utils.bottom)(this.state.layout);
    var containerPaddingY = this.props.containerPadding ? this.props.containerPadding[1] : this.props.margin[1];
    return nbRow * this.props.rowHeight + (nbRow - 1) * this.props.margin[1] + containerPaddingY * 2 + "px";
  };

  ReactGridLayout.prototype.compactType = function compactType(props) {
    if (!props) props = this.props;
    return props.verticalCompact === false ? null : props.compactType;
  };

  /**
   * When dragging starts
   * @param {String} i Id of the child
   * @param {Number} x X position of the move
   * @param {Number} y Y position of the move
   * @param {Event} e The mousedown event
   * @param {Element} node The current dragging DOM element
   */


  ReactGridLayout.prototype.onDragStart = function onDragStart(i, x, y, _ref) {
    var e = _ref.e,
        node = _ref.node;
    var layout = this.state.layout;

    var l = (0, _utils.getLayoutItem)(layout, i);
    if (!l) return;

    this.setState({
      oldDragItem: (0, _utils.cloneLayoutItem)(l),
      oldLayout: this.state.layout
    });

    return this.props.onDragStart(layout, l, l, null, e, node);
  };

  /**
   * Each drag movement create a new dragelement and move the element to the dragged location
   * @param {String} i Id of the child
   * @param {Number} x X position of the move
   * @param {Number} y Y position of the move
   * @param {Event} e The mousedown event
   * @param {Element} node The current dragging DOM element
   */


  ReactGridLayout.prototype.onDrag = function onDrag(i, x, y, _ref2) {
    var e = _ref2.e,
        node = _ref2.node;
    var oldDragItem = this.state.oldDragItem;
    var layout = this.state.layout;
    var cols = this.props.cols;

    var l = (0, _utils.getLayoutItem)(layout, i);
    if (!l) return;

    // Create placeholder (display only)
    var placeholder = {
      w: l.w,
      h: l.h,
      x: l.x,
      y: l.y,
      placeholder: true,
      i: i
    };

    // Move the element to the dragged location.
    var isUserAction = true;
    layout = (0, _utils.moveElement)(layout, l, x, y, isUserAction, this.props.preventCollision, this.compactType(), cols);

    this.props.onDrag(layout, oldDragItem, l, placeholder, e, node);

    this.setState({
      layout: (0, _utils.compact)(layout, this.compactType(), cols),
      activeDrag: placeholder
    });
  };

  /**
   * When dragging stops, figure out which position the element is closest to and update its x and y.
   * @param  {String} i Index of the child.
   * @param {Number} x X position of the move
   * @param {Number} y Y position of the move
   * @param {Event} e The mousedown event
   * @param {Element} node The current dragging DOM element
   */


  ReactGridLayout.prototype.onDragStop = function onDragStop(i, x, y, _ref3) {
    var e = _ref3.e,
        node = _ref3.node;
    var oldDragItem = this.state.oldDragItem;
    var layout = this.state.layout;
    var _props = this.props,
        cols = _props.cols,
        preventCollision = _props.preventCollision;

    var l = (0, _utils.getLayoutItem)(layout, i);
    if (!l) return;

    // Move the element here
    var isUserAction = true;
    layout = (0, _utils.moveElement)(layout, l, x, y, isUserAction, preventCollision, this.compactType(), cols);

    this.props.onDragStop(layout, oldDragItem, l, null, e, node);

    // Set state
    var newLayout = (0, _utils.compact)(layout, this.compactType(), cols);
    var oldLayout = this.state.oldLayout;

    this.setState({
      activeDrag: null,
      layout: newLayout,
      oldDragItem: null,
      oldLayout: null
    });

    this.onLayoutMaybeChanged(newLayout, oldLayout);
  };

  ReactGridLayout.prototype.onLayoutMaybeChanged = function onLayoutMaybeChanged(newLayout, oldLayout) {
    if (!oldLayout) oldLayout = this.state.layout;
    if (!(0, _lodash2.default)(oldLayout, newLayout)) {
      this.props.onLayoutChange(newLayout);
    }
  };

  ReactGridLayout.prototype.onResizeStart = function onResizeStart(i, w, h, _ref4) {
    var e = _ref4.e,
        node = _ref4.node;
    var layout = this.state.layout;

    var l = (0, _utils.getLayoutItem)(layout, i);
    if (!l) return;

    this.setState({
      oldResizeItem: (0, _utils.cloneLayoutItem)(l),
      oldLayout: this.state.layout
    });

    this.props.onResizeStart(layout, l, l, null, e, node);
  };

  ReactGridLayout.prototype.onResize = function onResize(i, w, h, _ref5) {
    var e = _ref5.e,
        node = _ref5.node;
    var _state = this.state,
        layout = _state.layout,
        oldResizeItem = _state.oldResizeItem;
    var _props2 = this.props,
        cols = _props2.cols,
        preventCollision = _props2.preventCollision;

    var l = (0, _utils.getLayoutItem)(layout, i);
    if (!l) return;

    // Something like quad tree should be used
    // to find collisions faster
    var hasCollisions = void 0;
    if (preventCollision) {
      var collisions = (0, _utils.getAllCollisions)(layout, _extends({}, l, { w: w, h: h })).filter(function (layoutItem) {
        return layoutItem.i !== l.i;
      });
      hasCollisions = collisions.length > 0;

      // If we're colliding, we need adjust the placeholder.
      if (hasCollisions) {
        // adjust w && h to maximum allowed space
        var leastX = Infinity,
            leastY = Infinity;
        collisions.forEach(function (layoutItem) {
          if (layoutItem.x > l.x) leastX = Math.min(leastX, layoutItem.x);
          if (layoutItem.y > l.y) leastY = Math.min(leastY, layoutItem.y);
        });

        if (Number.isFinite(leastX)) l.w = leastX - l.x;
        if (Number.isFinite(leastY)) l.h = leastY - l.y;
      }
    }

    if (!hasCollisions) {
      // Set new width and height.
      l.w = w;
      l.h = h;
    }

    // Create placeholder element (display only)
    var placeholder = {
      w: l.w,
      h: l.h,
      x: l.x,
      y: l.y,
      static: true,
      i: i
    };

    this.props.onResize(layout, oldResizeItem, l, placeholder, e, node);

    // Re-compact the layout and set the drag placeholder.
    this.setState({
      layout: (0, _utils.compact)(layout, this.compactType(), cols),
      activeDrag: placeholder
    });
  };

  ReactGridLayout.prototype.onResizeStop = function onResizeStop(i, w, h, _ref6) {
    var e = _ref6.e,
        node = _ref6.node;
    var _state2 = this.state,
        layout = _state2.layout,
        oldResizeItem = _state2.oldResizeItem;
    var cols = this.props.cols;

    var l = (0, _utils.getLayoutItem)(layout, i);

    this.props.onResizeStop(layout, oldResizeItem, l, null, e, node);

    // Set state
    var newLayout = (0, _utils.compact)(layout, this.compactType(), cols);
    var oldLayout = this.state.oldLayout;

    this.setState({
      activeDrag: null,
      layout: newLayout,
      oldResizeItem: null,
      oldLayout: null
    });

    this.onLayoutMaybeChanged(newLayout, oldLayout);
  };

  /**
   * Create a placeholder object.
   * @return {Element} Placeholder div.
   */


  ReactGridLayout.prototype.placeholder = function placeholder() {
    var activeDrag = this.state.activeDrag;

    if (!activeDrag) return null;
    var _props3 = this.props,
        width = _props3.width,
        cols = _props3.cols,
        margin = _props3.margin,
        containerPadding = _props3.containerPadding,
        rowHeight = _props3.rowHeight,
        maxRows = _props3.maxRows,
        useCSSTransforms = _props3.useCSSTransforms;

    // {...this.state.activeDrag} is pretty slow, actually

    return _react2.default.createElement(
      _GridItem2.default,
      {
        w: activeDrag.w,
        h: activeDrag.h,
        x: activeDrag.x,
        y: activeDrag.y,
        i: activeDrag.i,
        className: "react-grid-placeholder",
        containerWidth: width,
        cols: cols,
        margin: margin,
        containerPadding: containerPadding || margin,
        maxRows: maxRows,
        rowHeight: rowHeight,
        isDraggable: false,
        isResizable: false,
        useCSSTransforms: useCSSTransforms
      },
      _react2.default.createElement("div", null)
    );
  };

  /**
   * Given a grid item, set its style attributes & surround in a <Draggable>.
   * @param  {Element} child React element.
   * @return {Element}       Element wrapped in draggable and properly placed.
   */


  ReactGridLayout.prototype.processGridItem = function processGridItem(child) {
    if (!child || !child.key) return;
    var l = (0, _utils.getLayoutItem)(this.state.layout, String(child.key));
    if (!l) return null;
    var _props4 = this.props,
        width = _props4.width,
        cols = _props4.cols,
        margin = _props4.margin,
        containerPadding = _props4.containerPadding,
        rowHeight = _props4.rowHeight,
        maxRows = _props4.maxRows,
        isDraggable = _props4.isDraggable,
        isResizable = _props4.isResizable,
        useCSSTransforms = _props4.useCSSTransforms,
        draggableCancel = _props4.draggableCancel,
        draggableHandle = _props4.draggableHandle;
    var mounted = this.state.mounted;

    // Parse 'static'. Any properties defined directly on the grid item will take precedence.

    var draggable = Boolean(!l.static && isDraggable && (l.isDraggable || l.isDraggable == null));
    var resizable = Boolean(!l.static && isResizable && (l.isResizable || l.isResizable == null));

    return _react2.default.createElement(
      _GridItem2.default,
      {
        containerWidth: width,
        cols: cols,
        margin: margin,
        containerPadding: containerPadding || margin,
        maxRows: maxRows,
        rowHeight: rowHeight,
        cancel: draggableCancel,
        handle: draggableHandle,
        onDragStop: this.onDragStop,
        onDragStart: this.onDragStart,
        onDrag: this.onDrag,
        onResizeStart: this.onResizeStart,
        onResize: this.onResize,
        onResizeStop: this.onResizeStop,
        isDraggable: draggable,
        isResizable: resizable,
        useCSSTransforms: useCSSTransforms && mounted,
        usePercentages: !mounted,
        w: l.w,
        h: l.h,
        x: l.x,
        y: l.y,
        i: l.i,
        minH: l.minH,
        minW: l.minW,
        maxH: l.maxH,
        maxW: l.maxW,
        "static": l.static
      },
      child
    );
  };

  ReactGridLayout.prototype.render = function render() {
    var _this2 = this;

    var _props5 = this.props,
        className = _props5.className,
        style = _props5.style;


    var mergedClassName = (0, _classnames2.default)("react-grid-layout", className);
    var mergedStyle = _extends({
      height: this.containerHeight()
    }, style);

    return _react2.default.createElement(
      "div",
      { className: mergedClassName, style: mergedStyle },
      _react2.default.Children.map(this.props.children, function (child) {
        return _this2.processGridItem(child);
      }),
      this.placeholder()
    );
  };

  return ReactGridLayout;
}(_react2.default.Component);

ReactGridLayout.displayName = "ReactGridLayout";
ReactGridLayout.propTypes = {
  //
  // Basic props
  //
  className: _propTypes2.default.string,
  style: _propTypes2.default.object,

  // This can be set explicitly. If it is not set, it will automatically
  // be set to the container width. Note that resizes will *not* cause this to adjust.
  // If you need that behavior, use WidthProvider.
  width: _propTypes2.default.number,

  // If true, the container height swells and contracts to fit contents
  autoSize: _propTypes2.default.bool,
  // # of cols.
  cols: _propTypes2.default.number,

  // A selector that will not be draggable.
  draggableCancel: _propTypes2.default.string,
  // A selector for the draggable handler
  draggableHandle: _propTypes2.default.string,

  // Deprecated
  verticalCompact: function verticalCompact(props) {
    if (props.verticalCompact === false && "production" !== "production") {}
  },
  // Choose vertical or hotizontal compaction
  compactType: _propTypes2.default.oneOf(["vertical", "horizontal"]),

  // layout is an array of object with the format:
  // {x: Number, y: Number, w: Number, h: Number, i: String}
  layout: function layout(props) {
    var layout = props.layout;
    // I hope you're setting the data-grid property on the grid items
    if (layout === undefined) return;
    (0, _utils.validateLayout)(layout, "layout");
  },

  //
  // Grid Dimensions
  //

  // Margin between items [x, y] in px
  margin: _propTypes2.default.arrayOf(_propTypes2.default.number),
  // Padding inside the container [x, y] in px
  containerPadding: _propTypes2.default.arrayOf(_propTypes2.default.number),
  // Rows have a static height, but you can change this based on breakpoints if you like
  rowHeight: _propTypes2.default.number,
  // Default Infinity, but you can specify a max here if you like.
  // Note that this isn't fully fleshed out and won't error if you specify a layout that
  // extends beyond the row capacity. It will, however, not allow users to drag/resize
  // an item past the barrier. They can push items beyond the barrier, though.
  // Intentionally not documented for this reason.
  maxRows: _propTypes2.default.number,

  //
  // Flags
  //
  isDraggable: _propTypes2.default.bool,
  isResizable: _propTypes2.default.bool,
  // If true, grid items won't change position when being dragged over.
  preventCollision: _propTypes2.default.bool,
  // Use CSS transforms instead of top/left
  useCSSTransforms: _propTypes2.default.bool,

  //
  // Callbacks
  //

  // Callback so you can save the layout. Calls after each drag & resize stops.
  onLayoutChange: _propTypes2.default.func,

  // Calls when drag starts. Callback is of the signature (layout, oldItem, newItem, placeholder, e, ?node).
  // All callbacks below have the same signature. 'start' and 'stop' callbacks omit the 'placeholder'.
  onDragStart: _propTypes2.default.func,
  // Calls on each drag movement.
  onDrag: _propTypes2.default.func,
  // Calls when drag is complete.
  onDragStop: _propTypes2.default.func,
  //Calls when resize starts.
  onResizeStart: _propTypes2.default.func,
  // Calls when resize movement happens.
  onResize: _propTypes2.default.func,
  // Calls when resize is complete.
  onResizeStop: _propTypes2.default.func,

  //
  // Other validations
  //

  // Children must not have duplicate keys.
  children: function children(props, propName) {
    var children = props[propName];

    // Check children keys for duplicates. Throw if found.
    var keys = {};
    _react2.default.Children.forEach(children, function (child) {
      if (keys[child.key]) {
        throw new Error('Duplicate child key "' + child.key + '" found! This will cause problems in ReactGridLayout.');
      }
      keys[child.key] = true;
    });
  }
};
ReactGridLayout.defaultProps = {
  autoSize: true,
  cols: 12,
  className: "",
  style: {},
  draggableHandle: "",
  draggableCancel: "",
  containerPadding: null,
  rowHeight: 150,
  maxRows: Infinity, // infinite vertical growth
  layout: [],
  margin: [10, 10],
  isDraggable: true,
  isResizable: true,
  useCSSTransforms: true,
  verticalCompact: true,
  compactType: "vertical",
  preventCollision: false,
  onLayoutChange: _utils.noop,
  onDragStart: _utils.noop,
  onDrag: _utils.noop,
  onDragStop: _utils.noop,
  onResizeStart: _utils.noop,
  onResize: _utils.noop,
  onResizeStop: _utils.noop
};

var _initialiseProps = function _initialiseProps() {
  this.state = {
    activeDrag: null,
    layout: (0, _utils.synchronizeLayoutWithChildren)(this.props.layout, this.props.children, this.props.cols,
    // Legacy support for verticalCompact: false
    this.compactType()),
    mounted: false,
    oldDragItem: null,
    oldLayout: null,
    oldResizeItem: null
  };
};

exports.default = ReactGridLayout;

/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
  Copyright (c) 2017 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
/* global define */

(function () {
	'use strict';

	var hasOwn = {}.hasOwnProperty;

	function classNames () {
		var classes = [];

		for (var i = 0; i < arguments.length; i++) {
			var arg = arguments[i];
			if (!arg) continue;

			var argType = typeof arg;

			if (argType === 'string' || argType === 'number') {
				classes.push(arg);
			} else if (Array.isArray(arg) && arg.length) {
				var inner = classNames.apply(null, arg);
				if (inner) {
					classes.push(inner);
				}
			} else if (argType === 'object') {
				for (var key in arg) {
					if (hasOwn.call(arg, key) && arg[key]) {
						classes.push(key);
					}
				}
			}
		}

		return classes.join(' ');
	}

	if (  true && module.exports) {
		classNames.default = classNames;
		module.exports = classNames;
	} else if (true) {
		// register as 'classnames', consistent with npm package name
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () {
			return classNames;
		}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}
}());


/***/ }),
/* 341 */
/***/ (function(module, exports, __nested_webpack_require_1684797__) {

(function (global, factory) {
	  true ? module.exports = factory(__nested_webpack_require_1684797__(42), __nested_webpack_require_1684797__(1)) :
	0;
}(this, (function (ReactDOM,React) { 'use strict';

	ReactDOM = ReactDOM && ReactDOM.hasOwnProperty('default') ? ReactDOM['default'] : ReactDOM;
	React = React && React.hasOwnProperty('default') ? React['default'] : React;

	function createCommonjsModule(fn, module) {
		return module = { exports: {} }, fn(module, module.exports), module.exports;
	}

	/**
	 * Copyright (c) 2013-present, Facebook, Inc.
	 *
	 * This source code is licensed under the MIT license found in the
	 * LICENSE file in the root directory of this source tree.
	 *
	 * 
	 */

	function makeEmptyFunction(arg) {
	  return function () {
	    return arg;
	  };
	}

	/**
	 * This function accepts and discards inputs; it has no side effects. This is
	 * primarily useful idiomatically for overridable function endpoints which
	 * always need to be callable, since JS lacks a null-call idiom ala Cocoa.
	 */
	var emptyFunction = function emptyFunction() {};

	emptyFunction.thatReturns = makeEmptyFunction;
	emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
	emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
	emptyFunction.thatReturnsNull = makeEmptyFunction(null);
	emptyFunction.thatReturnsThis = function () {
	  return this;
	};
	emptyFunction.thatReturnsArgument = function (arg) {
	  return arg;
	};

	var emptyFunction_1 = emptyFunction;

	/**
	 * Copyright (c) 2013-present, Facebook, Inc.
	 *
	 * This source code is licensed under the MIT license found in the
	 * LICENSE file in the root directory of this source tree.
	 *
	 */

	/**
	 * Use invariant() to assert state which your program assumes to be true.
	 *
	 * Provide sprintf-style format (only %s is supported) and arguments
	 * to provide information about what broke and what you were
	 * expecting.
	 *
	 * The invariant message will be stripped in production, but the invariant
	 * will remain to ensure logic does not differ in production.
	 */

	var validateFormat = function validateFormat(format) {};

	{
	  validateFormat = function validateFormat(format) {
	    if (format === undefined) {
	      throw new Error('invariant requires an error message argument');
	    }
	  };
	}

	function invariant(condition, format, a, b, c, d, e, f) {
	  validateFormat(format);

	  if (!condition) {
	    var error;
	    if (format === undefined) {
	      error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
	    } else {
	      var args = [a, b, c, d, e, f];
	      var argIndex = 0;
	      error = new Error(format.replace(/%s/g, function () {
	        return args[argIndex++];
	      }));
	      error.name = 'Invariant Violation';
	    }

	    error.framesToPop = 1; // we don't care about invariant's own frame
	    throw error;
	  }
	}

	var invariant_1 = invariant;

	/**
	 * Similar to invariant but only logs a warning if the condition is not met.
	 * This can be used to log issues in development environments in critical
	 * paths. Removing the logging code for production environments will keep the
	 * same logic and follow the same code paths.
	 */

	var warning = emptyFunction_1;

	{
	  var printWarning = function printWarning(format) {
	    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
	      args[_key - 1] = arguments[_key];
	    }

	    var argIndex = 0;
	    var message = 'Warning: ' + format.replace(/%s/g, function () {
	      return args[argIndex++];
	    });
	    if (typeof console !== 'undefined') {
	      console.error(message);
	    }
	    try {
	      // --- Welcome to debugging React ---
	      // This error was thrown as a convenience so that you can use this stack
	      // to find the callsite that caused this warning to fire.
	      throw new Error(message);
	    } catch (x) {}
	  };

	  warning = function warning(condition, format) {
	    if (format === undefined) {
	      throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
	    }

	    if (format.indexOf('Failed Composite propType: ') === 0) {
	      return; // Ignore CompositeComponent proptype check.
	    }

	    if (!condition) {
	      for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
	        args[_key2 - 2] = arguments[_key2];
	      }

	      printWarning.apply(undefined, [format].concat(args));
	    }
	  };
	}

	var warning_1 = warning;

	/*
	object-assign
	(c) Sindre Sorhus
	@license MIT
	*/
	/* eslint-disable no-unused-vars */
	var getOwnPropertySymbols = Object.getOwnPropertySymbols;
	var hasOwnProperty = Object.prototype.hasOwnProperty;
	var propIsEnumerable = Object.prototype.propertyIsEnumerable;

	function toObject(val) {
		if (val === null || val === undefined) {
			throw new TypeError('Object.assign cannot be called with null or undefined');
		}

		return Object(val);
	}

	function shouldUseNative() {
		try {
			if (!Object.assign) {
				return false;
			}

			// Detect buggy property enumeration order in older V8 versions.

			// https://bugs.chromium.org/p/v8/issues/detail?id=4118
			var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
			test1[5] = 'de';
			if (Object.getOwnPropertyNames(test1)[0] === '5') {
				return false;
			}

			// https://bugs.chromium.org/p/v8/issues/detail?id=3056
			var test2 = {};
			for (var i = 0; i < 10; i++) {
				test2['_' + String.fromCharCode(i)] = i;
			}
			var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
				return test2[n];
			});
			if (order2.join('') !== '0123456789') {
				return false;
			}

			// https://bugs.chromium.org/p/v8/issues/detail?id=3056
			var test3 = {};
			'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
				test3[letter] = letter;
			});
			if (Object.keys(Object.assign({}, test3)).join('') !==
					'abcdefghijklmnopqrst') {
				return false;
			}

			return true;
		} catch (err) {
			// We don't expect any of the above to throw, but better to be safe.
			return false;
		}
	}

	var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
		var from;
		var to = toObject(target);
		var symbols;

		for (var s = 1; s < arguments.length; s++) {
			from = Object(arguments[s]);

			for (var key in from) {
				if (hasOwnProperty.call(from, key)) {
					to[key] = from[key];
				}
			}

			if (getOwnPropertySymbols) {
				symbols = getOwnPropertySymbols(from);
				for (var i = 0; i < symbols.length; i++) {
					if (propIsEnumerable.call(from, symbols[i])) {
						to[symbols[i]] = from[symbols[i]];
					}
				}
			}
		}

		return to;
	};

	/**
	 * Copyright (c) 2013-present, Facebook, Inc.
	 *
	 * This source code is licensed under the MIT license found in the
	 * LICENSE file in the root directory of this source tree.
	 */

	var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

	var ReactPropTypesSecret_1 = ReactPropTypesSecret;

	{
	  var invariant$1 = invariant_1;
	  var warning$1 = warning_1;
	  var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
	  var loggedTypeFailures = {};
	}

	/**
	 * Assert that the values match with the type specs.
	 * Error messages are memorized and will only be shown once.
	 *
	 * @param {object} typeSpecs Map of name to a ReactPropType
	 * @param {object} values Runtime values that need to be type-checked
	 * @param {string} location e.g. "prop", "context", "child context"
	 * @param {string} componentName Name of the component for error messages.
	 * @param {?Function} getStack Returns the component stack.
	 * @private
	 */
	function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
	  {
	    for (var typeSpecName in typeSpecs) {
	      if (typeSpecs.hasOwnProperty(typeSpecName)) {
	        var error;
	        // Prop type validation may throw. In case they do, we don't want to
	        // fail the render phase where it didn't fail before. So we log it.
	        // After these have been cleaned up, we'll let them throw.
	        try {
	          // This is intentionally an invariant that gets caught. It's the same
	          // behavior as without this statement except with a better message.
	          invariant$1(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
	          error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
	        } catch (ex) {
	          error = ex;
	        }
	        warning$1(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
	        if (error instanceof Error && !(error.message in loggedTypeFailures)) {
	          // Only monitor this failure once because there tends to be a lot of the
	          // same error.
	          loggedTypeFailures[error.message] = true;

	          var stack = getStack ? getStack() : '';

	          warning$1(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
	        }
	      }
	    }
	  }
	}

	var checkPropTypes_1 = checkPropTypes;

	var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
	  /* global Symbol */
	  var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
	  var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.

	  /**
	   * Returns the iterator method function contained on the iterable object.
	   *
	   * Be sure to invoke the function with the iterable as context:
	   *
	   *     var iteratorFn = getIteratorFn(myIterable);
	   *     if (iteratorFn) {
	   *       var iterator = iteratorFn.call(myIterable);
	   *       ...
	   *     }
	   *
	   * @param {?object} maybeIterable
	   * @return {?function}
	   */
	  function getIteratorFn(maybeIterable) {
	    var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
	    if (typeof iteratorFn === 'function') {
	      return iteratorFn;
	    }
	  }

	  /**
	   * Collection of methods that allow declaration and validation of props that are
	   * supplied to React components. Example usage:
	   *
	   *   var Props = require('ReactPropTypes');
	   *   var MyArticle = React.createClass({
	   *     propTypes: {
	   *       // An optional string prop named "description".
	   *       description: Props.string,
	   *
	   *       // A required enum prop named "category".
	   *       category: Props.oneOf(['News','Photos']).isRequired,
	   *
	   *       // A prop named "dialog" that requires an instance of Dialog.
	   *       dialog: Props.instanceOf(Dialog).isRequired
	   *     },
	   *     render: function() { ... }
	   *   });
	   *
	   * A more formal specification of how these methods are used:
	   *
	   *   type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
	   *   decl := ReactPropTypes.{type}(.isRequired)?
	   *
	   * Each and every declaration produces a function with the same signature. This
	   * allows the creation of custom validation functions. For example:
	   *
	   *  var MyLink = React.createClass({
	   *    propTypes: {
	   *      // An optional string or URI prop named "href".
	   *      href: function(props, propName, componentName) {
	   *        var propValue = props[propName];
	   *        if (propValue != null && typeof propValue !== 'string' &&
	   *            !(propValue instanceof URI)) {
	   *          return new Error(
	   *            'Expected a string or an URI for ' + propName + ' in ' +
	   *            componentName
	   *          );
	   *        }
	   *      }
	   *    },
	   *    render: function() {...}
	   *  });
	   *
	   * @internal
	   */

	  var ANONYMOUS = '<<anonymous>>';

	  // Important!
	  // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
	  var ReactPropTypes = {
	    array: createPrimitiveTypeChecker('array'),
	    bool: createPrimitiveTypeChecker('boolean'),
	    func: createPrimitiveTypeChecker('function'),
	    number: createPrimitiveTypeChecker('number'),
	    object: createPrimitiveTypeChecker('object'),
	    string: createPrimitiveTypeChecker('string'),
	    symbol: createPrimitiveTypeChecker('symbol'),

	    any: createAnyTypeChecker(),
	    arrayOf: createArrayOfTypeChecker,
	    element: createElementTypeChecker(),
	    instanceOf: createInstanceTypeChecker,
	    node: createNodeChecker(),
	    objectOf: createObjectOfTypeChecker,
	    oneOf: createEnumTypeChecker,
	    oneOfType: createUnionTypeChecker,
	    shape: createShapeTypeChecker,
	    exact: createStrictShapeTypeChecker,
	  };

	  /**
	   * inlined Object.is polyfill to avoid requiring consumers ship their own
	   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
	   */
	  /*eslint-disable no-self-compare*/
	  function is(x, y) {
	    // SameValue algorithm
	    if (x === y) {
	      // Steps 1-5, 7-10
	      // Steps 6.b-6.e: +0 != -0
	      return x !== 0 || 1 / x === 1 / y;
	    } else {
	      // Step 6.a: NaN == NaN
	      return x !== x && y !== y;
	    }
	  }
	  /*eslint-enable no-self-compare*/

	  /**
	   * We use an Error-like object for backward compatibility as people may call
	   * PropTypes directly and inspect their output. However, we don't use real
	   * Errors anymore. We don't inspect their stack anyway, and creating them
	   * is prohibitively expensive if they are created too often, such as what
	   * happens in oneOfType() for any type before the one that matched.
	   */
	  function PropTypeError(message) {
	    this.message = message;
	    this.stack = '';
	  }
	  // Make `instanceof Error` still work for returned errors.
	  PropTypeError.prototype = Error.prototype;

	  function createChainableTypeChecker(validate) {
	    {
	      var manualPropTypeCallCache = {};
	      var manualPropTypeWarningCount = 0;
	    }
	    function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
	      componentName = componentName || ANONYMOUS;
	      propFullName = propFullName || propName;

	      if (secret !== ReactPropTypesSecret_1) {
	        if (throwOnDirectAccess) {
	          // New behavior only for users of `prop-types` package
	          invariant_1(
	            false,
	            'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
	            'Use `PropTypes.checkPropTypes()` to call them. ' +
	            'Read more at http://fb.me/use-check-prop-types'
	          );
	        } else if (  true && typeof console !== 'undefined') {
	          // Old behavior for people using React.PropTypes
	          var cacheKey = componentName + ':' + propName;
	          if (
	            !manualPropTypeCallCache[cacheKey] &&
	            // Avoid spamming the console because they are often not actionable except for lib authors
	            manualPropTypeWarningCount < 3
	          ) {
	            warning_1(
	              false,
	              'You are manually calling a React.PropTypes validation ' +
	              'function for the `%s` prop on `%s`. This is deprecated ' +
	              'and will throw in the standalone `prop-types` package. ' +
	              'You may be seeing this warning due to a third-party PropTypes ' +
	              'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
	              propFullName,
	              componentName
	            );
	            manualPropTypeCallCache[cacheKey] = true;
	            manualPropTypeWarningCount++;
	          }
	        }
	      }
	      if (props[propName] == null) {
	        if (isRequired) {
	          if (props[propName] === null) {
	            return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
	          }
	          return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
	        }
	        return null;
	      } else {
	        return validate(props, propName, componentName, location, propFullName);
	      }
	    }

	    var chainedCheckType = checkType.bind(null, false);
	    chainedCheckType.isRequired = checkType.bind(null, true);

	    return chainedCheckType;
	  }

	  function createPrimitiveTypeChecker(expectedType) {
	    function validate(props, propName, componentName, location, propFullName, secret) {
	      var propValue = props[propName];
	      var propType = getPropType(propValue);
	      if (propType !== expectedType) {
	        // `propValue` being instance of, say, date/regexp, pass the 'object'
	        // check, but we can offer a more precise error message here rather than
	        // 'of type `object`'.
	        var preciseType = getPreciseType(propValue);

	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createAnyTypeChecker() {
	    return createChainableTypeChecker(emptyFunction_1.thatReturnsNull);
	  }

	  function createArrayOfTypeChecker(typeChecker) {
	    function validate(props, propName, componentName, location, propFullName) {
	      if (typeof typeChecker !== 'function') {
	        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
	      }
	      var propValue = props[propName];
	      if (!Array.isArray(propValue)) {
	        var propType = getPropType(propValue);
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
	      }
	      for (var i = 0; i < propValue.length; i++) {
	        var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
	        if (error instanceof Error) {
	          return error;
	        }
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createElementTypeChecker() {
	    function validate(props, propName, componentName, location, propFullName) {
	      var propValue = props[propName];
	      if (!isValidElement(propValue)) {
	        var propType = getPropType(propValue);
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createInstanceTypeChecker(expectedClass) {
	    function validate(props, propName, componentName, location, propFullName) {
	      if (!(props[propName] instanceof expectedClass)) {
	        var expectedClassName = expectedClass.name || ANONYMOUS;
	        var actualClassName = getClassName(props[propName]);
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createEnumTypeChecker(expectedValues) {
	    if (!Array.isArray(expectedValues)) {
	      warning_1(false, 'Invalid argument supplied to oneOf, expected an instance of array.');
	      return emptyFunction_1.thatReturnsNull;
	    }

	    function validate(props, propName, componentName, location, propFullName) {
	      var propValue = props[propName];
	      for (var i = 0; i < expectedValues.length; i++) {
	        if (is(propValue, expectedValues[i])) {
	          return null;
	        }
	      }

	      var valuesString = JSON.stringify(expectedValues);
	      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createObjectOfTypeChecker(typeChecker) {
	    function validate(props, propName, componentName, location, propFullName) {
	      if (typeof typeChecker !== 'function') {
	        return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
	      }
	      var propValue = props[propName];
	      var propType = getPropType(propValue);
	      if (propType !== 'object') {
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
	      }
	      for (var key in propValue) {
	        if (propValue.hasOwnProperty(key)) {
	          var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
	          if (error instanceof Error) {
	            return error;
	          }
	        }
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createUnionTypeChecker(arrayOfTypeCheckers) {
	    if (!Array.isArray(arrayOfTypeCheckers)) {
	      warning_1(false, 'Invalid argument supplied to oneOfType, expected an instance of array.');
	      return emptyFunction_1.thatReturnsNull;
	    }

	    for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
	      var checker = arrayOfTypeCheckers[i];
	      if (typeof checker !== 'function') {
	        warning_1(
	          false,
	          'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
	          'received %s at index %s.',
	          getPostfixForTypeWarning(checker),
	          i
	        );
	        return emptyFunction_1.thatReturnsNull;
	      }
	    }

	    function validate(props, propName, componentName, location, propFullName) {
	      for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
	        var checker = arrayOfTypeCheckers[i];
	        if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
	          return null;
	        }
	      }

	      return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createNodeChecker() {
	    function validate(props, propName, componentName, location, propFullName) {
	      if (!isNode(props[propName])) {
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createShapeTypeChecker(shapeTypes) {
	    function validate(props, propName, componentName, location, propFullName) {
	      var propValue = props[propName];
	      var propType = getPropType(propValue);
	      if (propType !== 'object') {
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
	      }
	      for (var key in shapeTypes) {
	        var checker = shapeTypes[key];
	        if (!checker) {
	          continue;
	        }
	        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
	        if (error) {
	          return error;
	        }
	      }
	      return null;
	    }
	    return createChainableTypeChecker(validate);
	  }

	  function createStrictShapeTypeChecker(shapeTypes) {
	    function validate(props, propName, componentName, location, propFullName) {
	      var propValue = props[propName];
	      var propType = getPropType(propValue);
	      if (propType !== 'object') {
	        return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
	      }
	      // We need to check all keys in case some are required but missing from
	      // props.
	      var allKeys = objectAssign({}, props[propName], shapeTypes);
	      for (var key in allKeys) {
	        var checker = shapeTypes[key];
	        if (!checker) {
	          return new PropTypeError(
	            'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
	            '\nBad object: ' + JSON.stringify(props[propName], null, '  ') +
	            '\nValid keys: ' +  JSON.stringify(Object.keys(shapeTypes), null, '  ')
	          );
	        }
	        var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
	        if (error) {
	          return error;
	        }
	      }
	      return null;
	    }

	    return createChainableTypeChecker(validate);
	  }

	  function isNode(propValue) {
	    switch (typeof propValue) {
	      case 'number':
	      case 'string':
	      case 'undefined':
	        return true;
	      case 'boolean':
	        return !propValue;
	      case 'object':
	        if (Array.isArray(propValue)) {
	          return propValue.every(isNode);
	        }
	        if (propValue === null || isValidElement(propValue)) {
	          return true;
	        }

	        var iteratorFn = getIteratorFn(propValue);
	        if (iteratorFn) {
	          var iterator = iteratorFn.call(propValue);
	          var step;
	          if (iteratorFn !== propValue.entries) {
	            while (!(step = iterator.next()).done) {
	              if (!isNode(step.value)) {
	                return false;
	              }
	            }
	          } else {
	            // Iterator will provide entry [k,v] tuples rather than values.
	            while (!(step = iterator.next()).done) {
	              var entry = step.value;
	              if (entry) {
	                if (!isNode(entry[1])) {
	                  return false;
	                }
	              }
	            }
	          }
	        } else {
	          return false;
	        }

	        return true;
	      default:
	        return false;
	    }
	  }

	  function isSymbol(propType, propValue) {
	    // Native Symbol.
	    if (propType === 'symbol') {
	      return true;
	    }

	    // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
	    if (propValue['@@toStringTag'] === 'Symbol') {
	      return true;
	    }

	    // Fallback for non-spec compliant Symbols which are polyfilled.
	    if (typeof Symbol === 'function' && propValue instanceof Symbol) {
	      return true;
	    }

	    return false;
	  }

	  // Equivalent of `typeof` but with special handling for array and regexp.
	  function getPropType(propValue) {
	    var propType = typeof propValue;
	    if (Array.isArray(propValue)) {
	      return 'array';
	    }
	    if (propValue instanceof RegExp) {
	      // Old webkits (at least until Android 4.0) return 'function' rather than
	      // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
	      // passes PropTypes.object.
	      return 'object';
	    }
	    if (isSymbol(propType, propValue)) {
	      return 'symbol';
	    }
	    return propType;
	  }

	  // This handles more types than `getPropType`. Only used for error messages.
	  // See `createPrimitiveTypeChecker`.
	  function getPreciseType(propValue) {
	    if (typeof propValue === 'undefined' || propValue === null) {
	      return '' + propValue;
	    }
	    var propType = getPropType(propValue);
	    if (propType === 'object') {
	      if (propValue instanceof Date) {
	        return 'date';
	      } else if (propValue instanceof RegExp) {
	        return 'regexp';
	      }
	    }
	    return propType;
	  }

	  // Returns a string that is postfixed to a warning about an invalid type.
	  // For example, "undefined" or "of type array"
	  function getPostfixForTypeWarning(value) {
	    var type = getPreciseType(value);
	    switch (type) {
	      case 'array':
	      case 'object':
	        return 'an ' + type;
	      case 'boolean':
	      case 'date':
	      case 'regexp':
	        return 'a ' + type;
	      default:
	        return type;
	    }
	  }

	  // Returns class name of the object, if any.
	  function getClassName(propValue) {
	    if (!propValue.constructor || !propValue.constructor.name) {
	      return ANONYMOUS;
	    }
	    return propValue.constructor.name;
	  }

	  ReactPropTypes.checkPropTypes = checkPropTypes_1;
	  ReactPropTypes.PropTypes = ReactPropTypes;

	  return ReactPropTypes;
	};

	var propTypes = createCommonjsModule(function (module) {
	/**
	 * Copyright (c) 2013-present, Facebook, Inc.
	 *
	 * This source code is licensed under the MIT license found in the
	 * LICENSE file in the root directory of this source tree.
	 */

	{
	  var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
	    Symbol.for &&
	    Symbol.for('react.element')) ||
	    0xeac7;

	  var isValidElement = function(object) {
	    return typeof object === 'object' &&
	      object !== null &&
	      object.$$typeof === REACT_ELEMENT_TYPE;
	  };

	  // By explicitly using `prop-types` you are opting into new development behavior.
	  // http://fb.me/prop-types-in-prod
	  var throwOnDirectAccess = true;
	  module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess);
	}
	});

	var classnames = createCommonjsModule(function (module) {
	/*!
	  Copyright (c) 2016 Jed Watson.
	  Licensed under the MIT License (MIT), see
	  http://jedwatson.github.io/classnames
	*/
	/* global define */

	(function () {

		var hasOwn = {}.hasOwnProperty;

		function classNames () {
			var classes = [];

			for (var i = 0; i < arguments.length; i++) {
				var arg = arguments[i];
				if (!arg) continue;

				var argType = typeof arg;

				if (argType === 'string' || argType === 'number') {
					classes.push(arg);
				} else if (Array.isArray(arg)) {
					classes.push(classNames.apply(null, arg));
				} else if (argType === 'object') {
					for (var key in arg) {
						if (hasOwn.call(arg, key) && arg[key]) {
							classes.push(key);
						}
					}
				}
			}

			return classes.join(' ');
		}

		if (  true && module.exports) {
			module.exports = classNames;
		} else if (false) {} else {
			window.classNames = classNames;
		}
	}());
	});

	// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc
	function findInArray(array /*: Array<any> | TouchList*/, callback /*: Function*/) /*: any*/ {
	  for (var i = 0, length = array.length; i < length; i++) {
	    if (callback.apply(callback, [array[i], i, array])) return array[i];
	  }
	}

	function isFunction(func /*: any*/) /*: boolean*/ {
	  return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';
	}

	function isNum(num /*: any*/) /*: boolean*/ {
	  return typeof num === 'number' && !isNaN(num);
	}

	function int(a /*: string*/) /*: number*/ {
	  return parseInt(a, 10);
	}

	function dontSetMe(props /*: Object*/, propName /*: string*/, componentName /*: string*/) {
	  if (props[propName]) {
	    return new Error('Invalid prop ' + propName + ' passed to ' + componentName + ' - do not set this, set it on the child.');
	  }
	}

	var prefixes = ['Moz', 'Webkit', 'O', 'ms'];
	function getPrefix() /*: string*/ {
	  var prop /*: string*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transform';

	  // Checking specifically for 'window.document' is for pseudo-browser server-side
	  // environments that define 'window' as the global context.
	  // E.g. React-rails (see https://github.com/reactjs/react-rails/pull/84)
	  if (typeof window === 'undefined' || typeof window.document === 'undefined') return '';

	  var style = window.document.documentElement.style;

	  if (prop in style) return '';

	  for (var i = 0; i < prefixes.length; i++) {
	    if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];
	  }

	  return '';
	}

	function browserPrefixToKey(prop /*: string*/, prefix /*: string*/) /*: string*/ {
	  return prefix ? '' + prefix + kebabToTitleCase(prop) : prop;
	}

	function kebabToTitleCase(str /*: string*/) /*: string*/ {
	  var out = '';
	  var shouldCapitalize = true;
	  for (var i = 0; i < str.length; i++) {
	    if (shouldCapitalize) {
	      out += str[i].toUpperCase();
	      shouldCapitalize = false;
	    } else if (str[i] === '-') {
	      shouldCapitalize = true;
	    } else {
	      out += str[i];
	    }
	  }
	  return out;
	}

	// Default export is the prefix itself, like 'Moz', 'Webkit', etc
	// Note that you may have to re-test for certain things; for instance, Chrome 50
	// can handle unprefixed `transform`, but not unprefixed `user-select`
	var browserPrefix = getPrefix();

	var classCallCheck = function (instance, Constructor) {
	  if (!(instance instanceof Constructor)) {
	    throw new TypeError("Cannot call a class as a function");
	  }
	};

	var createClass = function () {
	  function defineProperties(target, props) {
	    for (var i = 0; i < props.length; i++) {
	      var descriptor = props[i];
	      descriptor.enumerable = descriptor.enumerable || false;
	      descriptor.configurable = true;
	      if ("value" in descriptor) descriptor.writable = true;
	      Object.defineProperty(target, descriptor.key, descriptor);
	    }
	  }

	  return function (Constructor, protoProps, staticProps) {
	    if (protoProps) defineProperties(Constructor.prototype, protoProps);
	    if (staticProps) defineProperties(Constructor, staticProps);
	    return Constructor;
	  };
	}();

	var defineProperty = function (obj, key, value) {
	  if (key in obj) {
	    Object.defineProperty(obj, key, {
	      value: value,
	      enumerable: true,
	      configurable: true,
	      writable: true
	    });
	  } else {
	    obj[key] = value;
	  }

	  return obj;
	};

	var _extends = Object.assign || function (target) {
	  for (var i = 1; i < arguments.length; i++) {
	    var source = arguments[i];

	    for (var key in source) {
	      if (Object.prototype.hasOwnProperty.call(source, key)) {
	        target[key] = source[key];
	      }
	    }
	  }

	  return target;
	};

	var inherits = function (subClass, superClass) {
	  if (typeof superClass !== "function" && superClass !== null) {
	    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
	  }

	  subClass.prototype = Object.create(superClass && superClass.prototype, {
	    constructor: {
	      value: subClass,
	      enumerable: false,
	      writable: true,
	      configurable: true
	    }
	  });
	  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
	};

	var possibleConstructorReturn = function (self, call) {
	  if (!self) {
	    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
	  }

	  return call && (typeof call === "object" || typeof call === "function") ? call : self;
	};

	var slicedToArray = function () {
	  function sliceIterator(arr, i) {
	    var _arr = [];
	    var _n = true;
	    var _d = false;
	    var _e = undefined;

	    try {
	      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
	        _arr.push(_s.value);

	        if (i && _arr.length === i) break;
	      }
	    } catch (err) {
	      _d = true;
	      _e = err;
	    } finally {
	      try {
	        if (!_n && _i["return"]) _i["return"]();
	      } finally {
	        if (_d) throw _e;
	      }
	    }

	    return _arr;
	  }

	  return function (arr, i) {
	    if (Array.isArray(arr)) {
	      return arr;
	    } else if (Symbol.iterator in Object(arr)) {
	      return sliceIterator(arr, i);
	    } else {
	      throw new TypeError("Invalid attempt to destructure non-iterable instance");
	    }
	  };
	}();

	/*:: import type {ControlPosition, MouseTouchEvent} from './types';*/


	var matchesSelectorFunc = '';
	function matchesSelector(el /*: Node*/, selector /*: string*/) /*: boolean*/ {
	  if (!matchesSelectorFunc) {
	    matchesSelectorFunc = findInArray(['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'], function (method) {
	      // $FlowIgnore: Doesn't think elements are indexable
	      return isFunction(el[method]);
	    });
	  }

	  // Might not be found entirely (not an Element?) - in that case, bail
	  // $FlowIgnore: Doesn't think elements are indexable
	  if (!isFunction(el[matchesSelectorFunc])) return false;

	  // $FlowIgnore: Doesn't think elements are indexable
	  return el[matchesSelectorFunc](selector);
	}

	// Works up the tree to the draggable itself attempting to match selector.
	function matchesSelectorAndParentsTo(el /*: Node*/, selector /*: string*/, baseNode /*: Node*/) /*: boolean*/ {
	  var node = el;
	  do {
	    if (matchesSelector(node, selector)) return true;
	    if (node === baseNode) return false;
	    node = node.parentNode;
	  } while (node);

	  return false;
	}

	function addEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
	  if (!el) {
	    return;
	  }
	  if (el.attachEvent) {
	    el.attachEvent('on' + event, handler);
	  } else if (el.addEventListener) {
	    el.addEventListener(event, handler, true);
	  } else {
	    // $FlowIgnore: Doesn't think elements are indexable
	    el['on' + event] = handler;
	  }
	}

	function removeEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/) /*: void*/ {
	  if (!el) {
	    return;
	  }
	  if (el.detachEvent) {
	    el.detachEvent('on' + event, handler);
	  } else if (el.removeEventListener) {
	    el.removeEventListener(event, handler, true);
	  } else {
	    // $FlowIgnore: Doesn't think elements are indexable
	    el['on' + event] = null;
	  }
	}

	function outerHeight(node /*: HTMLElement*/) /*: number*/ {
	  // This is deliberately excluding margin for our calculations, since we are using
	  // offsetTop which is including margin. See getBoundPosition
	  var height = node.clientHeight;
	  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
	  height += int(computedStyle.borderTopWidth);
	  height += int(computedStyle.borderBottomWidth);
	  return height;
	}

	function outerWidth(node /*: HTMLElement*/) /*: number*/ {
	  // This is deliberately excluding margin for our calculations, since we are using
	  // offsetLeft which is including margin. See getBoundPosition
	  var width = node.clientWidth;
	  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
	  width += int(computedStyle.borderLeftWidth);
	  width += int(computedStyle.borderRightWidth);
	  return width;
	}
	function innerHeight(node /*: HTMLElement*/) /*: number*/ {
	  var height = node.clientHeight;
	  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
	  height -= int(computedStyle.paddingTop);
	  height -= int(computedStyle.paddingBottom);
	  return height;
	}

	function innerWidth(node /*: HTMLElement*/) /*: number*/ {
	  var width = node.clientWidth;
	  var computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
	  width -= int(computedStyle.paddingLeft);
	  width -= int(computedStyle.paddingRight);
	  return width;
	}

	// Get from offsetParent
	function offsetXYFromParent(evt /*: {clientX: number, clientY: number}*/, offsetParent /*: HTMLElement*/) /*: ControlPosition*/ {
	  var isBody = offsetParent === offsetParent.ownerDocument.body;
	  var offsetParentRect = isBody ? { left: 0, top: 0 } : offsetParent.getBoundingClientRect();

	  var x = evt.clientX + offsetParent.scrollLeft - offsetParentRect.left;
	  var y = evt.clientY + offsetParent.scrollTop - offsetParentRect.top;

	  return { x: x, y: y };
	}

	function createCSSTransform(_ref) /*: Object*/ {
	  var x = _ref.x,
	      y = _ref.y;

	  // Replace unitless items with px
	  return defineProperty({}, browserPrefixToKey('transform', browserPrefix), 'translate(' + x + 'px,' + y + 'px)');
	}

	function createSVGTransform(_ref3) /*: string*/ {
	  var x = _ref3.x,
	      y = _ref3.y;

	  return 'translate(' + x + ',' + y + ')';
	}

	function getTouch(e /*: MouseTouchEvent*/, identifier /*: number*/) /*: ?{clientX: number, clientY: number}*/ {
	  return e.targetTouches && findInArray(e.targetTouches, function (t) {
	    return identifier === t.identifier;
	  }) || e.changedTouches && findInArray(e.changedTouches, function (t) {
	    return identifier === t.identifier;
	  });
	}

	function getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/ {
	  if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
	  if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
	}

	// User-select Hacks:
	//
	// Useful for preventing blue highlights all over everything when dragging.

	// Note we're passing `document` b/c we could be iframed
	function addUserSelectStyles(doc /*: ?Document*/) {
	  if (!doc) return;
	  var styleEl = doc.getElementById('react-draggable-style-el');
	  if (!styleEl) {
	    styleEl = doc.createElement('style');
	    styleEl.type = 'text/css';
	    styleEl.id = 'react-draggable-style-el';
	    styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {background: transparent;}\n';
	    styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {background: transparent;}\n';
	    doc.getElementsByTagName('head')[0].appendChild(styleEl);
	  }
	  if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
	}

	function removeUserSelectStyles(doc /*: ?Document*/) {
	  try {
	    if (doc && doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
	    // $FlowIgnore: IE
	    if (doc.selection) {
	      // $FlowIgnore: IE
	      doc.selection.empty();
	    } else {
	      window.getSelection().removeAllRanges(); // remove selection caused by scroll
	    }
	  } catch (e) {
	    // probably IE
	  }
	}

	function styleHacks() /*: Object*/ {
	  var childStyle /*: Object*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

	  // Workaround IE pointer events; see #51
	  // https://github.com/mzabriskie/react-draggable/issues/51#issuecomment-103488278
	  return _extends({
	    touchAction: 'none'
	  }, childStyle);
	}

	function addClassName(el /*: HTMLElement*/, className /*: string*/) {
	  if (el.classList) {
	    el.classList.add(className);
	  } else {
	    if (!el.className.match(new RegExp('(?:^|\\s)' + className + '(?!\\S)'))) {
	      el.className += ' ' + className;
	    }
	  }
	}

	function removeClassName(el /*: HTMLElement*/, className /*: string*/) {
	  if (el.classList) {
	    el.classList.remove(className);
	  } else {
	    el.className = el.className.replace(new RegExp('(?:^|\\s)' + className + '(?!\\S)', 'g'), '');
	  }
	}

	/*:: import type Draggable from '../Draggable';*/
	/*:: import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';*/
	/*:: import type DraggableCore from '../DraggableCore';*/


	function getBoundPosition(draggable /*: Draggable*/, x /*: number*/, y /*: number*/) /*: [number, number]*/ {
	  // If no bounds, short-circuit and move on
	  if (!draggable.props.bounds) return [x, y];

	  // Clone new bounds
	  var bounds = draggable.props.bounds;

	  bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);
	  var node = findDOMNode(draggable);

	  if (typeof bounds === 'string') {
	    var ownerDocument = node.ownerDocument;

	    var ownerWindow = ownerDocument.defaultView;
	    var boundNode = void 0;
	    if (bounds === 'parent') {
	      boundNode = node.parentNode;
	    } else {
	      boundNode = ownerDocument.querySelector(bounds);
	    }
	    if (!(boundNode instanceof ownerWindow.HTMLElement)) {
	      throw new Error('Bounds selector "' + bounds + '" could not find an element.');
	    }
	    var nodeStyle = ownerWindow.getComputedStyle(node);
	    var boundNodeStyle = ownerWindow.getComputedStyle(boundNode);
	    // Compute bounds. This is a pain with padding and offsets but this gets it exactly right.
	    bounds = {
	      left: -node.offsetLeft + int(boundNodeStyle.paddingLeft) + int(nodeStyle.marginLeft),
	      top: -node.offsetTop + int(boundNodeStyle.paddingTop) + int(nodeStyle.marginTop),
	      right: innerWidth(boundNode) - outerWidth(node) - node.offsetLeft + int(boundNodeStyle.paddingRight) - int(nodeStyle.marginRight),
	      bottom: innerHeight(boundNode) - outerHeight(node) - node.offsetTop + int(boundNodeStyle.paddingBottom) - int(nodeStyle.marginBottom)
	    };
	  }

	  // Keep x and y below right and bottom limits...
	  if (isNum(bounds.right)) x = Math.min(x, bounds.right);
	  if (isNum(bounds.bottom)) y = Math.min(y, bounds.bottom);

	  // But above left and top limits.
	  if (isNum(bounds.left)) x = Math.max(x, bounds.left);
	  if (isNum(bounds.top)) y = Math.max(y, bounds.top);

	  return [x, y];
	}

	function snapToGrid(grid /*: [number, number]*/, pendingX /*: number*/, pendingY /*: number*/) /*: [number, number]*/ {
	  var x = Math.round(pendingX / grid[0]) * grid[0];
	  var y = Math.round(pendingY / grid[1]) * grid[1];
	  return [x, y];
	}

	function canDragX(draggable /*: Draggable*/) /*: boolean*/ {
	  return draggable.props.axis === 'both' || draggable.props.axis === 'x';
	}

	function canDragY(draggable /*: Draggable*/) /*: boolean*/ {
	  return draggable.props.axis === 'both' || draggable.props.axis === 'y';
	}

	// Get {x, y} positions from event.
	function getControlPosition(e /*: MouseTouchEvent*/, touchIdentifier /*: ?number*/, draggableCore /*: DraggableCore*/) /*: ?ControlPosition*/ {
	  var touchObj = typeof touchIdentifier === 'number' ? getTouch(e, touchIdentifier) : null;
	  if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch
	  var node = findDOMNode(draggableCore);
	  // User can provide an offsetParent if desired.
	  var offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
	  return offsetXYFromParent(touchObj || e, offsetParent);
	}

	// Create an data object exposed by <DraggableCore>'s events
	function createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/ {
	  var state = draggable.state;
	  var isStart = !isNum(state.lastX);
	  var node = findDOMNode(draggable);

	  if (isStart) {
	    // If this is our first move, use the x and y as last coords.
	    return {
	      node: node,
	      deltaX: 0, deltaY: 0,
	      lastX: x, lastY: y,
	      x: x, y: y
	    };
	  } else {
	    // Otherwise calculate proper values.
	    return {
	      node: node,
	      deltaX: x - state.lastX, deltaY: y - state.lastY,
	      lastX: state.lastX, lastY: state.lastY,
	      x: x, y: y
	    };
	  }
	}

	// Create an data exposed by <Draggable>'s events
	function createDraggableData(draggable /*: Draggable*/, coreData /*: DraggableData*/) /*: DraggableData*/ {
	  var scale = draggable.props.scale;
	  return {
	    node: coreData.node,
	    x: draggable.state.x + coreData.deltaX / scale,
	    y: draggable.state.y + coreData.deltaY / scale,
	    deltaX: coreData.deltaX / scale,
	    deltaY: coreData.deltaY / scale,
	    lastX: draggable.state.x,
	    lastY: draggable.state.y
	  };
	}

	// A lot faster than stringify/parse
	function cloneBounds(bounds /*: Bounds*/) /*: Bounds*/ {
	  return {
	    left: bounds.left,
	    top: bounds.top,
	    right: bounds.right,
	    bottom: bounds.bottom
	  };
	}

	function findDOMNode(draggable /*: Draggable | DraggableCore*/) /*: HTMLElement*/ {
	  var node = ReactDOM.findDOMNode(draggable);
	  if (!node) {
	    throw new Error('<DraggableCore>: Unmounted during event!');
	  }
	  // $FlowIgnore we can't assert on HTMLElement due to tests... FIXME
	  return node;
	}

	/*eslint no-console:0*/
	function log() {
	}

	/*:: import type {EventHandler, MouseTouchEvent} from './utils/types';*/


	// Simple abstraction for dragging events names.
	/*:: import type {Element as ReactElement} from 'react';*/
	var eventsFor = {
	  touch: {
	    start: 'touchstart',
	    move: 'touchmove',
	    stop: 'touchend'
	  },
	  mouse: {
	    start: 'mousedown',
	    move: 'mousemove',
	    stop: 'mouseup'
	  }
	};

	// Default to mouse events.
	var dragEventFor = eventsFor.mouse;

	/*:: type DraggableCoreState = {
	  dragging: boolean,
	  lastX: number,
	  lastY: number,
	  touchIdentifier: ?number
	};*/
	/*:: export type DraggableBounds = {
	  left: number,
	  right: number,
	  top: number,
	  bottom: number,
	};*/
	/*:: export type DraggableData = {
	  node: HTMLElement,
	  x: number, y: number,
	  deltaX: number, deltaY: number,
	  lastX: number, lastY: number,
	};*/
	/*:: export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void;*/
	/*:: export type ControlPosition = {x: number, y: number};*/


	//
	// Define <DraggableCore>.
	//
	// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can
	// work well with libraries that require more control over the element.
	//

	/*:: export type DraggableCoreProps = {
	  allowAnyClick: boolean,
	  cancel: string,
	  children: ReactElement<any>,
	  disabled: boolean,
	  enableUserSelectHack: boolean,
	  offsetParent: HTMLElement,
	  grid: [number, number],
	  handle: string,
	  onStart: DraggableEventHandler,
	  onDrag: DraggableEventHandler,
	  onStop: DraggableEventHandler,
	  onMouseDown: (e: MouseEvent) => void,
	};*/

	var DraggableCore = function (_React$Component) {
	  inherits(DraggableCore, _React$Component);

	  function DraggableCore() {
	    var _ref;

	    var _temp, _this, _ret;

	    classCallCheck(this, DraggableCore);

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

	    return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = DraggableCore.__proto__ || Object.getPrototypeOf(DraggableCore)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
	      dragging: false,
	      // Used while dragging to determine deltas.
	      lastX: NaN, lastY: NaN,
	      touchIdentifier: null
	    }, _this.handleDragStart = function (e) {
	      // Make it possible to attach event handlers on top of this one.
	      _this.props.onMouseDown(e);

	      // Only accept left-clicks.
	      if (!_this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;

	      // Get nodes. Be sure to grab relative document (could be iframed)
	      var thisNode = ReactDOM.findDOMNode(_this);
	      if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
	        throw new Error('<DraggableCore> not mounted on DragStart!');
	      }
	      var ownerDocument = thisNode.ownerDocument;

	      // Short circuit if handle or cancel prop was provided and selector doesn't match.

	      if (_this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || _this.props.handle && !matchesSelectorAndParentsTo(e.target, _this.props.handle, thisNode) || _this.props.cancel && matchesSelectorAndParentsTo(e.target, _this.props.cancel, thisNode)) {
	        return;
	      }

	      // Set touch identifier in component state if this is a touch event. This allows us to
	      // distinguish between individual touches on multitouch screens by identifying which
	      // touchpoint was set to this element.
	      var touchIdentifier = getTouchIdentifier(e);
	      _this.setState({ touchIdentifier: touchIdentifier });

	      // Get the current drag point from the event. This is used as the offset.
	      var position = getControlPosition(e, touchIdentifier, _this);
	      if (position == null) return; // not possible but satisfies flow
	      var x = position.x,
	          y = position.y;

	      // Create an event object with all the data parents need to make a decision here.

	      var coreEvent = createCoreData(_this, x, y);

	      // Call event handler. If it returns explicit false, cancel.
	      log('calling', _this.props.onStart);
	      var shouldUpdate = _this.props.onStart(e, coreEvent);
	      if (shouldUpdate === false) return;

	      // Add a style to the body to disable user-select. This prevents text from
	      // being selected all over the page.
	      if (_this.props.enableUserSelectHack) addUserSelectStyles(ownerDocument);

	      // Initiate dragging. Set the current x and y as offsets
	      // so we know how much we've moved during the drag. This allows us
	      // to drag elements around even if they have been moved, without issue.
	      _this.setState({
	        dragging: true,

	        lastX: x,
	        lastY: y
	      });

	      // Add events to the document directly so we catch when the user's mouse/touch moves outside of
	      // this element. We use different events depending on whether or not we have detected that this
	      // is a touch-capable device.
	      addEvent(ownerDocument, dragEventFor.move, _this.handleDrag);
	      addEvent(ownerDocument, dragEventFor.stop, _this.handleDragStop);
	    }, _this.handleDrag = function (e) {

	      // Prevent scrolling on mobile devices, like ipad/iphone.
	      if (e.type === 'touchmove') e.preventDefault();

	      // Get the current drag point from the event. This is used as the offset.
	      var position = getControlPosition(e, _this.state.touchIdentifier, _this);
	      if (position == null) return;
	      var x = position.x,
	          y = position.y;

	      // Snap to grid if prop has been provided

	      if (Array.isArray(_this.props.grid)) {
	        var _deltaX = x - _this.state.lastX,
	            _deltaY = y - _this.state.lastY;

	        var _snapToGrid = snapToGrid(_this.props.grid, _deltaX, _deltaY);

	        var _snapToGrid2 = slicedToArray(_snapToGrid, 2);

	        _deltaX = _snapToGrid2[0];
	        _deltaY = _snapToGrid2[1];

	        if (!_deltaX && !_deltaY) return; // skip useless drag
	        x = _this.state.lastX + _deltaX, y = _this.state.lastY + _deltaY;
	      }

	      var coreEvent = createCoreData(_this, x, y);

	      // Call event handler. If it returns explicit false, trigger end.
	      var shouldUpdate = _this.props.onDrag(e, coreEvent);
	      if (shouldUpdate === false) {
	        try {
	          // $FlowIgnore
	          _this.handleDragStop(new MouseEvent('mouseup'));
	        } catch (err) {
	          // Old browsers
	          var event = ((document.createEvent('MouseEvents') /*: any*/) /*: MouseTouchEvent*/);
	          // I see why this insanity was deprecated
	          // $FlowIgnore
	          event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	          _this.handleDragStop(event);
	        }
	        return;
	      }

	      _this.setState({
	        lastX: x,
	        lastY: y
	      });
	    }, _this.handleDragStop = function (e) {
	      if (!_this.state.dragging) return;

	      var position = getControlPosition(e, _this.state.touchIdentifier, _this);
	      if (position == null) return;
	      var x = position.x,
	          y = position.y;

	      var coreEvent = createCoreData(_this, x, y);

	      var thisNode = ReactDOM.findDOMNode(_this);
	      if (thisNode) {
	        // Remove user-select hack
	        if (_this.props.enableUserSelectHack) removeUserSelectStyles(thisNode.ownerDocument);
	      }

	      // Reset the el.
	      _this.setState({
	        dragging: false,
	        lastX: NaN,
	        lastY: NaN
	      });

	      // Call event handler
	      _this.props.onStop(e, coreEvent);

	      if (thisNode) {
	        removeEvent(thisNode.ownerDocument, dragEventFor.move, _this.handleDrag);
	        removeEvent(thisNode.ownerDocument, dragEventFor.stop, _this.handleDragStop);
	      }
	    }, _this.onMouseDown = function (e) {
	      dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse

	      return _this.handleDragStart(e);
	    }, _this.onMouseUp = function (e) {
	      dragEventFor = eventsFor.mouse;

	      return _this.handleDragStop(e);
	    }, _this.onTouchStart = function (e) {
	      // We're on a touch device now, so change the event handlers
	      dragEventFor = eventsFor.touch;

	      return _this.handleDragStart(e);
	    }, _this.onTouchEnd = function (e) {
	      // We're on a touch device now, so change the event handlers
	      dragEventFor = eventsFor.touch;

	      return _this.handleDragStop(e);
	    }, _temp), possibleConstructorReturn(_this, _ret);
	  }

	  createClass(DraggableCore, [{
	    key: 'componentWillUnmount',
	    value: function componentWillUnmount() {
	      // Remove any leftover event handlers. Remove both touch and mouse handlers in case
	      // some browser quirk caused a touch event to fire during a mouse move, or vice versa.
	      var thisNode = ReactDOM.findDOMNode(this);
	      if (thisNode) {
	        var ownerDocument = thisNode.ownerDocument;

	        removeEvent(ownerDocument, eventsFor.mouse.move, this.handleDrag);
	        removeEvent(ownerDocument, eventsFor.touch.move, this.handleDrag);
	        removeEvent(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
	        removeEvent(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
	        if (this.props.enableUserSelectHack) removeUserSelectStyles(ownerDocument);
	      }
	    }

	    // Same as onMouseDown (start drag), but now consider this a touch device.

	  }, {
	    key: 'render',
	    value: function render() {
	      // Reuse the child provided
	      // This makes it flexible to use whatever element is wanted (div, ul, etc)
	      return React.cloneElement(React.Children.only(this.props.children), {
	        style: styleHacks(this.props.children.props.style),

	        // Note: mouseMove handler is attached to document so it will still function
	        // when the user drags quickly and leaves the bounds of the element.
	        onMouseDown: this.onMouseDown,
	        onTouchStart: this.onTouchStart,
	        onMouseUp: this.onMouseUp,
	        onTouchEnd: this.onTouchEnd
	      });
	    }
	  }]);
	  return DraggableCore;
	}(React.Component);

	DraggableCore.displayName = 'DraggableCore';
	DraggableCore.propTypes = {
	  /**
	   * `allowAnyClick` allows dragging using any mouse button.
	   * By default, we only accept the left button.
	   *
	   * Defaults to `false`.
	   */
	  allowAnyClick: propTypes.bool,

	  /**
	   * `disabled`, if true, stops the <Draggable> from dragging. All handlers,
	   * with the exception of `onMouseDown`, will not fire.
	   */
	  disabled: propTypes.bool,

	  /**
	   * By default, we add 'user-select:none' attributes to the document body
	   * to prevent ugly text selection during drag. If this is causing problems
	   * for your app, set this to `false`.
	   */
	  enableUserSelectHack: propTypes.bool,

	  /**
	   * `offsetParent`, if set, uses the passed DOM node to compute drag offsets
	   * instead of using the parent node.
	   */
	  offsetParent: function offsetParent(props /*: DraggableCoreProps*/, propName /*: $Keys<DraggableCoreProps>*/) {
	    if (props[propName] && props[propName].nodeType !== 1) {
	      throw new Error('Draggable\'s offsetParent must be a DOM Node.');
	    }
	  },

	  /**
	   * `grid` specifies the x and y that dragging should snap to.
	   */
	  grid: propTypes.arrayOf(propTypes.number),

	  /**
	   * `scale` specifies the scale of the area you are dragging inside of. It allows
	   * the drag deltas to scale correctly with how far zoomed in/out you are.
	   */
	  scale: propTypes.number,

	  /**
	   * `handle` specifies a selector to be used as the handle that initiates drag.
	   *
	   * Example:
	   *
	   * ```jsx
	   *   let App = React.createClass({
	   *       render: function () {
	   *         return (
	   *            <Draggable handle=".handle">
	   *              <div>
	   *                  <div className="handle">Click me to drag</div>
	   *                  <div>This is some other content</div>
	   *              </div>
	   *           </Draggable>
	   *         );
	   *       }
	   *   });
	   * ```
	   */
	  handle: propTypes.string,

	  /**
	   * `cancel` specifies a selector to be used to prevent drag initialization.
	   *
	   * Example:
	   *
	   * ```jsx
	   *   let App = React.createClass({
	   *       render: function () {
	   *           return(
	   *               <Draggable cancel=".cancel">
	   *                   <div>
	   *                     <div className="cancel">You can't drag from here</div>
	   *                     <div>Dragging here works fine</div>
	   *                   </div>
	   *               </Draggable>
	   *           );
	   *       }
	   *   });
	   * ```
	   */
	  cancel: propTypes.string,

	  /**
	   * Called when dragging starts.
	   * If this function returns the boolean false, dragging will be canceled.
	   */
	  onStart: propTypes.func,

	  /**
	   * Called while dragging.
	   * If this function returns the boolean false, dragging will be canceled.
	   */
	  onDrag: propTypes.func,

	  /**
	   * Called when dragging stops.
	   * If this function returns the boolean false, the drag will remain active.
	   */
	  onStop: propTypes.func,

	  /**
	   * A workaround option which can be passed if onMouseDown needs to be accessed,
	   * since it'll always be blocked (as there is internal use of onMouseDown)
	   */
	  onMouseDown: propTypes.func,

	  /**
	   * These properties should be defined on the child, not here.
	   */
	  className: dontSetMe,
	  style: dontSetMe,
	  transform: dontSetMe
	};
	DraggableCore.defaultProps = {
	  allowAnyClick: false, // by default only accept left click
	  cancel: null,
	  disabled: false,
	  enableUserSelectHack: true,
	  offsetParent: null,
	  handle: null,
	  grid: null,
	  transform: null,
	  onStart: function onStart() {},
	  onDrag: function onDrag() {},
	  onStop: function onStop() {},
	  onMouseDown: function onMouseDown() {}
	};

	/*:: import type {DraggableEventHandler} from './utils/types';*/
	/*:: import type {Element as ReactElement} from 'react';*/
	/*:: type DraggableState = {
	  dragging: boolean,
	  dragged: boolean,
	  x: number, y: number,
	  slackX: number, slackY: number,
	  isElementSVG: boolean
	};*/


	//
	// Define <Draggable>
	//

	/*:: export type DraggableProps = {
	  ...$Exact<DraggableCoreProps>,
	  axis: 'both' | 'x' | 'y' | 'none',
	  bounds: DraggableBounds | string | false,
	  defaultClassName: string,
	  defaultClassNameDragging: string,
	  defaultClassNameDragged: string,
	  defaultPosition: ControlPosition,
	  position: ControlPosition,
	  scale: number
	};*/

	var Draggable = function (_React$Component) {
	  inherits(Draggable, _React$Component);

	  function Draggable(props /*: DraggableProps*/) {
	    classCallCheck(this, Draggable);

	    var _this = possibleConstructorReturn(this, (Draggable.__proto__ || Object.getPrototypeOf(Draggable)).call(this, props));

	    _this.onDragStart = function (e, coreData) {

	      // Short-circuit if user's callback killed it.
	      var shouldStart = _this.props.onStart(e, createDraggableData(_this, coreData));
	      // Kills start event on core as well, so move handlers are never bound.
	      if (shouldStart === false) return false;

	      _this.setState({ dragging: true, dragged: true });
	    };

	    _this.onDrag = function (e, coreData) {
	      if (!_this.state.dragging) return false;

	      var uiData = createDraggableData(_this, coreData);

	      var newState /*: $Shape<DraggableState>*/ = {
	        x: uiData.x,
	        y: uiData.y
	      };

	      // Keep within bounds.
	      if (_this.props.bounds) {
	        // Save original x and y.
	        var _x = newState.x,
	            _y = newState.y;

	        // Add slack to the values used to calculate bound position. This will ensure that if
	        // we start removing slack, the element won't react to it right away until it's been
	        // completely removed.

	        newState.x += _this.state.slackX;
	        newState.y += _this.state.slackY;

	        // Get bound position. This will ceil/floor the x and y within the boundaries.

	        var _getBoundPosition = getBoundPosition(_this, newState.x, newState.y),
	            _getBoundPosition2 = slicedToArray(_getBoundPosition, 2),
	            newStateX = _getBoundPosition2[0],
	            newStateY = _getBoundPosition2[1];

	        newState.x = newStateX;
	        newState.y = newStateY;

	        // Recalculate slack by noting how much was shaved by the boundPosition handler.
	        newState.slackX = _this.state.slackX + (_x - newState.x);
	        newState.slackY = _this.state.slackY + (_y - newState.y);

	        // Update the event we fire to reflect what really happened after bounds took effect.
	        uiData.x = newState.x;
	        uiData.y = newState.y;
	        uiData.deltaX = newState.x - _this.state.x;
	        uiData.deltaY = newState.y - _this.state.y;
	      }

	      // Short-circuit if user's callback killed it.
	      var shouldUpdate = _this.props.onDrag(e, uiData);
	      if (shouldUpdate === false) return false;

	      _this.setState(newState);
	    };

	    _this.onDragStop = function (e, coreData) {
	      if (!_this.state.dragging) return false;

	      // Short-circuit if user's callback killed it.
	      var shouldStop = _this.props.onStop(e, createDraggableData(_this, coreData));
	      if (shouldStop === false) return false;

	      var newState /*: $Shape<DraggableState>*/ = {
	        dragging: false,
	        slackX: 0,
	        slackY: 0
	      };

	      // If this is a controlled component, the result of this operation will be to
	      // revert back to the old position. We expect a handler on `onDragStop`, at the least.
	      var controlled = Boolean(_this.props.position);
	      if (controlled) {
	        var _this$props$position = _this.props.position,
	            _x2 = _this$props$position.x,
	            _y2 = _this$props$position.y;

	        newState.x = _x2;
	        newState.y = _y2;
	      }

	      _this.setState(newState);
	    };

	    _this.state = {
	      // Whether or not we are currently dragging.
	      dragging: false,

	      // Whether or not we have been dragged before.
	      dragged: false,

	      // Current transform x and y.
	      x: props.position ? props.position.x : props.defaultPosition.x,
	      y: props.position ? props.position.y : props.defaultPosition.y,

	      // Used for compensating for out-of-bounds drags
	      slackX: 0, slackY: 0,

	      // Can only determine if SVG after mounting
	      isElementSVG: false
	    };
	    return _this;
	  }

	  createClass(Draggable, [{
	    key: 'componentWillMount',
	    value: function componentWillMount() {
	      if (this.props.position && !(this.props.onDrag || this.props.onStop)) {
	        // eslint-disable-next-line
	        console.warn('A `position` was applied to this <Draggable>, without drag handlers. This will make this ' + 'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' + '`position` of this element.');
	      }
	    }
	  }, {
	    key: 'componentDidMount',
	    value: function componentDidMount() {
	      // Check to see if the element passed is an instanceof SVGElement
	      if (typeof window.SVGElement !== 'undefined' && ReactDOM.findDOMNode(this) instanceof window.SVGElement) {
	        this.setState({ isElementSVG: true });
	      }
	    }
	  }, {
	    key: 'componentWillReceiveProps',
	    value: function componentWillReceiveProps(nextProps /*: Object*/) {
	      // Set x/y if position has changed
	      if (nextProps.position && (!this.props.position || nextProps.position.x !== this.props.position.x || nextProps.position.y !== this.props.position.y)) {
	        this.setState({ x: nextProps.position.x, y: nextProps.position.y });
	      }
	    }
	  }, {
	    key: 'componentWillUnmount',
	    value: function componentWillUnmount() {
	      this.setState({ dragging: false }); // prevents invariant if unmounted while dragging
	    }
	  }, {
	    key: 'render',
	    value: function render() /*: ReactElement<any>*/ {
	      var _classNames;

	      var style = {},
	          svgTransform = null;

	      // If this is controlled, we don't want to move it - unless it's dragging.
	      var controlled = Boolean(this.props.position);
	      var draggable = !controlled || this.state.dragging;

	      var position = this.props.position || this.props.defaultPosition;
	      var transformOpts = {
	        // Set left if horizontal drag is enabled
	        x: canDragX(this) && draggable ? this.state.x : position.x,

	        // Set top if vertical drag is enabled
	        y: canDragY(this) && draggable ? this.state.y : position.y
	      };

	      // If this element was SVG, we use the `transform` attribute.
	      if (this.state.isElementSVG) {
	        svgTransform = createSVGTransform(transformOpts);
	      } else {
	        // Add a CSS transform to move the element around. This allows us to move the element around
	        // without worrying about whether or not it is relatively or absolutely positioned.
	        // If the item you are dragging already has a transform set, wrap it in a <span> so <Draggable>
	        // has a clean slate.
	        style = createCSSTransform(transformOpts);
	      }

	      var _props = this.props,
	          defaultClassName = _props.defaultClassName,
	          defaultClassNameDragging = _props.defaultClassNameDragging,
	          defaultClassNameDragged = _props.defaultClassNameDragged;


	      var children = React.Children.only(this.props.children);

	      // Mark with class while dragging
	      var className = classnames(children.props.className || '', defaultClassName, (_classNames = {}, defineProperty(_classNames, defaultClassNameDragging, this.state.dragging), defineProperty(_classNames, defaultClassNameDragged, this.state.dragged), _classNames));

	      // Reuse the child provided
	      // This makes it flexible to use whatever element is wanted (div, ul, etc)
	      return React.createElement(
	        DraggableCore,
	        _extends({}, this.props, { onStart: this.onDragStart, onDrag: this.onDrag, onStop: this.onDragStop }),
	        React.cloneElement(children, {
	          className: className,
	          style: _extends({}, children.props.style, style),
	          transform: svgTransform
	        })
	      );
	    }
	  }]);
	  return Draggable;
	}(React.Component);

	Draggable.displayName = 'Draggable';
	Draggable.propTypes = _extends({}, DraggableCore.propTypes, {

	  /**
	   * `axis` determines which axis the draggable can move.
	   *
	   *  Note that all callbacks will still return data as normal. This only
	   *  controls flushing to the DOM.
	   *
	   * 'both' allows movement horizontally and vertically.
	   * 'x' limits movement to horizontal axis.
	   * 'y' limits movement to vertical axis.
	   * 'none' limits all movement.
	   *
	   * Defaults to 'both'.
	   */
	  axis: propTypes.oneOf(['both', 'x', 'y', 'none']),

	  /**
	   * `bounds` determines the range of movement available to the element.
	   * Available values are:
	   *
	   * 'parent' restricts movement within the Draggable's parent node.
	   *
	   * Alternatively, pass an object with the following properties, all of which are optional:
	   *
	   * {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}
	   *
	   * All values are in px.
	   *
	   * Example:
	   *
	   * ```jsx
	   *   let App = React.createClass({
	   *       render: function () {
	   *         return (
	   *            <Draggable bounds={{right: 300, bottom: 300}}>
	   *              <div>Content</div>
	   *           </Draggable>
	   *         );
	   *       }
	   *   });
	   * ```
	   */
	  bounds: propTypes.oneOfType([propTypes.shape({
	    left: propTypes.number,
	    right: propTypes.number,
	    top: propTypes.number,
	    bottom: propTypes.number
	  }), propTypes.string, propTypes.oneOf([false])]),

	  defaultClassName: propTypes.string,
	  defaultClassNameDragging: propTypes.string,
	  defaultClassNameDragged: propTypes.string,

	  /**
	   * `defaultPosition` specifies the x and y that the dragged item should start at
	   *
	   * Example:
	   *
	   * ```jsx
	   *      let App = React.createClass({
	   *          render: function () {
	   *              return (
	   *                  <Draggable defaultPosition={{x: 25, y: 25}}>
	   *                      <div>I start with transformX: 25px and transformY: 25px;</div>
	   *                  </Draggable>
	   *              );
	   *          }
	   *      });
	   * ```
	   */
	  defaultPosition: propTypes.shape({
	    x: propTypes.number,
	    y: propTypes.number
	  }),

	  /**
	   * `position`, if present, defines the current position of the element.
	   *
	   *  This is similar to how form elements in React work - if no `position` is supplied, the component
	   *  is uncontrolled.
	   *
	   * Example:
	   *
	   * ```jsx
	   *      let App = React.createClass({
	   *          render: function () {
	   *              return (
	   *                  <Draggable position={{x: 25, y: 25}}>
	   *                      <div>I start with transformX: 25px and transformY: 25px;</div>
	   *                  </Draggable>
	   *              );
	   *          }
	   *      });
	   * ```
	   */
	  position: propTypes.shape({
	    x: propTypes.number,
	    y: propTypes.number
	  }),

	  /**
	   * These properties should be defined on the child, not here.
	   */
	  className: dontSetMe,
	  style: dontSetMe,
	  transform: dontSetMe
	});
	Draggable.defaultProps = _extends({}, DraggableCore.defaultProps, {
	  axis: 'both',
	  bounds: false,
	  defaultClassName: 'react-draggable',
	  defaultClassNameDragging: 'react-draggable-dragging',
	  defaultClassNameDragged: 'react-draggable-dragged',
	  defaultPosition: { x: 0, y: 0 },
	  position: null,
	  scale: 1
	});

	// Previous versions of this lib exported <Draggable> as the root export. As to not break
	// them, or TypeScript, we export *both* as the root and as 'default'.
	// See https://github.com/mzabriskie/react-draggable/pull/254
	// and https://github.com/mzabriskie/react-draggable/issues/266
	Draggable.default = Draggable;
	Draggable.DraggableCore = DraggableCore;

	return Draggable;

})));
//# sourceMappingURL=react-draggable.js.map


/***/ }),
/* 342 */
/***/ (function(module, exports, __nested_webpack_require_1760124__) {

"use strict";


exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_1760124__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_1760124__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDraggable = __nested_webpack_require_1760124__(341);

var _cloneElement = __nested_webpack_require_1760124__(597);

var _cloneElement2 = _interopRequireDefault(_cloneElement);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Resizable = function (_React$Component) {
  _inherits(Resizable, _React$Component);

  function Resizable() {
    var _temp, _this, _ret;

    _classCallCheck(this, Resizable);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
      resizing: false,
      width: _this.props.width, height: _this.props.height,
      slackW: 0, slackH: 0
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  Resizable.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    // If parent changes height/width, set that in our state.
    if (!this.state.resizing && (nextProps.width !== this.props.width || nextProps.height !== this.props.height)) {
      this.setState({
        width: nextProps.width,
        height: nextProps.height
      });
    }
  };

  Resizable.prototype.lockAspectRatio = function lockAspectRatio(width, height, aspectRatio) {
    height = width / aspectRatio;
    width = height * aspectRatio;
    return [width, height];
  };

  // If you do this, be careful of constraints


  Resizable.prototype.runConstraints = function runConstraints(width, height) {
    var _ref = [this.props.minConstraints, this.props.maxConstraints],
        min = _ref[0],
        max = _ref[1];


    if (this.props.lockAspectRatio) {
      var ratio = this.state.width / this.state.height;
      height = width / ratio;
      width = height * ratio;
    }

    if (!min && !max) return [width, height];

    var oldW = width,
        oldH = height;

    // Add slack to the values used to calculate bound position. This will ensure that if
    // we start removing slack, the element won't react to it right away until it's been
    // completely removed.

    var _state = this.state,
        slackW = _state.slackW,
        slackH = _state.slackH;

    width += slackW;
    height += slackH;

    if (min) {
      width = Math.max(min[0], width);
      height = Math.max(min[1], height);
    }
    if (max) {
      width = Math.min(max[0], width);
      height = Math.min(max[1], height);
    }

    // If the numbers changed, we must have introduced some slack. Record it for the next iteration.
    slackW += oldW - width;
    slackH += oldH - height;
    if (slackW !== this.state.slackW || slackH !== this.state.slackH) {
      this.setState({ slackW: slackW, slackH: slackH });
    }

    return [width, height];
  };

  /**
   * Wrapper around drag events to provide more useful data.
   *
   * @param  {String} handlerName Handler name to wrap.
   * @return {Function}           Handler function.
   */


  Resizable.prototype.resizeHandler = function resizeHandler(handlerName, axis) {
    var _this2 = this;

    return function (e, _ref2) {
      var node = _ref2.node,
          deltaX = _ref2.deltaX,
          deltaY = _ref2.deltaY;


      // Axis restrictions
      var canDragX = (_this2.props.axis === 'both' || _this2.props.axis === 'x') && ['n', 's'].indexOf(axis) === -1;
      var canDragY = (_this2.props.axis === 'both' || _this2.props.axis === 'y') && ['e', 'w'].indexOf(axis) === -1;

      // reverse delta if using top or left drag handles
      if (canDragX && axis[axis.length - 1] === 'w') {
        deltaX = -deltaX;
      }
      if (canDragY && axis[0] === 'n') {
        deltaY = -deltaY;
      }

      // Update w/h
      var width = _this2.state.width + (canDragX ? deltaX : 0);
      var height = _this2.state.height + (canDragY ? deltaY : 0);

      // Early return if no change
      var widthChanged = width !== _this2.state.width,
          heightChanged = height !== _this2.state.height;
      if (handlerName === 'onResize' && !widthChanged && !heightChanged) return;

      // Set the appropriate state for this handler.
      var _runConstraints = _this2.runConstraints(width, height);

      width = _runConstraints[0];
      height = _runConstraints[1];
      var newState = {};
      if (handlerName === 'onResizeStart') {
        newState.resizing = true;
      } else if (handlerName === 'onResizeStop') {
        newState.resizing = false;
        newState.slackW = newState.slackH = 0;
      } else {
        // Early return if no change after constraints
        if (width === _this2.state.width && height === _this2.state.height) return;
        newState.width = width;
        newState.height = height;
      }

      var hasCb = typeof _this2.props[handlerName] === 'function';
      if (hasCb) {
        // $FlowIgnore isn't refining this correctly to SyntheticEvent
        if (typeof e.persist === 'function') e.persist();
        _this2.setState(newState, function () {
          return _this2.props[handlerName](e, { node: node, size: { width: width, height: height }, handle: axis });
        });
      } else {
        _this2.setState(newState);
      }
    };
  };

  Resizable.prototype.renderResizeHandle = function renderResizeHandle(resizeHandle) {
    var handle = this.props.handle;

    if (handle) {
      if (typeof handle === 'function') {
        return handle(resizeHandle);
      }
      return handle;
    }
    return _react2.default.createElement('span', { className: 'react-resizable-handle react-resizable-handle-' + resizeHandle });
  };

  Resizable.prototype.render = function render() {
    var _this3 = this;

    // eslint-disable-next-line no-unused-vars
    var _props = this.props,
        children = _props.children,
        draggableOpts = _props.draggableOpts,
        width = _props.width,
        height = _props.height,
        handleSize = _props.handleSize,
        lockAspectRatio = _props.lockAspectRatio,
        axis = _props.axis,
        minConstraints = _props.minConstraints,
        maxConstraints = _props.maxConstraints,
        onResize = _props.onResize,
        onResizeStop = _props.onResizeStop,
        onResizeStart = _props.onResizeStart,
        resizeHandles = _props.resizeHandles,
        p = _objectWithoutProperties(_props, ['children', 'draggableOpts', 'width', 'height', 'handleSize', 'lockAspectRatio', 'axis', 'minConstraints', 'maxConstraints', 'onResize', 'onResizeStop', 'onResizeStart', 'resizeHandles']);

    var className = p.className ? p.className + ' react-resizable' : 'react-resizable';

    // What we're doing here is getting the child of this element, and cloning it with this element's props.
    // We are then defining its children as:
    // Its original children (resizable's child's children), and
    // One or more draggable handles.
    return (0, _cloneElement2.default)(children, _extends({}, p, {
      className: className,
      children: [children.props.children, resizeHandles.map(function (h) {
        return _react2.default.createElement(
          _reactDraggable.DraggableCore,
          _extends({}, draggableOpts, {
            key: 'resizableHandle-' + h,
            onStop: _this3.resizeHandler('onResizeStop', h),
            onStart: _this3.resizeHandler('onResizeStart', h),
            onDrag: _this3.resizeHandler('onResize', h)
          }),
          _this3.renderResizeHandle(h)
        );
      })]
    }));
  };

  return Resizable;
}(_react2.default.Component);

Resizable.propTypes = {
  //
  // Required Props
  //

  // Require that one and only one child be present.
  children: _propTypes2.default.element.isRequired,

  // Initial w/h
  width: _propTypes2.default.number.isRequired,
  height: _propTypes2.default.number.isRequired,

  //
  // Optional props
  //

  // Custom resize handle
  handle: _propTypes2.default.element,

  // If you change this, be sure to update your css
  handleSize: _propTypes2.default.array,

  // Defines which resize handles should be rendered (default: 'se')
  // Allows for any combination of:
  // 's' - South handle (bottom-center)
  // 'w' - West handle (left-center)
  // 'e' - East handle (right-center)
  // 'n' - North handle (top-center)
  // 'sw' - Southwest handle (bottom-left)
  // 'nw' - Northwest handle (top-left)
  // 'se' - Southeast handle (bottom-right)
  // 'ne' - Northeast handle (top-center)
  resizeHandles: _propTypes2.default.arrayOf(_propTypes2.default.oneOf(['s', 'w', 'e', 'n', 'sw', 'nw', 'se', 'ne'])),

  // If true, will only allow width/height to move in lockstep
  lockAspectRatio: _propTypes2.default.bool,

  // Restricts resizing to a particular axis (default: 'both')
  // 'both' - allows resizing by width or height
  // 'x' - only allows the width to be changed
  // 'y' - only allows the height to be changed
  // 'none' - disables resizing altogether
  axis: _propTypes2.default.oneOf(['both', 'x', 'y', 'none']),

  // Min/max size
  minConstraints: _propTypes2.default.arrayOf(_propTypes2.default.number),
  maxConstraints: _propTypes2.default.arrayOf(_propTypes2.default.number),

  // Callbacks
  onResizeStop: _propTypes2.default.func,
  onResizeStart: _propTypes2.default.func,
  onResize: _propTypes2.default.func,

  // These will be passed wholesale to react-draggable's DraggableCore
  draggableOpts: _propTypes2.default.object
};
Resizable.defaultProps = {
  handleSize: [20, 20],
  lockAspectRatio: false,
  axis: 'both',
  minConstraints: [20, 20],
  maxConstraints: [Infinity, Infinity],
  resizeHandles: ['se']
};
exports.default = Resizable;

/***/ }),
/* 343 */
/***/ (function(module, exports, __nested_webpack_require_1771464__) {

"use strict";


exports.__esModule = true;
exports.getBreakpointFromWidth = getBreakpointFromWidth;
exports.getColsFromBreakpoint = getColsFromBreakpoint;
exports.findOrGenerateResponsiveLayout = findOrGenerateResponsiveLayout;
exports.sortBreakpoints = sortBreakpoints;

var _utils = __nested_webpack_require_1771464__(133);

/**
 * Given a width, find the highest breakpoint that matches is valid for it (width > breakpoint).
 *
 * @param  {Object} breakpoints Breakpoints object (e.g. {lg: 1200, md: 960, ...})
 * @param  {Number} width Screen width.
 * @return {String}       Highest breakpoint that is less than width.
 */
function getBreakpointFromWidth(breakpoints, width) {
  var sorted = sortBreakpoints(breakpoints);
  var matching = sorted[0];
  for (var i = 1, len = sorted.length; i < len; i++) {
    var breakpointName = sorted[i];
    if (width > breakpoints[breakpointName]) matching = breakpointName;
  }
  return matching;
}

/**
 * Given a breakpoint, get the # of cols set for it.
 * @param  {String} breakpoint Breakpoint name.
 * @param  {Object} cols       Map of breakpoints to cols.
 * @return {Number}            Number of cols.
 */


function getColsFromBreakpoint(breakpoint, cols) {
  if (!cols[breakpoint]) {
    throw new Error("ResponsiveReactGridLayout: `cols` entry for breakpoint " + breakpoint + " is missing!");
  }
  return cols[breakpoint];
}

/**
 * Given existing layouts and a new breakpoint, find or generate a new layout.
 *
 * This finds the layout above the new one and generates from it, if it exists.
 *
 * @param  {Object} layouts     Existing layouts.
 * @param  {Array} breakpoints All breakpoints.
 * @param  {String} breakpoint New breakpoint.
 * @param  {String} breakpoint Last breakpoint (for fallback).
 * @param  {Number} cols       Column count at new breakpoint.
 * @param  {Boolean} verticalCompact Whether or not to compact the layout
 *   vertically.
 * @return {Array}             New layout.
 */
function findOrGenerateResponsiveLayout(layouts, breakpoints, breakpoint, lastBreakpoint, cols, compactType) {
  // If it already exists, just return it.
  if (layouts[breakpoint]) return (0, _utils.cloneLayout)(layouts[breakpoint]);
  // Find or generate the next layout
  var layout = layouts[lastBreakpoint];
  var breakpointsSorted = sortBreakpoints(breakpoints);
  var breakpointsAbove = breakpointsSorted.slice(breakpointsSorted.indexOf(breakpoint));
  for (var i = 0, len = breakpointsAbove.length; i < len; i++) {
    var b = breakpointsAbove[i];
    if (layouts[b]) {
      layout = layouts[b];
      break;
    }
  }
  layout = (0, _utils.cloneLayout)(layout || []); // clone layout so we don't modify existing items
  return (0, _utils.compact)((0, _utils.correctBounds)(layout, { cols: cols }), compactType, cols);
}

/**
 * Given breakpoints, return an array of breakpoints sorted by width. This is usually
 * e.g. ['xxs', 'xs', 'sm', ...]
 *
 * @param  {Object} breakpoints Key/value pair of breakpoint names to widths.
 * @return {Array}              Sorted breakpoints.
 */
function sortBreakpoints(breakpoints) {
  var keys = Object.keys(breakpoints);
  return keys.sort(function (a, b) {
    return breakpoints[a] - breakpoints[b];
  });
}

/***/ }),
/* 344 */
/***/ (function(module, exports, __nested_webpack_require_1774746__) {

module.exports = {
    ResizeSensor: __nested_webpack_require_1774746__(345),
    ElementQueries: __nested_webpack_require_1774746__(601)
};


/***/ }),
/* 345 */
/***/ (function(module, exports, __nested_webpack_require_1774936__) {

"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;

/**
 * Copyright Marc J. Schmidt. See the LICENSE file at the top-level
 * directory of this distribution and at
 * https://github.com/marcj/css-element-queries/blob/master/LICENSE.
 */
(function (root, factory) {
    if (true) {
        !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __nested_webpack_require_1774936__, exports, module)) :
				__WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else {}
}(typeof window !== 'undefined' ? window : this, function () {

    // Make sure it does not throw in a SSR (Server Side Rendering) situation
    if (typeof window === "undefined") {
        return null;
    }
    // Only used for the dirty checking, so the event callback count is limited to max 1 call per fps per sensor.
    // In combination with the event based resize sensor this saves cpu time, because the sensor is too fast and
    // would generate too many unnecessary events.
    var requestAnimationFrame = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        function (fn) {
            return window.setTimeout(fn, 20);
        };

    /**
     * Iterate over each of the provided element(s).
     *
     * @param {HTMLElement|HTMLElement[]} elements
     * @param {Function}                  callback
     */
    function forEachElement(elements, callback){
        var elementsType = Object.prototype.toString.call(elements);
        var isCollectionTyped = ('[object Array]' === elementsType
            || ('[object NodeList]' === elementsType)
            || ('[object HTMLCollection]' === elementsType)
            || ('[object Object]' === elementsType)
            || ('undefined' !== typeof jQuery && elements instanceof jQuery) //jquery
            || ('undefined' !== typeof Elements && elements instanceof Elements) //mootools
        );
        var i = 0, j = elements.length;
        if (isCollectionTyped) {
            for (; i < j; i++) {
                callback(elements[i]);
            }
        } else {
            callback(elements);
        }
    }

    /**
    * Get element size
    * @param {HTMLElement} element
    * @returns {Object} {width, height}
    */
    function getElementSize(element) {
        if (!element.getBoundingClientRect) {
            return {
                width: element.offsetWidth,
                height: element.offsetHeight
            }
        }

        var rect = element.getBoundingClientRect();
        return {
            width: Math.round(rect.width),
            height: Math.round(rect.height)
        }
    }

    /**
     * Class for dimension change detection.
     *
     * @param {Element|Element[]|Elements|jQuery} element
     * @param {Function} callback
     *
     * @constructor
     */
    var ResizeSensor = function(element, callback) {
        /**
         *
         * @constructor
         */
        function EventQueue() {
            var q = [];
            this.add = function(ev) {
                q.push(ev);
            };

            var i, j;
            this.call = function(sizeInfo) {
                for (i = 0, j = q.length; i < j; i++) {
                    q[i].call(this, sizeInfo);
                }
            };

            this.remove = function(ev) {
                var newQueue = [];
                for(i = 0, j = q.length; i < j; i++) {
                    if(q[i] !== ev) newQueue.push(q[i]);
                }
                q = newQueue;
            };

            this.length = function() {
                return q.length;
            }
        }

        /**
         *
         * @param {HTMLElement} element
         * @param {Function}    resized
         */
        function attachResizeEvent(element, resized) {
            if (!element) return;
            if (element.resizedAttached) {
                element.resizedAttached.add(resized);
                return;
            }

            element.resizedAttached = new EventQueue();
            element.resizedAttached.add(resized);

            element.resizeSensor = document.createElement('div');
            element.resizeSensor.dir = 'ltr';
            element.resizeSensor.className = 'resize-sensor';
            var style = 'pointer-events: none; position: absolute; left: 0px; top: 0px; right: 0; bottom: 0; ' +
                'overflow: hidden; z-index: -1; visibility: hidden; max-width: 100%;';
            var styleChild = 'position: absolute; left: 0; top: 0; transition: 0s;';

            element.resizeSensor.style.cssText = style;
            element.resizeSensor.innerHTML =
                '<div class="resize-sensor-expand" style="' + style + '">' +
                    '<div style="' + styleChild + '"></div>' +
                '</div>' +
                '<div class="resize-sensor-shrink" style="' + style + '">' +
                    '<div style="' + styleChild + ' width: 200%; height: 200%"></div>' +
                '</div>';
            element.appendChild(element.resizeSensor);

            var computedStyle = window.getComputedStyle(element);
            var position = computedStyle ? computedStyle.getPropertyValue('position') : null;
            if ('absolute' !== position && 'relative' !== position && 'fixed' !== position) {
                element.style.position = 'relative';
            }

            var expand = element.resizeSensor.childNodes[0];
            var expandChild = expand.childNodes[0];
            var shrink = element.resizeSensor.childNodes[1];
            var dirty, rafId;
            var size = getElementSize(element);
            var lastWidth = size.width;
            var lastHeight = size.height;
            var initialHiddenCheck = true;
            var lastAnimationFrame = 0;

            var resetExpandShrink = function () {
                var width = element.offsetWidth;
                var height = element.offsetHeight;

                expandChild.style.width = (width + 10) + 'px';
                expandChild.style.height = (height + 10) + 'px';

                expand.scrollLeft = width + 10;
                expand.scrollTop = height + 10;

                shrink.scrollLeft = width + 10;
                shrink.scrollTop = height + 10;
            };

            var reset = function() {
                // Check if element is hidden
                if (initialHiddenCheck) {
                    var invisible = element.offsetWidth === 0 && element.offsetHeight === 0;
                    if (invisible) {
                        // Check in next frame
                        if (!lastAnimationFrame){
                            lastAnimationFrame = requestAnimationFrame(function(){
                                lastAnimationFrame = 0;

                                reset();
                            });
                        }

                        return;
                    } else {
                        // Stop checking
                        initialHiddenCheck = false;
                    }
                }

                resetExpandShrink();
            };
            element.resizeSensor.resetSensor = reset;

            var onResized = function() {
                rafId = 0;

                if (!dirty) return;

                lastWidth = size.width;
                lastHeight = size.height;

                if (element.resizedAttached) {
                    element.resizedAttached.call(size);
                }
            };

            var onScroll = function() {
                size = getElementSize(element);
                dirty = size.width !== lastWidth || size.height !== lastHeight;

                if (dirty && !rafId) {
                    rafId = requestAnimationFrame(onResized);
                }

                reset();
            };

            var addEvent = function(el, name, cb) {
                if (el.attachEvent) {
                    el.attachEvent('on' + name, cb);
                } else {
                    el.addEventListener(name, cb);
                }
            };

            addEvent(expand, 'scroll', onScroll);
            addEvent(shrink, 'scroll', onScroll);

            // Fix for custom Elements
            requestAnimationFrame(reset);
        }

        forEachElement(element, function(elem){
            attachResizeEvent(elem, callback);
        });

        this.detach = function(ev) {
            ResizeSensor.detach(element, ev);
        };

        this.reset = function() {
            element.resizeSensor.resetSensor();
        };
    };

    ResizeSensor.reset = function(element) {
        forEachElement(element, function(elem){
            elem.resizeSensor.resetSensor();
        });
    };

    ResizeSensor.detach = function(element, ev) {
        forEachElement(element, function(elem){
            if (!elem) return;
            if(elem.resizedAttached && typeof ev === "function"){
                elem.resizedAttached.remove(ev);
                if(elem.resizedAttached.length()) return;
            }
            if (elem.resizeSensor) {
                if (elem.contains(elem.resizeSensor)) {
                    elem.removeChild(elem.resizeSensor);
                }
                delete elem.resizeSensor;
                delete elem.resizedAttached;
            }
        });
    };

    if (typeof MutationObserver !== "undefined") {
        var observer = new MutationObserver(function (mutations) {
            for (var i in mutations) {
                if (mutations.hasOwnProperty(i)) {
                    var items = mutations[i].addedNodes;
                    for (var j = 0; j < items.length; j++) {
                        if (items[j].resizeSensor) {
                            ResizeSensor.reset(items[j]);
                        }
                    }
                }
            }
        });

        document.addEventListener("DOMContentLoaded", function (event) {
            observer.observe(document.body, {
                childList: true,
                subtree: true,
            });
        });
    }

    return ResizeSensor;

}));


/***/ }),
/* 346 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"center-track":"CenterTrack-module_center-track-3ptRW","center-track-container":"CenterTrack-module_center-track-container-2ELhp"};

/***/ }),
/* 347 */
/***/ (function(module, exports, __nested_webpack_require_1785641__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1785641__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1785641__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1785641__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1785641__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1785641__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1785641__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _HorizontalTiled1DPixiTrack = __nested_webpack_require_1785641__(115);

var _HorizontalTiled1DPixiTrack2 = _interopRequireDefault(_HorizontalTiled1DPixiTrack);

var _configs = __nested_webpack_require_1785641__(11);

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

var IdHorizontal1DTiledPixiTrack = function (_HorizontalTiled1DPix) {
  (0, _inherits3['default'])(IdHorizontal1DTiledPixiTrack, _HorizontalTiled1DPix);

  function IdHorizontal1DTiledPixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, IdHorizontal1DTiledPixiTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (IdHorizontal1DTiledPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(IdHorizontal1DTiledPixiTrack)).call(this, context, options));

    _this.pMain = _this.pMobile;
    return _this;
  }

  (0, _createClass3['default'])(IdHorizontal1DTiledPixiTrack, [{
    key: 'areAllVisibleTilesLoaded',
    value: function () {
      function areAllVisibleTilesLoaded() {
        // we don't need to wait for any tiles to load before
        // drawing
        //
        return true;
      }

      return areAllVisibleTilesLoaded;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        /**
         * Create whatever is needed to draw this tile.
         */

        var graphics = tile.graphics;
        tile.textGraphics = new _configs.GLOBALS.PIXI.Graphics();

        tile.text = new _configs.GLOBALS.PIXI.Text(String(tile.tileData.zoomLevel) + '/' + String(tile.tileData.tilePos.join('/')), {
          fontFamily: 'Arial',
          fontSize: 32,
          fill: 0xff1010,
          align: 'center'
        });

        // tile.text.y = 100;
        tile.textGraphics.addChild(tile.text);

        tile.text.anchor.x = 0.5;
        tile.text.anchor.y = 0.5;

        graphics.addChild(tile.textGraphics);

        this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile) {}

      return destroyTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        (0, _get3['default'])(IdHorizontal1DTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(IdHorizontal1DTiledPixiTrack.prototype), 'drawTile', this).call(this, tile);

        if (!tile.graphics) {
          return;
        }

        var graphics = tile.graphics;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        // the text needs to be scaled down so that it doesn't become huge
        // when we zoom in


        var tSX = 1 / ((this._xScale(1) - this._xScale(0)) / (this._refXScale(1) - this._refXScale(0)));
        // let tSY = 1 / (
        //   (this._yScale(1) - this._yScale(0))
        //   / (this._refYScale(1) - this._refYScale(0))
        // );

        tile.text.scale.x = tSX;
        // tile.text.scale.y = tSY;

        graphics.clear();

        // line needs to be scaled down so that it doesn't become huge

        var tileScaledHeight = this.dimensions[1];
        // fun tile positioning when it's mirrored, except this is just a rectangle
        // that doesn't need to be rotated so it's easy
        var tileScaledWidth = this._refXScale(tileX + tileWidth) - this._refXScale(tileX);

        // add tileScaledHeight / 2 and tileScaledWidth / 2 to center the text on the tile
        tile.textGraphics.position.x = this._refXScale(tileX) + tileScaledWidth / 2;
        tile.textGraphics.position.y = tileScaledHeight / 2;

        var rectX = this._refXScale(tileX);

        // position the graphics
        // graphics.drawRect(rectX, 0, tileScaledWidth, tileScaledHeight);
        graphics.lineStyle(4 * tSX, 0x0000ff, 1);
        graphics.beginFill(0xff700b, 0.4);
        graphics.alpha = 0.5;

        graphics.moveTo(rectX, 0);
        graphics.lineTo(rectX, tileScaledHeight);

        graphics.moveTo(rectX + tileScaledWidth, 0);
        graphics.lineTo(rectX + tileScaledWidth, tileScaledHeight);

        graphics.lineStyle(0, 0x0000ff, 1);
        graphics.drawRect(rectX, 0, tileScaledWidth, tileScaledHeight);
      }

      return drawTile;
    }()
  }]);
  return IdHorizontal1DTiledPixiTrack;
}(_HorizontalTiled1DPixiTrack2['default']);

// Configs


exports['default'] = IdHorizontal1DTiledPixiTrack;

/***/ }),
/* 348 */
/***/ (function(module, exports, __nested_webpack_require_1790992__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1790992__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1790992__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1790992__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1790992__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1790992__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1790992__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _configs = __nested_webpack_require_1790992__(11);

var _VerticalTiled1DPixiTrack = __nested_webpack_require_1790992__(349);

var _VerticalTiled1DPixiTrack2 = _interopRequireDefault(_VerticalTiled1DPixiTrack);

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

// Configs
var IdVertical1DTiledPixiTrack = function (_VerticalTiled1DPixiT) {
  (0, _inherits3['default'])(IdVertical1DTiledPixiTrack, _VerticalTiled1DPixiT);

  function IdVertical1DTiledPixiTrack() {
    (0, _classCallCheck3['default'])(this, IdVertical1DTiledPixiTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (IdVertical1DTiledPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(IdVertical1DTiledPixiTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(IdVertical1DTiledPixiTrack, [{
    key: 'areAllVisibleTilesLoaded',
    value: function () {
      function areAllVisibleTilesLoaded() {
        // we don't need to wait for any tiles to load before
        // drawing
        //
        return true;
      }

      return areAllVisibleTilesLoaded;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        /**
         * Create whatever is needed to draw this tile.
         */

        var graphics = tile.graphics;
        tile.textGraphics = new _configs.GLOBALS.PIXI.Graphics();

        tile.text = new _configs.GLOBALS.PIXI.Text(String(tile.tileData.zoomLevel) + '/' + String(tile.tileData.tilePos.join('/')), {
          fontFamily: 'Arial',
          fontSize: 32,
          fill: 0xff1010,
          align: 'center'
        });

        // tile.text.y = 100;
        tile.textGraphics.addChild(tile.text);

        tile.text.anchor.x = 0.5;
        tile.text.anchor.y = 0.5;

        tile.text.rotation = -Math.PI / 2;

        graphics.addChild(tile.textGraphics);

        this.drawTile(tile, graphics);
      }

      return initTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile, graphics) {}

      return destroyTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        (0, _get3['default'])(IdVertical1DTiledPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(IdVertical1DTiledPixiTrack.prototype), 'drawTile', this).call(this, tile);

        if (!tile.graphics) {
          return;
        }

        var graphics = tile.graphics;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos),
            tileY = _getTilePosAndDimensi.tileY,
            tileHeight = _getTilePosAndDimensi.tileHeight;

        // the text needs to be scaled down so that it doesn't become huge
        // when we zoom in
        // let tSX = 1 / (
        //   (this._xScale(1) - this._xScale(0))
        //   / (this._refXScale(1) - this._refXScale(0))
        // );


        var tSY = 1 / ((this._yScale(1) - this._yScale(0)) / (this._refYScale(1) - this._refYScale(0)));

        // tile.text.scale.x = tSX;
        tile.text.scale.x = tSY;

        // console.log('tSX:', tSX, 'tSY:',tSY);

        graphics.clear();

        graphics.lineStyle(4 * tSY, 0x0000ff, 1);
        graphics.beginFill(0xff700b, 0.4);
        graphics.alpha = 0.5;

        // line needs to be scaled down so that it doesn't become huge

        var tileScaledWidth = this.dimensions[0];
        var tileScaledHeight = this._refYScale(tileY + tileHeight) - this._refYScale(tileY);

        // add tileScaledHeight / 2 and tileScaledWidth / 2 to center the text on the tile
        tile.textGraphics.position.x = tileScaledWidth / 2;
        tile.textGraphics.position.y = this._refYScale(tileY) + tileScaledHeight / 2;

        // position the graphics
        graphics.drawRect(0, this._refYScale(tileY), tileScaledWidth, tileScaledHeight);
      }

      return drawTile;
    }()
  }, {
    key: 'fetchNewTiles',
    value: function () {
      function fetchNewTiles(toFetch) {
        var _this2 = this;

        // no real fetching involved... we just need to display the data
        toFetch.forEach(function (x) {
          var key = x.remoteId;
          var keyParts = key.split('.');

          var data = {
            zoomLevel: keyParts[1],
            tilePos: keyParts.slice(2, keyParts.length).map(function (keyPart) {
              return +keyPart;
            })
          };

          _this2.fetchedTiles[x.tileId] = x;
          _this2.fetchedTiles[x.tileId].tileData = data;

          // since we're not actually fetching remote data, we can easily
          // remove these tiles from the fetching list
          if (_this2.fetching.has(x.remoteId)) {
            _this2.fetching['delete'](x.remoteId);
          }
        });

        this.synchronizeTilesAndGraphics();
      }

      return fetchNewTiles;
    }()
  }]);
  return IdVertical1DTiledPixiTrack;
}(_VerticalTiled1DPixiTrack2['default']);

exports['default'] = IdVertical1DTiledPixiTrack;

/***/ }),
/* 349 */
/***/ (function(module, exports, __nested_webpack_require_1796811__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1796811__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1796811__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1796811__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1796811__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1796811__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1796811__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _Tiled1DPixiTrack2 = __nested_webpack_require_1796811__(255);

var _Tiled1DPixiTrack3 = _interopRequireDefault(_Tiled1DPixiTrack2);

var _services = __nested_webpack_require_1796811__(24);

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

var VerticalTiled1DPixiTrack = function (_Tiled1DPixiTrack) {
  (0, _inherits3['default'])(VerticalTiled1DPixiTrack, _Tiled1DPixiTrack);

  function VerticalTiled1DPixiTrack() {
    (0, _classCallCheck3['default'])(this, VerticalTiled1DPixiTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (VerticalTiled1DPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(VerticalTiled1DPixiTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(VerticalTiled1DPixiTrack, [{
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._yScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);

        var zoomLevel = Math.min(yZoomLevel, this.maxZoom);

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'relevantScale',
    value: function () {
      function relevantScale() {
        /**
         * Which scale should we use for calculating tile positions?
         *
         * Horizontal tracks should use the xScale and vertical tracks
         * should use the yScale
         *
         * This function should be overwritten by HorizontalTiled1DPixiTrack.js
         * and VerticalTiled1DPixiTrack.js
         */
        return this._yScale;
      }

      return relevantScale;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        (0, _get3['default'])(VerticalTiled1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(VerticalTiled1DPixiTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);

        // we only scale along 1 dimension
        var scaleX = 1;
        var scaleY = (newYScale(1) - newYScale(0)) / (this._refYScale(1) - this._refYScale(0));

        var translateX = this.position[0];
        var translateY = newYScale(0) + this.position[1] - this._refYScale(1) * scaleY;

        this.pMain.position.x = translateX;
        this.pMain.position.y = translateY;

        this.pMain.scale.x = scaleX;
        this.pMain.scale.y = scaleY;
      }

      return zoomed;
    }()
  }]);
  return VerticalTiled1DPixiTrack;
}(_Tiled1DPixiTrack3['default']);

exports['default'] = VerticalTiled1DPixiTrack;

/***/ }),
/* 350 */
/***/ (function(module, exports, __nested_webpack_require_1800182__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1800182__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1800182__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1800182__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1800182__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1800182__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1800182__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Axis = __nested_webpack_require_1800182__(316);

var _SVGTrack2 = __nested_webpack_require_1800182__(80);

var _SVGTrack3 = _interopRequireDefault(_SVGTrack2);

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

var TopAxisTrack = function (_SVGTrack) {
  (0, _inherits3['default'])(TopAxisTrack, _SVGTrack);

  function TopAxisTrack(context, options) {
    (0, _classCallCheck3['default'])(this, TopAxisTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (TopAxisTrack.__proto__ || (0, _getPrototypeOf2['default'])(TopAxisTrack)).call(this, context, options));

    _this.axis = (0, _d3Axis.axisTop)(_this._xScale);
    _this.gAxis = _this.gMain.append('g');

    // to make sure that the isWaitingOnTiles functions
    // return immediately
    _this.tilesetInfo = true;
    return _this;
  }

  (0, _createClass3['default'])(TopAxisTrack, [{
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(TopAxisTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(TopAxisTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        // we generally want to be able display ticks for values in the billions
        // which means that we need extra spacing in our ticks
        this.axis.ticks(Math.ceil(this.dimensions[0] / 150));

        this.gAxis.attr('transform', 'translate(0,' + String(newDimensions[1]) + ')');
      }

      return setDimensions;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        this.axis.scale(this._xScale);

        this.gAxis.call(this.axis);

        return this;
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        (0, _get3['default'])(TopAxisTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(TopAxisTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }]);
  return TopAxisTrack;
}(_SVGTrack3['default']);

exports['default'] = TopAxisTrack;

/***/ }),
/* 351 */
/***/ (function(module, exports, __nested_webpack_require_1803132__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1803132__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1803132__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1803132__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1803132__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1803132__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1803132__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Axis = __nested_webpack_require_1803132__(316);

var _SVGTrack2 = __nested_webpack_require_1803132__(80);

var _SVGTrack3 = _interopRequireDefault(_SVGTrack2);

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

var LeftAxisTrack = function (_SVGTrack) {
  (0, _inherits3['default'])(LeftAxisTrack, _SVGTrack);

  function LeftAxisTrack(context, options) {
    (0, _classCallCheck3['default'])(this, LeftAxisTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (LeftAxisTrack.__proto__ || (0, _getPrototypeOf2['default'])(LeftAxisTrack)).call(this, context, options));

    _this.axis = (0, _d3Axis.axisLeft)(_this._yScale);
    _this.gAxis = _this.gMain.append('g');

    // to make sure that the isWaitingOnTiles functions
    // return immediately
    _this.tilesetInfo = true;
    return _this;
  }

  (0, _createClass3['default'])(LeftAxisTrack, [{
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(LeftAxisTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(LeftAxisTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        // match the spacing of the TopAxisTrack ticks
        this.axis.ticks(Math.ceil(this.dimensions[1] / 150));
        this.gAxis.attr('transform', 'translate(' + String(newDimensions[0]) + ',0)');
      }

      return setDimensions;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        this.axis.scale(this._yScale);
        this.gAxis.call(this.axis);

        return this;
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        (0, _get3['default'])(LeftAxisTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(LeftAxisTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }]);
  return LeftAxisTrack;
}(_SVGTrack3['default']);

exports['default'] = LeftAxisTrack;

/***/ }),
/* 352 */
/***/ (function(module, exports, __nested_webpack_require_1806005__) {

"use strict";


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

var _typeof2 = __nested_webpack_require_1806005__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

var _toConsumableArray2 = __nested_webpack_require_1806005__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _maxSafeInteger = __nested_webpack_require_1806005__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _isNan = __nested_webpack_require_1806005__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _keys = __nested_webpack_require_1806005__(18);

var _keys2 = _interopRequireDefault(_keys);

var _minSafeInteger = __nested_webpack_require_1806005__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

var _slicedToArray2 = __nested_webpack_require_1806005__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _values = __nested_webpack_require_1806005__(37);

var _values2 = _interopRequireDefault(_values);

var _getIterator2 = __nested_webpack_require_1806005__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _extends2 = __nested_webpack_require_1806005__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _getPrototypeOf = __nested_webpack_require_1806005__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1806005__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1806005__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1806005__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1806005__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1806005__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _boxIntersect = __nested_webpack_require_1806005__(180);

var _boxIntersect2 = _interopRequireDefault(_boxIntersect);

var _d3Array = __nested_webpack_require_1806005__(8);

var _d3Scale = __nested_webpack_require_1806005__(28);

var _robustPointInPolygon = __nested_webpack_require_1806005__(355);

var _robustPointInPolygon2 = _interopRequireDefault(_robustPointInPolygon);

var _d3Zoom = __nested_webpack_require_1806005__(157);

var _HorizontalTiled1DPixiTrack = __nested_webpack_require_1806005__(115);

var _HorizontalTiled1DPixiTrack2 = _interopRequireDefault(_HorizontalTiled1DPixiTrack);

var _services = __nested_webpack_require_1806005__(24);

var _utils = __nested_webpack_require_1806005__(10);

var _configs = __nested_webpack_require_1806005__(11);

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

// Utils
var GENE_RECT_HEIGHT = 16;

// Configs


// Services

var MAX_TEXTS = 50;
var MAX_TILE_ENTRIES = 5000;
var STAGGERED_OFFSET = 5;
var FONT_SIZE = 14;
// the label text should have a white outline so that it's more
// visible against a similar colored background
var TEXT_STYLE = {
  fontSize: FONT_SIZE + 'px',
  fontFamily: 'Arial',
  stroke: 'white',
  strokeThickness: 2,
  fontWeight: 400,
  dropShadow: true,
  dropShadowColor: 'white',
  dropShadowDistance: 0,
  dropShadowBlur: 2
};

var BedLikeTrack = function (_HorizontalTiled1DPix) {
  (0, _inherits3['default'])(BedLikeTrack, _HorizontalTiled1DPix);

  function BedLikeTrack(context, options) {
    (0, _classCallCheck3['default'])(this, BedLikeTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (BedLikeTrack.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack)).call(this, context, options));

    _this.valueScaleTransform = _d3Zoom.zoomIdentity;
    return _this;
  }

  /** Factor out some initialization code for the track. This is
   necessary because we can now load tiles synchronously and so
   we have to check if the track is initialized in renderTiles
   and not in the constructor */


  (0, _createClass3['default'])(BedLikeTrack, [{
    key: 'initialize',
    value: function () {
      function initialize() {
        if (this.initialized) return;

        var _ref = [1, 1, 0];
        this.prevK = _ref[0];
        this.vertK = _ref[1];
        this.vertY = _ref[2];


        if (!this.drawnRects) {
          this.drawnRects = {};
        }

        if (!this.colorScale) {
          if (this.options.colorRange) {
            this.colorScale = (0, _utils.colorDomainToRgbaArray)(this.options.colorRange);
          } else {
            this.colorScale = _configs.HEATED_OBJECT_MAP;
          }
        }

        this.initialized = true;
      }

      return initialize;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        var _this2 = this;

        // create texts
        tile.texts = {};

        tile.rectGraphics = new _configs.GLOBALS.PIXI.Graphics();
        tile.textGraphics = new _configs.GLOBALS.PIXI.Graphics();

        tile.graphics.addChild(tile.rectGraphics);
        tile.graphics.addChild(tile.textGraphics);

        var plusStrandRows = [];
        var minusStrandRows = [];

        if (tile.tileData && tile.tileData.length) {
          tile.tileData.sort(function (a, b) {
            return b.importance - a.importance;
          });
          // tile.tileData = tile.tileData.slice(0, MAX_TILE_ENTRIES);

          if (!this.options || !this.options.valueColumn) {
            // no value column so we can break entries up into separate
            // plus and minus strand segments
            var segments = tile.tileData.map(function (x) {
              var chrOffset = +x.chrOffset;

              return {
                from: +x.fields[1] + chrOffset,
                to: +x.fields[2] + chrOffset,
                value: x,
                text: x.fields[3],
                strand: x.fields.length >= 6 && x.fields[5] === '-' ? '-' : '+'
              };
            });

            plusStrandRows = (0, _utils.segmentsToRows)(segments.filter(function (x) {
              return x.strand === '+';
            }));
            minusStrandRows = (0, _utils.segmentsToRows)(segments.filter(function (x) {
              return x.strand === '-';
            }));
          } else {
            plusStrandRows = [tile.tileData.map(function (x) {
              return { value: x };
            })];
          }

          tile.plusStrandRows = plusStrandRows;
          tile.minusStrandRows = minusStrandRows;

          if (this.options.showTexts) {
            tile.tileData.forEach(function (td, i) {
              var geneInfo = td.fields;

              // A random importance helps with selective hiding
              // of overlapping texts
              if (!td.importance) {
                td.importance = Math.random();
              }
              tile.textWidths = {};
              tile.textHeights = {};

              // don't draw too many texts so they don't bog down the frame rate
              if (i >= (+_this2.options.maxTexts || MAX_TEXTS)) {
                return;
              }

              // geneInfo[3] is the gene symbol
              var text = new _configs.GLOBALS.PIXI.Text(geneInfo[3], (0, _extends3['default'])({}, TEXT_STYLE, {
                fontSize: +_this2.options.fontSize || TEXT_STYLE.fontSize
              }));
              if (_this2.flipText) {
                text.scale.x = -1;
              }

              text.anchor.x = 0.5;
              text.anchor.y = 0.5;

              tile.texts[td.uid] = text; // index by geneName

              tile.textGraphics.addChild(text);
            });
          }
        }

        tile.initialized = true;
      }

      return initTile;
    }()

    /**
     * Remove the tile's rectangles from the list of drawnRects so that they
     * can be drawn again.
     */

  }, {
    key: 'removeTileRects',
    value: function () {
      function removeTileRects(tile) {
        var _this3 = this;

        var zoomLevel = +tile.tileId.split('.')[0];
        tile.rectGraphics.clear();
        tile.rendered = false;

        if (tile.tileData && tile.tileData.length) {
          tile.tileData.forEach(function (td, i) {
            if (_this3.drawnRects[zoomLevel] && _this3.drawnRects[zoomLevel][td.uid]) {
              if (_this3.drawnRects[zoomLevel][td.uid][2] === tile.tileId) {
                // this was the tile that drew that rectangle
                delete _this3.drawnRects[zoomLevel][td.uid];
              }
            }
          });
        }
      }

      return removeTileRects;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile) {
        // remove texts
        this.removeTileRects(tile);

        tile.graphics.removeChild(tile.textGraphics);
        tile.graphics.removeChild(tile.rectGraphics);
      }

      return destroyTile;
    }()
  }, {
    key: 'removeTiles',
    value: function () {
      function removeTiles(toRemoveIds) {
        (0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'removeTiles', this).call(this, toRemoveIds);

        // Pete: we're going to rerender after destroying tiles to make sure
        // any rectangles that were listed under 'drawnRects' don't get
        // ignored
        // Fritz: this line is causing unnecessary rerenderings. Seems to work fine
        // without rerendering anyway, so I disabled it.
        // if (toRemoveIds.length > 0) this.rerender(this.options);
      }

      return removeTiles;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        if (this.options && this.options.valueColumn) {
          // there might no be a value scale if no valueColumn was specified
          if (this.valueScale) this.drawAxis(this.valueScale);
        }
      }

      return drawTile;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        (0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'rerender', this).call(this, options, force);

        // this will get instantiated if a value column is specified
        this.valueScale = null;
        this.drawnRects = {};

        if (this.options.colorRange) {
          this.colorScale = (0, _utils.colorDomainToRgbaArray)(this.options.colorRange);
        } else {
          this.colorScale = _configs.HEATED_OBJECT_MAP;
        }

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tile = _step.value;

            this.destroyTile(tile);
            this.initTile(tile);
            this.renderTile(tile);
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return rerender;
    }()
  }, {
    key: 'updateTile',
    value: function () {
      function updateTile(tile) {
        // this.destroyTile(tile);
        if (this.areAllVisibleTilesLoaded()) {
          // this.destroyTile(tile);
          // this.initTile(tile);
          this.renderTile(tile);
        }
      }

      return updateTile;
    }()

    /**
     * Use this only when there's one row
     *
     * @return {[type]} [description]
     */

  }, {
    key: 'allVisibleRects',
    value: function () {
      function allVisibleRects() {
        var allRects = {};

        (0, _values2['default'])(this.fetchedTiles).forEach(function (x) {
          if (!x.plusStrandRows) return;

          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = undefined;

          try {
            for (var _iterator2 = (0, _getIterator3['default'])(x.plusStrandRows[0]), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              var row = _step2.value;

              if (!allRects[row.value.uid]) {
                allRects[row.value.uid] = row;
              }
            }
          } catch (err) {
            _didIteratorError2 = true;
            _iteratorError2 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2['return']) {
                _iterator2['return']();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }
        });

        var sortedRows = (0, _values2['default'])(allRects).sort(function (a, b) {
          return a.from - b.from;
        });

        var startPos = 0;
        var startStaggered = 0;

        // find if any values have staggeredStartPosition set
        for (var i = 0; i < sortedRows.length; i++) {
          if (sortedRows[i].staggeredStartPosition !== undefined) {
            startPos = i;
            startStaggered = sortedRows[i].staggeredStartPosition;
            break;
          }
        }

        for (var _i = startPos; _i < sortedRows.length; _i++) {
          sortedRows[_i].staggeredStartPosition = (startStaggered + _i - startPos) % 2;
        }

        for (var _i2 = startPos; _i2 >= 0 && sortedRows.length; _i2--) {
          sortedRows[_i2].staggeredStartPosition = (startStaggered + startPos - _i2) % 2;
        }

        return allRects;
      }

      return allVisibleRects;
    }()
  }, {
    key: 'drawSegmentStyle',
    value: function () {
      function drawSegmentStyle(tile, xStartPos, xEndPos, rectY, rectHeight, strand) {
        var hw = 0.1; // half width of the line

        var centerY = rectY + rectHeight / 2;

        var poly = [xStartPos, rectY, // upper left
        xStartPos + 2 * hw, rectY, // upper right
        xStartPos + 2 * hw, centerY - hw, xEndPos - 2 * hw, centerY - hw, xEndPos - 2 * hw, rectY, xEndPos, rectY, xEndPos, rectY + rectHeight, xEndPos - 2 * hw, rectY + rectHeight, xEndPos - 2 * hw, centerY + hw, xStartPos + 2 * hw, centerY + hw, xStartPos + 2 * hw, rectY + rectHeight, xStartPos, rectY + rectHeight];

        tile.rectGraphics.drawPolygon(poly);
        return poly;
      }

      return drawSegmentStyle;
    }()
  }, {
    key: 'drawPoly',
    value: function () {
      function drawPoly(tile, xStartPos, xEndPos, rectY, rectHeight, strand) {
        var drawnPoly = null;

        if (this.options.annotationStyle === 'segment') {
          return this.drawSegmentStyle(tile, xStartPos, xEndPos, rectY, rectHeight, strand);
        }

        if ((strand === '+' || strand === '-') && xEndPos - xStartPos < GENE_RECT_HEIGHT / 2) {
          // only draw if it's not too wide
          drawnPoly = [xStartPos, rectY, // top
          xStartPos + rectHeight / 2, rectY + rectHeight / 2, // right point
          xStartPos, rectY + rectHeight];

          if (strand === '+') {
            tile.rectGraphics.drawPolygon(drawnPoly);
          } else {
            drawnPoly = [xEndPos, rectY, // top
            xEndPos - rectHeight / 2, rectY + rectHeight / 2, // left point
            xEndPos, rectY + rectHeight];
            tile.rectGraphics.drawPolygon(drawnPoly);
          }
        } else {
          if (strand === '+') {
            drawnPoly = [xStartPos, rectY, // left top
            xEndPos - rectHeight / 2, rectY, // right top
            xEndPos, rectY + rectHeight / 2, xEndPos - rectHeight / 2, rectY + rectHeight, // right bottom
            xStartPos, rectY + rectHeight];
          } else if (strand === '-') {
            drawnPoly = [xStartPos + rectHeight / 2, rectY, // left top
            xEndPos, rectY, // right top
            xEndPos, rectY + rectHeight, // right bottom
            xStartPos + rectHeight / 2, rectY + rectHeight, // left bottom
            xStartPos, rectY + rectHeight / 2];
          } else {
            drawnPoly = [xStartPos, rectY, // left top
            xEndPos, rectY, // right top
            xEndPos, rectY + rectHeight, // right bottom
            xStartPos, rectY + rectHeight];
          }

          tile.rectGraphics.drawPolygon(drawnPoly);
        }

        return drawnPoly;
      }

      return drawPoly;
    }()

    /** The value scale is used to arrange annotations vertically
        based on a value */

  }, {
    key: 'setValueScale',
    value: function () {
      function setValueScale() {
        this.valueScale = null;

        if (this.options && this.options.valueColumn) {
          /**
           * These intervals come with some y-value that we want to plot
           */

          var min = this.options.colorEncodingRange ? +this.options.colorEncodingRange[0] : this.minVisibleValueInTiles(+this.options.valueColumn);
          var max = this.options.colorEncodingRange ? +this.options.colorEncodingRange[1] : this.maxVisibleValueInTiles(+this.options.valueColumn);

          if (this.options.valueColumn) {
            var _makeValueScale = this.makeValueScale(min, this.calculateMedianVisibleValue(+this.options.valueColumn), max);

            var _makeValueScale2 = (0, _slicedToArray3['default'])(_makeValueScale, 1);

            this.valueScale = _makeValueScale2[0];
          }
        }
      }

      return setValueScale;
    }()

    /** The color value scale is used to map some value to a coloring */

  }, {
    key: 'setColorValueScale',
    value: function () {
      function setColorValueScale() {
        this.colorValueScale = null;

        if (this.options && this.options.colorEncoding && this.options.colorEncoding !== 'itemRgb') {
          var min = this.options.colorEncodingRange ? +this.options.colorEncodingRange[0] : this.minVisibleValueInTiles(+this.options.colorEncoding);
          var max = this.options.colorEncodingRange ? +this.options.colorEncodingRange[1] : this.maxVisibleValueInTiles(+this.options.colorEncoding);

          this.colorValueScale = (0, _d3Scale.scaleLinear)().domain([min, max]).range([0, 255]);
        }
      }

      return setColorValueScale;
    }()
  }, {
    key: 'renderRows',
    value: function () {
      function renderRows(tile, rows, maxRows, startY, endY, fill) {
        var zoomLevel = +tile.tileId.split('.')[0];
        var maxValue = _minSafeInteger2['default'];

        this.initialize();

        var rowScale = (0, _d3Scale.scaleBand)().domain((0, _d3Array.range)(maxRows)).range([startY, endY]).paddingInner(0.3);

        this.allVisibleRects();
        var allRects = null;

        if (this.options.staggered) {
          allRects = this.allVisibleRects();
        }

        for (var j = 0; j < rows.length; j++) {
          for (var i = 0; i < rows[j].length; i++) {
            // rendered += 1;
            var td = rows[j][i].value;
            var geneInfo = td.fields;

            // the returned positions are chromosome-based and they need to
            // be converted to genome-based
            var chrOffset = +td.chrOffset;
            var txStart = +geneInfo[1] + chrOffset;
            var txEnd = +geneInfo[2] + chrOffset;
            var txMiddle = (txStart + txEnd) / 2;
            var yMiddle = rowScale(j) + rowScale.step() / 2;

            var rectHeight = this.options.annotationHeight || GENE_RECT_HEIGHT;

            if (rectHeight === 'scaled') {
              rectHeight = rowScale.bandwidth();

              if (this.options.maxAnnotationHeight) {
                rectHeight = Math.min(rectHeight, +this.options.maxAnnotationHeight);
              }
            }

            if (this.options && this.options.colorEncoding === 'itemRgb' && td.fields[8]) {
              var parts = td.fields[8].split(',');

              if (parts.length === 3) {
                var color = 'rgb(' + String(td.fields[8]) + ')';

                fill = color;
              }
            } else if (this.colorValueScale) {
              var rgb = (0, _utils.valueToColor)(this.colorValueScale, this.colorScale, 0, // pseudocounts
              -Number.MIN_VALUE)(+geneInfo[+this.options.colorEncoding - 1]);
              fill = 'rgba(' + String(rgb.join(',')) + ')';
            }

            if (this.valueScale) {
              var value = +geneInfo[+this.options.valueColumn - 1];
              if (value > maxValue) {
                maxValue = value;
              }

              yMiddle = this.valueScale(value);
            }

            var opacity = this.options.fillOpacity || 0.3;
            tile.rectGraphics.lineStyle(1, (0, _utils.colorToHex)(fill), opacity);
            tile.rectGraphics.beginFill((0, _utils.colorToHex)(fill), opacity);

            var rectY = yMiddle - rectHeight / 2;
            var xStartPos = this._xScale(txStart);
            var xEndPos = this._xScale(txEnd);

            if (this.options.staggered) {
              var rect = allRects[td.uid];

              if (rect.staggeredStartPosition) {
                rectY -= STAGGERED_OFFSET / 2;
              } else {
                rectY += STAGGERED_OFFSET / 2;
              }
            }

            var alreadyDrawn = true;

            // don't draw anything that has already been drawn
            if (!(zoomLevel in this.drawnRects && td.uid in this.drawnRects[zoomLevel])) {
              alreadyDrawn = false;

              if (!this.drawnRects[zoomLevel]) this.drawnRects[zoomLevel] = {};

              var drawnPoly = this.drawPoly(tile, xStartPos, xEndPos, rectY * this.prevK, rectHeight * this.prevK, geneInfo[5]);

              this.drawnRects[zoomLevel][td.uid] = [drawnPoly, {
                start: txStart,
                end: txEnd,
                value: td,
                tile: tile,
                fill: fill
              }, tile.tileId];
            }

            if (!this.options.showTexts) continue;

            // tile probably hasn't been initialized yet
            if (!tile.texts) return;

            // don't draw too many texts so they don't bog down the frame rate
            if (i >= (+this.options.maxTexts || MAX_TEXTS)) continue;

            if (!tile.texts[td.uid]) continue;

            var text = tile.texts[td.uid];

            text.position.x = this._xScale(txMiddle);
            text.position.y = rectY + rectHeight / 2;
            text.nominalY = rectY + rectHeight / 2;

            if (alreadyDrawn) {
              text.alreadyDrawn = true;
            }

            var fontColor = this.options.fontColor !== undefined ? (0, _utils.colorToHex)(this.options.fontColor) : fill;

            text.style = (0, _extends3['default'])({}, TEXT_STYLE, {
              fill: fontColor,
              fontSize: +this.options.fontSize || TEXT_STYLE.fontSize
            });

            if (!(geneInfo[3] in tile.textWidths)) {
              text.updateTransform();
              var textWidth = text.getBounds().width;
              var textHeight = text.getBounds().height;

              // the text size adjustment compensates for the extra
              // size that the show gives it
              var TEXT_SIZE_ADJUSTMENT = 5;

              tile.textWidths[geneInfo[3]] = textWidth;
              tile.textHeights[geneInfo[3]] = textHeight - TEXT_SIZE_ADJUSTMENT;
            }
          }
        }
      }

      return renderRows;
    }()
  }, {
    key: 'renderTile',
    value: function () {
      function renderTile(tile) {
        var maxPlusRows = tile.plusStrandRows ? tile.plusStrandRows.length : 1;
        var maxMinusRows = tile.minusStrandRows ? tile.minusStrandRows.length : 1;

        // const visibleAndFetchedTiles = this.visibleAndFetchedTiles();

        // if (!visibleAndFetchedTiles.length) return;

        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = undefined;

        try {
          for (var _iterator3 = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
            var otherTile = _step3.value;

            if (!otherTile.initialized) return;
            if (!otherTile.plusStrandRows && !otherTile.minusStrandRows) continue;

            maxPlusRows = Math.max(otherTile.plusStrandRows.length, maxPlusRows);
            maxMinusRows = Math.max(otherTile.minusStrandRows.length, maxMinusRows);
          }

          // store the scale at while the tile was drawn at so that
          // we only resize it when redrawing
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3['return']) {
              _iterator3['return']();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }

        if (tile.rendered) {
          this.removeTileRects(tile);
        }

        tile.drawnAtScale = this._xScale.copy();
        tile.rendered = true;

        // configure vertical positioning of annotations if
        // this.options.valueColumn is set
        this.setValueScale();

        // configure coloring of annotations if
        // this.options.colorEncoding is set
        this.setColorValueScale();

        if (tile.tileData && tile.tileData.length) {
          var fill = this.options.plusStrandColor || this.options.fillColor || 'blue';
          var minusStrandFill = this.options.minusStrandColor || this.options.fillColor || 'purple';

          var MIDDLE_SPACE = 0;
          var plusHeight = 0;

          if (this.options.separatePlusMinusStrands) {
            plusHeight = maxPlusRows * this.dimensions[1] / (maxPlusRows + maxMinusRows) - MIDDLE_SPACE / 2;
          } else {
            plusHeight = this.dimensions[1];
          }

          this.renderRows(tile, tile.plusStrandRows, maxPlusRows, 0, plusHeight, fill);
          this.renderRows(tile, tile.minusStrandRows, maxMinusRows, this.options.separatePlusMinusStrands ? plusHeight + MIDDLE_SPACE / 2 : 0, this.dimensions[1], minusStrandFill);
        }

        _utils.trackUtils.stretchRects(this, [function (x) {
          return x.rectGraphics;
        }]);
      }

      return renderTile;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        // offset by 2 because 1D tiles are more dense than 2D tiles
        // 1024 points per tile vs 256 for 2D tiles
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);

        var zoomLevel = Math.min(xZoomLevel, this.maxZoom);
        zoomLevel = Math.max(zoomLevel, 0);

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'minVisibleValueInTiles',
    value: function () {
      function minVisibleValueInTiles(valueColumn) {
        var _this4 = this;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var min = Math.min.apply(null, visibleAndFetchedIds.map(function (x) {
          return _this4.fetchedTiles[x];
        }).filter(function (x) {
          return x.tileData && x.tileData.length;
        }).map(function (x) {
          return Math.min.apply(null, x.tileData.sort(function (a, b) {
            return b.importance - a.importance;
          }).slice(0, MAX_TILE_ENTRIES).map(function (y) {
            return +y.fields[valueColumn - 1];
          }).filter(function (y) {
            return !(0, _isNan2['default'])(y);
          }));
        }));

        // if there's no data, use null
        if (min === _maxSafeInteger2['default']) {
          min = null;
        }

        return min;
      }

      return minVisibleValueInTiles;
    }()
  }, {
    key: 'maxVisibleValueInTiles',
    value: function () {
      function maxVisibleValueInTiles(valueColumn) {
        var _this5 = this;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var max = Math.max.apply(null, visibleAndFetchedIds.map(function (x) {
          return _this5.fetchedTiles[x];
        }).filter(function (x) {
          return x.tileData && x.tileData.length;
        }).map(function (x) {
          return Math.max.apply(null, x.tileData.sort(function (a, b) {
            return b.importance - a.importance;
          }).slice(0, MAX_TILE_ENTRIES).map(function (y) {
            return +y.fields[valueColumn - 1];
          }).filter(function (y) {
            return !(0, _isNan2['default'])(y);
          }));
        }));

        // if there's no data, use null
        if (max === _minSafeInteger2['default']) {
          max = null;
        }

        return max;
      }

      return maxVisibleValueInTiles;
    }()
  }, {
    key: 'calculateMedianVisibleValue',
    value: function () {
      function calculateMedianVisibleValue(valueColumn) {
        var _ref2,
            _this6 = this;

        if (this.areAllVisibleTilesLoaded()) {
          this.allTilesLoaded();
        }

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var values = (_ref2 = []).concat.apply(_ref2, (0, _toConsumableArray3['default'])(visibleAndFetchedIds.map(function (x) {
          return _this6.fetchedTiles[x];
        }).filter(function (x) {
          return x.tileData && x.tileData.length;
        }).map(function (x) {
          return x.tileData.sort(function (a, b) {
            return b.importance - a.importance;
          }).slice(0, MAX_TILE_ENTRIES).map(function (y) {
            return +y.fields[valueColumn - 1];
          });
        }))).filter(function (x) {
          return x > 0;
        });

        this.medianVisibleValue = (0, _d3Array.median)(values);
      }

      return calculateMedianVisibleValue;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var _this7 = this;

        (0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'draw', this).call(this);

        this.allTexts = [];
        this.allBoxes = [];

        var _loop = function () {
          function _loop(fetchedTileId) {
            var tile = _this7.fetchedTiles[fetchedTileId];

            // these values control vertical scaling and they
            // need to be set in the draw method otherwise when
            // the window is resized, the zoomedY method won't
            // be called
            tile.rectGraphics.scale.y = _this7.vertK;
            tile.rectGraphics.position.y = _this7.vertY;

            // hasn't been rendered yet
            if (!tile.drawnAtScale) {
              return {
                v: void 0
              };
            }

            _utils.trackUtils.stretchRects(_this7, [function (x) {
              return x.rectGraphics;
            }]);

            // move the texts

            var parentInFetched = _this7.parentInFetched(tile);

            if (!tile.initialized) {
              return 'continue';
            }

            if (tile.tileData && tile.tileData.length) {
              tile.tileData.forEach(function (td) {
                if (!tile.texts) {
                  // tile probably hasn't been initialized yet
                  return;
                }

                var geneInfo = td.fields;
                var geneName = geneInfo[3];
                var text = tile.texts[td.uid];

                if (!text) {
                  return;
                }

                var chrOffset = +td.chrOffset;
                var txStart = +geneInfo[1] + chrOffset;
                var txEnd = +geneInfo[2] + chrOffset;
                var txMiddle = (txStart + txEnd) / 2;

                text.position.x = _this7._xScale(txMiddle);
                text.position.y = text.nominalY * (_this7.vertK * _this7.prevK) + _this7.vertY;

                if (!parentInFetched && !text.alreadyDrawn) {
                  text.visible = true;
                  // TODO, change the line below to true if texts are desired in the future
                  // text.visible = false;
                  var TEXT_MARGIN = 3;
                  _this7.allBoxes.push([text.position.x - TEXT_MARGIN, text.position.y - tile.textHeights[geneInfo[3]] / 2, text.position.x + tile.textWidths[geneInfo[3]] + TEXT_MARGIN, text.position.y + tile.textHeights[geneInfo[3]] / 2]);
                  _this7.allTexts.push({
                    importance: td.importance,
                    text: text,
                    caption: geneName,
                    strand: geneInfo[5]
                  });
                } else {
                  text.visible = false;
                }
              });
            }
          }

          return _loop;
        }();

        for (var fetchedTileId in this.fetchedTiles) {
          var _ret = _loop(fetchedTileId);

          switch (_ret) {
            case 'continue':
              continue;

            default:
              if ((typeof _ret === 'undefined' ? 'undefined' : (0, _typeof3['default'])(_ret)) === "object") return _ret.v;
          }
        }

        this.hideOverlaps(this.allBoxes, this.allTexts);
      }

      return draw;
    }()
  }, {
    key: 'hideOverlaps',
    value: function () {
      function hideOverlaps(allBoxes, allTexts) {
        // Calculate overlaps from the bounding boxes of the texts

        (0, _boxIntersect2['default'])(allBoxes, function (i, j) {
          if (allTexts[i].importance > allTexts[j].importance) {
            if (allTexts[i].text.visible) {
              allTexts[j].text.visible = false;
            }
          } else if (allTexts[j].text.visible) {
            allTexts[i].text.visible = false;
          }
        });
      }

      return hideOverlaps;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'setPosition', this).call(this, newPosition);

        var _position = (0, _slicedToArray3['default'])(this.position, 2);

        this.pMain.position.x = _position[0];
        this.pMain.position.y = _position[1];
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'setDimensions', this).call(this, newDimensions);
      }

      return setDimensions;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTiles();

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var _this8 = this;

        var track = null;
        var base = null;

        if ((0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(BedLikeTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(BedLikeTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);
        var rectOutput = document.createElement('g');
        var textOutput = document.createElement('g');

        output.appendChild(rectOutput);
        output.appendChild(textOutput);

        var _loop2 = function () {
          function _loop2(_tile) {
            if (!_tile.tileData.length) {
              return 'continue';
            }

            _tile.tileData.forEach(function (td) {
              var zoomLevel = +_tile.tileId.split('.')[0];

              var gTile = document.createElement('g');
              gTile.setAttribute('transform', 'translate(' + String(_tile.rectGraphics.position.x) + ',' + String(_tile.rectGraphics.position.y) + ')scale(' + String(_tile.rectGraphics.scale.x) + ',' + String(_tile.rectGraphics.scale.y) + ')');
              rectOutput.appendChild(gTile);

              if (_this8.drawnRects[zoomLevel] && td.uid in _this8.drawnRects[zoomLevel]) {
                var rect = _this8.drawnRects[zoomLevel][td.uid][0];
                var r = document.createElement('path');
                var d = 'M ' + String(rect[0]) + ' ' + String(rect[1]);

                for (var i = 2; i < rect.length; i += 2) {
                  d += ' L ' + String(rect[i]) + ' ' + String(rect[i + 1]);
                }

                var fill = _this8.drawnRects[zoomLevel][td.uid][1].fill;
                var fontColor = _this8.options.fontColor !== undefined ? (0, _utils.colorToHex)(_this8.options.fontColor) : fill;

                r.setAttribute('d', d);
                r.setAttribute('fill', fill);
                r.setAttribute('opacity', 0.3);

                r.style.stroke = fill;
                r.style.strokeWidth = '1px';

                gTile.appendChild(r);

                if (_tile.texts[td.uid]) {
                  var text = _tile.texts[td.uid];

                  if (!text.visible) {
                    return;
                  }

                  var g = document.createElement('g');
                  var t = document.createElement('text');

                  textOutput.appendChild(g);
                  g.appendChild(t);
                  g.setAttribute('transform', 'translate(' + String(text.x) + ',' + String(text.y) + ')scale(' + String(text.scale.x) + ',1)');

                  t.setAttribute('text-anchor', 'middle');
                  t.setAttribute('font-family', TEXT_STYLE.fontFamily);
                  t.setAttribute('font-size', +_this8.options.fontSize || TEXT_STYLE.fontSize);
                  t.setAttribute('font-weight', 'bold');
                  t.setAttribute('dy', '5px');
                  t.setAttribute('fill', fontColor);
                  t.setAttribute('stroke', TEXT_STYLE.stroke);
                  t.setAttribute('stroke-width', '0.4');
                  t.setAttribute('text-shadow', '0px 0px 2px grey');

                  t.innerHTML = text.text;
                }
              }
            });
          }

          return _loop2;
        }();

        var _iteratorNormalCompletion4 = true;
        var _didIteratorError4 = false;
        var _iteratorError4 = undefined;

        try {
          for (var _iterator4 = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
            var _tile = _step4.value;

            var _ret2 = _loop2(_tile);

            if (_ret2 === 'continue') continue;
          }
        } catch (err) {
          _didIteratorError4 = true;
          _iteratorError4 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion4 && _iterator4['return']) {
              _iterator4['return']();
            }
          } finally {
            if (_didIteratorError4) {
              throw _iteratorError4;
            }
          }
        }

        return [base, base];
      }

      return exportSVG;
    }()

    /** Move event for the y-axis */

  }, {
    key: 'movedY',
    value: function () {
      function movedY(dY) {
        var _this9 = this;

        (0, _values2['default'])(this.fetchedTiles).forEach(function (tile) {
          var vst = _this9.valueScaleTransform;
          var y = vst.y,
              k = vst.k;

          var height = _this9.dimensions[1];
          // clamp at the bottom and top
          if (y + dY / k > -(k - 1) * height && y + dY / k < 0) {
            _this9.valueScaleTransform = vst.translate(0, dY / k);
          }
          tile.rectGraphics.position.y = _this9.valueScaleTransform.y;
          _this9.vertY = _this9.valueScaleTransform.y;
        });
        this.animate();
      }

      return movedY;
    }()

    /** Zoomed along the y-axis */

  }, {
    key: 'zoomedY',
    value: function () {
      function zoomedY(yPos, kMultiplier) {
        var _this10 = this;

        var newTransform = _utils.trackUtils.zoomedY(yPos, kMultiplier, this.valueScaleTransform, this.dimensions[1]);
        this.valueScaleTransform = newTransform;

        var k1 = newTransform.k;
        var t1 = newTransform.y;

        var toStretch = false;
        k1 /= this.prevK;

        if (k1 > 1.5 || k1 < 1 / 1.5) {
          // this is to make sure that annotations aren't getting
          // too stretched vertically
          this.prevK *= k1;

          k1 = 1;

          toStretch = true;
        }

        this.vertK = k1;
        this.vertY = t1;

        (0, _values2['default'])(this.fetchedTiles).forEach(function (tile) {
          if (toStretch) _this10.renderTile(tile);

          tile.rectGraphics.scale.y = k1;
          tile.rectGraphics.position.y = t1;
        });

        this.draw();
        this.animate();
      }

      return zoomedY;
    }()
  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX, trackY) {
        if (!this.tilesetInfo) {
          return '';
        }

        var zoomLevel = this.calculateZoomLevel();
        var point = [trackX, trackY];

        if (this.drawnRects[zoomLevel]) {
          var visibleRects = (0, _values2['default'])(this.drawnRects[zoomLevel]);

          for (var i = 0; i < visibleRects.length; i++) {
            var rect = visibleRects[i][0].slice(0);

            // graphics have been scaled so we need to scale the points themselves
            var tileKx = visibleRects[i][1].tile.rectGraphics.scale.x;
            var tilePx = visibleRects[i][1].tile.rectGraphics.position.x;

            var tileKy = visibleRects[i][1].tile.rectGraphics.scale.y;
            var tilePy = visibleRects[i][1].tile.rectGraphics.position.y;

            var newArr = [];

            while (rect.length) {
              var _rect$splice = rect.splice(0, 2),
                  _rect$splice2 = (0, _slicedToArray3['default'])(_rect$splice, 2),
                  x = _rect$splice2[0],
                  y = _rect$splice2[1];

              newArr.push([x * tileKx + tilePx, y * tileKy + tilePy]);
            }

            var pc = (0, _robustPointInPolygon2['default'])(newArr, point);

            if (pc === -1) {
              var parts = visibleRects[i][1].value.fields;

              return parts.join(' ');
            }
          }
        }

        return '';
      }

      return getMouseOverHtml;
    }()
  }]);
  return BedLikeTrack;
}(_HorizontalTiled1DPixiTrack2['default']);

exports['default'] = BedLikeTrack;

/***/ }),
/* 353 */
/***/ (function(module, exports, __nested_webpack_require_1849787__) {

"use strict";


module.exports = {
  init:           sqInit,
  sweepBipartite: sweepBipartite,
  sweepComplete:  sweepComplete,
  scanBipartite:  scanBipartite,
  scanComplete:   scanComplete
}

var pool  = __nested_webpack_require_1849787__(257)
var bits  = __nested_webpack_require_1849787__(258)
var isort = __nested_webpack_require_1849787__(621)

//Flag for blue
var BLUE_FLAG = (1<<28)

//1D sweep event queue stuff (use pool to save space)
var INIT_CAPACITY      = 1024
var RED_SWEEP_QUEUE    = pool.mallocInt32(INIT_CAPACITY)
var RED_SWEEP_INDEX    = pool.mallocInt32(INIT_CAPACITY)
var BLUE_SWEEP_QUEUE   = pool.mallocInt32(INIT_CAPACITY)
var BLUE_SWEEP_INDEX   = pool.mallocInt32(INIT_CAPACITY)
var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY)
var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY)
var SWEEP_EVENTS       = pool.mallocDouble(INIT_CAPACITY * 8)

//Reserves memory for the 1D sweep data structures
function sqInit(count) {
  var rcount = bits.nextPow2(count)
  if(RED_SWEEP_QUEUE.length < rcount) {
    pool.free(RED_SWEEP_QUEUE)
    RED_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(RED_SWEEP_INDEX.length < rcount) {
    pool.free(RED_SWEEP_INDEX)
    RED_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  if(BLUE_SWEEP_QUEUE.length < rcount) {
    pool.free(BLUE_SWEEP_QUEUE)
    BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(BLUE_SWEEP_INDEX.length < rcount) {
    pool.free(BLUE_SWEEP_INDEX)
    BLUE_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  if(COMMON_SWEEP_QUEUE.length < rcount) {
    pool.free(COMMON_SWEEP_QUEUE)
    COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount)
  }
  if(COMMON_SWEEP_INDEX.length < rcount) {
    pool.free(COMMON_SWEEP_INDEX)
    COMMON_SWEEP_INDEX = pool.mallocInt32(rcount)
  }
  var eventLength = 8 * rcount
  if(SWEEP_EVENTS.length < eventLength) {
    pool.free(SWEEP_EVENTS)
    SWEEP_EVENTS = pool.mallocDouble(eventLength)
  }
}

//Remove an item from the active queue in O(1)
function sqPop(queue, index, count, item) {
  var idx = index[item]
  var top = queue[count-1]
  queue[idx] = top
  index[top] = idx
}

//Insert an item into the active queue in O(1)
function sqPush(queue, index, count, item) {
  queue[count] = item
  index[item]  = count
}

//Recursion base case: use 1D sweep algorithm
function sweepBipartite(
    d, visit,
    redStart,  redEnd, red, redIndex,
    blueStart, blueEnd, blue, blueIndex) {

  //store events as pairs [coordinate, idx]
  //
  //  red create:  -(idx+1)
  //  red destroy: idx
  //  blue create: -(idx+BLUE_FLAG)
  //  blue destroy: idx+BLUE_FLAG
  //
  var ptr      = 0
  var elemSize = 2*d
  var istart   = d-1
  var iend     = elemSize-1

  for(var i=redStart; i<redEnd; ++i) {
    var idx = redIndex[i]
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -(idx+1)
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = blueIndex[i]+BLUE_FLAG
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive  = 0
  var blueActive = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e >= BLUE_FLAG) {
      //blue destroy event
      e = (e-BLUE_FLAG)|0
      sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e)
    } else if(e >= 0) {
      //red destroy event
      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e)
    } else if(e <= -BLUE_FLAG) {
      //blue create event
      e = (-e-BLUE_FLAG)|0
      for(var j=0; j<redActive; ++j) {
        var retval = visit(RED_SWEEP_QUEUE[j], e)
        if(retval !== void 0) {
          return retval
        }
      }
      sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, e)
    } else {
      //red create event
      e = (-e-1)|0
      for(var j=0; j<blueActive; ++j) {
        var retval = visit(e, BLUE_SWEEP_QUEUE[j])
        if(retval !== void 0) {
          return retval
        }
      }
      sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, e)
    }
  }
}

//Complete sweep
function sweepComplete(d, visit, 
  redStart, redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {

  var ptr      = 0
  var elemSize = 2*d
  var istart   = d-1
  var iend     = elemSize-1

  for(var i=redStart; i<redEnd; ++i) {
    var idx = (redIndex[i]+1)<<1
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }

  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = (blueIndex[i]+1)<<1
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = (-idx)|1
    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
    SWEEP_EVENTS[ptr++] = idx|1
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  var blueActive   = 0
  var commonActive = 0
  for(var i=0; i<n; ++i) {
    var e     = SWEEP_EVENTS[2*i+1]|0
    var color = e&1
    if(i < n-1 && (e>>1) === (SWEEP_EVENTS[2*i+3]>>1)) {
      color = 2
      i += 1
    }
    
    if(e < 0) {
      //Create event
      var id = -(e>>1) - 1

      //Intersect with common
      for(var j=0; j<commonActive; ++j) {
        var retval = visit(COMMON_SWEEP_QUEUE[j], id)
        if(retval !== void 0) {
          return retval
        }
      }

      if(color !== 0) {
        //Intersect with red
        for(var j=0; j<redActive; ++j) {
          var retval = visit(RED_SWEEP_QUEUE[j], id)
          if(retval !== void 0) {
            return retval
          }
        }
      }

      if(color !== 1) {
        //Intersect with blue
        for(var j=0; j<blueActive; ++j) {
          var retval = visit(BLUE_SWEEP_QUEUE[j], id)
          if(retval !== void 0) {
            return retval
          }
        }
      }

      if(color === 0) {
        //Red
        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id)
      } else if(color === 1) {
        //Blue
        sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id)
      } else if(color === 2) {
        //Both
        sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id)
      }
    } else {
      //Destroy event
      var id = (e>>1) - 1
      if(color === 0) {
        //Red
        sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id)
      } else if(color === 1) {
        //Blue
        sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id)
      } else if(color === 2) {
        //Both
        sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id)
      }
    }
  }
}

//Sweep and prune/scanline algorithm:
//  Scan along axis, detect intersections
//  Brute force all boxes along axis
function scanBipartite(
  d, axis, visit, flip,
  redStart,  redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {
  
  var ptr      = 0
  var elemSize = 2*d
  var istart   = axis
  var iend     = axis+d

  var redShift  = 1
  var blueShift = 1
  if(flip) {
    blueShift = BLUE_FLAG
  } else {
    redShift  = BLUE_FLAG
  }

  for(var i=redStart; i<redEnd; ++i) {
    var idx = i + redShift
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }
  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = i + blueShift
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e < 0) {
      var idx   = -e
      var isRed = false
      if(idx >= BLUE_FLAG) {
        isRed = !flip
        idx -= BLUE_FLAG 
      } else {
        isRed = !!flip
        idx -= 1
      }
      if(isRed) {
        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx)
      } else {
        var blueId  = blueIndex[idx]
        var bluePtr = elemSize * idx
        
        var b0 = blue[bluePtr+axis+1]
        var b1 = blue[bluePtr+axis+1+d]

red_loop:
        for(var j=0; j<redActive; ++j) {
          var oidx   = RED_SWEEP_QUEUE[j]
          var redPtr = elemSize * oidx

          if(b1 < red[redPtr+axis+1] || 
             red[redPtr+axis+1+d] < b0) {
            continue
          }

          for(var k=axis+2; k<d; ++k) {
            if(blue[bluePtr + k + d] < red[redPtr + k] || 
               red[redPtr + k + d] < blue[bluePtr + k]) {
              continue red_loop
            }
          }

          var redId  = redIndex[oidx]
          var retval
          if(flip) {
            retval = visit(blueId, redId)
          } else {
            retval = visit(redId, blueId)
          }
          if(retval !== void 0) {
            return retval 
          }
        }
      }
    } else {
      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift)
    }
  }
}

function scanComplete(
  d, axis, visit,
  redStart,  redEnd, red, redIndex,
  blueStart, blueEnd, blue, blueIndex) {

  var ptr      = 0
  var elemSize = 2*d
  var istart   = axis
  var iend     = axis+d

  for(var i=redStart; i<redEnd; ++i) {
    var idx = i + BLUE_FLAG
    var redOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
    SWEEP_EVENTS[ptr++] = idx
  }
  for(var i=blueStart; i<blueEnd; ++i) {
    var idx = i + 1
    var blueOffset = elemSize*i
    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
    SWEEP_EVENTS[ptr++] = -idx
  }

  //process events from left->right
  var n = ptr >>> 1
  isort(SWEEP_EVENTS, n)
  
  var redActive    = 0
  for(var i=0; i<n; ++i) {
    var e = SWEEP_EVENTS[2*i+1]|0
    if(e < 0) {
      var idx   = -e
      if(idx >= BLUE_FLAG) {
        RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG
      } else {
        idx -= 1
        var blueId  = blueIndex[idx]
        var bluePtr = elemSize * idx

        var b0 = blue[bluePtr+axis+1]
        var b1 = blue[bluePtr+axis+1+d]

red_loop:
        for(var j=0; j<redActive; ++j) {
          var oidx   = RED_SWEEP_QUEUE[j]
          var redId  = redIndex[oidx]

          if(redId === blueId) {
            break
          }

          var redPtr = elemSize * oidx
          if(b1 < red[redPtr+axis+1] || 
            red[redPtr+axis+1+d] < b0) {
            continue
          }
          for(var k=axis+2; k<d; ++k) {
            if(blue[bluePtr + k + d] < red[redPtr + k] || 
               red[redPtr + k + d]   < blue[bluePtr + k]) {
              continue red_loop
            }
          }

          var retval = visit(redId, blueId)
          if(retval !== void 0) {
            return retval 
          }
        }
      }
    } else {
      var idx = e - BLUE_FLAG
      for(var j=redActive-1; j>=0; --j) {
        if(RED_SWEEP_QUEUE[j] === idx) {
          for(var k=j+1; k<redActive; ++k) {
            RED_SWEEP_QUEUE[k-1] = RED_SWEEP_QUEUE[k]
          }
          break
        }
      }
      --redActive
    }
  }
}

/***/ }),
/* 354 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = genPartition

var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m'

function genPartition(predicate, args) {
  var fargs ='abcdef'.split('').concat(args)
  var reads = []
  if(predicate.indexOf('lo') >= 0) {
    reads.push('lo=e[k+n]')
  }
  if(predicate.indexOf('hi') >= 0) {
    reads.push('hi=e[k+o]')
  }
  fargs.push(
    code.replace('_', reads.join())
        .replace('$', predicate))
  return Function.apply(void 0, fargs)
}

/***/ }),
/* 355 */
/***/ (function(module, exports, __nested_webpack_require_1861867__) {

module.exports = robustPointInPolygon

var orient = __nested_webpack_require_1861867__(625)

function robustPointInPolygon(vs, point) {
  var x = point[0]
  var y = point[1]
  var n = vs.length
  var inside = 1
  var lim = n
  for(var i = 0, j = n-1; i<lim; j=i++) {
    var a = vs[i]
    var b = vs[j]
    var yi = a[1]
    var yj = b[1]
    if(yj < yi) {
      if(yj < y && y < yi) {
        var s = orient(a, b, point)
        if(s === 0) {
          return 0
        } else {
          inside ^= (0 < s)|0
        }
      } else if(y === yi) {
        var c = vs[(i+1)%n]
        var yk = c[1]
        if(yi < yk) {
          var s = orient(a, b, point)
          if(s === 0) {
            return 0
          } else {
            inside ^= (0 < s)|0
          }
        }
      }
    } else if(yi < yj) {
      if(yi < y && y < yj) {
        var s = orient(a, b, point)
        if(s === 0) {
          return 0
        } else {
          inside ^= (s < 0)|0
        }
      } else if(y === yi) {
        var c = vs[(i+1)%n]
        var yk = c[1]
        if(yk < yi) {
          var s = orient(a, b, point)
          if(s === 0) {
            return 0
          } else {
            inside ^= (s < 0)|0
          }
        }
      }
    } else if(y === yi) {
      var x0 = Math.min(a[0], b[0])
      var x1 = Math.max(a[0], b[0])
      if(i === 0) {
        while(j>0) {
          var k = (j+n-1)%n
          var p = vs[k]
          if(p[1] !== y) {
            break
          }
          var px = p[0]
          x0 = Math.min(x0, px)
          x1 = Math.max(x1, px)
          j = k
        }
        if(j === 0) {
          if(x0 <= x && x <= x1) {
            return 0
          }
          return 1 
        }
        lim = j+1
      }
      var y0 = vs[(j+n-1)%n][1]
      while(i+1<lim) {
        var p = vs[i+1]
        if(p[1] !== y) {
          break
        }
        var px = p[0]
        x0 = Math.min(x0, px)
        x1 = Math.max(x1, px)
        i += 1
      }
      if(x0 <= x && x <= x1) {
        return 0
      }
      var y1 = vs[(i+1)%n][1]
      if(x < x0 && (y0 < y !== y1 < y)) {
        inside ^= 1
      }
    }
  }
  return 2 * inside - 1
}

/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = twoProduct

var SPLITTER = +(Math.pow(2, 27) + 1.0)

function twoProduct(a, b, result) {
  var x = a * b

  var c = SPLITTER * a
  var abig = c - a
  var ahi = c - abig
  var alo = a - ahi

  var d = SPLITTER * b
  var bbig = d - b
  var bhi = d - bbig
  var blo = b - bhi

  var err1 = x - (ahi * bhi)
  var err2 = err1 - (alo * bhi)
  var err3 = err2 - (ahi * blo)

  var y = alo * blo - err3

  if(result) {
    result[0] = y
    result[1] = x
    return result
  }

  return [ y, x ]
}

/***/ }),
/* 357 */
/***/ (function(module, exports, __nested_webpack_require_1864702__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_1864702__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _isNan = __nested_webpack_require_1864702__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _getPrototypeOf = __nested_webpack_require_1864702__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1864702__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1864702__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1864702__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1864702__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1864702__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _PixiTrack2 = __nested_webpack_require_1864702__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _utils = __nested_webpack_require_1864702__(10);

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

var drawRectOnGraphics = function drawRectOnGraphics(x, y, width, height, graphics) {
  graphics.drawRect(x, y, width, height);
};

// Utils


var drawRectOnSvg = function drawRectOnSvg(x, y, width, height, svg) {
  var _ref = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {},
      _ref$fill = _ref.fill,
      fill = _ref$fill === undefined ? 0x000000 : _ref$fill,
      _ref$fillOpacity = _ref.fillOpacity,
      fillOpacity = _ref$fillOpacity === undefined ? 0 : _ref$fillOpacity,
      _ref$stroke = _ref.stroke,
      stroke = _ref$stroke === undefined ? 0x000000 : _ref$stroke,
      _ref$strokeWidth = _ref.strokeWidth,
      strokeWidth = _ref$strokeWidth === undefined ? 0 : _ref$strokeWidth,
      _ref$strokeOpacity = _ref.strokeOpacity,
      strokeOpacity = _ref$strokeOpacity === undefined ? 0 : _ref$strokeOpacity;

  var r = document.createElement('rect');

  r.setAttribute('x', x);
  r.setAttribute('y', y);
  r.setAttribute('width', width);
  r.setAttribute('height', height);

  r.setAttribute('fill', '#' + String((0, _utils.decToHexStr)(fill)));
  r.setAttribute('fill-opacity', fillOpacity);
  r.setAttribute('stroke', '#' + String((0, _utils.decToHexStr)(stroke)));
  r.setAttribute('stroke-opacity', strokeOpacity);
  r.setAttribute('stroke-width', strokeWidth);

  svg.appendChild(r);
};

var drawRect = function drawRect(x, y, width, height, target, options) {
  if (target instanceof HTMLElement) drawRectOnSvg(x, y, width, height, target, options);else drawRectOnGraphics(x, y, width, height, target);
};

var drawRectWithPositionedBorder = function drawRectWithPositionedBorder(graphics, xPos, yPos, width, height, fill, stroke, outline) {
  var _ref2 = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : {},
      _ref2$isVertical = _ref2.isVertical,
      isVertical = _ref2$isVertical === undefined ? false : _ref2$isVertical,
      _ref2$svg = _ref2.svg,
      svg = _ref2$svg === undefined ? null : _ref2$svg;

  var finalXPos = xPos;
  var finalYPos = yPos;
  var finalWidth = width;
  var finalHeight = height;

  // The size of an outline is one dimensional so width when the outline
  // is veritcal is the same as the height when the outline is horizontal.
  // The reason I call the size `outline.width` is just to stay close to
  // how the stroke is defined and the stroke definition is aligned to SVG's
  // strokeWidth.
  var outlineWidth = outline.width * 2 > width ? width / 2 : outline.width;
  var outlineHeight = outline.width * 2 > height ? height / 2 : outline.width;

  var target = svg || graphics;
  var colors = {
    fill: 0x000000,
    fillOpacity: 0,
    stroke: 0x000000,
    strokeOpacity: 0,
    strokeWidth: 1
  };

  if (outline.positions && outline.positions.length) {
    graphics.lineStyle(1, 0x000000, 0);
    graphics.beginFill(outline.color, outline.opacity);

    colors.fill = outline.color;
    colors.fillOpacity = outline.opacity;
    colors.stroke = 0x000000;
    colors.strokeOpacity = 0;
    colors.strokeWidth = 1;

    outline.positions.forEach(function (pos) {
      if (pos === 'top' && !isVertical || pos === 'left' && isVertical) {
        drawRect(xPos - outlineWidth, yPos - outlineHeight, width + outlineWidth * 2, outlineHeight, target, colors);
      } else if (pos === 'bottom' && !isVertical || pos === 'right' && isVertical) {
        drawRect(xPos - outlineWidth, yPos + height, width + outlineWidth * 2, outlineHeight, target, colors);
      } else if (pos === 'left' && !isVertical || pos === 'top' && isVertical) {
        drawRect(xPos - outlineWidth, yPos - outlineHeight, outlineWidth, height + outlineHeight * 2, target, colors);
      } else if (pos === 'right' && !isVertical || pos === 'bottom' && isVertical) {
        drawRect(xPos + width, yPos - outlineHeight, outlineWidth, height + outlineHeight * 2, target, colors);
      }
    });
  } else if (outline.width > 0 && outline.opacity > 0) {
    graphics.lineStyle(outline.width, outline.color, outline.opacity);
    graphics.beginFill(0x000000, 0);
    colors.fill = 0x000000;
    colors.fillOpacity = 0;
    colors.stroke = outline.color;
    colors.strokeOpacity = outline.opacity;
    colors.strokeWidth = outline.width;
    drawRect(xPos - outlineWidth, yPos - outlineHeight, width + outlineWidth * 2, height + outlineHeight * 2, target, colors);
  }

  if (stroke.positions && stroke.positions.length) {
    graphics.lineStyle(1, 0x000000, 0);
    graphics.beginFill(stroke.color, stroke.opacity);

    // The size of the stroke is one dimensional so width when the stroke
    // is veritcal is the same as the height when the stroke is horizontal.
    // The stroke definition is aligned to SVG's strokeWidth.
    var strokeWidth = stroke.width * 2 > width ? width / 2 : stroke.width;
    var strokeHeight = stroke.width * 2 > height ? height / 2 : stroke.width;

    colors.fill = stroke.color;
    colors.fillOpacity = stroke.opacity;
    colors.stroke = 0x000000;
    colors.strokeOpacity = 0;
    colors.strokeWidth = 1;

    stroke.positions.forEach(function (pos) {
      if (pos === 'top' && !isVertical || pos === 'left' && isVertical) {
        drawRect(xPos, yPos, width, strokeHeight, target, colors);
        finalYPos += strokeHeight;
        finalHeight -= strokeHeight;
      } else if (pos === 'bottom' && !isVertical || pos === 'right' && isVertical) {
        drawRect(xPos, yPos + height - strokeHeight, width, strokeHeight, target, colors);
        finalHeight -= strokeHeight;
      } else if (pos === 'left' && !isVertical || pos === 'top' && isVertical) {
        drawRect(xPos, yPos, strokeWidth, height, target, colors);
        finalXPos += strokeWidth;
        finalWidth -= strokeWidth;
      } else if (pos === 'right' && !isVertical || pos === 'bottom' && isVertical) {
        drawRect(xPos + width - strokeWidth, yPos, strokeWidth, height, target, colors);
        finalWidth -= strokeWidth;
      }
    });
  } else {
    graphics.lineStyle(stroke.width, stroke.color, stroke.opacity);
    colors.stroke = stroke.color;
    colors.strokeOpacity = stroke.opacity;
    colors.strokeWidth = stroke.width;
  }

  graphics.beginFill(fill.color, fill.opacity);
  colors.fill = fill.color;
  colors.fillOpacity = fill.opacity;
  drawRect(finalXPos, finalYPos, finalWidth, finalHeight, target, colors);
};

var OverlayTrack = function (_PixiTrack) {
  (0, _inherits3['default'])(OverlayTrack, _PixiTrack);

  function OverlayTrack(context, options) {
    (0, _classCallCheck3['default'])(this, OverlayTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (OverlayTrack.__proto__ || (0, _getPrototypeOf2['default'])(OverlayTrack)).call(this, context, options));

    _this.options = options || {};
    _this.drawnRects = {};
    return _this;
  }

  (0, _createClass3['default'])(OverlayTrack, [{
    key: 'drawHorizontalOverlay',
    value: function () {
      function drawHorizontalOverlay(graphics, position, extent) {
        var minWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
        var fill = arguments[4];
        var stroke = arguments[5];
        var outline = arguments[6];
        var options = arguments[7];

        if (!extent || extent.length < 2) return;

        var xPos = this.position[0] + position.left + this._xScale(extent[0]);

        var yPos = this.position[1] + position.top;
        var height = position.height;
        var width = this._xScale(extent[1]) - this._xScale(extent[0]);

        if (width < minWidth) {
          // To center the overlay
          xPos -= (minWidth - width) / 2;
          width = minWidth;
        }

        drawRectWithPositionedBorder(graphics, xPos, yPos, width, height, fill, stroke, outline, options);
      }

      return drawHorizontalOverlay;
    }()
  }, {
    key: 'drawVerticalOverlay',
    value: function () {
      function drawVerticalOverlay(graphics, position, extent) {
        var minHeight = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
        var fill = arguments[4];
        var stroke = arguments[5];
        var outline = arguments[6];
        var options = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : {};

        if (!extent || extent.length < 2) return;

        var xPos = this.position[0] + position.left;
        var yPos = this.position[1] + position.top + this._yScale(extent.length >= 4 ? extent[2] : extent[0]);

        // the position of the left bounary of this track
        var topPosition = this.position[1] + position.top;
        var bottomPosition = this.position[1] + position.top + position.height;

        if (yPos > bottomPosition) {
          // this annotation is off the bottom
          return;
        }

        if (yPos < topPosition) {
          // this overlay is partially off the top side of the
          // track and needs to be truncated
          yPos = topPosition;
        }

        var width = position.width;
        var height = this._yScale(extent.length >= 4 ? extent[3] : extent[1]) - yPos + position.top + this.position[1];

        if (height < 0) {
          // this overlay is off the top end of the track and
          // doesn't need to be drawn
          return;
        }

        if (yPos + height > bottomPosition) {
          height += bottomPosition - (yPos + height);
        }

        if (height < minHeight) {
          // To center the overlay
          yPos -= (minHeight - height) / 2;
          height = minHeight;
        }

        options.isVertical = true;

        drawRectWithPositionedBorder(graphics, xPos, yPos, width, height, fill, stroke, outline, options);
      }

      return drawVerticalOverlay;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw(options) {
        var _this2 = this;

        (0, _get3['default'])(OverlayTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OverlayTrack.prototype), 'draw', this).call(this);

        var graphics = this.pMain;
        var fill = {
          color: (0, _utils.colorToHex)(this.options.fill || this.options.fillColor || 'blue'),
          opacity: (0, _isNan2['default'])(+this.options.fillOpacity) ? 0.3 : +this.options.fillOpacity
        };
        var stroke = {
          color: (0, _utils.colorToHex)(this.options.stroke || 'blue'),
          opacity: +this.options.strokeOpacity || 1,
          width: +this.options.strokeWidth || 0,
          positions: !this.options.strokePos || Array.isArray(this.options.strokePos) ? this.options.strokePos : [this.options.strokePos]
        };
        var outline = {
          color: (0, _utils.colorToHex)(this.options.outline || 'white'),
          opacity: +this.options.outlineOpacity || 1,
          width: +this.options.outlineWidth || 0,
          positions: !this.options.outlinePos || Array.isArray(this.options.outlinePos) ? this.options.outlinePos : [this.options.outlinePos]
        };

        if (!options || !options.svg) graphics.clear();
        graphics.lineStyle(stroke.width, stroke, +!stroke.positions * stroke.opacity);
        graphics.beginFill(fill.color, fill.opacity);

        var minWidth = Math.max(0, +this.options.minWidth || 0);
        var minHeight = Math.max(0, +this.options.minHeight || 0);

        if (Array.isArray(this.options.extent)) {
          this.options.orientationsAndPositions.forEach(function (op) {
            if (op.orientation === '1d-horizontal' || op.orientation === '2d') {
              _this2.options.extent.forEach(function (extent) {
                return _this2.drawHorizontalOverlay(graphics, op.position, extent, minWidth, fill, stroke, outline, options);
              });
            }

            if (op.orientation === '1d-vertical' || op.orientation === '2d') {
              _this2.options.extent.forEach(function (extent) {
                return _this2.drawVerticalOverlay(graphics, op.position, extent, minHeight, fill, stroke, outline, options);
              });
            }
          });
        }
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(OverlayTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OverlayTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.draw();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(OverlayTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OverlayTrack.prototype), 'setDimensions', this).call(this, newDimensions);

        this.draw();
      }

      return setDimensions;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(OverlayTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OverlayTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(OverlayTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OverlayTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }

        var output = document.createElement('g');
        track.appendChild(output);

        this.draw({ svg: output });

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return OverlayTrack;
}(_PixiTrack3['default']);

exports['default'] = OverlayTrack;

/***/ }),
/* 358 */
/***/ (function(module, exports, __nested_webpack_require_1879895__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_1879895__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getIterator2 = __nested_webpack_require_1879895__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _getPrototypeOf = __nested_webpack_require_1879895__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1879895__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1879895__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1879895__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1879895__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1879895__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_1879895__(28);

var _HorizontalLine1DPixiTrack = __nested_webpack_require_1879895__(116);

var _HorizontalLine1DPixiTrack2 = _interopRequireDefault(_HorizontalLine1DPixiTrack);

var _utils = __nested_webpack_require_1879895__(10);

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

var HorizontalPoint1DPixiTrack = function (_HorizontalLine1DPixi) {
  (0, _inherits3['default'])(HorizontalPoint1DPixiTrack, _HorizontalLine1DPixi);

  function HorizontalPoint1DPixiTrack() {
    (0, _classCallCheck3['default'])(this, HorizontalPoint1DPixiTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (HorizontalPoint1DPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalPoint1DPixiTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(HorizontalPoint1DPixiTrack, [{
    key: 'initTile',

    /**
     * Create whatever is needed to draw this tile.
     */
    value: function () {
      function initTile(tile) {
        tile.barXValues = new Array(tile.tileData.dense.length);
        tile.barYValues = new Array(tile.tileData.dense.length);
        tile.barWidths = new Array(tile.tileData.dense.length);
        tile.barHeights = new Array(tile.tileData.dense.length);

        (0, _get3['default'])(HorizontalPoint1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalPoint1DPixiTrack.prototype), 'initTile', this).call(this, tile);
      }

      return initTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        if (!tile.graphics) {
          return;
        }

        if (!tile.tileData || !tile.tileData.dense) {
          return;
        }

        var graphics = tile.graphics;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileValues = tile.tileData.dense;

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

        var pseudocount = 0; // if we use a log scale, then we'll set a pseudocount
        // equal to the smallest non-zero value
        this.valueScale = null;

        if (this.options.valueScaling === 'log') {
          var offsetValue = this.medianVisibleValue;

          if (!this.medianVisibleValue) {
            offsetValue = this.minValue();
          }

          this.valueScale = (0, _d3Scale.scaleLog)()
          // .base(Math.E)
          .domain([offsetValue, this.maxValue() + offsetValue]).range([this.dimensions[1], 0]);
          pseudocount = offsetValue;
        } else {
          // linear scale
          this.valueScale = (0, _d3Scale.scaleLinear)().domain([this.minValue(), this.maxValue()]).range([this.dimensions[1], 0]);
        }

        graphics.clear();

        this.drawAxis(this.valueScale);

        if (this.options.valueScaling === 'log' && this.valueScale.domain()[1] < 0) {
          console.warn('Negative values present when using a log scale', this.valueScale.domain());
          return;
        }

        var stroke = (0, _utils.colorToHex)(this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue');
        // this scale should go from an index in the data array to
        // a position in the genome coordinates
        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, this.tilesetInfo.tile_size]).range([tileX, tileX + tileWidth]);

        // let strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1;

        var strokeWidth = 0;
        graphics.lineStyle(strokeWidth, stroke, 1);

        var squareSide = this.options.pointSize ? this.options.pointSize : 3;
        var pointColor = (0, _utils.colorToHex)(this.options.pointColor ? this.options.pointColor : 'red');

        graphics.beginFill(pointColor, 1);

        tile.drawnAtScale = this._xScale.copy();

        for (var i = 0; i < tileValues.length; i++) {
          var xPos = this._xScale(tileXScale(i));
          var yPos = this.valueScale(tileValues[i] + pseudocount);

          tile.barXValues[i] = xPos - squareSide / 2 / this.pMain.scale.x;
          tile.barYValues[i] = yPos - squareSide / 2 / this.pMain.scale.y;
          tile.barWidths[i] = squareSide / this.pMain.scale.x;
          tile.barHeights[i] = squareSide / this.pMain.scale.y;

          if (tileXScale(i) > this.tilesetInfo.max_pos[0]) {
            break;
          }
          // this data is in the last tile and extends beyond the length
          // of the coordinate system

          // console.log('drawRect');
          // console.log('xPos:', xPos)

          graphics.drawRect(xPos - squareSide / 2 / this.pMain.scale.x, yPos - squareSide / 2 / this.pMain.scale.y, squareSide / this.pMain.scale.x, squareSide / this.pMain.scale.y);
        }
      }

      return drawTile;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        (0, _get3['default'])(HorizontalPoint1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalPoint1DPixiTrack.prototype), 'draw', this).call(this);

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])((0, _utils.dictValues)(this.fetchedTiles)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tile = _step.value;

            // scaling between tiles
            var tileK = (tile.drawnAtScale.domain()[1] - tile.drawnAtScale.domain()[0]) / (this._xScale.domain()[1] - this._xScale.domain()[0]);

            // let posOffset = newRange[0];

            var newRange = this._xScale.domain().map(tile.drawnAtScale);

            var posOffset = newRange[0];
            tile.graphics.scale.x = tileK;
            tile.graphics.position.x = -posOffset * tileK;
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, tx, ty) {
        (0, _get3['default'])(HorizontalPoint1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalPoint1DPixiTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);
      }

      return zoomed;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        var _get$call = (0, _get3['default'])(HorizontalPoint1DPixiTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalPoint1DPixiTrack.prototype), 'superSVG', this).call(this);

        var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

        base = _get$call2[0];
        track = _get$call2[1];


        base.setAttribute('class', 'exported-line-track');
        var output = document.createElement('g');

        track.appendChild(output);
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var tile = _step2.value;

            for (var i = 0; i < tile.barXValues.length; i++) {
              var rect = document.createElement('rect');

              var strokeColor = this.options.lineStrokeColor || 'blue';
              var pointColor = this.options.pointColor || 'red';

              rect.setAttribute('fill', pointColor);
              rect.setAttribute('stroke', strokeColor);
              rect.setAttribute('stroke-width', 0);

              rect.setAttribute('x', tile.barXValues[i]);
              rect.setAttribute('y', tile.barYValues[i]);
              rect.setAttribute('height', tile.barHeights[i]);
              rect.setAttribute('width', tile.barWidths[i]);

              output.appendChild(rect);
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        var gAxis = document.createElement('g');
        gAxis.setAttribute('id', 'axis');

        // append the axis to base so that it's not clipped
        base.appendChild(gAxis);
        gAxis.setAttribute('transform', 'translate(' + String(this.axis.pAxis.position.x) + ', ' + String(this.axis.pAxis.position.y) + ')');

        // add the axis to the export
        if (this.options.axisPositionHorizontal === 'left' || this.options.axisPositionVertical === 'top') {
          // left axis are shown at the beginning of the plot
          var gDrawnAxis = this.axis.exportAxisLeftSVG(this.valueScale, this.dimensions[1]);
          gAxis.appendChild(gDrawnAxis);
        } else if (this.options.axisPositionHorizontal === 'right' || this.options.axisPositionVertical === 'bottom') {
          var _gDrawnAxis = this.axis.exportAxisRightSVG(this.valueScale, this.dimensions[1]);
          gAxis.appendChild(_gDrawnAxis);
        }

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return HorizontalPoint1DPixiTrack;
}(_HorizontalLine1DPixiTrack2['default']);

exports['default'] = HorizontalPoint1DPixiTrack;

/***/ }),
/* 359 */
/***/ (function(module, exports, __nested_webpack_require_1891388__) {

"use strict";


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

var _isNan = __nested_webpack_require_1891388__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _values = __nested_webpack_require_1891388__(37);

var _values2 = _interopRequireDefault(_values);

var _typeof2 = __nested_webpack_require_1891388__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

var _keys = __nested_webpack_require_1891388__(18);

var _keys2 = _interopRequireDefault(_keys);

var _extends2 = __nested_webpack_require_1891388__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _stringify = __nested_webpack_require_1891388__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = __nested_webpack_require_1891388__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1891388__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1891388__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1891388__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1891388__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1891388__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Format = __nested_webpack_require_1891388__(20);

var _HeatmapTiledPixiTrack = __nested_webpack_require_1891388__(135);

var _HeatmapTiledPixiTrack2 = _interopRequireDefault(_HeatmapTiledPixiTrack);

var _services = __nested_webpack_require_1891388__(24);

var _selectedItemsToSize = __nested_webpack_require_1891388__(139);

var _selectedItemsToSize2 = _interopRequireDefault(_selectedItemsToSize);

var _selectedItemsToCumWeights = __nested_webpack_require_1891388__(630);

var _selectedItemsToCumWeights2 = _interopRequireDefault(_selectedItemsToCumWeights);

var _getAggregationFunction = __nested_webpack_require_1891388__(181);

var _getAggregationFunction2 = _interopRequireDefault(_getAggregationFunction);

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

var HorizontalMultivecTrack = function (_HeatmapTiledPixiTrac) {
  (0, _inherits3['default'])(HorizontalMultivecTrack, _HeatmapTiledPixiTrac);

  function HorizontalMultivecTrack(context, options) {
    (0, _classCallCheck3['default'])(this, HorizontalMultivecTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HorizontalMultivecTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalMultivecTrack)).call(this, context, options));

    _this.pMain = _this.pMobile;

    // Continuous scaling is currently not supported
    _this.continuousScaling = false;

    _this.updateDataFetcher(options);
    return _this;
  }

  (0, _createClass3['default'])(HorizontalMultivecTrack, [{
    key: 'updateDataFetcher',
    value: function () {
      function updateDataFetcher(options) {
        if (options && options.selectRows && options.selectRowsAggregationMethod === 'server') {
          var pubSub = this.pubSub,
              prevDataFetcher = this.dataFetcher;

          var prevDataConfigOptions = prevDataFetcher.dataConfig.options;
          var nextDataConfigOptions = {
            aggGroups: options.selectRows,
            aggFunc: options.selectRowsAggregationMode
          };
          if ((0, _stringify2['default'])(prevDataConfigOptions) !== (0, _stringify2['default'])(nextDataConfigOptions)) {
            // Override the dataFetcher object with a new dataConfig,
            // containing the .options property.
            // This would otherwise be set in the call to super()
            // in the TiledPixiTrack ancestor constructor.
            var newDataConfig = (0, _extends3['default'])({}, prevDataFetcher.dataConfig, {
              options: nextDataConfigOptions
            });
            this.dataFetcher = new prevDataFetcher.constructor(newDataConfig, pubSub);

            // Only fetch new tiles if the tileset has been registered
            // and has a tilesetUid (for example, due to file url-based tracks).
            if (this.dataFetcher.dataConfig.tilesetUid) {
              this.fetchNewTiles((0, _keys2['default'])(this.fetchedTiles).map(function (x) {
                return {
                  tileId: x,
                  remoteId: x
                };
              }));
            }
          }
        }
      }

      return updateDataFetcher;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        this.updateDataFetcher(options);
        (0, _get3['default'])(HorizontalMultivecTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalMultivecTrack.prototype), 'rerender', this).call(this, options, force);

        if (options.selectRows) {
          // The weights for selectRows groups must be computed
          // any time options.selectRows changes.
          this.selectRowsCumWeights = (0, _selectedItemsToCumWeights2['default'])(options.selectRows, options.selectRowsAggregationWithRelativeHeight);
        }
      }

      return rerender;
    }()
  }, {
    key: 'tileDataToCanvas',
    value: function () {
      function tileDataToCanvas(pixData) {
        var canvas = document.createElement('canvas');

        if (this.options.selectRows && this.tilesetInfo.shape) {
          canvas.width = this.tilesetInfo.shape[0];
          canvas.height = (0, _selectedItemsToSize2['default'])(this.options.selectRows, this.options.selectRowsAggregationWithRelativeHeight);
        } else if (this.tilesetInfo.shape) {
          canvas.width = this.tilesetInfo.shape[0];
          canvas.height = this.tilesetInfo.shape[1];
        } else {
          canvas.width = this.tilesetInfo.tile_size; // , pixData.length / 4);
          canvas.height = 1;
        }

        var ctx = canvas.getContext('2d');

        ctx.fillStyle = 'transparent';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        if (pixData.length !== 0 && pixData.length === 4 * canvas.width * canvas.height) {
          var pix = new ImageData(pixData, canvas.width, canvas.height);
          ctx.putImageData(pix, 0, 0);
        } else {
          console.warn('HorizontalMultivecTrack: pixData has an incorrect length.');
        }

        return canvas;
      }

      return tileDataToCanvas;
    }()
  }, {
    key: 'setSpriteProperties',
    value: function () {
      function setSpriteProperties(sprite, zoomLevel, tilePos) {
        var _getTilePosAndDimensi = this.getTilePosAndDimensions(zoomLevel, tilePos, this.tilesetInfo.tile_size),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileEndX = tileX + tileWidth;

        sprite.width = this._refXScale(tileEndX) - this._refXScale(tileX);
        sprite.height = this.dimensions[1];

        sprite.x = this._refXScale(tileX);
        sprite.y = 0;
      }

      return setSpriteProperties;
    }()
  }, {
    key: 'leftTrackZoomed',
    value: function () {
      function leftTrackZoomed(newXScale, newYScale, k, tx, ty) {
        // a separate zoom function if the track is drawn on
        // the left
        var offset = this._xScale(0) - k * this._refXScale(0);
        this.pMobile.position.x = offset + this.position[0];
        this.pMobile.position.y = this.position[1];

        this.pMobile.scale.x = k;
        this.pMobile.scale.y = 1;
      }

      return leftTrackZoomed;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, tx) {
        (0, _get3['default'])(HorizontalMultivecTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalMultivecTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale);

        this.pMain.position.x = tx; // translateX;
        this.pMain.position.y = this.position[1]; // translateY;

        this.pMain.scale.x = k; // scaleX;
        this.pMain.scale.y = 1; // scaleY;

        this.drawColorbar();
      }

      return zoomed;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        var _this2 = this;

        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        this.zoomLevel = this.calculateZoomLevel();

        if (this.tilesetInfo.resolutions) {
          var sortedResolutions = this.tilesetInfo.resolutions.map(function (x) {
            return +x;
          }).sort(function (a, b) {
            return b - a;
          });

          this.xTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], this._xScale, this.tilesetInfo.min_pos[0], null, this.tilesetInfo.tile_size);
        } else {
          this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);
        }

        var tiles = this.xTiles.map(function (x) {
          return [_this2.zoomLevel, x];
        });

        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        if (!this.tilesetInfo) return undefined;

        var minX = this.tilesetInfo.min_pos[0];

        var zoomIndexX = null;

        if (this.tilesetInfo.resolutions) {
          zoomIndexX = _services.tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, minX);
        } else {
          zoomIndexX = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
        }

        return zoomIndexX;
      }

      return calculateZoomLevel;
    }()

    /**
     * Create the local tile identifier, which be used with the
     * tile stores in TiledPixiTrack
     *
     * @param {array} tile: [zoomLevel, xPos]
     */

  }, {
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        return tile.join('.');
      }

      return tileToLocalId;
    }()

    /**
     * Create the remote tile identifier, which will be used to identify the
     * tile on the server
     *
     * @param {array} tile: [zoomLevel, xPos]
     */

  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        return tile.join('.');
      }

      return tileToRemoteId;
    }()

    /**
     * Calculate the tile position at the given track position
     *
     * @param {Number} trackX: The track's X position
     * @param {Number} trackY: The track's Y position
     *
     * @return {array} [zoomLevel, tilePos]
     */

  }, {
    key: 'getTilePosAtPosition',
    value: function () {
      function getTilePosAtPosition(trackX, trackY) {
        if (!this.tilesetInfo) return undefined;

        var zoomLevel = this.calculateZoomLevel();

        // the width of the tile in base pairs
        var tileWidth = _services.tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

        // the position of the tile containing the query position
        var tilePos = this._xScale.invert(trackX) / tileWidth;

        return [zoomLevel, Math.floor(tilePos)];
      }

      return getTilePosAtPosition;
    }()

    /**
     * Return the data currently visible at position X and Y
     *
     * @param {Number} trackX: The x position relative to the track's start and end
     * @param {Number} trakcY: The y position relative to the track's start and end
     */

  }, {
    key: 'getVisibleData',
    value: function () {
      function getVisibleData(trackX, trackY) {
        var _this3 = this;

        var zoomLevel = this.calculateZoomLevel();

        // the width of the tile in base pairs
        var tileWidth = _services.tileProxy.calculateTileWidth(this.tilesetInfo, zoomLevel, this.tilesetInfo.tile_size);

        // the position of the tile containing the query position
        var tilePos = this._xScale.invert(trackX) / tileWidth;
        var numRows = this.tilesetInfo.shape ? this.tilesetInfo.shape[1] : 1;
        if (this.options.selectRows) {
          numRows = (0, _selectedItemsToSize2['default'])(this.options.selectRows, this.options.selectRowsAggregationWithRelativeHeight);
        }

        // the position of query within the tile
        var posInTileX = this.tilesetInfo.tile_size * (tilePos - Math.floor(tilePos));
        var posInTileYNormalized = trackY / this.dimensions[1];
        var posInTileY = posInTileYNormalized * numRows;

        var selectedRowIndex = Math.floor(posInTileY);
        var selectedRowItem = void 0;
        if (this.options.selectRows) {
          // The `posInTileY` may not directly correspond to data indices if rows are filtered/reordered,
          // the `selectRows` array must be checked to convert the y-position to a data index/indices first.
          if (this.options.selectRowsAggregationWithRelativeHeight) {
            // Height must take into account the size of sub-arrays, so use the cumulative weight array.
            selectedRowIndex = this.selectRowsCumWeights.findIndex(function (weight, i) {
              return posInTileYNormalized <= weight && (i === _this3.selectRowsCumWeights.length - 1 || _this3.selectRowsCumWeights[i + 1] >= posInTileYNormalized);
            });
          }
          selectedRowItem = this.options.selectRows[selectedRowIndex];
        }

        var tileId = this.tileToLocalId([zoomLevel, Math.floor(tilePos)]);
        var fetchedTile = this.fetchedTiles[tileId];

        var value = '';

        if (fetchedTile) {
          if (!this.tilesetInfo.shape) {
            posInTileX = fetchedTile.tileData.dense.length * (tilePos - Math.floor(tilePos));
          }
          /*
          const a = rangeQuery2d(fetchedTile.tileData.dense,
            this.tilesetInfo.shape[0],
            this.tilesetInfo.shape[1],
            [Math.floor(posInTileX), Math.floor(posInTileX)],
            [posInTileY, posInTileY],
          */
          var index = null;
          if (this.tilesetInfo.shape) {
            // Accomodate data from vector sources
            if (Array.isArray(selectedRowItem) && this.options.selectRowsAggregationMethod === 'client') {
              // Need to aggregate, so `index` will actually be an array.
              index = selectedRowItem.map(function (rowI) {
                return _this3.tilesetInfo.shape[0] * rowI + Math.floor(posInTileX);
              });
            } else if (selectedRowItem && this.options.selectRowsAggregationMethod === 'client') {
              index = this.tilesetInfo.shape[0] * selectedRowItem + Math.floor(posInTileX);
            } else {
              // No need to aggregate, `index` will contain a single item.
              index = this.tilesetInfo.shape[0] * selectedRowIndex + Math.floor(posInTileX);
            }
          } else {
            index = fetchedTile.tileData.dense.length * selectedRowIndex + Math.floor(posInTileX);
          }
          if (Array.isArray(index)) {
            // Need to aggregate to compute `value`.
            var aggFunc = (0, _getAggregationFunction2['default'])(this.options.selectRowsAggregationMode);
            var values = index.map(function (i) {
              return fetchedTile.tileData.dense[i];
            });
            value = (0, _d3Format.format)('.3f')(aggFunc(values));
            value += '<br/>';
            value += String(index.length) + '-item ' + String(this.options.selectRowsAggregationMode);
          } else {
            value = (0, _d3Format.format)('.3f')(fetchedTile.tileData.dense[index]);
            if (Array.isArray(selectedRowItem)) {
              value += '<br/>';
              value += String(selectedRowItem.length) + '-item ' + String(this.options.selectRowsAggregationMode);
            }
          }
        }

        // add information about the row
        if (this.tilesetInfo.row_infos) {
          value += '<br/>';
          var rowInfo = '';
          if (this.options.selectRows && !Array.isArray(selectedRowItem)) {
            rowInfo = this.tilesetInfo.row_infos[selectedRowItem];
          } else if (selectedRowIndex >= 0 && selectedRowIndex < this.tilesetInfo.row_infos.length) {
            rowInfo = this.tilesetInfo.row_infos[selectedRowIndex];
          }
          if ((typeof rowInfo === 'undefined' ? 'undefined' : (0, _typeof3['default'])(rowInfo)) === 'object') {
            // The simplest thing to do here is conform to the tab-separated values convention.
            value += (0, _values2['default'])(rowInfo).join('\t');
          } else {
            // Probably a tab-separated string since not an object.
            value += rowInfo;
          }
        }

        return '' + String(value);
      }

      return getVisibleData;
    }()

    /**
     * Get some information to display when the mouse is over this
     * track
     *
     * @param {Number} trackX: the x position of the mouse over the track
     * @param {Number} trackY: the y position of the mouse over the track
     *
     * @return {string}: A HTML string containing the information to display
     *
     */

  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX, trackY) {
        if (!this.tilesetInfo) return '';

        var tilePos = this.getTilePosAtPosition(trackX, trackY);

        var output = '';

        if (this.options && this.options.heatmapValueScaling && this.options.heatmapValueScaling === 'categorical' && this.options.colorRange) {
          var visibleData = this.getVisibleData(trackX, trackY);
          var elements = visibleData.split('<br/>');
          var color = this.options.colorRange[parseInt(elements[0], 10) - 1];
          var label = elements[1];
          if ((0, _isNan2['default'])(color) || color === 'NaN' || typeof color === 'undefined' || color === 'undefined') return '';
          output = '<svg width="10" height="10" style="position:relative;bottom:1px"><rect width="10" height="10" rx="2" ry="2"\n                 style="fill:' + String(color) + ';stroke:black;stroke-width:2;"></svg> ' + String(label);
        } else {
          output += 'Data value: ' + String(this.getVisibleData(trackX, trackY)) + '</br>';
          output += 'Zoom level: ' + String(tilePos[0]) + ' tile position: ' + String(tilePos[1]);
        }

        return output;
      }

      return getMouseOverHtml;
    }()
  }]);
  return HorizontalMultivecTrack;
}(_HeatmapTiledPixiTrack2['default']);

exports['default'] = HorizontalMultivecTrack;

/***/ }),
/* 360 */
/***/ (function(module, exports, __nested_webpack_require_1910115__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1910115__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1910115__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1910115__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1910115__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1910115__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_1910115__(28);

var _BarTrack2 = __nested_webpack_require_1910115__(259);

var _BarTrack3 = _interopRequireDefault(_BarTrack2);

var _utils = __nested_webpack_require_1910115__(10);

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

var DivergentBarTrack = function (_BarTrack) {
  (0, _inherits3['default'])(DivergentBarTrack, _BarTrack);

  function DivergentBarTrack() {
    (0, _classCallCheck3['default'])(this, DivergentBarTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (DivergentBarTrack.__proto__ || (0, _getPrototypeOf2['default'])(DivergentBarTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(DivergentBarTrack, [{
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        this.renderTile(tile);
      }

      return drawTile;
    }()
  }, {
    key: 'renderTile',
    value: function () {
      function renderTile(tile) {
        // super.drawTile(tile);
        if (!tile.graphics) {
          return;
        }

        var graphics = tile.graphics;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos, this.tilesetInfo.tile_size || this.tilesetInfo.bins_per_dimension),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileValues = tile.tileData.dense;

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

        var pseudocount = 0; // if we use a log scale, then we'll set a pseudocount
        // equal to the smallest non-zero value
        this.valueScale = null;

        // console.log('valueScaling:', this.options.valueScaling);
        if (this.options.valueScaling === 'log') {
          var offsetValue = this.medianVisibleValue;

          if (!this.medianVisibleValue) {
            offsetValue = this.minValue();
          }

          this.valueScale = (0, _d3Scale.scaleLog)()
          // .base(Math.E)
          .domain([offsetValue, this.maxValue() + offsetValue]).range([this.dimensions[1], 0]);
          pseudocount = offsetValue;
        } else {
          // linear scale
          this.valueScale = (0, _d3Scale.scaleLinear)().domain([this.minValue(), this.maxValue()]).range([this.dimensions[1], 0]);
        }

        /*
        tile.scale = {
          minValue: this.valueScale.domain()[0],
          maxValue: this.valueScale.domain()[1]
        };
        */

        graphics.clear();
        this.drawAxis(this.valueScale);

        if (this.options.valueScaling === 'log' && this.valueScale.domain()[1] < 0) {
          console.warn('Negative values present when using a log scale', this.valueScale.domain());
          return;
        }

        var stroke = (0, _utils.colorToHex)(this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue');
        // this scale should go from an index in the data array to
        // a position in the genome coordinates
        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, this.tilesetInfo.tile_size]).range([tileX, tileX + tileWidth]);

        // let strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1;

        var strokeWidth = 0;
        graphics.lineStyle(strokeWidth, stroke, 1);

        var topColor = this.options.barFillColorTop ? this.options.barFillColorTop : 'green';
        var bottomColor = this.options.barFillColorBottom ? this.options.barFillColorBottom : 'red';

        // PIXI wants hex colors whereas d3 wants regular colors
        var topColorHex = (0, _utils.colorToHex)(topColor);
        var bottomColorHex = (0, _utils.colorToHex)(bottomColor);

        var opacity = 'barOpacity' in this.options ? this.options.barOpacity : 1;

        tile.drawnAtScale = this._xScale.copy();

        // the line at which the values will diverge
        var baseline = 0;
        if (this.options.valueScaling === 'log') {
          baseline = this.valueScale(1);
        } else {
          baseline = this.valueScale(0);
        }

        delete tile.svgData;

        for (var i = 0; i < tileValues.length; i++) {
          var xPos = this._xScale(tileXScale(i));
          var yPos = this.valueScale(tileValues[i] + pseudocount);

          var width = this._xScale(tileXScale(i + 1)) - xPos;
          // const height = this.dimensions[1] - yPos;

          if (yPos > baseline) {
            graphics.beginFill(bottomColorHex, opacity);
            this.addSVGInfo(tile, xPos, baseline, width, yPos - baseline, bottomColor);
          } else {
            graphics.beginFill(topColorHex, opacity);
            this.addSVGInfo(tile, xPos, yPos, width, baseline - yPos, topColor);
          }

          if (tileXScale(i) > this.tilesetInfo.max_pos[0]) {
            break;
          }
          // this data is in the last tile and extends beyond the length
          // of the coordinate system

          graphics.drawRect(xPos, tile.svgData.barYValues[i], width, tile.svgData.barHeights[i]);
        }
      }

      return renderTile;
    }()
  }]);
  return DivergentBarTrack;
}(_BarTrack3['default']);

// Utils


exports['default'] = DivergentBarTrack;

/***/ }),
/* 361 */
/***/ (function(module, exports, __nested_webpack_require_1916031__) {

"use strict";


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

var _isNan = __nested_webpack_require_1916031__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _slicedToArray2 = __nested_webpack_require_1916031__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_1916031__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1916031__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1916031__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1916031__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1916031__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1916031__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_1916031__(28);

var _HorizontalLine1DPixiTrack = __nested_webpack_require_1916031__(116);

var _HorizontalLine1DPixiTrack2 = _interopRequireDefault(_HorizontalLine1DPixiTrack);

var _utils = __nested_webpack_require_1916031__(10);

var _configs = __nested_webpack_require_1916031__(11);

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

var Horizontal1dHeatmapTrack = function (_HorizontalLine1DPixi) {
  (0, _inherits3['default'])(Horizontal1dHeatmapTrack, _HorizontalLine1DPixi);

  function Horizontal1dHeatmapTrack(context, options) {
    (0, _classCallCheck3['default'])(this, Horizontal1dHeatmapTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Horizontal1dHeatmapTrack.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal1dHeatmapTrack)).call(this, context, options));

    _this.setColorScale(options.colorRange);

    _this.opacity = options.opacity || 1;
    return _this;
  }

  (0, _createClass3['default'])(Horizontal1dHeatmapTrack, [{
    key: 'setColorScale',
    value: function () {
      function setColorScale(colorRange) {
        this.colorScale = colorRange ? (0, _utils.colorDomainToRgbaArray)(colorRange) : _configs.HEATED_OBJECT_MAP;

        // Normalize colormap upfront to save 3 divisions per data point during the
        // rendering.
        this.colorScale = this.colorScale.map(function (rgb) {
          return rgb.map(function (channel) {
            return channel / 255.0;
          });
        });
      }

      return setColorScale;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options) {
        if (options && options.colorRange) {
          this.setColorScale(options.colorRange);
        }

        this.opacity = options.opacity || 1;

        (0, _get3['default'])(Horizontal1dHeatmapTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal1dHeatmapTrack.prototype), 'rerender', this).call(this, options);
      }

      return rerender;
    }()
  }, {
    key: 'drawAxis',
    value: function () {
      function drawAxis() {
        // Disable axis for now.
      }

      return drawAxis;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        if (!tile.graphics || !tile.tileData || !tile.tileData.dense) return;

        var graphics = tile.graphics;

        var _getTilePosAndDimensi = this.getTilePosAndDimensions(tile.tileData.zoomLevel, tile.tileData.tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileWidth = _getTilePosAndDimensi.tileWidth;

        var tileValues = tile.tileData.dense;

        if (tileValues.length === 0) return;

        var _makeValueScale = this.makeValueScale(this.minValue(), this.medianVisibleValue, this.maxValue()),
            _makeValueScale2 = (0, _slicedToArray3['default'])(_makeValueScale, 2),
            valueScale = _makeValueScale2[0],
            pseudocount = _makeValueScale2[1];

        valueScale.range([254, 0]).clamp(true);
        this.valueScale = valueScale;

        graphics.clear();

        if (this.options.valueScaling === 'log' && this.valueScale.domain()[1] < 0) {
          console.warn('Negative values present when using a log scale', this.valueScale.domain());
          return;
        }

        // this scale should go from an index in the data array to
        // a position in the genome coordinates
        var tileXScale = (0, _d3Scale.scaleLinear)().domain([0, this.tilesetInfo.tile_size]).range([tileX, tileX + tileWidth]);

        graphics.lineStyle(0, 0, 0);

        // const logScaling = this.options.valueScaling === 'log';

        for (var i = 0; i < tileValues.length; i++) {
          if ((0, _isNan2['default'])(tileValues[i])) continue;

          var rgbIdx = Math.round(this.valueScale(tileValues[i] + pseudocount));

          if ((0, _isNan2['default'])(+rgbIdx)) continue;

          var xPos = this._xScale(tileXScale(i));
          var width = this._xScale(tileXScale(i + 1)) - xPos;
          var height = this.dimensions[1];

          tile.xValues[i] = xPos;
          tile.yValues[i] = rgbIdx;

          var rgb = this.colorScale[rgbIdx];
          var hex = _configs.GLOBALS.PIXI.utils.rgb2hex(rgb);

          graphics.beginFill(hex, this.opacity);

          if (i === 0) continue;

          if (tileXScale(i) > this.tilesetInfo.max_pos[0]) {
            // this data is in the last tile and extends beyond the length
            // of the coordinate system
            break;
          }

          if (tileValues[i] !== 0) {
            graphics.drawRect(xPos, 0, width, height);
          }
        }
      }

      return drawTile;
    }()
  }]);
  return Horizontal1dHeatmapTrack;
}(_HorizontalLine1DPixiTrack2['default']);

exports['default'] = Horizontal1dHeatmapTrack;

/***/ }),
/* 362 */
/***/ (function(module, exports, __nested_webpack_require_1921866__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_1921866__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _set = __nested_webpack_require_1921866__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1921866__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1921866__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1921866__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1921866__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_1921866__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_1921866__(28);

var _d3Array = __nested_webpack_require_1921866__(8);

var _utils = __nested_webpack_require_1921866__(10);

var _HorizontalTiled1DPixiTrack = __nested_webpack_require_1921866__(115);

var _HorizontalTiled1DPixiTrack2 = _interopRequireDefault(_HorizontalTiled1DPixiTrack);

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

var CNVIntervalTrack = function (_HorizontalTiled1DPix) {
  (0, _inherits3['default'])(CNVIntervalTrack, _HorizontalTiled1DPix);

  function CNVIntervalTrack(context, options) {
    (0, _classCallCheck3['default'])(this, CNVIntervalTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (CNVIntervalTrack.__proto__ || (0, _getPrototypeOf2['default'])(CNVIntervalTrack)).call(this, context, options));

    _this.seen = new _set2['default']();
    _this.pMain = _this.pMobile;

    _this.rows = [];
    return _this;
  }

  (0, _createClass3['default'])(CNVIntervalTrack, [{
    key: 'uid',
    value: function () {
      function uid(item) {
        return item[item.length - 2];
      }

      return uid;
    }()
  }, {
    key: 'segmentOverlap',
    value: function () {
      function segmentOverlap(segment1, segment2) {}

      return segmentOverlap;
    }()
  }, {
    key: 'drawAll',
    value: function () {
      function drawAll(allTileData) {
        var _this2 = this;

        this.pMain.clear();
        var seen = new _set2['default']();

        var segments = allTileData.map(function (x) {
          if (seen.has(_this2.uid(x))) {
            return null;
          }
          seen.add(_this2.uid(x));
          // console.log('length:', +x[2] - +x[1], 'id', tile.tileId)
          return {
            from: +x[1],
            to: +x[2],
            type: x[4],
            uid: _this2.uid(x)
          };
        }).filter(function (x) {
          return x;
        }); // filter out null values

        var rows = (0, _utils.segmentsToRows)(segments);
        this.rows = rows;

        this.draw();
      }

      return drawAll;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var rows = this.rows;

        if (!rows) {
          return;
        }

        var valueScale = (0, _d3Scale.scaleBand)().range([0, this.dimensions[1]]).padding(0.1).domain((0, _d3Array.range)(0, this.maxRows())); // draw one away from the center
        // .domain(range(0, 10));  // draw one away from the center

        var graphics = this.pMain;

        graphics.clear();

        graphics.lineStyle(1, 0x0000ff, 0);
        graphics.beginFill(0xff700b, 0.8);

        for (var i = 0; i < rows.length; i++) {
          for (var j = 0; j < rows[i].length; j++) {
            var interval = rows[i][j];

            var x1 = this._refXScale(interval.from);
            var x2 = this._refXScale(interval.to);

            var y1 = valueScale(i);
            var y2 = y1 + valueScale.bandwidth();

            var width = x2 - x1;
            var height = y2 - y1;

            graphics.drawRect(x1, y1, width, height);
          }
        }
      }

      return draw;
    }()
  }, {
    key: 'allTilesLoaded',
    value: function () {
      function allTilesLoaded() {
        var _this3 = this,
            _ref;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        var tileDatas = visibleAndFetchedIds.map(function (x) {
          return _this3.fetchedTiles[x].tileData.discrete;
        });
        var allTileData = (_ref = []).concat.apply(_ref, (0, _toConsumableArray3['default'])(tileDatas));

        this.drawAll(allTileData);
      }

      return allTilesLoaded;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {}

      return initTile;
    }()
  }, {
    key: 'maxRows',
    value: function () {
      function maxRows() {
        return this.rows.length;
      }

      return maxRows;
    }()
  }, {
    key: 'updateTile',
    value: function () {
      function updateTile(tile) {
        // this.redraw(tile);
      }

      return updateTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile) {
        var _this4 = this;

        tile.tileData.discrete.forEach(function (x) {
          var uid = x[x.length - 2];

          if (_this4.seen.has(uid)) {
            _this4.seen['delete'](uid);
          }
        });
      }

      return destroyTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {}

      return drawTile;
    }()
  }]);
  return CNVIntervalTrack;
}(_HorizontalTiled1DPixiTrack2['default']);

exports['default'] = CNVIntervalTrack;

/***/ }),
/* 363 */
/***/ (function(module, exports, __nested_webpack_require_1927468__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_1927468__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _slicedToArray2 = __nested_webpack_require_1927468__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _set = __nested_webpack_require_1927468__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1927468__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1927468__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1927468__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1927468__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1927468__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1927468__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _pubSubEs = __nested_webpack_require_1927468__(134);

var _pubSubEs2 = _interopRequireDefault(_pubSubEs);

var _TiledPixiTrack2 = __nested_webpack_require_1927468__(79);

var _TiledPixiTrack3 = _interopRequireDefault(_TiledPixiTrack2);

var _services = __nested_webpack_require_1927468__(24);

var _utils = __nested_webpack_require_1927468__(10);

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

// Services
function drawAnnotation(track, graphics, td, minSquareSize, xMin, xMax, yMin, yMax, minThres, flipDiagonal) {
  var startX = flipDiagonal ? track._xScale(td.yStart) : track._xScale(td.xStart);
  var endX = flipDiagonal ? track._xScale(td.yEnd) : track._xScale(td.xEnd);

  var startY = flipDiagonal ? track._yScale(td.xStart) : track._yScale(td.yStart);
  var endY = flipDiagonal ? track._yScale(td.xEnd) : track._yScale(td.yEnd);

  var uid = td.uid + flipDiagonal;

  var width = endX - startX;
  var height = endY - startY;

  var drawnRect = {
    x: startX,
    y: startY,
    width: width,
    height: height
  };

  if (minSquareSize) {
    if (width < minSquareSize || height < minSquareSize) {
      drawnRect = {
        x: startX - minSquareSize / 2,
        y: startY - minSquareSize / 2,
        width: minSquareSize,
        height: minSquareSize
      };
    }
  }

  track.drawnRects[uid] = drawnRect;

  var dRxMax = drawnRect.x + drawnRect.width;
  var dRyMax = drawnRect.y + drawnRect.height;

  // Only draw annotations that falls somehow within the viewport
  if (drawnRect.x > xMin && drawnRect.x < xMax || dRxMax > xMin && dRxMax < xMax || drawnRect.y > yMin && drawnRect.y < yMax || dRyMax > yMin && dRyMax < yMax) {
    if (drawnRect.width > minThres || drawnRect.height > minThres) {
      // console.log('x', drawnRect.x, 'y', drawnRect.y, 'xMin:', xMin, 'xMax', xMax);
      graphics.drawRect(drawnRect.x, drawnRect.y, drawnRect.width, drawnRect.height);

      track.publish('annotationDrawn', {
        trackUuid: track.uuid,
        annotationUuid: uid,
        viewPos: [drawnRect.x, drawnRect.y, drawnRect.width, drawnRect.height],
        dataPos: [td.xStart, td.xEnd, td.yStart, td.yEnd],
        importance: td.importance,
        info: {
          patternType: track.options.patternType
        }
      });
    }
  }
}

// Utils

var ArrowheadDomainsTrack = function (_TiledPixiTrack) {
  (0, _inherits3['default'])(ArrowheadDomainsTrack, _TiledPixiTrack);

  function ArrowheadDomainsTrack() {
    var _ref;

    (0, _classCallCheck3['default'])(this, ArrowheadDomainsTrack);

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

    var _this = (0, _possibleConstructorReturn3['default'])(this, (_ref = ArrowheadDomainsTrack.__proto__ || (0, _getPrototypeOf2['default'])(ArrowheadDomainsTrack)).call.apply(_ref, [this].concat(args)));

    _this.drawnRects = {};

    // Create a custom pubSub interface

    var _createPubSub = (0, _pubSubEs2['default'])(),
        publish = _createPubSub.publish,
        subscribe = _createPubSub.subscribe,
        unsubscribe = _createPubSub.unsubscribe;

    _this.publish = publish;
    _this.subscribe = subscribe;
    _this.unsubscribe = unsubscribe;
    return _this;
  }

  /*
   * The local tile identifier
   */


  (0, _createClass3['default'])(ArrowheadDomainsTrack, [{
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToLocalId;
    }()

    /**
     * The tile identifier used on the server
     */

  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'localToRemoteId',
    value: function () {
      function localToRemoteId(remoteId) {
        var idParts = remoteId.split('.');
        return idParts.slice(0, idParts.length - 1).join('.');
      }

      return localToRemoteId;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
        var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1]);

        var zoomLevel = Math.max(xZoomLevel, yZoomLevel);
        zoomLevel = Math.min(zoomLevel, this.maxZoom);

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()

    /**
     * Set which tiles are visible right now.
     *
     * @param tiles: A set of tiles which will be considered the currently visible
     * tile positions.
     */

  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this2 = this;

        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this2.tileToLocalId(x),
            remoteId: _this2.tileToRemoteId(x)
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.remoteId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        this.zoomLevel = this.calculateZoomLevel();
        // this.zoomLevel = 0;

        this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._yScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        var rows = this.xTiles;
        var cols = this.yTiles;
        var zoomLevel = this.zoomLevel;

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < rows.length; i++) {
          for (var j = 0; j < cols.length; j++) {
            var newTile = [zoomLevel, rows[i], cols[j]];

            tiles.push(newTile);
          }
        }

        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()

    /**
     * Create whatever is needed to draw this tile.
     */

  }, {
    key: 'initTile',
    value: function () {
      function initTile() /* tile */{
        // this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile() {
        // Nothing
      }

      return destroyTile;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        this.drawnRects = {};

        (0, _get3['default'])(ArrowheadDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ArrowheadDomainsTrack.prototype), 'draw', this).call(this);
      }

      return draw;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        var _this3 = this;

        var graphics = tile.graphics;

        if (!graphics) {
          return;
        }

        graphics.clear();

        var stroke = (0, _utils.colorToHex)(this.options.rectangleDomainStrokeColor || 'black');
        var fill = (0, _utils.colorToHex)(this.options.rectangleDomainFillColor || 'grey');

        graphics.lineStyle(typeof this.options.rectangleDomainStrokeWidth !== 'undefined' ? this.options.rectangleDomainStrokeWidth : 1, stroke, typeof this.options.rectangleDomainStrokeOpacity !== 'undefined' ? this.options.rectangleDomainStrokeOpacity : 1);
        graphics.beginFill(fill, typeof this.options.rectangleDomainFillOpacity !== 'undefined' ? this.options.rectangleDomainFillOpacity : 0.4);

        graphics.alpha = this.options.rectangleDomainOpacity || 0.5;

        var minSquareSize = this.options.minSquareSize && this.options.minSquareSize !== 'none' ? +this.options.minSquareSize : 0;

        var minThres = this.options.rectangleMinSize ? +this.options.rectangleMinSize : 0;

        var xMin = this._xScale.range()[0];
        var xMax = this._xScale.range()[1];
        var yMin = this._yScale.range()[0];
        var yMax = this._yScale.range()[1];

        if (!tile.tileData.length) return;

        // line needs to be scaled down so that it doesn't become huge
        tile.tileData.filter(function (td) {
          return !(td.uid in _this3.drawnRects);
        }).forEach(function (td) {
          drawAnnotation(_this3, graphics, td, minSquareSize, xMin, xMax, yMin, yMax, minThres, _this3.options.flipDiagonal === 'yes');

          if (_this3.options.flipDiagonal && _this3.options.flipDiagonal === 'copy') {
            drawAnnotation(_this3, graphics, td, minSquareSize, xMin, xMax, yMin, yMax, minThres, true);
          }
        });
      }

      return drawTile;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var _this4 = this;

        var track = null;
        var base = null;

        if ((0, _get3['default'])(ArrowheadDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ArrowheadDomainsTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(ArrowheadDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ArrowheadDomainsTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);

        var _loop = function () {
          function _loop(flipDiagonal) {
            var _loop2 = function () {
              function _loop2(tile) {
                // this tile has no data
                if (!tile.tileData || !tile.tileData.length) return 'continue';

                tile.tileData.forEach(function (td) {
                  var uid = td.uid + flipDiagonal;
                  var gTile = document.createElement('g');
                  gTile.setAttribute('transform', 'translate(' + String(tile.graphics.position.x) + ',' + String(tile.graphics.position.y) + ')scale(' + String(tile.graphics.scale.x) + ',' + String(tile.graphics.scale.y) + ')');
                  output.appendChild(gTile);

                  if (uid in _this4.drawnRects) {
                    var rect = _this4.drawnRects[uid];

                    var r = document.createElement('rect');
                    r.setAttribute('x', rect.x);
                    r.setAttribute('y', rect.y);
                    r.setAttribute('width', rect.width);
                    r.setAttribute('height', rect.height);

                    r.setAttribute('fill', _this4.options.rectangleDomainFillColor ? _this4.options.rectangleDomainFillColor : 'grey');
                    r.setAttribute('opacity', 0.3);

                    r.style.stroke = 'black';
                    r.style.strokeWidth = '1px';

                    gTile.appendChild(r);
                  }
                });
              }

              return _loop2;
            }();

            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
              for (var _iterator = (0, _getIterator3['default'])(_this4.visibleAndFetchedTiles()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var tile = _step.value;

                var _ret2 = _loop2(tile);

                if (_ret2 === 'continue') continue;
              }
            } catch (err) {
              _didIteratorError = true;
              _iteratorError = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion && _iterator['return']) {
                  _iterator['return']();
                }
              } finally {
                if (_didIteratorError) {
                  throw _iteratorError;
                }
              }
            }
          }

          return _loop;
        }();

        var _arr = [true, false];
        for (var _i = 0; _i < _arr.length; _i++) {
          var flipDiagonal = _arr[_i];
          _loop(flipDiagonal);
        }

        return [base, base];
      }

      return exportSVG;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(ArrowheadDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ArrowheadDomainsTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        if (this.xScale().domain()[0] === newXScale.domain()[0] && this.xScale().domain()[1] === newXScale.domain()[1] && this.yScale().domain()[0] === newYScale.domain()[0] && this.yScale().domain()[1] === newYScale.domain()[1]) return;

        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTiles();

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'leftTrackDraw',
    value: function () {
      function leftTrackDraw() {
        this.draw();
      }

      return leftTrackDraw;
    }()
  }]);
  return ArrowheadDomainsTrack;
}(_TiledPixiTrack3['default']);

exports['default'] = ArrowheadDomainsTrack;

/***/ }),
/* 364 */
/***/ (function(module, exports, __nested_webpack_require_1942845__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_1942845__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _set = __nested_webpack_require_1942845__(38);

var _set2 = _interopRequireDefault(_set);

var _slicedToArray2 = __nested_webpack_require_1942845__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_1942845__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1942845__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1942845__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1942845__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1942845__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1942845__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _pubSubEs = __nested_webpack_require_1942845__(134);

var _pubSubEs2 = _interopRequireDefault(_pubSubEs);

var _TiledPixiTrack2 = __nested_webpack_require_1942845__(79);

var _TiledPixiTrack3 = _interopRequireDefault(_TiledPixiTrack2);

var _configs = __nested_webpack_require_1942845__(11);

var _services = __nested_webpack_require_1942845__(24);

var _utils = __nested_webpack_require_1942845__(10);

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

// Services
var MOUSE_CLICK_TIME = 250;

// Utils


// Configs

var Annotations2dTrack = function (_TiledPixiTrack) {
  (0, _inherits3['default'])(Annotations2dTrack, _TiledPixiTrack);

  function Annotations2dTrack(context, options) {
    (0, _classCallCheck3['default'])(this, Annotations2dTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Annotations2dTrack.__proto__ || (0, _getPrototypeOf2['default'])(Annotations2dTrack)).call(this, context, options));

    var pubSub = context.pubSub;


    _this.drawnAnnotations = {};
    _this.drawnAnnoGfx = {};

    _this.selectedAnno = null;

    _this.options.minSquareSize = +_this.options.minSquareSize;

    var _createPubSub = (0, _pubSubEs2['default'])(),
        publish = _createPubSub.publish,
        subscribe = _createPubSub.subscribe,
        unsubscribe = _createPubSub.unsubscribe;

    _this.publish = publish;
    _this.subscribe = subscribe;
    _this.unsubscribe = unsubscribe;

    _this.sT = 0;

    _this.annoSelectedBound = _this.annoSelected.bind(_this);

    _this.pubSubs.push(pubSub.subscribe('annoSelected', _this.annoSelectedBound));
    return _this;
  }

  /* --------------------------- Getter / Setter ---------------------------- */

  (0, _createClass3['default'])(Annotations2dTrack, [{
    key: 'projection',


    /**
     * Point projection from the data to the view (pixel) coordinates
     * @param   {number}  x  Data X coordinate
     * @param   {number}  y  Data Y coordinate
     * @return  {array}  Tuple [x,y] containing the translated view coordinates.
     */
    value: function () {
      function projection(_ref) {
        var _ref2 = (0, _slicedToArray3['default'])(_ref, 2),
            x = _ref2[0],
            y = _ref2[1];

        return [this._xScale(x), this._yScale(y)];
      }

      return projection;
    }()

    /**
     * The local tile identifier
     *
     * @param  {Array}  tile  Array containing [zoomLevel, xPos, yPos]
     * @return  {String}  Joined ID string
     */

  }, {
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToLocalId;
    }()

    /**
     * The tile identifier used on the server
     *
     * @param  {Array}  tile  Array containing [zoomLevel, xPos, yPos]
     * @return  {String}  Joined ID string
     */

  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        return '' + String(tile.join('.'));
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'localToRemoteId',
    value: function () {
      function localToRemoteId(remoteId) {
        var idParts = remoteId.split('.');
        return idParts.slice(0, idParts.length - 1).join('.');
      }

      return localToRemoteId;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.minX, this.maxX);
        var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._yScale, this.minY, this.maxY);

        return (0, _utils.min)((0, _utils.max)(xZoomLevel, yZoomLevel), this.maxZoom);
      }

      return calculateZoomLevel;
    }()

    /**
     * Set which tiles are visible right now.
     *
     * @param tiles: A set of tiles which will be considered the currently visible
     * tile positions.
     */

  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this2 = this;

        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this2.tileToLocalId(x),
            remoteId: _this2.tileToRemoteId(x)
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.tileId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) return;

        this.zoomLevel = this.calculateZoomLevel();

        this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._xScale, this.minX, this.maxX, this.tilesetInfo.max_zoom, this.maxSize);

        this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._yScale, this.minY, this.maxY, this.tilesetInfo.max_zoom, this.maxSize);

        var zoomLevel = this.zoomLevel;

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < this.xTiles.length; i++) {
          for (var j = 0; j < this.yTiles.length; j++) {
            tiles.push([zoomLevel, this.xTiles[i], this.yTiles[j]]);
          }
        }

        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        this.drawnAnnotations = {};

        (0, _get3['default'])(Annotations2dTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Annotations2dTrack.prototype), 'draw', this).call(this);
      }

      return draw;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        var _this3 = this;

        var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var silent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

        if (!tile.graphics) return;

        tile.graphics.__tile__ = tile;

        var graphics = tile.graphics;
        graphics.clear();

        this.setBorderStyle(graphics);
        this.setFill(graphics);

        graphics.alpha = +this.options.rectangleDomainOpacity;

        if (!tile.tileData.length) return;

        tile.tileData.filter(function (td) {
          return !(td.uid in _this3.drawnAnnotations) || force;
        }).forEach(function (td) {
          var _projection = _this3.projection([td.xStart, td.yStart]),
              _projection2 = (0, _slicedToArray3['default'])(_projection, 2),
              startX = _projection2[0],
              startY = _projection2[1];

          var _projection3 = _this3.projection([td.xEnd, td.yEnd]),
              _projection4 = (0, _slicedToArray3['default'])(_projection3, 2),
              endX = _projection4[0],
              endY = _projection4[1];

          if (_this3.options.exclude && _this3.options.exclude.indexOf(td.uid) >= 0) {
            return;
          }

          _this3.drawAnnotation(_this3.prepAnnotation(graphics, td.uid, startX, startY, endX - startX, endY - startY, td), silent);
        });
      }

      return drawTile;
    }()
  }, {
    key: 'prepAnnotation',
    value: function () {
      function prepAnnotation(graphics, uid, startX, startY, width, height, td) {
        var info = void 0;

        try {
          info = JSON.parse(td.fields);
        } catch (e) {
          // Nothing
        }

        return {
          graphics: graphics,
          id: td.id,
          uid: uid,
          annotation: {
            x: startX,
            y: startY,
            width: width,
            height: height
          },
          dataPos: [td.xStart, td.xEnd, td.yStart, td.yEnd],
          importance: td.importance,
          info: info
        };
      }

      return prepAnnotation;
    }()
  }, {
    key: 'drawAnnotation',
    value: function () {
      function drawAnnotation(_ref3, silent) {
        var _this4 = this;

        var graphics = _ref3.graphics,
            id = _ref3.id,
            uid = _ref3.uid,
            annotation = _ref3.annotation,
            dataPos = _ref3.dataPos,
            importance = _ref3.importance,
            info = _ref3.info;

        if (this.options.minSquareSize) {
          if (annotation.width < this.options.minSquareSize || annotation.height < this.options.minSquareSize) {
            annotation.x = (annotation.x + annotation.width) / 2;
            annotation.y = (annotation.y + annotation.height) / 2;
            annotation.width = this.options.minSquareSize;
            annotation.height = this.options.minSquareSize;
          }
        }

        this.drawnAnnotations[uid] = annotation;

        var viewPos = [annotation.x, annotation.y, annotation.width, annotation.height];

        var rectGfx = this.drawnAnnoGfx[uid];
        if (!rectGfx) {
          rectGfx = new _configs.GLOBALS.PIXI.Graphics();
          this.drawnAnnoGfx[uid] = rectGfx;
        }

        if (graphics.children.indexOf(rectGfx) === -1) {
          graphics.addChild(rectGfx);
        }

        this._drawRect(rectGfx, viewPos, uid);

        graphics.interactive = true;
        rectGfx.interactive = true;
        rectGfx.buttonMode = true;

        var payload = {
          id: id,
          uid: uid,
          dataPos: dataPos,
          importance: importance,
          info: info,
          viewPos: [annotation.x, annotation.y,
          // To have the same format as `dataPos`, i.e.:
          // a quadruple of [x0, y0, x1, y1]
          annotation.x + annotation.width, annotation.y + annotation.height]
        };

        rectGfx.mouseover = function () {
          return _this4.hover(rectGfx, viewPos, uid);
        };
        rectGfx.mouseout = function () {
          return _this4.blur(rectGfx, viewPos, uid);
        };

        rectGfx.mousedown = function () {
          return _this4.mouseDown();
        };
        rectGfx.mouseup = function (event) {
          return _this4.mouseUp(rectGfx, viewPos, uid, event, payload);
        };

        if (!silent) {
          this.publish('annotationDrawn', {
            trackUuids: this.uuid,
            annotationUuid: uid,
            annotationId: id,
            viewPos: viewPos,
            dataPos: dataPos,
            importance: importance,
            info: info
          });
        }
      }

      return drawAnnotation;
    }()
  }, {
    key: '_drawRect',
    value: function () {
      function _drawRect(graphics, viewPos, uid) {
        var stroke = this.options.rectangleDomainStrokeColor;
        var strokeWidth = this.options.rectangleDomainStrokeWidth;
        var strokeAlpha = this.options.rectangleDomainStrokeOpacity;
        var fill = this.options.rectangleDomainFillColor;
        var fillAlpha = this.options.rectangleDomainFillOpacity;

        if (this.hoveredAnno === uid) {
          stroke = this.options.hoverColor;
          strokeWidth = this.options.rectangleDomainStrokeWidth + 1 || 2;
          strokeAlpha = 1;
          fill = this.options.hoverColor;
          fillAlpha = this.options.rectangleDomainFillOpacity;
        }

        if (this.selectedAnno && this.selectedAnno.uid === uid) {
          stroke = this.options.selectColor;
          strokeWidth = this.options.rectangleDomainStrokeWidth + 1 || 2;
          strokeAlpha = 1;
          fill = this.options.selectColor;
          fillAlpha = (0, _utils.max)(0.33, this.options.rectangleDomainFillOpacity);
        }

        graphics.clear();
        if (this.options.trackBorderBgWidth) {
          this.setBorderStyle(graphics, this.options.trackBorderBgColor, this.options.trackBorderBgWidth, this.options.trackBorderBgAlpha);
          this.setFill(graphics, fill, 0);
          graphics.drawRect.apply(graphics, (0, _toConsumableArray3['default'])(viewPos));
        }
        this.setBorderStyle(graphics, stroke, strokeWidth, strokeAlpha);
        this.setFill(graphics, fill, fillAlpha);
        graphics.drawRect.apply(graphics, (0, _toConsumableArray3['default'])(viewPos));
        graphics.__viewPos__ = viewPos;
      }

      return _drawRect;
    }()
  }, {
    key: 'context',
    value: function () {
      function context(graphics, viewPos, uid) {
        return function (proc) {
          return proc(graphics, viewPos, uid);
        };
      }

      return context;
    }()
  }, {
    key: 'click',
    value: function () {
      function click(graphics, viewPos, uid, event, payload) {
        this.select(graphics, viewPos, uid);
        this.pubSub.publish('app.click', {
          type: 'annotation',
          event: event,
          payload: payload
        });
      }

      return click;
    }()
  }, {
    key: 'mouseDown',
    value: function () {
      function mouseDown() {
        this.sT = performance.now();
      }

      return mouseDown;
    }()
  }, {
    key: 'mouseUp',
    value: function () {
      function mouseUp(graphics, viewPos, uid, event, payload) {
        if (performance.now() - this.sT <= MOUSE_CLICK_TIME) {
          this.click(graphics, viewPos, uid, event, payload);
        }
      }

      return mouseUp;
    }()
  }, {
    key: 'hover',
    value: function () {
      function hover(graphics, viewPos, uid) {
        this.hoveredAnno = uid;
        this._drawRect(graphics, viewPos, uid);
        this.animate();
      }

      return hover;
    }()
  }, {
    key: 'focus',
    value: function () {
      function focus(graphics, viewPos, uid) {
        this._drawRect(graphics, viewPos, uid);
        this.animate();
      }

      return focus;
    }()
  }, {
    key: 'blur',
    value: function () {
      function blur(graphics, viewPos, uid) {
        this.hoveredAnno = null;
        this._drawRect(graphics, viewPos, uid);
        this.animate();
      }

      return blur;
    }()
  }, {
    key: 'select',
    value: function () {
      function select(graphics, viewPos, uid) {
        var silent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

        var prevGfx = null;
        var prevUid = null;

        if (this.selectedAnno) {
          prevGfx = this.selectedAnno.graphics;
          prevUid = this.selectedAnno.uid;
        }

        this.selectedAnno = { graphics: graphics, uid: uid };
        this.focus(graphics, viewPos, uid);

        if (this.options.onSelect && !silent) {
          window[this.options.onSelect](uid);
          this.pubSub.publish('annoSelected', uid);
        }

        if (prevGfx && prevUid) {
          this.blur(prevGfx, prevGfx.__viewPos__, prevUid);
        }
      }

      return select;
    }()
  }, {
    key: 'unselect',
    value: function () {
      function unselect() {
        var gfx = this.selectedAnno.graphics;
        var uid = this.selectedAnno.uid;
        this.selectedAnno = null;
        this.blur(gfx, gfx.__viewPos__, uid);
      }

      return unselect;
    }()
  }, {
    key: 'annoSelected',
    value: function () {
      function annoSelected(uid) {
        if (!this.selectedAnno || this.selectedAnno.uid !== uid) {
          if (this.selectedAnno) this.unselect();
          var gfx = this.drawnAnnoGfx[uid];
          if (gfx) this.select(gfx, gfx.__viewPos__, uid, true);
        }
      }

      return annoSelected;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var _this5 = this;

        var track = null;
        var base = null;

        if ((0, _get3['default'])(Annotations2dTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Annotations2dTrack.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(Annotations2dTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Annotations2dTrack.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }

        var output = document.createElement('g');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);

        this.visibleAndFetchedTiles().filter(function (tile) {
          return tile.tileData && tile.tileData.length;
        }).map(function (tile) {
          return { graphics: tile.graphics, td: tile.tileData };
        }).forEach(function (_ref4) {
          var td = _ref4.td,
              graphics = _ref4.graphics;

          var gTile = document.createElement('g');

          gTile.setAttribute('transform', 'translate(' + String(graphics.position.x) + ',' + String(graphics.position.y) + ')scale(' + String(graphics.scale.x) + ',' + String(graphics.scale.y) + ')');
          output.appendChild(gTile);

          if (td.uid in _this5.drawnAnnotations) {
            var rect = _this5.drawnAnnotations[td.uid];
            var r = document.createElement('rect');

            r.setAttribute('x', rect.x);
            r.setAttribute('y', rect.y);
            r.setAttribute('width', rect.width);
            r.setAttribute('height', rect.height);

            r.setAttribute('fill', _this5.options.fillColor || 'grey');
            r.setAttribute('opacity', 0.3);

            r.style.stroke = _this5.options.fillColor || 'grey';
            r.style.strokeWidth = '1px';

            gTile.appendChild(r);
          }
        });

        return [base, base];
      }

      return exportSVG;
    }()
  }, {
    key: 'setBorderStyle',
    value: function () {
      function setBorderStyle(graphics) {
        var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.options.rectangleDomainStrokeColor;
        var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.options.rectangleDomainStrokeWidth;
        var alpha = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : this.options.rectangleDomainStrokeOpacity;

        graphics.lineStyle(typeof width !== 'undefined' ? width : 1, (0, _utils.colorToHex)(color || 'black'), typeof alpha !== 'undefined' ? alpha : 1);
      }

      return setBorderStyle;
    }()
  }, {
    key: 'setFill',
    value: function () {
      function setFill(graphics) {
        var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.options.rectangleDomainFillColor;
        var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.options.rectangleDomainFillOpacity;

        graphics.beginFill((0, _utils.colorToHex)(color || 'grey'), typeof alpha !== 'undefined' ? alpha : 0.4);
      }

      return setFill;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(Annotations2dTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Annotations2dTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTiles();
        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'minX',
    get: function () {
      function get() {
        return this.tilesetInfo && this.tilesetInfo.min_pos ? this.tilesetInfo.min_pos[0] : 0;
      }

      return get;
    }()
  }, {
    key: 'maxX',
    get: function () {
      function get() {
        return this.tilesetInfo && this.tilesetInfo.max_pos ? this.tilesetInfo.max_pos[0] : this.tilesetInfo.max_width || this.tilesetInfo.max_size;
      }

      return get;
    }()
  }, {
    key: 'minY',
    get: function () {
      function get() {
        // Currently HiGlass only supports squared tile sets
        return this.minX;
      }

      return get;
    }()
  }, {
    key: 'maxY',
    get: function () {
      function get() {
        // Currently HiGlass only supports squared tile sets
        return this.maxX;
      }

      return get;
    }()
  }, {
    key: 'maxSize',
    get: function () {
      function get() {
        var maxSize = this.tilesetInfo.max_pos && Math.max(this.tilesetInfo.max_pos[0] - this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[1] - this.tilesetInfo.min_pos[1]);

        if (maxSize) return maxSize;

        if (this.tilesetInfo.max_size) return this.tilesetInfo.max_size;

        return 0;
      }

      return get;
    }()
  }]);
  return Annotations2dTrack;
}(_TiledPixiTrack3['default']);

exports['default'] = Annotations2dTrack;

/***/ }),
/* 365 */
/***/ (function(module, exports, __nested_webpack_require_1964986__) {

"use strict";


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

var _values = __nested_webpack_require_1964986__(37);

var _values2 = _interopRequireDefault(_values);

var _getPrototypeOf = __nested_webpack_require_1964986__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1964986__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1964986__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1964986__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1964986__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1964986__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Color = __nested_webpack_require_1964986__(9);

var _PixiTrack2 = __nested_webpack_require_1964986__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _configs = __nested_webpack_require_1964986__(11);

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

var Annotations1dTrack = function (_PixiTrack) {
  (0, _inherits3['default'])(Annotations1dTrack, _PixiTrack);

  function Annotations1dTrack(context, options, isVertical) {
    (0, _classCallCheck3['default'])(this, Annotations1dTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Annotations1dTrack.__proto__ || (0, _getPrototypeOf2['default'])(Annotations1dTrack)).call(this, context, options));

    _this.pubSub = context.pubSub;
    _this.options = options;
    _this.isVertical = isVertical;

    _this.rects = {};

    _this.defaultColor = (0, _d3Color.color)('red');
    return _this;
  }

  (0, _createClass3['default'])(Annotations1dTrack, [{
    key: 'draw',
    value: function () {
      function draw() {
        var _this2 = this;

        var globalMinRectWidth = typeof this.options.minRectWidth !== 'undefined' ? this.options.minRectWidth : 10;

        var globalFill = typeof this.options.fill !== 'undefined' ? (0, _d3Color.color)(this.options.fill) : this.defaultColor;

        var globalFillOpacity = typeof this.options.fillOpacity !== 'undefined' ? +this.options.fillOpacity : 0.2;

        var globalStroke = typeof this.options.stroke !== 'undefined' ? (0, _d3Color.color)(this.options.stroke) : this.defaultColor;

        var globalStrokeWidth = typeof this.options.strokeWidth !== 'undefined' ? +this.options.strokeWidth : 1;

        var globalStrokeOpacity = typeof this.options.strokeOpacity !== 'undefined' ? +this.options.strokeOpacity : 0;

        var strokePos = void 0;
        if (this.options.strokePos && this.options.strokePos.length) {
          strokePos = Array.isArray(this.options.strokePos) ? this.options.strokePos : [this.options.strokePos];
        }

        (0, _get3['default'])(Annotations1dTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Annotations1dTrack.prototype), 'draw', this).call(this);
        var graphics = this.pMain;
        graphics.clear();

        // The time stamp is used to keep track which rectangles have been drawn per
        // draw call. Each rectangle previously drawn that is not visible anymore
        // (i.e., is not drawn in the current draw call) will be removed at the end
        // by checking against the time stamp.
        var timeStamp = performance.now();

        // Regions have to follow the following form:
        // start, end, fill, stroke, fillOpacity, strokeOpcaity, min-size
        // If `color-line` is not given, `color-fill` is used
        this.options.regions.forEach(function (region) {
          var id = String(region[0]) + '-' + String(region[1]);

          if (!_this2.rects[id]) {
            _this2.rects[id] = { graphics: new _configs.GLOBALS.PIXI.Graphics() };
            graphics.addChild(_this2.rects[id].graphics);
          }

          _this2.rects[id].timeStamp = timeStamp;

          var fill = (0, _d3Color.color)(region[2]) || globalFill;
          var stroke = (0, _d3Color.color)(region[3]) || globalStroke;

          if (!stroke) {
            stroke = fill;
          }

          var fillHex = _configs.GLOBALS.PIXI.utils.rgb2hex([fill.r / 255.0, fill.g / 255.0, fill.b / 255.0]);
          var strokeHex = _configs.GLOBALS.PIXI.utils.rgb2hex([stroke.r / 255.0, stroke.g / 255.0, stroke.b / 255.0]);

          if (strokePos) {
            graphics.lineStyle(1, strokeHex, 0);
            graphics.beginFill(strokeHex, +region[5] || globalStrokeOpacity);
          } else {
            graphics.lineStyle(globalStrokeWidth, strokeHex, +region[5] || globalStrokeOpacity);
            graphics.beginFill(fillHex, +region[4] || globalFillOpacity);
          }

          var scale = _this2.isVertical ? _this2._yScale : _this2._xScale;

          var start = scale(+region[0]);
          var end = scale(+region[1]);

          var width = end - start;

          var minRectWidth = typeof region[6] !== 'undefined' ? region[6] : globalMinRectWidth;

          if (width < minRectWidth) {
            // this region is too small to draw so center it on the location
            // where it would be drawn
            start = (start + end) / 2 - minRectWidth / 2;
            width = minRectWidth;
          }

          if (strokePos) {
            graphics.lineStyle(1, strokeHex, 0);
            graphics.beginFill(strokeHex, +region[5] || globalStrokeOpacity);

            strokePos.forEach(function (pos) {
              if (pos === 'top' || pos === 'around') {
                if (_this2.isVertical) {
                  graphics.drawRect(0, start, globalStrokeWidth, width);
                } else {
                  graphics.drawRect(start, 0, width, globalStrokeWidth);
                }
              }

              if (pos === 'right' || pos === 'around') {
                if (_this2.isVertical) {
                  graphics.drawRect(0, start, _this2.dimensions[0], globalStrokeWidth);
                } else {
                  graphics.drawRect(start, 0, globalStrokeWidth, _this2.dimensions[1]);
                }
              }

              if (pos === 'bottom' || pos === 'around') {
                if (_this2.isVertical) {
                  graphics.drawRect(_this2.dimensions[0] - globalStrokeWidth, start, globalStrokeWidth, width);
                } else {
                  graphics.drawRect(start, _this2.dimensions[1] - globalStrokeWidth, width, globalStrokeWidth);
                }
              }

              if (pos === 'left' || pos === 'around') {
                if (_this2.isVertical) {
                  graphics.drawRect(0, start + width - globalStrokeWidth, _this2.dimensions[0], globalStrokeWidth);
                } else {
                  graphics.drawRect(start + width - globalStrokeWidth, 0, globalStrokeWidth, _this2.dimensions[1]);
                }
              }
            });
          } else {
            graphics.lineStyle(globalStrokeWidth, strokeHex, +region[5] || globalStrokeOpacity);
          }

          // Make annotation clickable
          _this2.rects[id].graphics.clear();
          _this2.rects[id].graphics.interactive = true;
          _this2.rects[id].graphics.buttonMode = true;

          graphics.beginFill(fillHex, +region[4] || globalFillOpacity);
          if (_this2.isVertical) {
            graphics.drawRect(0, start, _this2.dimensions[0], width);
            _this2.rects[id].graphics.hitArea = new _configs.GLOBALS.PIXI.Rectangle(0, start, _this2.dimensions[0], width);
          } else {
            graphics.drawRect(start, 0, width, _this2.dimensions[1]);
            _this2.rects[id].graphics.hitArea = new _configs.GLOBALS.PIXI.Rectangle(start, 0, width, _this2.dimensions[1]);
          }

          _this2.rects[id].graphics.mousedown = function () {
            _this2.rects[id].mouseDownTime = performance.now();
          };

          _this2.rects[id].graphics.mouseup = function (event) {
            if (performance.now() - _this2.rects[id].mouseDownTime < _configs.MAX_CLICK_DELAY) {
              _this2.pubSub.publish('app.click', {
                type: 'annotation',
                event: event,
                payload: region
              });
            }
          };
        });

        // Remove outdated rects, i.e., rects whose time stamp is not the current
        // time stamp stored above.
        (0, _values2['default'])(this.rects).filter(function (rect) {
          return rect.timeStamp !== timeStamp;
        }).forEach(function (rect) {
          return graphics.removeChild(rect.graphics);
        });
      }

      return draw;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(Annotations1dTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Annotations1dTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }]);
  return Annotations1dTrack;
}(_PixiTrack3['default']);

// Maximum delay in ms between mousedown and mouseup that is registered as a
// click. Note we need to use mousedown and mouseup as PIXI doesn't recognize
// click events with out current setup. Since most UIs treat long clicks as
// either something special or a cancelation we follow best practices and
// implement a threshold on the delay as well.


exports['default'] = Annotations1dTrack;

/***/ }),
/* 366 */
/***/ (function(module, exports, __nested_webpack_require_1974824__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_1974824__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _set = __nested_webpack_require_1974824__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1974824__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1974824__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1974824__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1974824__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1974824__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1974824__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _TiledPixiTrack2 = __nested_webpack_require_1974824__(79);

var _TiledPixiTrack3 = _interopRequireDefault(_TiledPixiTrack2);

var _services = __nested_webpack_require_1974824__(24);

var _utils = __nested_webpack_require_1974824__(10);

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

var Horizontal2DDomainsTrack = function (_TiledPixiTrack) {
  (0, _inherits3['default'])(Horizontal2DDomainsTrack, _TiledPixiTrack);

  function Horizontal2DDomainsTrack(context, options) {
    (0, _classCallCheck3['default'])(this, Horizontal2DDomainsTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Horizontal2DDomainsTrack.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal2DDomainsTrack)).call(this, context, options));

    _this.drawnRects = new _set2['default']();
    _this.pMain = _this.pMobile;
    return _this;
  }

  (0, _createClass3['default'])(Horizontal2DDomainsTrack, [{
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        /*
         * The local tile identifier
         */

        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToLocalId;
    }()
  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        /**
         * The tile identifier used on the server
         */

        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'localToRemoteId',
    value: function () {
      function localToRemoteId(remoteId) {
        var idParts = remoteId.split('.');
        return idParts.slice(0, idParts.length - 1).join('.');
      }

      return localToRemoteId;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
        var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1]);

        var zoomLevel = Math.max(xZoomLevel, yZoomLevel);
        zoomLevel = Math.min(zoomLevel, this.maxZoom);

        if (this.options && this.options.maxZoom) {
          if (this.options.maxZoom >= 0) {
            zoomLevel = Math.min(this.options.maxZoom, zoomLevel);
          } else {
            console.error('Invalid maxZoom on track:', this);
          }
        }

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this2 = this;

        /**
         * Set which tiles are visible right now.
         *
         * @param tiles: A set of tiles which will be considered the currently visible
         * tile positions.
         */
        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this2.tileToLocalId(x),
            remoteId: _this2.tileToRemoteId(x)
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.tileId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        /**
         * Taken from HorizontalHeatmapTrack.js
         */

        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        this.zoomLevel = this.calculateZoomLevel();

        // this.zoomLevel = 0;
        var expandedXScale = this._xScale.copy();

        // we need to expand the domain of the X-scale because we are showing diagonal tiles.
        // to make sure the view is covered up the entire height, we need to expand by
        // viewHeight * sqrt(2)
        // on each side
        expandedXScale.domain([this._xScale.invert(this._xScale.range()[0] - this.dimensions[1] * Math.sqrt(2)), this._xScale.invert(this._xScale.range()[1] + this.dimensions[1] * Math.sqrt(2))]);

        this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, expandedXScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, expandedXScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        var rows = this.xTiles;
        var cols = this.yTiles;
        var zoomLevel = this.zoomLevel;

        var maxWidth = this.tilesetInfo.max_width;
        var tileWidth = maxWidth / Math.pow(2, zoomLevel);

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < rows.length; i++) {
          for (var j = i; j < cols.length; j++) {
            // the length between the bottom of the track and the bottom corner of the tile
            // draw it out to understand better!
            var tileBottomPosition = (j - i - 2) * (this._xScale(tileWidth) - this._xScale(0)) * Math.sqrt(2) / 2;

            if (tileBottomPosition > this.dimensions[1]) {
              // this tile won't be visible so we don't need to fetch it
              continue;
            }

            var newTile = [zoomLevel, rows[i], cols[j]];
            newTile.mirrored = false;

            tiles.push(newTile);
          }
        }

        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        /**
         * Create whatever is needed to draw this tile.
         */
        (0, _get3['default'])(Horizontal2DDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal2DDomainsTrack.prototype), 'initTile', this).call(this, tile);

        // this.drawTile(tile);
        this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile, graphics) {}

      return destroyTile;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        // console.log('delayDrawing:', this.delayDrawing, this.dimensions[1]);
        if (!this.delayDrawing) {
          this.drawnRects.clear();
        }

        (0, _get3['default'])(Horizontal2DDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal2DDomainsTrack.prototype), 'draw', this).call(this);
      }

      return draw;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        if (!tile.graphics) {
          return;
        }

        // console.log('Id2DTiled drawTile...');
        var graphics = tile.graphics;

        graphics.clear();

        var stroke = (0, _utils.colorToHex)(this.options.rectangleDomainStrokeColor ? this.options.rectangleDomainStrokeColor : 'black');
        var fill = (0, _utils.colorToHex)(this.options.rectangleDomainFillColor ? this.options.rectangleDomainFillColor : 'grey');

        graphics.lineStyle(1 / this.pMain.scale.x, stroke, 1);
        graphics.beginFill(fill, 0.4);
        graphics.alpha = this.options.rectangleDomainOpacity ? this.options.rectangleDomainOpacity : 0.5;

        if (!tile.tileData.sort) return;

        // line needs to be scaled down so that it doesn't become huge
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(tile.tileData), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var td = _step.value;

            var startX = this._refXScale(td.xStart);
            var endX = this._refXScale(td.xEnd);

            var startY = this._refYScale(td.yStart);
            var endY = this._refYScale(td.yEnd);

            var uid = td.uid;

            if (this.drawnRects.has(uid)) {
              continue;
            }
            // we've already drawn this rectangle in another tile

            this.drawnRects.add(uid);
            graphics.drawRect(startX, startY, endX - startX, endY - startY);

            graphics.pivot.x = this._refXScale(0);
            graphics.pivot.y = this._refYScale(0);
            graphics.scale.x = -1 / Math.sqrt(2);
            graphics.rotation = -3 * Math.PI / 4;
            graphics.scale.y = 1 / Math.sqrt(2);

            graphics.position.x = this._refXScale(0);
            graphics.position.y = 0;
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return drawTile;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(Horizontal2DDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal2DDomainsTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        (0, _get3['default'])(Horizontal2DDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal2DDomainsTrack.prototype), 'refScalesChanged', this).call(this, refXScale, refYScale);

        for (var uid in this.fetchedTiles) {
          var tile = this.fetchedTiles[uid];

          if (tile.sprite) {
            var graphics = tile.graphics;

            graphics.pivot.x = this._refXScale(0);
            graphics.pivot.y = this._refYScale(0);
            graphics.scale.x = -1 / Math.sqrt(2);
            graphics.rotation = -3 * Math.PI / 4;
            graphics.scale.y = 1 / Math.sqrt(2);

            graphics.position.x = this._refXScale(0);
            graphics.position.y = 0;
          } else {
            // console.log('skipping...', tile.tileId);
          }
        }
      }

      return refScalesChanged;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, tx, ty) {
        (0, _get3['default'])(Horizontal2DDomainsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Horizontal2DDomainsTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale, k, tx, ty);
        // console.log('zoomed this.pMain.position:', this.pMain.position.x, this.pMain.position.y,
        // this.pMain.scale.x, this.pMain.scale.y);

        this.pMain.position.x = tx;
        this.pMain.position.y = this.position[1] + this.dimensions[1]; // translateY;

        this.pMain.scale.x = k; // scaleX;
        this.pMain.scale.y = k; // scaleY;

        if (this.options.oneDHeatmapFlipped) {
          this.pMain.scale.y = -k;
          this.pMain.position.y = this.position[1];
        }

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'leftTrackDraw',
    value: function () {
      function leftTrackDraw() {
        this.draw();
      }

      return leftTrackDraw;
    }()
  }]);
  return Horizontal2DDomainsTrack;
}(_TiledPixiTrack3['default']);

exports['default'] = Horizontal2DDomainsTrack;

/***/ }),
/* 367 */
/***/ (function(module, exports, __nested_webpack_require_1987704__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_1987704__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _set = __nested_webpack_require_1987704__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_1987704__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1987704__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1987704__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1987704__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1987704__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1987704__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _TiledPixiTrack2 = __nested_webpack_require_1987704__(79);

var _TiledPixiTrack3 = _interopRequireDefault(_TiledPixiTrack2);

var _services = __nested_webpack_require_1987704__(24);

var _utils = __nested_webpack_require_1987704__(10);

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

var SquareMarkersTrack = function (_TiledPixiTrack) {
  (0, _inherits3['default'])(SquareMarkersTrack, _TiledPixiTrack);

  function SquareMarkersTrack(context, options) {
    (0, _classCallCheck3['default'])(this, SquareMarkersTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (SquareMarkersTrack.__proto__ || (0, _getPrototypeOf2['default'])(SquareMarkersTrack)).call(this, context, options));

    _this.drawnRects = new _set2['default']();
    return _this;
  }

  /*
   * The local tile identifier
   */


  (0, _createClass3['default'])(SquareMarkersTrack, [{
    key: 'tileToLocalId',
    value: function () {
      function tileToLocalId(tile) {
        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToLocalId;
    }()

    /**
     * The tile identifier used on the server
     */

  }, {
    key: 'tileToRemoteId',
    value: function () {
      function tileToRemoteId(tile) {
        // tile contains [zoomLevel, xPos, yPos]
        return '' + String(tile.join('.'));
      }

      return tileToRemoteId;
    }()
  }, {
    key: 'localToRemoteId',
    value: function () {
      function localToRemoteId(remoteId) {
        var idParts = remoteId.split('.');
        return idParts.slice(0, idParts.length - 1).join('.');
      }

      return localToRemoteId;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
        var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1]);

        var zoomLevel = Math.max(xZoomLevel, yZoomLevel);
        zoomLevel = Math.min(zoomLevel, this.maxZoom);

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'setVisibleTiles',
    value: function () {
      function setVisibleTiles(tilePositions) {
        var _this2 = this;

        /**
         * Set which tiles are visible right now.
         *
         * @param tiles: A set of tiles which will be considered the currently visible
         * tile positions.
         */
        this.visibleTiles = tilePositions.map(function (x) {
          return {
            tileId: _this2.tileToLocalId(x),
            remoteId: _this2.tileToRemoteId(x)
          };
        });

        this.visibleTileIds = new _set2['default'](this.visibleTiles.map(function (x) {
          return x.tileId;
        }));
      }

      return setVisibleTiles;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        var mirrorTiles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        this.zoomLevel = this.calculateZoomLevel();
        // this.zoomLevel = 0;

        this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, this._yScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

        var rows = this.xTiles;
        var cols = this.yTiles;
        var zoomLevel = this.zoomLevel;

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < rows.length; i++) {
          for (var j = 0; j < cols.length; j++) {
            var newTile = [zoomLevel, rows[i], cols[j]];

            tiles.push(newTile);
          }
        }

        //
        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        /**
         * Create whatever is needed to draw this tile.
         */
        // this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'destroyTile',
    value: function () {
      function destroyTile(tile, graphics) {}

      return destroyTile;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        this.drawnRects.clear();

        (0, _get3['default'])(SquareMarkersTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(SquareMarkersTrack.prototype), 'draw', this).call(this);
      }

      return draw;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        if (!tile.graphics) {
          return;
        }

        // console.log('tile:', tile);
        // console.log('Id2DTiled drawTile...');
        var graphics = tile.graphics;

        graphics.clear();

        var fill = (0, _utils.colorToHex)('green');

        graphics.lineStyle(1, 0x0000ff, 1);
        graphics.beginFill(fill, 0.8);
        graphics.alpha = 0.5;

        // line needs to be scaled down so that it doesn't become huge
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(tile.tileData), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var td = _step.value;

            var startX = this._xScale(td.xStart);
            var endX = this._xScale(td.xEnd);

            var startY = this._yScale(td.yStart);
            var endY = this._yScale(td.yEnd);

            var uid = td.uid;

            if (this.drawnRects.has(uid)) {
              continue;
            }
            // we've already drawn this rectangle in another tile

            this.drawnRects.add(uid);

            var MIN_WIDTH = 6;
            var MIN_HEIGHT = 6;

            var width = endY - startY;
            var height = endX - startX;

            // we're going to draw stuff relative to the center of this marker so
            // that if we have to draw a bigger outline
            var centerX = (startX + endX) / 2;
            var centerY = (startY + endY) / 2;

            if (width < MIN_WIDTH) {
              width = MIN_WIDTH;
            }
            if (height < MIN_HEIGHT) {
              height = MIN_HEIGHT;
            }

            graphics.drawRect(centerX - width / 2, centerY - height / 2, width, height);
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
      }

      return drawTile;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(SquareMarkersTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(SquareMarkersTrack.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.refreshTiles();

        this.draw();
      }

      return zoomed;
    }()
  }]);
  return SquareMarkersTrack;
}(_TiledPixiTrack3['default']);

exports['default'] = SquareMarkersTrack;

/***/ }),
/* 368 */
/***/ (function(module, exports, __nested_webpack_require_1996936__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_1996936__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_1996936__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_1996936__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_1996936__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_1996936__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_1996936__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _boxIntersect = __nested_webpack_require_1996936__(180);

var _boxIntersect2 = _interopRequireDefault(_boxIntersect);

var _PixiTrack2 = __nested_webpack_require_1996936__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _ChromosomeInfo = __nested_webpack_require_1996936__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _SearchField = __nested_webpack_require_1996936__(140);

var _SearchField2 = _interopRequireDefault(_SearchField);

var _utils = __nested_webpack_require_1996936__(10);

var _configs = __nested_webpack_require_1996936__(11);

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

var Chromosome2DLabels = function (_PixiTrack) {
  (0, _inherits3['default'])(Chromosome2DLabels, _PixiTrack);

  function Chromosome2DLabels(context, options) {
    (0, _classCallCheck3['default'])(this, Chromosome2DLabels);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Chromosome2DLabels.__proto__ || (0, _getPrototypeOf2['default'])(Chromosome2DLabels)).call(this, context, options));

    var dataConfig = context.dataConfig,
        animate = context.animate,
        pubSub = context.pubSub;


    _this.searchField = null;
    _this.chromInfo = null;
    _this.animate = animate;

    var server = dataConfig.server;
    var uid = dataConfig.tilesetUid;

    var chromSizesPath = String(server) + '/chrom-sizes/?id=' + String(uid);

    (0, _ChromosomeInfo2['default'])(chromSizesPath, function (newChromInfo) {
      _this.chromInfo = newChromInfo;
      //

      _this.searchField = new _SearchField2['default'](_this.chromInfo);
      _this.draw();

      _this.texts = [];

      for (var i = 0; i < _this.chromInfo.cumPositions.length; i++) {
        var thisTexts = [];

        for (var j = 0; j < _this.chromInfo.cumPositions.length; j++) {
          var textStr = String(_this.chromInfo.cumPositions[i].chr) + '/' + String(_this.chromInfo.cumPositions[j].chr);
          var text = new _configs.GLOBALS.PIXI.Text(textStr, {
            fontSize: '14px',
            fontFamily: 'Arial',
            fill: 'red'
          });

          text.anchor.x = 0.5;
          text.anchor.y = 0.5;
          text.visible = false;

          // give each string a random hash so that some get hidden
          // when there's overlaps
          text.hashValue = Math.random();

          thisTexts.push(text);

          _this.pMain.addChild(text);
        }

        _this.texts.push(thisTexts);
      }
      _this.draw();
      _this.animate();
    }, pubSub);
    return _this;
  }

  (0, _createClass3['default'])(Chromosome2DLabels, [{
    key: 'draw',
    value: function () {
      function draw() {
        var allTexts = [];

        if (!this.texts) {
          return;
        }

        if (!this.searchField) {
          return;
        }

        var x1 = (0, _utils.absToChr)(this._xScale.domain()[0], this.chromInfo);
        var x2 = (0, _utils.absToChr)(this._xScale.domain()[1], this.chromInfo);

        var y1 = (0, _utils.absToChr)(this._yScale.domain()[0], this.chromInfo);
        var y2 = (0, _utils.absToChr)(this._yScale.domain()[1], this.chromInfo);

        for (var i = 0; i < this.texts.length; i++) {
          for (var j = 0; j < this.texts.length; j++) {
            this.texts[i][j].visible = false;
          }
        }

        for (var _i = x1[3]; _i <= x2[3]; _i++) {
          for (var _j = y1[3]; _j <= y2[3]; _j++) {
            var xCumPos = this.chromInfo.cumPositions[_i];
            var yCumPos = this.chromInfo.cumPositions[_j];

            var midX = xCumPos.pos + this.chromInfo.chromLengths[xCumPos.chr] / 2;
            var midY = yCumPos.pos + this.chromInfo.chromLengths[yCumPos.chr] / 2;

            var viewportMidX = this._xScale(midX);
            var viewportMidY = this._yScale(midY);

            var text = this.texts[_i][_j];

            text.x = viewportMidX;
            text.y = viewportMidY;
            text.updateTransform();

            var bbox = text.getBounds();

            var bwh = bbox.width / 2;
            var bhh = bbox.height / 2;

            // make sure the chrosome label fits in the x range
            if (viewportMidX + bwh > this.dimensions[0]) {
              text.x -= viewportMidX + bwh - this.dimensions[0];
            } else if (viewportMidX - bwh < 0) {
              //
              text.x -= viewportMidX - bwh;
            }

            // make sure the chro
            if (viewportMidY + bhh > this.dimensions[1]) {
              text.y -= viewportMidY + bhh - this.dimensions[1];
            } else if (viewportMidY - bhh < 0) {
              text.y -= viewportMidY - bhh;
            }

            text.visible = true;

            allTexts.push({
              importance: this.texts[_i][_j].hashValue,
              text: this.texts[_i][_j],
              caption: null
            });
          }
        }

        // define the edge chromosome which are visible
        this.hideOverlaps(allTexts);
      }

      return draw;
    }()
  }, {
    key: 'hideOverlaps',
    value: function () {
      function hideOverlaps(allTexts) {
        var allBoxes = []; // store the bounding boxes of the text objects so we can
        // calculate overlaps
        allBoxes = allTexts.map(function (val) {
          var text = val.text;
          text.updateTransform();
          var b = text.getBounds();
          var box = [b.x, b.y, b.x + b.width, b.y + b.height];

          return box;
        });

        (0, _boxIntersect2['default'])(allBoxes, function (i, j) {
          if (allTexts[i].importance > allTexts[j].importance) {
            allTexts[j].text.visible = 0;
          } else {
            allTexts[i].text.visible = 0;
          }
        });
      }

      return hideOverlaps;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(Chromosome2DLabels.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Chromosome2DLabels.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }]);
  return Chromosome2DLabels;
}(_PixiTrack3['default']);

// Configs


exports['default'] = Chromosome2DLabels;

/***/ }),
/* 369 */
/***/ (function(module, exports, __nested_webpack_require_2004267__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_2004267__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _slicedToArray2 = __nested_webpack_require_2004267__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_2004267__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2004267__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2004267__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2004267__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2004267__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2004267__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _PixiTrack2 = __nested_webpack_require_2004267__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _ChromosomeInfo = __nested_webpack_require_2004267__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _SearchField = __nested_webpack_require_2004267__(140);

var _SearchField2 = _interopRequireDefault(_SearchField);

var _utils = __nested_webpack_require_2004267__(10);

var _configs = __nested_webpack_require_2004267__(11);

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

var ChromosomeGrid = function (_PixiTrack) {
  (0, _inherits3['default'])(ChromosomeGrid, _PixiTrack);

  function ChromosomeGrid(context, options) {
    (0, _classCallCheck3['default'])(this, ChromosomeGrid);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ChromosomeGrid.__proto__ || (0, _getPrototypeOf2['default'])(ChromosomeGrid)).call(this, context, options));

    var chromInfoPath = context.chromInfoPath,
        dataConfig = context.dataConfig,
        animate = context.animate,
        pubSub = context.pubSub,
        _context$orientation = context.orientation,
        orientation = _context$orientation === undefined ? '2d' : _context$orientation,
        _context$isOverlay = context.isOverlay,
        isOverlay = _context$isOverlay === undefined ? false : _context$isOverlay;


    _this.searchField = null;
    _this.chromInfo = null;
    _this.animate = animate;
    _this.orientation = orientation;
    _this.isOverlay = isOverlay;

    var chromSizesPath = chromInfoPath;

    if (!chromSizesPath) {
      chromSizesPath = String(dataConfig.server) + '/chrom-sizes/?id=' + String(dataConfig.tilesetUid);
    }

    (0, _ChromosomeInfo2['default'])(chromSizesPath, function (newChromInfo) {
      _this.chromInfo = newChromInfo;

      _this.searchField = new _SearchField2['default'](_this.chromInfo);

      _this.texts = [];
      _this.lineGraphics = new _configs.GLOBALS.PIXI.Graphics();
      _this.lineGraphics1dH = new _configs.GLOBALS.PIXI.Graphics();
      _this.lineGraphics1dV = new _configs.GLOBALS.PIXI.Graphics();
      _this.lineGraphics2d = new _configs.GLOBALS.PIXI.Graphics();
      _this.mask1dH = new _configs.GLOBALS.PIXI.Graphics();
      _this.mask1dV = new _configs.GLOBALS.PIXI.Graphics();
      _this.mask2d = new _configs.GLOBALS.PIXI.Graphics();

      _this.lineGraphics.addChild(_this.lineGraphics1dH);
      _this.lineGraphics1dH.addChild(_this.mask1dH);
      _this.lineGraphics.addChild(_this.lineGraphics1dV);
      _this.lineGraphics1dV.addChild(_this.mask1dV);
      _this.lineGraphics.addChild(_this.lineGraphics2d);
      _this.lineGraphics2d.addChild(_this.mask2d);
      _this.pMain.addChild(_this.lineGraphics);

      _this.draw();
      _this.animate();
    }, pubSub);
    return _this;
  }

  (0, _createClass3['default'])(ChromosomeGrid, [{
    key: 'drawLines',
    value: function () {
      function drawLines() {
        var orientation = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.orientation;
        var left = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
        var top = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;

        var graphics = this.lineGraphics;

        if (this.isOverlay && orientation === '1d-horizontal') {
          graphics = this.lineGraphics1dH;
        }

        if (this.isOverlay && orientation === '1d-vertical') {
          graphics = this.lineGraphics1dV;
        }

        if (this.isOverlay && orientation === '2d') {
          graphics = this.lineGraphics2d;
        }

        var strokeColor = (0, _utils.colorToHex)(this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue');

        var strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1;

        graphics.lineStyle(strokeWidth, strokeColor, 1.0);

        // Vertical lines
        if (orientation === '2d' || orientation === '1d-horizontal') {
          graphics.moveTo(this._xScale(0) + left, top);
          graphics.lineTo(this._xScale(0) + left, this.dimensions[1] + top);
        }

        // Horizontal lines
        if (orientation === '2d' || orientation === '1d-vertical') {
          graphics.moveTo(left, this._yScale(0) + top);
          graphics.lineTo(this.dimensions[0] + left, this._yScale(0) + top);
        }

        for (var i = 0; i < this.chromInfo.cumPositions.length; i++) {
          var chrPos = this.chromInfo.cumPositions[i];
          var chrEnd = chrPos.pos + +this.chromInfo.chromLengths[chrPos.chr] + 1;

          // Vertical lines
          if (orientation === '2d' || orientation === '1d-horizontal') {
            graphics.moveTo(this._xScale(chrEnd) + left, top);
            graphics.lineTo(this._xScale(chrEnd) + left, this.dimensions[1] + top);
          }

          // Horizontal lines
          if (orientation === '2d' || orientation === '1d-vertical') {
            graphics.moveTo(left, this._yScale(chrEnd) + top);
            graphics.lineTo(this.dimensions[0] + left, this._yScale(chrEnd) + top);
          }
        }
      }

      return drawLines;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        if (!this.texts) {
          return;
        }

        if (!this.searchField) {
          return;
        }

        this.lineGraphics.clear();

        if (this.isOverlay) {
          this.lineGraphics1dH.clear();
          this.lineGraphics1dV.clear();
          this.lineGraphics2d.clear();
          this.mask1dH.clear();
          this.mask1dV.clear();
          this.mask2d.clear();
          this.mask1dH.beginFill(0xffffff);
          this.mask1dV.beginFill(0xffffff);
          this.mask2d.beginFill(0xff0000);

          for (var i = 0; i < this.options.orientationsAndPositions.length; i++) {
            var orientation = this.options.orientationsAndPositions[i].orientation;
            var _options$orientations = this.options.orientationsAndPositions[i].position,
                left = _options$orientations.left,
                top = _options$orientations.top,
                width = _options$orientations.width,
                height = _options$orientations.height;


            if (orientation === '1d-horizontal') {
              this.mask1dH.drawRect(left, top, width, height);
            }

            if (orientation === '1d-vertical') {
              this.mask1dV.drawRect(left, top, width, height);
            }

            if (orientation === '2d') {
              this.mask2d.drawRect(left, top, width, height);
            }

            this.drawLines(orientation, left, top);
          }

          this.lineGraphics1dH.mask = this.mask1dH;
          this.lineGraphics1dV.mask = this.mask1dV;
          this.lineGraphics2d.mask = this.mask2d;
        } else {
          this.drawLines();
        }
      }

      return draw;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(ChromosomeGrid.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ChromosomeGrid.prototype), 'setPosition', this).call(this, newPosition);

        var _position = (0, _slicedToArray3['default'])(this.position, 2);

        this.pMain.position.x = _position[0];
        this.pMain.position.y = _position[1];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'createSvgLine',
    value: function () {
      function createSvgLine(x1, x2, y1, y2, stroke, strokeWidth) {
        var line = document.createElement('line');

        line.setAttribute('x1', x1);
        line.setAttribute('x2', x2);

        line.setAttribute('y1', y1);
        line.setAttribute('y2', y2);

        line.setAttribute('stroke', stroke);
        line.setAttribute('stroke-width', strokeWidth);

        return line;
      }

      return createSvgLine;
    }()
  }, {
    key: 'drawLinesSvg',
    value: function () {
      function drawLinesSvg(output, orientation, width, height) {
        var left = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
        var top = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;

        var strokeColor = this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue';
        var strokeWidth = this.options.lineStrokeWidth;

        // First horizontal line
        if (orientation === '2d' || orientation === '1d-vertical') {
          var y = this._yScale(0);
          if (y > 0 && y < top + height) {
            output.appendChild(this.createSvgLine(left, width + left, y + top, y + top, strokeColor, strokeWidth));
          }
        }

        // First vertical line
        if (orientation === '2d' || orientation === '1d-horizontal') {
          var x = this._xScale(0);
          if (x > 0 && x < left + width) {
            output.appendChild(this.createSvgLine(x + left, x + left, top, height + top, strokeColor, strokeWidth));
          }
        }

        for (var i = 0; i < this.chromInfo.cumPositions.length; i++) {
          var chrPos = this.chromInfo.cumPositions[i];
          var chrEnd = chrPos.pos + +this.chromInfo.chromLengths[chrPos.chr] + 1;

          if (orientation === '2d' || orientation === '1d-vertical') {
            var _y = this._yScale(chrEnd);
            if (_y > 0 && _y < top + height) {
              output.appendChild(this.createSvgLine(left, width + left, _y + top, _y + top, strokeColor, strokeWidth));
            }
          }

          if (orientation === '2d' || orientation === '1d-horizontal') {
            var _x6 = this._xScale(chrEnd);
            if (_x6 > 0 && _x6 < left + width) {
              output.appendChild(this.createSvgLine(_x6 + left, _x6 + left, top, height + top, strokeColor, strokeWidth));
            }
          }
        }
      }

      return drawLinesSvg;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(ChromosomeGrid.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ChromosomeGrid.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(ChromosomeGrid.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ChromosomeGrid.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        track.appendChild(output);

        base.setAttribute('id', 'ChromosomeGrid');

        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        if (!this.chromInfo) {
          // we haven't received the chromosome info yet
          return [base, track];
        }

        if (this.isOverlay) {
          for (var i = 0; i < this.options.orientationsAndPositions.length; i++) {
            var orientation = this.options.orientationsAndPositions[i].orientation;
            var _options$orientations2 = this.options.orientationsAndPositions[i].position,
                left = _options$orientations2.left,
                top = _options$orientations2.top,
                width = _options$orientations2.width,
                height = _options$orientations2.height;

            this.drawLinesSvg(output, orientation, width, height, left, top);
          }
        } else {
          this.drawLinesSvg.apply(this, [output, this.orientation].concat((0, _toConsumableArray3['default'])(this.dimensions)));
        }

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return ChromosomeGrid;
}(_PixiTrack3['default']);

// Configs


exports['default'] = ChromosomeGrid;

/***/ }),
/* 370 */
/***/ (function(module, exports, __nested_webpack_require_2017399__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2017399__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2017399__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2017399__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2017399__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2017399__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2017399__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Color = __nested_webpack_require_2017399__(9);

var _PixiTrack2 = __nested_webpack_require_2017399__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _ChromosomeInfo = __nested_webpack_require_2017399__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _configs = __nested_webpack_require_2017399__(11);

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

// Maximum delay in ms between mousedown and mouseup that is registered as a
// click. Note we need to use mousedown and mouseup as PIXI doesn't recognize
// click events with our current setup. Since most UIs treat long clicks as
// either something special or a cancelation we follow best practices and
// implement a threshold on the delay as well.
var MAX_CLICK_DELAY = 300;

// Configs

var Chromosome2DAnnotations = function (_PixiTrack) {
  (0, _inherits3['default'])(Chromosome2DAnnotations, _PixiTrack);

  function Chromosome2DAnnotations(context, options) {
    (0, _classCallCheck3['default'])(this, Chromosome2DAnnotations);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Chromosome2DAnnotations.__proto__ || (0, _getPrototypeOf2['default'])(Chromosome2DAnnotations)).call(this, context, options));

    var chromInfoPath = context.chromInfoPath,
        pubSub = context.pubSub;


    _this.pubSub = pubSub;
    _this.rects = {};

    (0, _ChromosomeInfo2['default'])(chromInfoPath, function (newChromInfo) {
      _this.chromInfo = newChromInfo;
      _this.draw();
    }, _this.pubSub);
    return _this;
  }

  (0, _createClass3['default'])(Chromosome2DAnnotations, [{
    key: 'draw',
    value: function () {
      function draw() {
        var _this2 = this;

        if (!this.chromInfo) {
          return;
        }

        var minRectWidth = this.options.minRectWidth ? this.options.minRectWidth : 10;
        var minRectHeight = this.options.minRectWidth ? this.options.minRectHeight : 10;

        (0, _get3['default'])(Chromosome2DAnnotations.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Chromosome2DAnnotations.prototype), 'draw', this).call(this);
        var graphics = this.pMain;
        graphics.clear();

        // The time stamp is used to keep track which rectangles have been drawn per
        // draw call. Each rectangle previously drawn that is not visible anymore
        // (i.e., is not drawn in the current draw call) will be removed at the end
        // by checking against the time stamp.
        var timeStamp = performance.now();

        // Regions have to follow the following form:
        // chrom1, start1, end1, chrom2, start2, end2, color-fill, color-line, min-width, min-height
        // If `color-line` is not given, `color-fill` is used
        this.options.regions.forEach(function (region) {
          var id = region.slice(0, 6).join('-');

          if (!_this2.rects[id]) {
            _this2.rects[id] = { graphics: new _configs.GLOBALS.PIXI.Graphics() };
            graphics.addChild(_this2.rects[id].graphics);
          }

          _this2.rects[id].timeStamp = timeStamp;

          var colorFill = (0, _d3Color.color)(region[6]);
          var colorLine = (0, _d3Color.color)(region[7]);

          if (!colorLine) {
            colorLine = colorFill;
          }

          var colorFillHex = _configs.GLOBALS.PIXI.utils.rgb2hex([colorFill.r / 255.0, colorFill.g / 255.0, colorFill.b / 255.0]);
          var colorLineHex = _configs.GLOBALS.PIXI.utils.rgb2hex([colorLine.r / 255.0, colorLine.g / 255.0, colorLine.b / 255.0]);

          graphics.lineStyle(1, colorLineHex, colorLine.opacity);
          graphics.beginFill(colorFillHex, colorFill.opacity);

          // console.log('region:', region);
          var startX = _this2._xScale(_this2.chromInfo.chrPositions[region[0]].pos + +region[1]);
          var endX = _this2._xScale(_this2.chromInfo.chrPositions[region[0]].pos + +region[2]);

          var startY = _this2._yScale(_this2.chromInfo.chrPositions[region[3]].pos + +region[4]);
          var endY = _this2._yScale(_this2.chromInfo.chrPositions[region[3]].pos + +region[5]);

          var width = endX - startX;
          var height = endY - startY;

          var _minRectWidth = typeof region[8] !== 'undefined' ? region[8] : minRectWidth;
          var _minRectHeight = typeof region[9] !== 'undefined' ? region[9] : minRectHeight;

          if (width < _minRectWidth) {
            // this region is too small to draw so center it on the location
            // where it would be drawn
            startX = (startX + endX) / 2 - _minRectWidth / 2;
            width = _minRectWidth;
          }

          if (height < _minRectHeight) {
            startY = (startY + endY) / 2 - _minRectHeight / 2;
            height = _minRectHeight;
          }

          graphics.drawRect(startX, startY, width, height);

          // Make annotation clickable
          _this2.rects[id].graphics.clear();
          _this2.rects[id].graphics.interactive = true;
          _this2.rects[id].graphics.buttonMode = true;
          _this2.rects[id].graphics.hitArea = new _configs.GLOBALS.PIXI.Rectangle(startX, startY, width, height);

          _this2.rects[id].graphics.mousedown = function () {
            _this2.rects[id].mouseDownTime = performance.now();
          };

          _this2.rects[id].graphics.mouseup = function (event) {
            if (performance.now() - _this2.rects[id].mouseDownTime < MAX_CLICK_DELAY) {
              _this2.pubSub.publish('app.click', {
                type: 'annotation',
                event: event,
                payload: region
              });
            }
          };
        });
      }

      return draw;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(Chromosome2DAnnotations.prototype.__proto__ || (0, _getPrototypeOf2['default'])(Chromosome2DAnnotations.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }]);
  return Chromosome2DAnnotations;
}(_PixiTrack3['default']);

exports['default'] = Chromosome2DAnnotations;

/***/ }),
/* 371 */
/***/ (function(module, exports, __nested_webpack_require_2024663__) {

"use strict";


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

var _values = __nested_webpack_require_2024663__(37);

var _values2 = _interopRequireDefault(_values);

var _slicedToArray2 = __nested_webpack_require_2024663__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _keys = __nested_webpack_require_2024663__(18);

var _keys2 = _interopRequireDefault(_keys);

var _isInteger = __nested_webpack_require_2024663__(632);

var _isInteger2 = _interopRequireDefault(_isInteger);

var _stringify = __nested_webpack_require_2024663__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = __nested_webpack_require_2024663__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2024663__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2024663__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2024663__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2024663__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2024663__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _boxIntersect = __nested_webpack_require_2024663__(180);

var _boxIntersect2 = _interopRequireDefault(_boxIntersect);

var _d3Scale = __nested_webpack_require_2024663__(28);

var _d3Format = __nested_webpack_require_2024663__(20);

var _PixiTrack2 = __nested_webpack_require_2024663__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

var _ChromosomeInfo = __nested_webpack_require_2024663__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _SearchField = __nested_webpack_require_2024663__(140);

var _SearchField2 = _interopRequireDefault(_SearchField);

var _utils = __nested_webpack_require_2024663__(10);

var _configs = __nested_webpack_require_2024663__(11);

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

var TICK_WIDTH = 200;
var TICK_HEIGHT = 6;
var TICK_TEXT_SEPARATION = 2;
var TICK_COLOR = 0x777777;

var HorizontalChromosomeLabels = function (_PixiTrack) {
  (0, _inherits3['default'])(HorizontalChromosomeLabels, _PixiTrack);

  function HorizontalChromosomeLabels(context, options) {
    (0, _classCallCheck3['default'])(this, HorizontalChromosomeLabels);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HorizontalChromosomeLabels.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalChromosomeLabels)).call(this, context, options));

    var dataConfig = context.dataConfig,
        animate = context.animate,
        chromInfoPath = context.chromInfoPath,
        isShowGlobalMousePosition = context.isShowGlobalMousePosition;


    _this.searchField = null;
    _this.chromInfo = null;
    _this.dataConfig = dataConfig;

    _this.pTicks = new _configs.GLOBALS.PIXI.Graphics();
    _this.pMain.addChild(_this.pTicks);

    _this.gTicks = {};
    _this.tickTexts = {};

    _this.options = options;
    _this.isShowGlobalMousePosition = isShowGlobalMousePosition;

    _this.textFontSize = 12;
    _this.textFontFamily = 'Arial';
    _this.textFontColor = '#808080';
    _this.textStrokeColor = _this.getTheme() === _configs.THEME_DARK ? '#000000' : '#ffffff';
    _this.pixiTextConfig = {
      fontSize: +_this.options.fontSize ? +_this.options.fontSize + 'px' : String(_this.textFontSize) + 'px',
      fontFamily: _this.textFontFamily,
      fill: _this.options.color || _this.textFontColor,
      lineJoin: 'round',
      stroke: _this.options.stroke || _this.textStrokeColor,
      strokeThickness: 2
    };
    _this.stroke = (0, _utils.colorToHex)(_this.pixiTextConfig.stroke);

    // text objects to use if the tick style is "bounds", meaning
    // we only draw two ticks on the left and the right of the screen

    _this.tickWidth = TICK_WIDTH;
    _this.tickHeight = TICK_HEIGHT;
    _this.tickTextSeparation = TICK_TEXT_SEPARATION;
    _this.tickColor = _this.options.tickColor ? (0, _utils.colorToHex)(_this.options.tickColor) : TICK_COLOR;

    _this.animate = animate;

    _this.pubSubs = [];

    if (_this.options.showMousePosition && !_this.hideMousePosition) {
      _this.hideMousePosition = (0, _utils.showMousePosition)(_this, _this.is2d, _this.isShowGlobalMousePosition());
    }

    var chromSizesPath = chromInfoPath;

    if (!chromSizesPath) {
      chromSizesPath = String(dataConfig.server) + '/chrom-sizes/?id=' + String(dataConfig.tilesetUid);
    }

    (0, _ChromosomeInfo2['default'])(chromSizesPath, function (newChromInfo) {
      _this.chromInfo = newChromInfo;

      _this.searchField = new _SearchField2['default'](_this.chromInfo);

      _this.rerender(_this.options, true);
      _this.draw();
      _this.animate();
    }, _this.pubSub);
    return _this;
  }

  (0, _createClass3['default'])(HorizontalChromosomeLabels, [{
    key: 'initBoundsTicks',
    value: function () {
      function initBoundsTicks() {
        if (this.pTicks) {
          this.pMain.removeChild(this.pTicks);
          this.pTicks = null;
        }

        if (!this.gBoundTicks) {
          this.gBoundTicks = new _configs.GLOBALS.PIXI.Graphics();

          this.leftBoundTick = new _configs.GLOBALS.PIXI.Text('', this.pixiTextConfig);
          this.rightBoundTick = new _configs.GLOBALS.PIXI.Text('', this.pixiTextConfig);

          this.gBoundTicks.addChild(this.leftBoundTick);
          this.gBoundTicks.addChild(this.rightBoundTick);

          this.pMain.addChild(this.gBoundTicks);
        }

        this.texts = [];
      }

      return initBoundsTicks;
    }()
  }, {
    key: 'initChromLabels',
    value: function () {
      function initChromLabels() {
        if (!this.chromInfo) return;

        if (this.gBoundTicks) {
          this.pMain.removeChild(this.gBoundTicks);
          this.gBoundTicks = null;
        }

        if (!this.pTicks) {
          this.pTicks = new _configs.GLOBALS.PIXI.Graphics();
          this.pMain.addChild(this.pTicks);
        }

        this.texts = [];
        this.pTicks.removeChildren();

        for (var i = 0; i < this.chromInfo.cumPositions.length; i++) {
          var chromName = this.chromInfo.cumPositions[i].chr;
          this.gTicks[chromName] = new _configs.GLOBALS.PIXI.Graphics();

          // create the array that will store tick TEXT objects
          if (!this.tickTexts[chromName]) this.tickTexts[chromName] = [];

          var text = new _configs.GLOBALS.PIXI.Text(chromName, this.pixiTextConfig);

          // give each string a random hash so that some get hidden
          // when there's overlaps
          text.hashValue = Math.random();

          this.pTicks.addChild(text);
          this.pTicks.addChild(this.gTicks[chromName]);

          this.texts.push(text);
        }
      }

      return initChromLabels;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        var strOptions = (0, _stringify2['default'])(options);

        if (!force && strOptions === this.prevOptions) return;

        this.prevOptions = strOptions;
        this.options = options;

        this.pixiTextConfig.fontSize = +this.options.fontSize ? +this.options.fontSize + 'px' : this.pixiTextConfig.fontSize;
        this.pixiTextConfig.fill = this.options.color || this.pixiTextConfig.fill;
        this.pixiTextConfig.stroke = this.options.stroke || this.pixiTextConfig.stroke;
        this.stroke = (0, _utils.colorToHex)(this.pixiTextConfig.stroke);

        this.tickColor = this.options.tickColor ? (0, _utils.colorToHex)(this.options.tickColor) : TICK_COLOR;

        if (this.options.tickPositions === 'ends') {
          this.initBoundsTicks();
        } else {
          this.initChromLabels();
        }

        (0, _get3['default'])(HorizontalChromosomeLabels.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalChromosomeLabels.prototype), 'rerender', this).call(this, options, force);

        if (this.options.showMousePosition && !this.hideMousePosition) {
          this.hideMousePosition = (0, _utils.showMousePosition)(this, this.is2d, this.isShowGlobalMousePosition());
        }

        if (!this.options.showMousePosition && this.hideMousePosition) {
          this.hideMousePosition();
          this.hideMousePosition = undefined;
        }
      }

      return rerender;
    }()
  }, {
    key: 'formatTick',
    value: function () {
      function formatTick(pos) {
        var domain = this._xScale.domain();

        var viewWidth = domain[1] - domain[0];

        var p = (0, _d3Format.precisionPrefix)(pos, viewWidth);

        var fPlain = (0, _d3Format.format)(',');
        var fPrecision = (0, _d3Format.formatPrefix)(',.' + String(p), viewWidth);
        var f = fPlain;

        if (this.options.tickFormat === 'si') {
          f = fPrecision;
        } else if (this.options.tickFormat === 'plain') {
          f = fPlain;
        } else if (this.options.tickPositions === 'ends') {
          // if no format is specified but tickPositions are at 'ends'
          // then use precision format
          f = fPrecision;
        }

        return f(pos);
      }

      return formatTick;
    }()
  }, {
    key: 'drawBoundsTicks',
    value: function () {
      function drawBoundsTicks(x1, x2) {
        var graphics = this.gBoundTicks;
        graphics.clear();
        graphics.lineStyle(1, 0);

        // determine the stard and end positions of tick lines along the vertical axis
        var lineYStart = this.options.reverseOrientation ? 0 : this.dimensions[1];
        var lineYEnd = this.options.reverseOrientation ? this.tickHeight : this.dimensions[1] - this.tickHeight;

        // left tick
        // line is offset by one because it's right on the edge of the
        // visible region and we want to get the full width
        graphics.moveTo(1, lineYStart);
        graphics.lineTo(1, lineYEnd);

        // right tick
        graphics.moveTo(this.dimensions[0] - 1, lineYStart);
        graphics.lineTo(this.dimensions[0] - 1, lineYEnd);

        // we want to control the precision of the tick labels
        // so that we don't end up with labels like 15.123131M
        this.leftBoundTick.x = 0;
        this.leftBoundTick.y = this.options.reverseOrientation ? lineYEnd + this.tickTextSeparation : lineYEnd - this.tickTextSeparation;
        this.leftBoundTick.text = String(x1[0]) + ': ' + String(this.formatTick(x1[1]));
        this.leftBoundTick.anchor.y = this.options.reverseOrientation ? 0 : 1;

        this.rightBoundTick.x = this.dimensions[0];
        this.rightBoundTick.text = String(x2[0]) + ': ' + String(this.formatTick(x2[1]));
        this.rightBoundTick.y = this.options.reverseOrientation ? lineYEnd + this.tickTextSeparation : lineYEnd - this.tickTextSeparation;
        this.rightBoundTick.anchor.y = this.options.reverseOrientation ? 0 : 1;

        this.rightBoundTick.anchor.x = 1;

        if (this.flipText) {
          // this means this track is displayed vertically, so update the anchor and scale of labels to make them readable!
          this.leftBoundTick.scale.x = -1;
          this.leftBoundTick.anchor.x = 1;
          this.rightBoundTick.scale.x = -1;
          this.rightBoundTick.anchor.x = 0;
        }

        // line is offset by one because it's right on the edge of the
        // visible region and we want to get the full width
        this.leftBoundTick.tickLine = [1, this.dimensions[1], 1, this.dimensions[1] - this.tickHeight];
        this.rightBoundTick.tickLine = [this.dimensions[0] - 1, this.dimensions[1], this.dimensions[0] - 1, this.dimensions[1] - this.tickHeight];

        this.tickTexts = {};
        this.tickTexts.all = [this.leftBoundTick, this.rightBoundTick];
        // this.rightBoundTick
      }

      return drawBoundsTicks;
    }()
  }, {
    key: 'drawTicks',
    value: function () {
      function drawTicks(cumPos) {
        var graphics = this.gTicks[cumPos.chr];

        graphics.visible = true;

        // clear graphics *and* ticktexts otherwise the two are out of sync!
        graphics.clear();

        var chromLen = +this.chromInfo.chromLengths[cumPos.chr];

        var vpLeft = Math.max(this._xScale(cumPos.pos), 0);
        var vpRight = Math.min(this._xScale(cumPos.pos + chromLen), this.dimensions[0]);

        var numTicks = (vpRight - vpLeft) / this.tickWidth;

        // what is the domain of this chromosome that is visible?
        var xScale = (0, _d3Scale.scaleLinear)().domain([Math.max(1, this._xScale.invert(0) - cumPos.pos), Math.min(chromLen, this._xScale.invert(this.dimensions[0]) - cumPos.pos)]).range(vpLeft, vpRight);

        // calculate a certain number of ticks
        var ticks = xScale.ticks(numTicks).filter(function (tick) {
          return (0, _isInteger2['default'])(tick);
        });

        // not sure why we're separating these out by chromosome, but ok
        var tickTexts = this.tickTexts[cumPos.chr];

        var tickHeight = this.options.fontIsLeftAligned ? (+this.options.fontSize || this.textFontSize) / 2 : this.tickHeight;

        var flipTextSign = this.flipText ? -1 : 1;

        var xPadding = this.options.fontIsLeftAligned ? flipTextSign * 4 : 0;

        var yPadding = this.options.fontIsLeftAligned ? 0 : tickHeight + this.tickTextSeparation;

        if (this.options.reverseOrientation) {
          yPadding = this.dimensions[1] - yPadding;
        }

        // these two loops reuse existing text objects so that
        // we're not constantly recreating texts that already
        // exist
        while (tickTexts.length < ticks.length) {
          var newText = new _configs.GLOBALS.PIXI.Text('', this.pixiTextConfig);
          tickTexts.push(newText);
          this.gTicks[cumPos.chr].addChild(newText);
        }

        while (tickTexts.length > ticks.length) {
          var text = tickTexts.pop();
          this.gTicks[cumPos.chr].removeChild(text);
        }

        var i = 0;
        while (i < ticks.length) {
          tickTexts[i].visible = true;

          tickTexts[i].anchor.x = this.options.fontIsLeftAligned ? 0 : 0.5;
          tickTexts[i].anchor.y = this.options.reverseOrientation ? 0 : 1;

          if (this.flipText) tickTexts[i].scale.x = -1;

          // draw the tick labels
          tickTexts[i].x = this._xScale(cumPos.pos + ticks[i]) + xPadding;
          tickTexts[i].y = this.dimensions[1] - yPadding;

          tickTexts[i].text = ticks[i] === 0 ? String(cumPos.chr) + ': 1' : String(cumPos.chr) + ': ' + String(this.formatTick(ticks[i]));

          var x = this._xScale(cumPos.pos + ticks[i]);

          // store the position of the tick line so that it can
          // be used in the export function
          tickTexts[i].tickLine = [x - 1, this.dimensions[1], x - 1, this.dimensions[1] - tickHeight - 1];

          // draw outline
          var lineYStart = this.options.reverseOrientation ? 0 : this.dimensions[1];
          var lineYEnd = this.options.reverseOrientation ? tickHeight : this.dimensions[1] - tickHeight;
          graphics.lineStyle(1, this.stroke);
          graphics.moveTo(x - 1, lineYStart);
          graphics.lineTo(x - 1, lineYEnd - 1);
          if (this.options.fontIsLeftAligned) {
            graphics.lineTo(x + 2 * flipTextSign + 1 * flipTextSign, lineYEnd - 1);
            graphics.lineTo(x + 2 * flipTextSign + 1 * flipTextSign, lineYEnd + 1);
            graphics.lineTo(x + 1, lineYEnd + 1);
          } else {
            graphics.lineTo(x + 1, lineYEnd - 1);
          }
          graphics.lineTo(x + 1, lineYStart);

          // draw the tick lines
          graphics.lineStyle(1, this.tickColor);
          graphics.moveTo(x, lineYStart);
          graphics.lineTo(x, lineYEnd);

          if (this.options.fontIsLeftAligned) {
            graphics.lineTo(x + 2 * flipTextSign, lineYEnd);
          }

          i += 1;
        }

        while (i < tickTexts.length) {
          // we don't need this text so we'll turn it off for now
          tickTexts[i].visible = false;

          i += 1;
        }

        return ticks.length;
      }

      return drawTicks;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var _this2 = this;

        this.allTexts = [];

        if (!this.texts || !this.searchField) return;

        var x1 = (0, _utils.absToChr)(this._xScale.domain()[0], this.chromInfo);
        var x2 = (0, _utils.absToChr)(this._xScale.domain()[1], this.chromInfo);

        if (!x1 || !x2) {
          console.warn('Empty chromInfo:', this.dataConfig, this.chromInfo);
          return;
        }

        if (this.options.tickPositions === 'ends') {
          if (!this.gBoundTicks) return;

          this.gBoundTicks.visible = true;

          this.drawBoundsTicks(x1, x2);

          return;
        }

        if (!this.pTicks) {
          // options.tickPositiosn was probably just changed to 'even'
          // and initChromLabels hasn't been called yet
          return;
        }

        for (var i = 0; i < this.texts.length; i++) {
          this.texts[i].visible = false;
          this.gTicks[this.chromInfo.cumPositions[i].chr].visible = false;
        }

        var yPadding = this.options.fontIsLeftAligned ? 0 : this.tickHeight + this.tickTextSeparation;

        if (this.options.reverseOrientation) {
          yPadding = this.dimensions[1] - yPadding;
        }

        // hide all the chromosome labels in preparation for drawing
        // new ones
        (0, _keys2['default'])(this.chromInfo.chrPositions).forEach(function (chrom) {
          if (_this2.tickTexts[chrom]) {
            for (var j = 0; j < _this2.tickTexts[chrom].length; j++) {
              _this2.tickTexts[chrom][j].visible = false;
            }
          }
        });

        // iterate over each chromosome
        for (var _i = x1[3]; _i <= x2[3]; _i++) {
          var xCumPos = this.chromInfo.cumPositions[_i];

          var midX = xCumPos.pos + this.chromInfo.chromLengths[xCumPos.chr] / 2;

          var viewportMidX = this._xScale(midX);

          // This is ONLY the bare chromosome name. Not the tick label!
          var text = this.texts[_i];

          text.anchor.x = this.options.fontIsLeftAligned ? 0 : 0.5;
          text.anchor.y = this.options.reverseOrientation ? 0 : 1;
          text.x = viewportMidX;
          text.y = this.dimensions[1] - yPadding;
          text.updateTransform();

          if (this.flipText) text.scale.x = -1;

          var numTicksDrawn = this.drawTicks(xCumPos);

          // only show chromsome labels if there's no ticks drawn
          text.visible = numTicksDrawn <= 0;

          this.allTexts.push({
            importance: text.hashValue,
            text: text,
            caption: null
          });
        }

        // define the edge chromosome which are visible
        this.hideOverlaps(this.allTexts);
      }

      return draw;
    }()
  }, {
    key: 'hideOverlaps',
    value: function () {
      function hideOverlaps(allTexts) {
        var allBoxes = []; // store the bounding boxes of the text objects so we can
        // calculate overlaps
        allBoxes = allTexts.map(function (_ref, i) {
          var text = _ref.text;

          text.updateTransform();
          var b = text.getBounds();
          var box = [b.x, b.y, b.x + b.width, b.y + b.height];

          return box;
        });

        (0, _boxIntersect2['default'])(allBoxes, function (i, j) {
          if (allTexts[i].importance > allTexts[j].importance) {
            allTexts[j].text.visible = false;
          } else {
            allTexts[i].text.visible = false;
          }
        });
      }

      return hideOverlaps;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(HorizontalChromosomeLabels.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalChromosomeLabels.prototype), 'setPosition', this).call(this, newPosition);

        var _position = (0, _slicedToArray3['default'])(this.position, 2);

        this.pMain.position.x = _position[0];
        this.pMain.position.y = _position[1];
      }

      return setPosition;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var _this3 = this;

        var track = null;
        var base = null;

        if ((0, _get3['default'])(HorizontalChromosomeLabels.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalChromosomeLabels.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(HorizontalChromosomeLabels.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalChromosomeLabels.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        base.setAttribute('class', 'chromosome-labels');

        var output = document.createElement('g');
        track.appendChild(output);

        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        this.allTexts.filter(function (text) {
          return text.text.visible;
        }).forEach(function (text) {
          var g = (0, _utils.pixiTextToSvg)(text.text);
          output.appendChild(g);
        });

        (0, _values2['default'])(this.tickTexts).forEach(function (texts) {
          texts.filter(function (x) {
            return x.visible;
          }).forEach(function (text) {
            var g = (0, _utils.pixiTextToSvg)(text);
            output.appendChild(g);
            g = (0, _utils.svgLine)(text.x, _this3.options.reverseOrientation ? 0 : _this3.dimensions[1], text.x, _this3.options.reverseOrientation ? _this3.tickHeight : _this3.dimensions[1] - _this3.tickHeight, 1, _this3.tickColor);

            var line = document.createElement('line');

            line.setAttribute('x1', text.tickLine[0]);
            line.setAttribute('y1', text.tickLine[1]);
            line.setAttribute('x2', text.tickLine[2]);
            line.setAttribute('y2', text.tickLine[3]);
            line.setAttribute('style', 'stroke: grey');

            output.appendChild(g);
            output.appendChild(line);
          });
        });

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return HorizontalChromosomeLabels;
}(_PixiTrack3['default']);

exports['default'] = HorizontalChromosomeLabels;

/***/ }),
/* 372 */
/***/ (function(module, exports, __nested_webpack_require_2047528__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_2047528__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _slicedToArray2 = __nested_webpack_require_2047528__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_2047528__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2047528__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2047528__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2047528__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2047528__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2047528__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _HeatmapTiledPixiTrack = __nested_webpack_require_2047528__(135);

var _HeatmapTiledPixiTrack2 = _interopRequireDefault(_HeatmapTiledPixiTrack);

var _services = __nested_webpack_require_2047528__(24);

var _utils = __nested_webpack_require_2047528__(10);

var _configs = __nested_webpack_require_2047528__(11);

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

// Utils
var HorizontalHeatmapTrack = function (_HeatmapTiledPixiTrac) {
  (0, _inherits3['default'])(HorizontalHeatmapTrack, _HeatmapTiledPixiTrac);

  /**
   * @param scene: A PIXI.js scene to draw everything to.
   * @param dataConfig: An object defining where the data should be pulled from
   */
  function HorizontalHeatmapTrack(context, options) {
    (0, _classCallCheck3['default'])(this, HorizontalHeatmapTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HorizontalHeatmapTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalHeatmapTrack)).call(this, context, options));

    var animate = context.animate;


    _this.pMain = _this.pMobile;

    // [[255,255,255,0], [237,218,10,4] ...
    // a 256 element array mapping the values 0-255 to rgba values
    // not a d3 color scale for speed
    // this.colorScale = HEATED_OBJECT_MAP;
    _this.colorScale = _configs.HEATED_OBJECT_MAP;

    // Continuous scaling is currently not supported
    _this.continuousScaling = false;

    if (options && options.colorRange) {
      _this.colorScale = (0, _utils.colorDomainToRgbaArray)(options.colorRange);
    }

    _this.animate = animate;
    _this.options = options;

    _this.pubSubs = [];
    return _this;
  }

  (0, _createClass3['default'])(HorizontalHeatmapTrack, [{
    key: 'rerender',
    value: function () {
      function rerender(options, force) {
        (0, _get3['default'])(HorizontalHeatmapTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalHeatmapTrack.prototype), 'rerender', this).call(this, options, force);

        // zoom so that if the heatmap is flipped, the scale of this.pMain changes
        this.zoomed(this.xScale(), this.yScale(), this.pMain.scale.x, this.pMain.position.x, this.pMain.position.y);
      }

      return rerender;
    }()
  }, {
    key: 'calculateZoomLevel',
    value: function () {
      function calculateZoomLevel() {
        var zoomLevel = null;

        if (this.tilesetInfo.resolutions) {
          var zoomIndexX = _services.tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);

          var zoomIndexY = _services.tileProxy.calculateZoomLevelFromResolutions(this.tilesetInfo.resolutions, this._xScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1]);

          zoomLevel = Math.min(zoomIndexX, zoomIndexY);
        } else {
          var xZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);

          var yZoomLevel = _services.tileProxy.calculateZoomLevel(this._xScale, this.tilesetInfo.min_pos[1], this.tilesetInfo.max_pos[1]);

          zoomLevel = Math.max(xZoomLevel, yZoomLevel);
          zoomLevel = Math.min(zoomLevel, this.maxZoom);
        }

        if (this.options && this.options.maxZoom) {
          if (this.options.maxZoom >= 0) {
            zoomLevel = Math.min(this.options.maxZoom, zoomLevel);
          } else {
            console.error('Invalid maxZoom on track:', this);
          }
        }

        return zoomLevel;
      }

      return calculateZoomLevel;
    }()
  }, {
    key: 'calculateVisibleTiles',
    value: function () {
      function calculateVisibleTiles() {
        // if we don't know anything about this dataset, no point
        // in trying to get tiles
        if (!this.tilesetInfo) {
          return;
        }

        this.zoomLevel = this.calculateZoomLevel();

        // this.zoomLevel = 0;
        var expandedXScale = this._xScale.copy();

        // we need to expand the domain of the X-scale because we are showing diagonal tiles.
        // to make sure the view is covered up the entire height, we need to expand by
        // viewHeight * sqrt(2)
        // on each side
        expandedXScale.domain([this._xScale.invert(this._xScale.range()[0] - this.dimensions[1] * Math.sqrt(2)), this._xScale.invert(this._xScale.range()[1] + this.dimensions[1] * Math.sqrt(2))]);

        if (this.tilesetInfo.resolutions) {
          var sortedResolutions = this.tilesetInfo.resolutions.map(function (x) {
            return +x;
          }).sort(function (a, b) {
            return b - a;
          });

          this.xTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], expandedXScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
          this.yTiles = _services.tileProxy.calculateTilesFromResolution(sortedResolutions[this.zoomLevel], expandedXScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0]);
        } else {
          this.xTiles = _services.tileProxy.calculateTiles(this.zoomLevel, expandedXScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);

          this.yTiles = _services.tileProxy.calculateTiles(this.zoomLevel, expandedXScale, this.tilesetInfo.min_pos[0], this.tilesetInfo.max_pos[0], this.tilesetInfo.max_zoom, this.tilesetInfo.max_width);
        }

        var rows = this.xTiles;
        var cols = this.yTiles;
        var zoomLevel = this.zoomLevel;

        var maxWidth = this.tilesetInfo.max_width;
        var tileWidth = maxWidth / Math.pow(2, zoomLevel);

        // if we're mirroring tiles, then we only need tiles along the diagonal
        var tiles = [];

        // calculate the ids of the tiles that should be visible
        for (var i = 0; i < rows.length; i++) {
          for (var j = i; j < cols.length; j++) {
            // the length between the bottom of the track and the bottom corner of the tile
            // draw it out to understand better!
            var tileBottomPosition = (j - i - 2) * (this._xScale(tileWidth) - this._xScale(0)) * Math.sqrt(2) / 2;

            if (tileBottomPosition > this.dimensions[1]) {
              // this tile won't be visible so we don't need to fetch it
              continue;
            }

            var newTile = [zoomLevel, rows[i], cols[j]];
            newTile.mirrored = false;
            newTile.dataTransform = this.options.dataTransform ? this.options.dataTransform : 'default';

            tiles.push(newTile);
          }
        }

        this.setVisibleTiles(tiles);
      }

      return calculateVisibleTiles;
    }()
  }, {
    key: 'tileDataToCanvas',
    value: function () {
      function tileDataToCanvas(pixData) {
        var canvas = document.createElement('canvas');

        canvas.width = 256;
        canvas.height = 256;
        //

        var ctx = canvas.getContext('2d');

        ctx.fillStyle = 'transparent';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        var pix = new ImageData(pixData, canvas.width, canvas.height);

        ctx.putImageData(pix, 0, 0);

        return canvas;
      }

      return tileDataToCanvas;
    }()
  }, {
    key: 'setSpriteProperties',
    value: function () {
      function setSpriteProperties(sprite, zoomLevel, tilePos, mirrored) {
        var _getTilePosAndDimensi = this.getTilePosAndDimensions(zoomLevel, tilePos),
            tileX = _getTilePosAndDimensi.tileX,
            tileY = _getTilePosAndDimensi.tileY,
            tileWidth = _getTilePosAndDimensi.tileWidth,
            tileHeight = _getTilePosAndDimensi.tileHeight;

        var tileEndX = tileX + tileWidth;
        var tileEndY = tileY + tileHeight;

        sprite.width = this._refXScale(tileEndX) - this._refXScale(tileX);
        sprite.height = this._refYScale(tileEndY) - this._refYScale(tileY);

        sprite.x = this._refXScale(tileX);
        sprite.y = this._refYScale(tileY);
      }

      return setSpriteProperties;
    }()
  }, {
    key: 'pixDataFunction',
    value: function () {
      function pixDataFunction(tile, pixData) {
        // the tileData has been converted to pixData by the worker script and needs to be loaded
        // as a sprite
        if (pixData) {
          var graphics = tile.graphics;

          var canvas = this.tileDataToCanvas(pixData.pixData);

          var texture = _configs.GLOBALS.PIXI.VERSION[0] === '4' ? _configs.GLOBALS.PIXI.Texture.fromCanvas(canvas, _configs.GLOBALS.PIXI.SCALE_MODES.NEAREST) : _configs.GLOBALS.PIXI.Texture.from(canvas, {
            scaleMode: _configs.GLOBALS.PIXI.SCALE_MODES.NEAREST
          });

          tile.sprite = new _configs.GLOBALS.PIXI.Sprite(texture);
          tile.canvas = canvas;

          this.setSpriteProperties(tile.sprite, tile.tileData.zoomLevel, tile.tileData.tilePos, tile.mirrored);

          graphics.pivot.x = this._refXScale(0);
          graphics.pivot.y = this._refYScale(0);
          graphics.scale.x = -1 / Math.sqrt(2);
          graphics.rotation = -3 * Math.PI / 4;
          graphics.scale.y = 1 / Math.sqrt(2);

          graphics.position.x = this._refXScale(0);
          graphics.position.y = 0;

          graphics.removeChildren();
          graphics.addChild(tile.sprite);
        }

        this.renderingTiles['delete'](tile.tileId);
        /*
            this.animate();
            this.refreshTiles();
            */
      }

      return pixDataFunction;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        (0, _get3['default'])(HorizontalHeatmapTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalHeatmapTrack.prototype), 'refScalesChanged', this).call(this, refXScale, refYScale);

        for (var uid in this.fetchedTiles) {
          var tile = this.fetchedTiles[uid];

          if (tile.sprite) {
            this.setSpriteProperties(tile.sprite, tile.tileData.zoomLevel, tile.tileData.tilePos, tile.mirrored);

            var graphics = tile.graphics;

            graphics.pivot.x = this._refXScale(0);
            graphics.pivot.y = this._refYScale(0);
            graphics.scale.x = -1 / Math.sqrt(2);
            graphics.rotation = -3 * Math.PI / 4;
            graphics.scale.y = 1 / Math.sqrt(2);

            graphics.position.x = this._refXScale(0);
            graphics.position.y = 0;
          } else {
            // console.log('skipping...', tile.tileId);
          }
        }
      }

      return refScalesChanged;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale, k, tx, ty) {
        (0, _get3['default'])(HorizontalHeatmapTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalHeatmapTrack.prototype), 'zoomed', this).call(this, newXScale, newYScale, k, tx, ty);
        (0, _get3['default'])(HorizontalHeatmapTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalHeatmapTrack.prototype), 'draw', this).call(this);

        this.pMain.position.x = tx;
        this.pMain.position.y = this.position[1] + this.dimensions[1]; // translateY;

        this.pMain.scale.x = k; // scaleX;
        this.pMain.scale.y = k; // scaleY;

        if (this.options.oneDHeatmapFlipped) {
          this.pMain.scale.y = -k;
          this.pMain.position.y = this.position[1];
        }
      }

      return zoomed;
    }()
  }, {
    key: 'leftTrackDraw',
    value: function () {
      function leftTrackDraw() {
        this.draw();
      }

      return leftTrackDraw;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        var _get$call = (0, _get3['default'])(HorizontalHeatmapTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalHeatmapTrack.prototype), 'superSVG', this).call(this);

        var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

        base = _get$call2[0];
        track = _get$call2[1];


        var output = document.createElement('g');
        track.appendChild(output);

        output.setAttribute('transform', 'translate(' + String(this.pMain.position.x) + ',' + String(this.pMain.position.y) + ') scale(' + String(this.pMain.scale.x) + ',' + String(this.pMain.scale.y) + ')');

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(this.visibleAndFetchedTiles()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tile = _step.value;

            var gGraphics = document.createElement('g');
            var graphics = tile.graphics;
            var graphicsRotation = graphics.rotation * 180 / Math.PI;
            var transformText = 'translate(' + String(graphics.position.x) + ',' + String(graphics.position.y) + ') rotate(' + graphicsRotation + ') scale(' + String(graphics.scale.x) + ',' + String(graphics.scale.y) + ') translate(' + -graphics.pivot.x + ',' + -graphics.pivot.y + ')';
            gGraphics.setAttribute('transform', transformText);

            var rotation = tile.sprite.rotation * 180 / Math.PI;
            var g = document.createElement('g');
            g.setAttribute('transform', 'translate(' + String(tile.sprite.x) + ',' + String(tile.sprite.y) + ') rotate(' + rotation + ') scale(' + String(tile.sprite.scale.x) + ',' + String(tile.sprite.scale.y) + ')');

            var image = document.createElement('image');
            image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', tile.canvas.toDataURL());
            image.setAttribute('width', 256);
            image.setAttribute('height', 256);

            g.appendChild(image);
            gGraphics.appendChild(g);

            output.appendChild(gGraphics);
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var gColorbar = this.exportColorBarSVG();
        track.appendChild(gColorbar);

        return [base, base];
      }

      return exportSVG;
    }()
  }]);
  return HorizontalHeatmapTrack;
}(_HeatmapTiledPixiTrack2['default']);

// Configs


// Services


exports['default'] = HorizontalHeatmapTrack;

/***/ }),
/* 373 */
/***/ (function(module, exports, __nested_webpack_require_2063263__) {

"use strict";


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

var _isNan = __nested_webpack_require_2063263__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _toConsumableArray2 = __nested_webpack_require_2063263__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _keys = __nested_webpack_require_2063263__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getPrototypeOf = __nested_webpack_require_2063263__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2063263__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2063263__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2063263__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2063263__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Scale = __nested_webpack_require_2063263__(28);

var _HorizontalLine1DPixiTrack = __nested_webpack_require_2063263__(116);

var _HorizontalLine1DPixiTrack2 = _interopRequireDefault(_HorizontalLine1DPixiTrack);

var _AxisPixi = __nested_webpack_require_2063263__(179);

var _AxisPixi2 = _interopRequireDefault(_AxisPixi);

var _utils = __nested_webpack_require_2063263__(10);

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

var ValueIntervalTrack = function (_HorizontalLine1DPixi) {
  (0, _inherits3['default'])(ValueIntervalTrack, _HorizontalLine1DPixi);

  function ValueIntervalTrack(context, options) {
    (0, _classCallCheck3['default'])(this, ValueIntervalTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ValueIntervalTrack.__proto__ || (0, _getPrototypeOf2['default'])(ValueIntervalTrack)).call(this, context, options));

    _this.axis = new _AxisPixi2['default'](_this);
    _this.pBase.addChild(_this.axis.pAxis);
    return _this;
  }

  (0, _createClass3['default'])(ValueIntervalTrack, [{
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        // create the tile
        // should be overwritten by child classes
        this.scale.minRawValue = this.minVisibleValueInTiles();
        this.scale.maxRawValue = this.minVisibleValueInTiles();

        this.scale.minValue = this.scale.minRawValue;
        this.scale.maxValue = this.scale.maxRawValue;

        this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        var _this2 = this;

        if (!tile.graphics) {
          return;
        }

        var graphics = tile.graphics;
        var RECT_HEIGHT = 6;
        var MIN_RECT_WIDTH = 4;

        graphics.clear();

        this.valueScale = (0, _d3Scale.scaleLog)().domain([this.minValue() + 0.01, this.maxValue()]).range([this.dimensions[1] - RECT_HEIGHT / 2, RECT_HEIGHT / 2]);

        var fill = (0, _utils.colorToHex)('black');

        graphics.lineStyle(1, fill, 0.3);
        graphics.beginFill(fill, 0.3);

        this.drawAxis(this.valueScale);

        tile.tileData.forEach(function (td) {
          var fields = td.fields;

          var chrOffset = +td.chrOffset;

          var genomeStart = +fields[1] + chrOffset;
          var genomeEnd = +fields[2] + chrOffset;
          var value = +fields[3];

          var startPos = _this2._xScale(genomeStart);
          var endPos = _this2._xScale(genomeEnd);

          var width = Math.max(endPos - startPos, MIN_RECT_WIDTH);
          var midY = _this2.valueScale(value);
          var midX = (endPos + startPos) / 2;

          graphics.drawRect(midX - width / 2, midY - RECT_HEIGHT / 2, width, RECT_HEIGHT);
        });
      }

      return drawTile;
    }()
  }, {
    key: 'minVisibleValueInTiles',
    value: function () {
      function minVisibleValueInTiles() {
        var _this3 = this;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var min = Math.min.apply(null, visibleAndFetchedIds.map(function (x) {
          return +Math.min.apply(Math, (0, _toConsumableArray3['default'])(_this3.fetchedTiles[x].tileData.filter(function (y) {
            return !(0, _isNan2['default'])(y.fields[3]);
          }).map(function (y) {
            return +y.fields[3];
          })));
        }));

        return min;
      }

      return minVisibleValueInTiles;
    }()
  }, {
    key: 'maxVisibleValueInTiles',
    value: function () {
      function maxVisibleValueInTiles() {
        var _this4 = this;

        var visibleAndFetchedIds = this.visibleAndFetchedIds();

        if (visibleAndFetchedIds.length === 0) {
          visibleAndFetchedIds = (0, _keys2['default'])(this.fetchedTiles);
        }

        var max = Math.max.apply(null, visibleAndFetchedIds.map(function (x) {
          return +Math.max.apply(Math, (0, _toConsumableArray3['default'])(_this4.fetchedTiles[x].tileData.filter(function (y) {
            return !(0, _isNan2['default'])(y.fields[3]);
          }).map(function (y) {
            return +y.fields[3];
          })));
        }));

        return max;
      }

      return maxVisibleValueInTiles;
    }()
  }]);
  return ValueIntervalTrack;
}(_HorizontalLine1DPixiTrack2['default']);

exports['default'] = ValueIntervalTrack;

/***/ }),
/* 374 */
/***/ (function(module, exports, __nested_webpack_require_2068758__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2068758__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2068758__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2068758__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2068758__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2068758__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2068758__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _slugid = __nested_webpack_require_2068758__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _d3Brush = __nested_webpack_require_2068758__(83);

var _d3Selection = __nested_webpack_require_2068758__(0);

var _SVGTrack2 = __nested_webpack_require_2068758__(80);

var _SVGTrack3 = _interopRequireDefault(_SVGTrack2);

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

var ViewportTracker2D = function (_SVGTrack) {
  (0, _inherits3['default'])(ViewportTracker2D, _SVGTrack);

  function ViewportTracker2D(context, options) {
    (0, _classCallCheck3['default'])(this, ViewportTracker2D);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ViewportTracker2D.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTracker2D)).call(this, context, options));
    // create a clipped SVG Path


    var registerViewportChanged = context.registerViewportChanged,
        removeViewportChanged = context.removeViewportChanged,
        setDomainsCallback = context.setDomainsCallback;


    var uid = _slugid2['default'].nice();
    _this.uid = uid;
    _this.options = options;

    // Is there actually a linked _from_ view? Or is this projection "independent"?
    _this.hasFromView = !context.projectionXDomain || !context.projectionYDomain;

    _this.removeViewportChanged = removeViewportChanged;
    _this.setDomainsCallback = setDomainsCallback;

    _this.viewportXDomain = _this.hasFromView ? null : context.projectionXDomain;
    _this.viewportYDomain = _this.hasFromView ? null : context.projectionYDomain;

    _this.brush = (0, _d3Brush.brush)().on('brush', _this.brushed.bind(_this));

    _this.gBrush = _this.gMain.append('g').attr('id', 'brush-' + String(_this.uid)).call(_this.brush);

    /*
    // This is used to draw a border that is completely outside of the
    // drawn rectangle
    this.gBorder = this.gMain
      .append('path')
      .style('pointer-events', 'none');
    */

    // turn off the ability to select new regions for this brush
    _this.gBrush.selectAll('.overlay').style('pointer-events', 'none');

    // turn off the ability to modify the aspect ratio of the brush
    _this.gBrush.selectAll('.handle--n').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--s').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--w').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--e').style('pointer-events', 'none');

    // the viewport will call this.viewportChanged immediately upon
    // hearing registerViewportChanged
    registerViewportChanged(uid, _this.viewportChanged.bind(_this));

    _this.rerender();
    _this.draw();
    return _this;
  }

  (0, _createClass3['default'])(ViewportTracker2D, [{
    key: 'brushed',
    value: function () {
      function brushed() {
        /**
         * Should only be called  on active brushing, not in response to the
         * draw event
         */
        var s = _d3Selection.event.selection;

        if (!this._xScale || !this._yScale) {
          return;
        }

        var xDomain = [this._xScale.invert(s[0][0]), this._xScale.invert(s[1][0])];

        var yDomain = [this._yScale.invert(s[0][1]), this._yScale.invert(s[1][1])];

        if (!this.hasFromView) {
          this.viewportXDomain = xDomain;
          this.viewportYDomain = yDomain;
        }

        this.setDomainsCallback(xDomain, yDomain);
      }

      return brushed;
    }()
  }, {
    key: 'viewportChanged',
    value: function () {
      function viewportChanged(viewportXScale, viewportYScale) {
        var viewportXDomain = viewportXScale.domain();
        var viewportYDomain = viewportYScale.domain();

        this.viewportXDomain = viewportXDomain;
        this.viewportYDomain = viewportYDomain;

        this.draw();
      }

      return viewportChanged;
    }()
  }, {
    key: 'remove',
    value: function () {
      function remove() {
        // remove the event handler that updates this viewport tracker
        this.removeViewportChanged(this.uid);

        (0, _get3['default'])(ViewportTracker2D.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTracker2D.prototype), 'remove', this).call(this);
      }

      return remove;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender() {
        // set the fill and stroke colors
        // console.log('rerender');
        this.gBrush.selectAll('.selection').attr('fill', this.options.projectionFillColor).attr('stroke', this.options.projectionStrokeColor).attr('fill-opacity', this.options.projectionFillOpacity).attr('stroke-opacity', this.options.projectionStrokeOpacity).attr('stroke-width', this.options.strokeWidth);

        /*
        this.gBorder
          .style('fill', this.options.projectionStrokeColor)
          .style('opacity', this.options.projectionStrokeOpacity)
        */
      }

      return rerender;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        if (!this._xScale || !this.yScale) {
          return;
        }

        if (!this.viewportXDomain || !this.viewportYDomain) {
          return;
        }

        var x0 = this._xScale(this.viewportXDomain[0]);
        var y0 = this._yScale(this.viewportYDomain[0]);

        var x1 = this._xScale(this.viewportXDomain[1]);
        var y1 = this._yScale(this.viewportYDomain[1]);

        var dest = [[x0, y0], [x1, y1]];

        // user hasn't actively brushed so we don't want to emit a
        // 'brushed' event
        this.brush.on('brush', null);
        this.gBrush.call(this.brush.move, dest);
        this.brush.on('brush', this.brushed.bind(this));

        /*
        const sW = this.options.strokeWidth;
         this.gBorder
        .attr('d', `M${x0} ${y0} H ${x1} V ${y1} H ${x0} V ${y0 - sW} H ${x0 - sW}
                    V ${y1 + sW} H ${x1 + sW} V ${y0 - sW} H ${x0 - sW} V ${y0}`);
        */
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(ViewportTracker2D.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTracker2D.prototype), 'setPosition', this).call(this, newPosition);

        this.draw();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(ViewportTracker2D.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTracker2D.prototype), 'setDimensions', this).call(this, newDimensions);

        var xRange = this._xScale.range();
        var yRange = this._yScale.range();
        var xDiff = xRange[1] - xRange[0];
        var yDiff = yRange[1] - yRange[0];
        this.brush.extent([[xRange[0] - xDiff, yRange[0] - yDiff], [xRange[1] + xDiff, yRange[1] + yDiff]]);
        this.gBrush.call(this.brush);

        this.draw();
      }

      return setDimensions;
    }()
  }]);
  return ViewportTracker2D;
}(_SVGTrack3['default']);

exports['default'] = ViewportTracker2D;

/***/ }),
/* 375 */
/***/ (function(module, exports, __nested_webpack_require_2076847__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2076847__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2076847__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2076847__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2076847__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2076847__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2076847__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Brush = __nested_webpack_require_2076847__(83);

var _d3Selection = __nested_webpack_require_2076847__(0);

var _slugid = __nested_webpack_require_2076847__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _SVGTrack2 = __nested_webpack_require_2076847__(80);

var _SVGTrack3 = _interopRequireDefault(_SVGTrack2);

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

var ViewportTrackerHorizontal = function (_SVGTrack) {
  (0, _inherits3['default'])(ViewportTrackerHorizontal, _SVGTrack);

  function ViewportTrackerHorizontal(context, options) {
    (0, _classCallCheck3['default'])(this, ViewportTrackerHorizontal);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ViewportTrackerHorizontal.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerHorizontal)).call(this, context, options));
    // create a clipped SVG Path


    var registerViewportChanged = context.registerViewportChanged,
        removeViewportChanged = context.removeViewportChanged,
        setDomainsCallback = context.setDomainsCallback;


    var uid = _slugid2['default'].nice();
    _this.uid = uid;
    _this.options = options;

    // Is there actually a linked _from_ view? Or is this projection "independent"?
    _this.hasFromView = !context.projectionXDomain;

    _this.removeViewportChanged = removeViewportChanged;
    _this.setDomainsCallback = setDomainsCallback;

    _this.viewportXDomain = _this.hasFromView ? null : context.projectionXDomain;
    _this.viewportYDomain = _this.hasFromView ? null : [0, 0];

    _this.brush = (0, _d3Brush.brushX)().on('brush', _this.brushed.bind(_this));

    _this.gBrush = _this.gMain.append('g').attr('id', 'brush-' + String(_this.uid)).call(_this.brush);

    // turn off the ability to select new regions for this brush
    _this.gBrush.selectAll('.overlay').style('pointer-events', 'none');

    // turn off the ability to modify the aspect ratio of the brush
    _this.gBrush.selectAll('.handle--ne').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--nw').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--sw').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--se').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--n').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--s').style('pointer-events', 'none');

    // the viewport will call this.viewportChanged immediately upon
    // hearing registerViewportChanged
    registerViewportChanged(uid, _this.viewportChanged.bind(_this));

    _this.rerender();
    _this.draw();
    return _this;
  }

  (0, _createClass3['default'])(ViewportTrackerHorizontal, [{
    key: 'brushed',
    value: function () {
      function brushed() {
        /**
         * Should only be called  on active brushing, not in response to the
         * draw event
         */
        var s = _d3Selection.event.selection;

        if (!this._xScale || !this._yScale) {
          return;
        }

        var xDomain = [this._xScale.invert(s[0]), this._xScale.invert(s[1])];

        var yDomain = this.viewportYDomain;

        if (!this.hasFromView) {
          this.viewportXDomain = xDomain;
        }

        // console.log('xDomain:', xDomain);
        // console.log('yDomain:', yDomain);

        this.setDomainsCallback(xDomain, yDomain);
      }

      return brushed;
    }()
  }, {
    key: 'viewportChanged',
    value: function () {
      function viewportChanged(viewportXScale, viewportYScale) {
        var update = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

        // console.log('viewport changed:', viewportXScale.domain());
        var viewportXDomain = viewportXScale.domain();
        var viewportYDomain = viewportYScale.domain();

        this.viewportXDomain = viewportXDomain;
        this.viewportYDomain = viewportYDomain;

        this.draw();
      }

      return viewportChanged;
    }()
  }, {
    key: 'remove',
    value: function () {
      function remove() {
        // remove the event handler that updates this viewport tracker
        this.removeViewportChanged(this.uid);

        (0, _get3['default'])(ViewportTrackerHorizontal.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerHorizontal.prototype), 'remove', this).call(this);
      }

      return remove;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender() {
        // set the fill and stroke colors
        this.gBrush.selectAll('.selection').attr('fill', this.options.projectionFillColor).attr('stroke', this.options.projectionStrokeColor).attr('fill-opacity', this.options.projectionFillOpacity).attr('stroke-opacity', this.options.projectionStrokeOpacity).attr('stroke-width', this.options.strokeWidth);
      }

      return rerender;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        if (!this._xScale || !this.yScale) {
          return;
        }

        if (!this.viewportXDomain || !this.viewportYDomain) {
          return;
        }

        var x0 = this._xScale(this.viewportXDomain[0]);
        var x1 = this._xScale(this.viewportXDomain[1]);

        var dest = [x0, x1];

        // console.log('dest:', dest[0], dest[1]);

        // user hasn't actively brushed so we don't want to emit a
        // 'brushed' event
        this.brush.on('brush', null);
        this.gBrush.call(this.brush.move, dest);
        this.brush.on('brush', this.brushed.bind(this));
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(ViewportTrackerHorizontal.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerHorizontal.prototype), 'setPosition', this).call(this, newPosition);

        this.draw();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(ViewportTrackerHorizontal.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerHorizontal.prototype), 'setDimensions', this).call(this, newDimensions);

        var xRange = this._xScale.range();
        var yRange = this._yScale.range();
        var xDiff = xRange[1] - xRange[0];

        this.brush.extent([[xRange[0] - xDiff, yRange[0]], [xRange[1] + xDiff, yRange[1]]]);
        this.gBrush.call(this.brush);

        this.draw();
      }

      return setDimensions;
    }()
  }]);
  return ViewportTrackerHorizontal;
}(_SVGTrack3['default']);

exports['default'] = ViewportTrackerHorizontal;

/***/ }),
/* 376 */
/***/ (function(module, exports, __nested_webpack_require_2084536__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2084536__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2084536__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2084536__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2084536__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2084536__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2084536__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Brush = __nested_webpack_require_2084536__(83);

var _d3Selection = __nested_webpack_require_2084536__(0);

var _slugid = __nested_webpack_require_2084536__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _SVGTrack2 = __nested_webpack_require_2084536__(80);

var _SVGTrack3 = _interopRequireDefault(_SVGTrack2);

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

var ViewportTrackerVertical = function (_SVGTrack) {
  (0, _inherits3['default'])(ViewportTrackerVertical, _SVGTrack);

  function ViewportTrackerVertical(context, options) {
    (0, _classCallCheck3['default'])(this, ViewportTrackerVertical);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ViewportTrackerVertical.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerVertical)).call(this, context, options));

    var registerViewportChanged = context.registerViewportChanged,
        removeViewportChanged = context.removeViewportChanged,
        setDomainsCallback = context.setDomainsCallback;


    var uid = _slugid2['default'].nice();
    _this.uid = uid;
    _this.options = options;

    // Is there actually a linked _from_ view? Or is this projection "independent"?
    _this.hasFromView = !context.projectionYDomain;

    _this.removeViewportChanged = removeViewportChanged;
    _this.setDomainsCallback = setDomainsCallback;

    _this.viewportXDomain = _this.hasFromView ? null : [0, 0];
    _this.viewportYDomain = _this.hasFromView ? null : context.projectionYDomain;

    _this.brush = (0, _d3Brush.brushY)().on('brush', _this.brushed.bind(_this));

    _this.gBrush = _this.gMain.append('g').attr('id', 'brush-' + String(_this.uid)).call(_this.brush);

    // turn off the ability to select new regions for this brush
    _this.gBrush.selectAll('.overlay').style('pointer-events', 'none');

    // turn off the ability to modify the aspect ratio of the brush
    _this.gBrush.selectAll('.handle--ne').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--nw').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--sw').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--se').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--e').style('pointer-events', 'none');

    _this.gBrush.selectAll('.handle--w').style('pointer-events', 'none');

    // the viewport will call this.viewportChanged immediately upon
    // hearing registerViewportChanged
    registerViewportChanged(uid, _this.viewportChanged.bind(_this));

    _this.rerender();
    _this.draw();
    return _this;
  }

  (0, _createClass3['default'])(ViewportTrackerVertical, [{
    key: 'brushed',
    value: function () {
      function brushed() {
        /**
         * Should only be called  on active brushing, not in response to the
         * draw event
         */
        var s = _d3Selection.event.selection;

        if (!this._xScale || !this._yScale) {
          return;
        }

        var xDomain = this.viewportXDomain;

        var yDomain = [this._yScale.invert(s[0]), this._yScale.invert(s[1])];

        if (!this.hasFromView) {
          this.viewportYDomain = yDomain;
        }

        // console.log('xDomain:', xDomain);
        // console.log('yDomain:', yDomain);

        this.setDomainsCallback(xDomain, yDomain);
      }

      return brushed;
    }()
  }, {
    key: 'viewportChanged',
    value: function () {
      function viewportChanged(viewportXScale, viewportYScale) {
        var update = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

        // console.log('viewport changed:', viewportXScale.domain());
        var viewportXDomain = viewportXScale.domain();
        var viewportYDomain = viewportYScale.domain();

        this.viewportXDomain = viewportXDomain;
        this.viewportYDomain = viewportYDomain;

        this.draw();
      }

      return viewportChanged;
    }()
  }, {
    key: 'remove',
    value: function () {
      function remove() {
        // remove the event handler that updates this viewport tracker
        this.removeViewportChanged(this.uid);

        (0, _get3['default'])(ViewportTrackerVertical.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerVertical.prototype), 'remove', this).call(this);
      }

      return remove;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender() {
        // set the fill and stroke colors
        this.gBrush.selectAll('.selection').attr('fill', this.options.projectionFillColor).attr('stroke', this.options.projectionStrokeColor).attr('fill-opacity', this.options.projectionFillOpacity).attr('stroke-opacity', this.options.projectionStrokeOpacity).attr('stroke-width', this.options.strokeWidth);
      }

      return rerender;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        if (!this._xScale || !this.yScale) {
          return;
        }

        if (!this.viewportXDomain || !this.viewportYDomain) {
          return;
        }

        var y0 = this._yScale(this.viewportYDomain[0]);
        var y1 = this._yScale(this.viewportYDomain[1]);

        var dest = [y0, y1];

        // console.log('dest:', dest[0], dest[1]);

        // user hasn't actively brushed so we don't want to emit a
        // 'brushed' event
        this.brush.on('brush', null);
        this.gBrush.call(this.brush.move, dest);
        this.brush.on('brush', this.brushed.bind(this));
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(ViewportTrackerVertical.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerVertical.prototype), 'setPosition', this).call(this, newPosition);

        this.draw();
      }

      return setPosition;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        (0, _get3['default'])(ViewportTrackerVertical.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTrackerVertical.prototype), 'setDimensions', this).call(this, newDimensions);

        var xRange = this._xScale.range();
        var yRange = this._yScale.range();
        var yDiff = yRange[1] - yRange[0];
        this.brush.extent([[xRange[0], yRange[0] - yDiff], [xRange[1], yRange[1] + yDiff]]);
        this.gBrush.call(this.brush);

        this.draw();
      }

      return setDimensions;
    }()
  }]);
  return ViewportTrackerVertical;
}(_SVGTrack3['default']);

exports['default'] = ViewportTrackerVertical;

/***/ }),
/* 377 */
/***/ (function(module, exports, __nested_webpack_require_2092160__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_2092160__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _get2 = __nested_webpack_require_2092160__(14);

var _get3 = _interopRequireDefault(_get2);

var _getPrototypeOf = __nested_webpack_require_2092160__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2092160__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2092160__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2092160__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2092160__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _mixwith = __nested_webpack_require_2092160__(81);

var _PixiTrack = __nested_webpack_require_2092160__(40);

var _PixiTrack2 = _interopRequireDefault(_PixiTrack);

var _RuleMixin = __nested_webpack_require_2092160__(261);

var _RuleMixin2 = _interopRequireDefault(_RuleMixin);

var _utils = __nested_webpack_require_2092160__(10);

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

var HorizontalRuleMixin = exports.HorizontalRuleMixin = (0, _mixwith.Mixin)(function (superclass) {
  return function (_superclass) {
    (0, _inherits3['default'])(_class, _superclass);

    function _class() {
      (0, _classCallCheck3['default'])(this, _class);
      return (0, _possibleConstructorReturn3['default'])(this, (_class.__proto__ || (0, _getPrototypeOf2['default'])(_class)).apply(this, arguments));
    }

    (0, _createClass3['default'])(_class, [{
      key: 'drawHorizontalRule',
      value: function () {
        function drawHorizontalRule(graphics) {
          var stroke = (0, _utils.colorToHex)(this.options.color || 'black');

          if (this.highlighted) {
            stroke = (0, _utils.colorToHex)('red');
          }

          graphics.lineStyle(this.strokeWidth, stroke, this.strokeOpacity);

          var pos = 0;

          while (pos < this.dimensions[0]) {
            graphics.moveTo(pos, this._yScale(this.yPosition));
            graphics.lineTo(pos + this.dashLength, this._yScale(this.yPosition));

            pos += this.dashLength + this.dashGap;
          }
        }

        return drawHorizontalRule;
      }()
    }, {
      key: 'isMouseOverHorizontalLine',
      value: function () {
        function isMouseOverHorizontalLine(mousePos) {
          if (Math.abs(mousePos.y - this.position[1] - this._yScale(this.yPosition)) < this.MOUSEOVER_RADIUS) {
            return true;
          }
          return false;
        }

        return isMouseOverHorizontalLine;
      }()
    }]);
    return _class;
  }(superclass);
});

var HorizontalRule = function (_mix$with) {
  (0, _inherits3['default'])(HorizontalRule, _mix$with);

  function HorizontalRule(context, options) {
    (0, _classCallCheck3['default'])(this, HorizontalRule);

    var _this2 = (0, _possibleConstructorReturn3['default'])(this, (HorizontalRule.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalRule)).call(this, context, options));

    _this2.yPosition = context.yPosition;

    _this2.strokeWidth = 2;
    _this2.strokeOpacity = 1;
    _this2.dashLength = 5;
    _this2.dashGap = 3;
    return _this2;
  }

  (0, _createClass3['default'])(HorizontalRule, [{
    key: 'mouseMoveHandler',
    value: function () {
      function mouseMoveHandler(mousePos) {
        if (this.isWithin(mousePos.x, mousePos.y) && this.isMouseOverHorizontalLine(mousePos)) {
          this.highlighted = true;
          this.draw();
          return;
        }

        this.highlighted = false;
        this.draw();
      }

      return mouseMoveHandler;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var graphics = this.pMain;
        graphics.clear();

        this.drawHorizontalRule(graphics);
        this.animate();
      }

      return draw;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(HorizontalRule.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalRule.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(HorizontalRule.prototype.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalRule.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        output.setAttribute('class', 'horizontal-rule');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);

        var stroke = this.options.color || 'black';

        var line = document.createElement('line');
        line.setAttribute('stroke', stroke);
        line.setAttribute('stroke-width', this.strokeWidth);
        line.setAttribute('stroke-dasharray', String(this.dashLength) + ' ' + String(this.dashGap));
        line.setAttribute('x1', 0);
        line.setAttribute('y1', this._yScale(this.yPosition));
        line.setAttribute('x2', this.dimensions[0]);
        line.setAttribute('y2', this._yScale(this.yPosition));

        output.appendChild(line);

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return HorizontalRule;
}((0, _mixwith.mix)(_PixiTrack2['default'])['with'](_RuleMixin2['default'], HorizontalRuleMixin));

exports['default'] = HorizontalRule;

/***/ }),
/* 378 */
/***/ (function(module, exports, __nested_webpack_require_2098393__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_2098393__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getPrototypeOf = __nested_webpack_require_2098393__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2098393__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2098393__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2098393__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2098393__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2098393__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _utils = __nested_webpack_require_2098393__(10);

var _mixwith = __nested_webpack_require_2098393__(81);

var _PixiTrack = __nested_webpack_require_2098393__(40);

var _PixiTrack2 = _interopRequireDefault(_PixiTrack);

var _RuleMixin = __nested_webpack_require_2098393__(261);

var _RuleMixin2 = _interopRequireDefault(_RuleMixin);

var _VerticalRule = __nested_webpack_require_2098393__(262);

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

var CrossRule = function (_mix$with) {
  (0, _inherits3['default'])(CrossRule, _mix$with);

  function CrossRule(context, options) {
    (0, _classCallCheck3['default'])(this, CrossRule);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (CrossRule.__proto__ || (0, _getPrototypeOf2['default'])(CrossRule)).call(this, context, options));

    var x = context.x,
        y = context.y;


    _this.xPosition = x;
    _this.yPosition = y;

    _this.strokeWidth = 2;
    _this.strokeOpacity = 1;
    _this.dashLength = 5;
    _this.dashGap = 3;
    return _this;
  }

  (0, _createClass3['default'])(CrossRule, [{
    key: 'draw',
    value: function () {
      function draw() {
        var graphics = this.pMain;
        graphics.clear();

        this.drawHorizontalRule(graphics);
        this.drawVerticalRule(graphics);
      }

      return draw;
    }()
  }, {
    key: 'mouseMoveHandler',
    value: function () {
      function mouseMoveHandler(mousePos) {
        this.highlighted = this.isWithin(mousePos.x, mousePos.y) && (this.isMouseOverHorizontalLine(mousePos) || this.isMouseOverVerticalLine(mousePos));

        this.draw();
      }

      return mouseMoveHandler;
    }()
  }, {
    key: 'drawHorizontalRule',
    value: function () {
      function drawHorizontalRule(graphics) {
        var stroke = (0, _utils.colorToHex)(this.options.color || 'black');

        if (this.highlighted) {
          stroke = (0, _utils.colorToHex)('red');
        }

        graphics.lineStyle(this.strokeWidth, stroke, this.strokeOpacity);

        var pos = 0;

        // console.log('this._yScale.range()', this._yScale.range());

        while (pos < this.dimensions[0]) {
          graphics.moveTo(pos, this._yScale(this.yPosition));
          graphics.lineTo(pos + this.dashLength, this._yScale(this.yPosition));

          pos += this.dashLength + this.dashGap;
        }
      }

      return drawHorizontalRule;
    }()
  }, {
    key: 'isMouseOverHorizontalLine',
    value: function () {
      function isMouseOverHorizontalLine(mousePos) {
        return Math.abs(mousePos.y - this.position[1] - this._yScale(this.yPosition)) < this.MOUSEOVER_RADIUS;
      }

      return isMouseOverHorizontalLine;
    }()

    /**
     * Export an SVG representation of this track
     *
     * @returns {Array} The two returned DOM nodes are both SVG
     * elements [base,track]. Base is a parent which contains track as a
     * child. Track is clipped with a clipping rectangle contained in base.
     *
     */

  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var track = null;
        var base = null;

        if ((0, _get3['default'])(CrossRule.prototype.__proto__ || (0, _getPrototypeOf2['default'])(CrossRule.prototype), 'exportSVG', this)) {
          var _get$call = (0, _get3['default'])(CrossRule.prototype.__proto__ || (0, _getPrototypeOf2['default'])(CrossRule.prototype), 'exportSVG', this).call(this);

          var _get$call2 = (0, _slicedToArray3['default'])(_get$call, 2);

          base = _get$call2[0];
          track = _get$call2[1];
        } else {
          base = document.createElement('g');
          track = base;
        }
        var output = document.createElement('g');
        output.setAttribute('class', 'cross-rule');
        output.setAttribute('transform', 'translate(' + String(this.position[0]) + ',' + String(this.position[1]) + ')');

        track.appendChild(output);

        var stroke = this.options.color || 'black';

        var verticalLine = document.createElement('line');
        verticalLine.setAttribute('stroke', stroke);
        verticalLine.setAttribute('stroke-width', this.strokeWidth);
        verticalLine.setAttribute('stroke-dasharray', String(this.dashLength) + ' ' + String(this.dashGap));
        verticalLine.setAttribute('x1', this._xScale(this.xPosition));
        verticalLine.setAttribute('y1', 0);
        verticalLine.setAttribute('x2', this._xScale(this.xPosition));
        verticalLine.setAttribute('y2', this.dimensions[1]);

        var horizontalLine = document.createElement('line');
        horizontalLine.setAttribute('stroke', stroke);
        horizontalLine.setAttribute('stroke-width', this.strokeWidth);
        horizontalLine.setAttribute('stroke-dasharray', String(this.dashLength) + ' ' + String(this.dashGap));
        horizontalLine.setAttribute('x1', 0);
        horizontalLine.setAttribute('y1', this._yScale(this.yPosition));
        horizontalLine.setAttribute('x2', this.dimensions[0]);
        horizontalLine.setAttribute('y2', this._yScale(this.yPosition));

        output.appendChild(verticalLine);
        output.appendChild(horizontalLine);

        return [base, track];
      }

      return exportSVG;
    }()
  }]);
  return CrossRule;
}((0, _mixwith.mix)(_PixiTrack2['default'])['with'](_RuleMixin2['default'], _VerticalRule.VerticalRuleMixin));

exports['default'] = CrossRule;

/***/ }),
/* 379 */
/***/ (function(module, exports, __nested_webpack_require_2104697__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2104697__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2104697__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2104697__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2104697__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2104697__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2104697__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _Id2DTiledPixiTrack = __nested_webpack_require_2104697__(254);

var _OSMTilesTrack2 = __nested_webpack_require_2104697__(141);

var _OSMTilesTrack3 = _interopRequireDefault(_OSMTilesTrack2);

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

var OSMTileIdsTrack = function (_OSMTilesTrack) {
  (0, _inherits3['default'])(OSMTileIdsTrack, _OSMTilesTrack);

  function OSMTileIdsTrack() {
    (0, _classCallCheck3['default'])(this, OSMTileIdsTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (OSMTileIdsTrack.__proto__ || (0, _getPrototypeOf2['default'])(OSMTileIdsTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(OSMTileIdsTrack, [{
    key: 'initTile',
    value: function () {
      function initTile(tile) {
        _Id2DTiledPixiTrack.initTile.bind(this)(tile);

        this.drawTile(tile);
      }

      return initTile;
    }()
  }, {
    key: 'drawTile',
    value: function () {
      function drawTile(tile) {
        _Id2DTiledPixiTrack.drawTile.bind(this)(tile);
      }

      return drawTile;
    }()
  }, {
    key: 'areAllVisibleTilesLoaded',
    value: function () {
      function areAllVisibleTilesLoaded() {
        // we don't need to wait for any tiles to load before
        // drawing
        //
        return true;
      }

      return areAllVisibleTilesLoaded;
    }()
  }, {
    key: 'fetchNewTiles',
    value: function () {
      function fetchNewTiles(toFetch) {
        var _this2 = this;

        // no real fetching involved... we just need to display the data
        toFetch.forEach(function (x) {
          var key = x.remoteId;
          var keyParts = key.split('.');

          var data = {
            zoomLevel: keyParts[0],
            tilePos: keyParts.slice(1, keyParts.length).map(function (keyPart) {
              return +keyPart;
            })
          };

          _this2.fetchedTiles[x.tileId] = x;
          _this2.fetchedTiles[x.tileId].tileData = data;

          // since we're not actually fetching remote data, we can easily
          // remove these tiles from the fetching list
          if (_this2.fetching.has(x.remoteId)) {
            _this2.fetching['delete'](x.remoteId);
          }
        });

        this.synchronizeTilesAndGraphics();

        this.draw();
        this.animate();
      }

      return fetchNewTiles;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        (0, _get3['default'])(OSMTileIdsTrack.prototype.__proto__ || (0, _getPrototypeOf2['default'])(OSMTileIdsTrack.prototype), 'draw', this).call(this);

        // this.animate();
      }

      return draw;
    }()
  }]);
  return OSMTileIdsTrack;
}(_OSMTilesTrack3['default']);

exports['default'] = OSMTileIdsTrack;

/***/ }),
/* 380 */
/***/ (function(module, exports, __nested_webpack_require_2108273__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2108273__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2108273__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2108273__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2108273__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_2108273__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_2108273__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _OSMTilesTrack2 = __nested_webpack_require_2108273__(141);

var _OSMTilesTrack3 = _interopRequireDefault(_OSMTilesTrack2);

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

/**
 * A track that must pull remote tiles
 */
var MapboxTilesTrack = function (_OSMTilesTrack) {
  (0, _inherits3["default"])(MapboxTilesTrack, _OSMTilesTrack);

  /**
   * @param scene: A PIXI.js scene to draw everything to.
   * @param server: The server to pull tiles from.
   * @param tilesetUid: The data set to get the tiles from the server
   */
  function MapboxTilesTrack(context, options) {
    (0, _classCallCheck3["default"])(this, MapboxTilesTrack);

    // Force Mapbox and OpenStreetMaps copyright
    var _this = (0, _possibleConstructorReturn3["default"])(this, (MapboxTilesTrack.__proto__ || (0, _getPrototypeOf2["default"])(MapboxTilesTrack)).call(this, context, options));

    _this.style = options.style;

    if (!_this.options.accessToken) {
      _this.errorTextText = "No access token provided in the viewconf's track options " + "('accessToken' option).";
      _this.drawError();
    }
    return _this;
  }

  (0, _createClass3["default"])(MapboxTilesTrack, [{
    key: "rerender",
    value: function () {
      function rerender(newOptions) {
        (0, _get3["default"])(MapboxTilesTrack.prototype.__proto__ || (0, _getPrototypeOf2["default"])(MapboxTilesTrack.prototype), "rerender", this).call(this, newOptions);

        if (newOptions.style === this.style) return;

        this.style = newOptions.style;

        this.removeAllTiles();
        this.refreshTiles();
      }

      return rerender;
    }()

    /**
     * Get the url used to fetch the tile data
     */

  }, {
    key: "getTileUrl",
    value: function () {
      function getTileUrl(tileZxy) {
        var mapStyle = this.options && this.options.style ? this.options.style : 'streets-v10';

        var tileSize = this.options && +this.options.tileSize ? +this.options.tileSize : 256;

        return "https://api.mapbox.com/styles/v1/mapbox/" + String(mapStyle) + "/tiles/" + tileSize + "/" + String(tileZxy[0]) + "/" + String(tileZxy[1]) + "/" + String(tileZxy[2]) + "?access_token=" + String(this.options.accessToken);
      }

      return getTileUrl;
    }()
  }]);
  return MapboxTilesTrack;
}(_OSMTilesTrack3["default"]);

exports["default"] = MapboxTilesTrack;

/***/ }),
/* 381 */
/***/ (function(module, exports, __nested_webpack_require_2111477__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2111477__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2111477__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2111477__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2111477__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2111477__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _OSMTilesTrack2 = __nested_webpack_require_2111477__(141);

var _OSMTilesTrack3 = _interopRequireDefault(_OSMTilesTrack2);

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

/**
 * A track that must pull remote tiles
 */
var RasterTilesTrack = function (_OSMTilesTrack) {
  (0, _inherits3['default'])(RasterTilesTrack, _OSMTilesTrack);

  /**
   * @param scene: A PIXI.js scene to draw everything to.
   * @param server: The server to pull tiles from.
   * @param tilesetUid: The data set to get the tiles from the server
   */
  function RasterTilesTrack(context, options) {
    (0, _classCallCheck3['default'])(this, RasterTilesTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (RasterTilesTrack.__proto__ || (0, _getPrototypeOf2['default'])(RasterTilesTrack)).call(this, context, options));

    _this.style = options.style;

    if (!_this.options.tileSource) {
      _this.errorTextText = 'No tile source string provided in the options. It should be in the form of http://a.com/{z}/{x}/{y}';
      _this.drawError();
    }
    return _this;
  }

  (0, _createClass3['default'])(RasterTilesTrack, [{
    key: 'getTileUrl',
    value: function () {
      function getTileUrl(tileZxy) {
        /**
         * Get the url used to fetch the tile data
         */
        var newUrl = this.options.tileSource.replace('{z}', tileZxy[0]);
        newUrl = newUrl.replace('{x}', tileZxy[1]);
        newUrl = newUrl.replace('{y}', tileZxy[2]);

        return newUrl;
      }

      return getTileUrl;
    }()
  }]);
  return RasterTilesTrack;
}(_OSMTilesTrack3['default']);

exports['default'] = RasterTilesTrack;

/***/ }),
/* 382 */
/***/ (function(module, exports, __nested_webpack_require_2113886__) {

"use strict";


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

var _genbankFetcher = __nested_webpack_require_2113886__(383);

var _genbankFetcher2 = _interopRequireDefault(_genbankFetcher);

var _localTileFetcher = __nested_webpack_require_2113886__(389);

var _localTileFetcher2 = _interopRequireDefault(_localTileFetcher);

var _DataFetcher = __nested_webpack_require_2113886__(245);

var _DataFetcher2 = _interopRequireDefault(_DataFetcher);

var _configs = __nested_webpack_require_2113886__(11);

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

var getDataFetcher = function getDataFetcher(dataConfig, pubSub, pluginDataFetchers) {
  // Check if a plugin data fetcher is available.
  var pluginDataFetcher = pluginDataFetchers[dataConfig.type];
  if (pluginDataFetcher) {
    // eslint-disable-next-line new-cap
    return new pluginDataFetcher.dataFetcher(_configs.AVAILABLE_FOR_PLUGINS, dataConfig, pubSub);
  }

  if (dataConfig.type === 'genbank') {
    return new _genbankFetcher2['default'](dataConfig, pubSub);
  }

  if (dataConfig.type === 'local-tiles') {
    return new _localTileFetcher2['default'](dataConfig, pubSub);
  }

  return new _DataFetcher2['default'](dataConfig, pubSub);
};

exports['default'] = getDataFetcher;

/***/ }),
/* 383 */
/***/ (function(module, exports, __nested_webpack_require_2115217__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_2115217__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _isNan = __nested_webpack_require_2115217__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _getIterator2 = __nested_webpack_require_2115217__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _promise = __nested_webpack_require_2115217__(62);

var _promise2 = _interopRequireDefault(_promise);

var _slicedToArray2 = __nested_webpack_require_2115217__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _classCallCheck2 = __nested_webpack_require_2115217__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2115217__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _slugid = __nested_webpack_require_2115217__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _pako = __nested_webpack_require_2115217__(645);

var _pako2 = _interopRequireDefault(_pako);

var _genbankParser = __nested_webpack_require_2115217__(654);

var _genbankParser2 = _interopRequireDefault(_genbankParser);

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

/**
 * Take a list of genes, which can be any list with elements containing
 * { start, end } fields and return another list of { start, end }
 * fields containing the collapsed genes.
 *
 * The segments should be sorted by their start coordinate.
 *
 * The scale parameter is the number of base pairs per pixels
 */
function collapse(segments, scale) {
  var collapsed = [];

  // the maximum distance we allow between segments before collapsing them
  var MAX_DIST_BETWEEN = 5;

  // no segments in, no segments out
  if (!segments.length) {
    return [];
  }

  // start with the first segment
  var currStart = segments[0].start;
  var currEnd = segments[0].end;

  // continue on to the next segments
  for (var i = 1; i < segments.length; i++) {
    if (segments[i].start < currEnd + MAX_DIST_BETWEEN * 1 / scale) {
      // this segment is within merging distance -- merge it
      currEnd = Math.max(currEnd, segments[i].end);
    } else {
      // this segment is outside of the merging distance, dump the current
      // collapsed segment and start a new one
      collapsed.push({
        type: 'filler',
        start: currStart,
        end: currEnd
      });

      // start a new collapsed segment
      currStart = segments[i].start;
      currEnd = segments[i].end;
    }
  }

  // add the final segment
  collapsed.push({
    start: currStart,
    end: currEnd,
    type: 'filler'
  });

  return collapsed;
}

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
  for (var i = a.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var x = a[i];
    a[i] = a[j];
    a[j] = x;
  }
  return a;
}

function gbToHgGene(gb) {
  var importance = gb.end - gb.start;
  var strand = gb.strand === 1 ? '+' : '-';
  var uid = _slugid2['default'].nice();

  if (gb.type === 'filler') {
    // this is annotation that was generated by collapsing genes and is
    // only meant to show that there is something there.
    return {
      xStart: gb.start,
      xEnd: gb.end,
      strand: gb.strand,
      fields: [],
      type: 'filler',
      uid: uid
    };
  }

  return {
    xStart: gb.start,
    xEnd: gb.end,
    strand: strand,
    chrOffset: 0,
    importance: gb.end - gb.start,
    uid: uid,
    type: gb.type,
    fields: ['chrom', gb.start, gb.end, gb.name, importance, strand, '', '', gb.type, gb.name, gb.start.toString(), gb.end.toString(), gb.start.toString(), gb.end.toString()]
  };
}

/** Convert genbank text to a JSON representation and extract features * */
var gbToJsonAndFeatures = function gbToJsonAndFeatures(gbText) {
  var gbJson = (0, _genbankParser2['default'])(gbText);
  var features = shuffle(gbJson[0].features.filter(function (f) {
    return f.type !== 'source';
  }).sort(function (a, b) {
    return a.start - b.start;
  }));

  return [gbJson, features];
};

var GBKDataFetcher = function () {
  function GBKDataFetcher(dataConfig) {
    var _this = this;

    (0, _classCallCheck3['default'])(this, GBKDataFetcher);

    this.dataConfig = dataConfig;
    this.trackUid = _slugid2['default'].nice();

    if (dataConfig.url) {
      var extension = dataConfig.url.slice(dataConfig.url.length - 3);
      var gzipped = extension === '.gz';
      this.errorTxt = '';

      this.dataPromise = fetch(dataConfig.url, {
        mode: 'cors',
        redirect: 'follow',
        method: 'GET'
      }).then(function (response) {
        return gzipped ? response.arrayBuffer() : response.text();
      }).then(function (buffer) {
        var gffText = gzipped ? _pako2['default'].inflate(buffer, { to: 'string' }) : buffer;

        var _gbToJsonAndFeatures = gbToJsonAndFeatures(gffText);

        var _gbToJsonAndFeatures2 = (0, _slicedToArray3['default'])(_gbToJsonAndFeatures, 2);

        _this.gbJson = _gbToJsonAndFeatures2[0];
        _this.cdss = _gbToJsonAndFeatures2[1];
      });
    } else if (dataConfig.text) {
      this.dataPromise = new _promise2['default'](function (resolve, reject) {
        var _gbToJsonAndFeatures3 = gbToJsonAndFeatures(dataConfig.text);

        var _gbToJsonAndFeatures4 = (0, _slicedToArray3['default'])(_gbToJsonAndFeatures3, 2);

        _this.gbJson = _gbToJsonAndFeatures4[0];
        _this.cdss = _gbToJsonAndFeatures4[1];

        resolve();
      });
    }
  }

  (0, _createClass3['default'])(GBKDataFetcher, [{
    key: 'tilesetInfo',
    value: function () {
      function tilesetInfo(callback) {
        var _this2 = this;

        this.tilesetInfoLoading = true;

        return this.dataPromise.then(function () {
          _this2.tilesetInfoLoading = false;

          var TILE_SIZE = 1024;
          var retVal = {};
          // retVal[this.trackUid] = {
          retVal = {
            tile_size: TILE_SIZE,
            max_zoom: Math.ceil(Math.log(_this2.gbJson[0].size / TILE_SIZE) / Math.log(2)),
            max_width: _this2.gbJson[0].size,
            min_pos: [0],
            max_pos: [_this2.gbJson[0].size]
          };

          if (callback) {
            callback(retVal);
          }

          return retVal;
        })['catch'](function (err) {
          _this2.tilesetInfoLoading = false;

          if (callback) {
            callback({
              error: 'Error parsing genbank: ' + String(err)
            });
          }
        });
      }

      return tilesetInfo;
    }()
  }, {
    key: 'fetchTilesDebounced',
    value: function () {
      function fetchTilesDebounced(receivedTiles, tileIds) {
        var tiles = {};

        var validTileIds = [];
        var tilePromises = [];

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(tileIds), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tileId = _step.value;

            var parts = tileId.split('.');
            var z = parseInt(parts[0], 10);
            var x = parseInt(parts[1], 10);

            if ((0, _isNan2['default'])(x) || (0, _isNan2['default'])(z)) {
              console.warn('Invalid tile zoom or position:', z, x);
              continue;
            }

            validTileIds.push(tileId);
            tilePromises.push(this.tile(z, x));
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        _promise2['default'].all(tilePromises).then(function (values) {
          for (var i = 0; i < values.length; i++) {
            var validTileId = validTileIds[i];
            tiles[validTileId] = values[i];
            tiles[validTileId].tilePositionId = validTileId;
          }

          receivedTiles(tiles);
        });
        // tiles = tileResponseToData(tiles, null, tileIds);
        return tiles;
      }

      return fetchTilesDebounced;
    }()
  }, {
    key: 'tile',
    value: function () {
      function tile(z, x) {
        var _this3 = this;

        return this.tilesetInfo().then(function (tsInfo) {
          var tileWidth = +tsInfo.max_width / Math.pow(2, +z);

          // get the bounds of the tile
          var minX = tsInfo.min_pos[0] + x * tileWidth;
          var maxX = tsInfo.min_pos[0] + (x + 1) * tileWidth;

          var filtered = _this3.cdss.filter(function (v) {
            return v.end > minX && v.start < maxX;
          });
          var scaleFactor = 1024 / Math.pow(2, tsInfo.max_zoom - z);

          var collapsedPlus = collapse(filtered.filter(function (v) {
            return v.strand === 1;
          }), scaleFactor);
          var collapsedMinus = collapse(filtered.filter(function (v) {
            return v.strand !== 1;
          }), scaleFactor);

          collapsedPlus.forEach(function (v) {
            v.strand = '+';
          });
          collapsedMinus.forEach(function (v) {
            v.strand = '-';
          });

          var values = [];
          var TILE_CAPACITY = 20;
          // fill the tile with entries that are within it
          for (var i = 0; i < _this3.cdss.length; i++) {
            if (values.length >= TILE_CAPACITY) break;

            if (_this3.cdss[i].end >= minX && _this3.cdss[i].start <= maxX) {
              values.push(_this3.cdss[i]);
            }
          }

          values = [].concat((0, _toConsumableArray3['default'])(values), (0, _toConsumableArray3['default'])(collapsedPlus), (0, _toConsumableArray3['default'])(collapsedMinus));
          // values = values.concat(collapsedPlus).concat(collapsedMinus);
          // we're not going to take into account importance
          return values.map(function (v) {
            return gbToHgGene(v);
          });
        });
      }

      return tile;
    }()
  }]);
  return GBKDataFetcher;
}();

exports['default'] = GBKDataFetcher;

/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It isn't worth it to make additional optimizations as in original.
// Small size is preferable.

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

function adler32(adler, buf, len, pos) {
  var s1 = (adler & 0xffff) |0,
      s2 = ((adler >>> 16) & 0xffff) |0,
      n = 0;

  while (len !== 0) {
    // Set limit ~ twice less than 5552, to keep
    // s2 in 31-bits, because we force signed ints.
    // in other case %= will fail.
    n = len > 2000 ? 2000 : len;
    len -= n;

    do {
      s1 = (s1 + buf[pos++]) |0;
      s2 = (s2 + s1) |0;
    } while (--n);

    s1 %= 65521;
    s2 %= 65521;
  }

  return (s1 | (s2 << 16)) |0;
}


module.exports = adler32;


/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.

// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

// Use ordinary array, since untyped makes no boost here
function makeTable() {
  var c, table = [];

  for (var n = 0; n < 256; n++) {
    c = n;
    for (var k = 0; k < 8; k++) {
      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
    }
    table[n] = c;
  }

  return table;
}

// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();


function crc32(crc, buf, len, pos) {
  var t = crcTable,
      end = pos + len;

  crc ^= -1;

  for (var i = pos; i < end; i++) {
    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  }

  return (crc ^ (-1)); // >>> 0;
}


module.exports = crc32;


/***/ }),
/* 386 */
/***/ (function(module, exports, __nested_webpack_require_2129232__) {

"use strict";
// String encode/decode helpers



var utils = __nested_webpack_require_2129232__(82);


// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safari
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;

try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }


// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q = 0; q < 256; q++) {
  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start


// convert string to array (typed, when possible)
exports.string2buf = function (str) {
  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;

  // count binary size
  for (m_pos = 0; m_pos < str_len; m_pos++) {
    c = str.charCodeAt(m_pos);
    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
      c2 = str.charCodeAt(m_pos + 1);
      if ((c2 & 0xfc00) === 0xdc00) {
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
        m_pos++;
      }
    }
    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  }

  // allocate buffer
  buf = new utils.Buf8(buf_len);

  // convert
  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
    c = str.charCodeAt(m_pos);
    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
      c2 = str.charCodeAt(m_pos + 1);
      if ((c2 & 0xfc00) === 0xdc00) {
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
        m_pos++;
      }
    }
    if (c < 0x80) {
      /* one byte */
      buf[i++] = c;
    } else if (c < 0x800) {
      /* two bytes */
      buf[i++] = 0xC0 | (c >>> 6);
      buf[i++] = 0x80 | (c & 0x3f);
    } else if (c < 0x10000) {
      /* three bytes */
      buf[i++] = 0xE0 | (c >>> 12);
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
      buf[i++] = 0x80 | (c & 0x3f);
    } else {
      /* four bytes */
      buf[i++] = 0xf0 | (c >>> 18);
      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
      buf[i++] = 0x80 | (c & 0x3f);
    }
  }

  return buf;
};

// Helper (used in 2 places)
function buf2binstring(buf, len) {
  // On Chrome, the arguments in a function call that are allowed is `65534`.
  // If the length of the buffer is smaller than that, we can use this optimization,
  // otherwise we will take a slower path.
  if (len < 65534) {
    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
    }
  }

  var result = '';
  for (var i = 0; i < len; i++) {
    result += String.fromCharCode(buf[i]);
  }
  return result;
}


// Convert byte array to binary string
exports.buf2binstring = function (buf) {
  return buf2binstring(buf, buf.length);
};


// Convert binary string (typed, when possible)
exports.binstring2buf = function (str) {
  var buf = new utils.Buf8(str.length);
  for (var i = 0, len = buf.length; i < len; i++) {
    buf[i] = str.charCodeAt(i);
  }
  return buf;
};


// convert array to string
exports.buf2string = function (buf, max) {
  var i, out, c, c_len;
  var len = max || buf.length;

  // Reserve max possible length (2 words per char)
  // NB: by unknown reasons, Array is significantly faster for
  //     String.fromCharCode.apply than Uint16Array.
  var utf16buf = new Array(len * 2);

  for (out = 0, i = 0; i < len;) {
    c = buf[i++];
    // quick process ascii
    if (c < 0x80) { utf16buf[out++] = c; continue; }

    c_len = _utf8len[c];
    // skip 5 & 6 byte codes
    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }

    // apply mask on first byte
    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
    // join the rest
    while (c_len > 1 && i < len) {
      c = (c << 6) | (buf[i++] & 0x3f);
      c_len--;
    }

    // terminated by end of string?
    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }

    if (c < 0x10000) {
      utf16buf[out++] = c;
    } else {
      c -= 0x10000;
      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
    }
  }

  return buf2binstring(utf16buf, out);
};


// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max   - length limit (mandatory);
exports.utf8border = function (buf, max) {
  var pos;

  max = max || buf.length;
  if (max > buf.length) { max = buf.length; }

  // go back from last position, until start of sequence found
  pos = max - 1;
  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }

  // Very small and broken sequence,
  // return max, because we should return something anyway.
  if (pos < 0) { return max; }

  // If we came to start of buffer - that means buffer is too small,
  // return max too.
  if (pos === 0) { return max; }

  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};


/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

function ZStream() {
  /* next input byte */
  this.input = null; // JS specific, because we have no pointers
  this.next_in = 0;
  /* number of bytes available at input */
  this.avail_in = 0;
  /* total number of input bytes read so far */
  this.total_in = 0;
  /* next output byte should be put there */
  this.output = null; // JS specific, because we have no pointers
  this.next_out = 0;
  /* remaining free space at output */
  this.avail_out = 0;
  /* total number of bytes output so far */
  this.total_out = 0;
  /* last error message, NULL if no error */
  this.msg = ''/*Z_NULL*/;
  /* not visible by applications */
  this.state = null;
  /* best guess about the data type: binary or text */
  this.data_type = 2/*Z_UNKNOWN*/;
  /* adler32 value of the uncompressed data */
  this.adler = 0;
}

module.exports = ZStream;


/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

module.exports = {

  /* Allowed flush values; see deflate() and inflate() below for details */
  Z_NO_FLUSH:         0,
  Z_PARTIAL_FLUSH:    1,
  Z_SYNC_FLUSH:       2,
  Z_FULL_FLUSH:       3,
  Z_FINISH:           4,
  Z_BLOCK:            5,
  Z_TREES:            6,

  /* Return codes for the compression/decompression functions. Negative values
  * are errors, positive values are used for special but normal events.
  */
  Z_OK:               0,
  Z_STREAM_END:       1,
  Z_NEED_DICT:        2,
  Z_ERRNO:           -1,
  Z_STREAM_ERROR:    -2,
  Z_DATA_ERROR:      -3,
  //Z_MEM_ERROR:     -4,
  Z_BUF_ERROR:       -5,
  //Z_VERSION_ERROR: -6,

  /* compression levels */
  Z_NO_COMPRESSION:         0,
  Z_BEST_SPEED:             1,
  Z_BEST_COMPRESSION:       9,
  Z_DEFAULT_COMPRESSION:   -1,


  Z_FILTERED:               1,
  Z_HUFFMAN_ONLY:           2,
  Z_RLE:                    3,
  Z_FIXED:                  4,
  Z_DEFAULT_STRATEGY:       0,

  /* Possible values of the data_type field (though see inflate()) */
  Z_BINARY:                 0,
  Z_TEXT:                   1,
  //Z_ASCII:                1, // = Z_TEXT (deprecated)
  Z_UNKNOWN:                2,

  /* The deflate compression method */
  Z_DEFLATED:               8
  //Z_NULL:                 null // Use -1 or null inline, depending on var type
};


/***/ }),
/* 389 */
/***/ (function(module, exports, __nested_webpack_require_2138892__) {

"use strict";


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

var _keys = __nested_webpack_require_2138892__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getIterator2 = __nested_webpack_require_2138892__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _values = __nested_webpack_require_2138892__(37);

var _values2 = _interopRequireDefault(_values);

var _classCallCheck2 = __nested_webpack_require_2138892__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2138892__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _worker = __nested_webpack_require_2138892__(182);

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

var LocalTileDataFetcher = function () {
  function LocalTileDataFetcher(dataConfig) {
    (0, _classCallCheck3['default'])(this, LocalTileDataFetcher);

    this.dataConfig = dataConfig;

    this.tilesetInfoData = (0, _values2['default'])(this.dataConfig.tilesetInfo)[0];
  }

  (0, _createClass3['default'])(LocalTileDataFetcher, [{
    key: 'tilesetInfo',
    value: function () {
      function tilesetInfo(callback) {
        this.tilesetInfoLoading = false;

        callback(this.tilesetInfoData);
      }

      return tilesetInfo;
    }()

    /** We expect there to be a tilesetUid in the provided tilesetInfo
     * and tiles data since tileResponseToData needs it
     *
     * It is also easier for users to paste in request responses for debugging.
     */

  }, {
    key: 'fetchTilesDebounced',
    value: function () {
      function fetchTilesDebounced(receivedTiles, tileIds) {
        this.tilesData = {};

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])((0, _keys2['default'])(this.dataConfig.tiles)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var key = _step.value;

            var keyParts = key.split('.');
            var newKey = 'localtile.' + String(keyParts.slice(1).join('.'));
            this.tilesData[newKey] = this.dataConfig.tiles[key];
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var ret = {};

        var newTileIds = tileIds.map(function (x) {
          return 'localtile.' + String(x);
        });
        (0, _worker.tileResponseToData)(this.tilesData, '', newTileIds);

        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])(tileIds), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var tileId = _step2.value;

            ret[tileId] = this.tilesData['localtile.' + String(tileId)];
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        receivedTiles(ret);
      }

      return fetchTilesDebounced;
    }()
  }, {
    key: 'tile',
    value: function () {
      function tile(z, x) {}

      return tile;
    }()
  }]);
  return LocalTileDataFetcher;
}();

exports['default'] = LocalTileDataFetcher;

/***/ }),
/* 390 */
/***/ (function(module, exports, __nested_webpack_require_2142901__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2142901__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2142901__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2142901__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2142901__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2142901__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_2142901__(1);

var _react2 = _interopRequireDefault(_react);

var _mixwith = __nested_webpack_require_2142901__(81);

var _SeriesListMenu = __nested_webpack_require_2142901__(665);

var _SeriesListMenu2 = _interopRequireDefault(_SeriesListMenu);

var _SeriesListItems = __nested_webpack_require_2142901__(183);

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

var SeriesListSubmenuMixin = (0, _mixwith.Mixin)(function (superclass) {
  return function (_superclass) {
    (0, _inherits3['default'])(_class, _superclass);

    function _class() {
      (0, _classCallCheck3['default'])(this, _class);
      return (0, _possibleConstructorReturn3['default'])(this, (_class.__proto__ || (0, _getPrototypeOf2['default'])(_class)).apply(this, arguments));
    }

    (0, _createClass3['default'])(_class, [{
      key: 'getSubmenu',
      value: function () {
        function getSubmenu() {
          var _this2 = this;

          if (this.state.submenuShown) {
            // the bounding box of the element which initiated the subMenu
            // necessary so that we can position the submenu next to the initiating
            // element
            var bbox = this.state.submenuSourceBbox;
            var position = null;

            if (this.state.orientation === 'left') {
              position = {
                left: this.state.left,
                top: bbox.top
              };
            } else {
              position = {
                left: this.state.left + bbox.width + 7,
                top: bbox.top
              };
            }

            var series = (0, _SeriesListItems.getAllTracksAndSubtracks)(this.props.tracks);
            var selectedTrack = series.filter(function (t) {
              return t.uid === _this2.state.submenuShown.uid;
            })[0];

            // for now we can't replace 'whole' tracks because they're
            // just the horizontal and vertical rule tracks
            var canBeReplaced = selectedTrack && !(selectedTrack.position === 'whole');

            return _react2['default'].createElement(_SeriesListMenu2['default'], {
              key: 'series-list-menu-' + String(selectedTrack.uid),
              ref: function () {
                function ref(c) {
                  _this2.seriesListMenu = c;
                }

                return ref;
              }(),
              closeMenu: this.props.closeMenu,
              hostTrack: this.props.tracks[0],
              onAddDivisor: this.props.onAddDivisor,
              onAddSeries: canBeReplaced ? this.props.onAddSeries : null,
              onChangeTrackData: this.props.onChangeTrackData,
              onChangeTrackType: this.props.onChangeTrackType,
              onCloseTrack: function () {
                function onCloseTrack() {
                  return _this2.props.onCloseTrack(_this2.state.submenuShown.uid);
                }

                return onCloseTrack;
              }(),
              onConfigureTrack: this.props.onConfigureTrack,
              onDivideSeries: this.props.onDivideSeries,
              onExportData: this.props.onExportData,
              onLockScales: this.props.onLockScales,
              onTrackOptionsChanged: this.props.onTrackOptionsChanged,
              orientation: this.state.orientation,
              parentBbox: bbox,
              position: position,
              series: this.state.submenuShown,
              theme: this.props.theme,
              track: selectedTrack,
              trackOrientation: this.props.trackOrientation,
              trackSourceServers: this.props.trackSourceServers
            });
          }
          return _react2['default'].createElement('div', null);
        }

        return getSubmenu;
      }()
    }]);
    return _class;
  }(superclass);
});

exports['default'] = SeriesListSubmenuMixin;

/***/ }),
/* 391 */
/***/ (function(module, exports, __nested_webpack_require_2147489__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2147489__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2147489__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2147489__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2147489__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2147489__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_2147489__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_2147489__(1);

var _react2 = _interopRequireDefault(_react);

var _ContextMenuContainer2 = __nested_webpack_require_2147489__(96);

var _ContextMenuContainer3 = _interopRequireDefault(_ContextMenuContainer2);

var _ContextMenuItem = __nested_webpack_require_2147489__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _configs = __nested_webpack_require_2147489__(11);

__nested_webpack_require_2147489__(68);

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

var _styleModuleImportMap = {
  '../styles/ContextMenu.module.scss': {
    'context-menu': 'ContextMenu-module_context-menu-2OwvL',
    'context-menu-dark': 'ContextMenu-module_context-menu-dark-2PO31',
    'context-menu-icon': 'ContextMenu-module_context-menu-icon-I4kiw',
    'context-menu-item': 'ContextMenu-module_context-menu-item-1HeVv',
    'context-menu-hr': 'ContextMenu-module_context-menu-hr-3yapb',
    'play-icon': 'ContextMenu-module_play-icon-R4pIO',
    'context-menu-span': 'ContextMenu-module_context-menu-span-8EUfZ',
    'context-menu-thumbnail': 'ContextMenu-module_context-menu-thumbnail-2vHLD',
    'context-menu-thumbnail-inline': 'ContextMenu-module_context-menu-thumbnail-inline-1iOcg'
  }
};

// Styles

var NestedContextMenu = function (_ContextMenuContainer) {
  (0, _inherits3['default'])(NestedContextMenu, _ContextMenuContainer);

  function NestedContextMenu() {
    (0, _classCallCheck3['default'])(this, NestedContextMenu);
    return (0, _possibleConstructorReturn3['default'])(this, (NestedContextMenu.__proto__ || (0, _getPrototypeOf2['default'])(NestedContextMenu)).apply(this, arguments));
  }

  (0, _createClass3['default'])(NestedContextMenu, [{
    key: 'getSubmenu',
    value: function () {
      function getSubmenu() {
        if (this.state.submenuShown) {
          // the bounding box of the element which initiated the subMenu
          // necessary so that we can position the submenu next to the initiating
          // element
          var bbox = this.state.submenuSourceBbox;
          var position = this.state.orientation === 'left' ? {
            left: this.state.left,
            top: bbox.top
          } : {
            left: this.state.left + bbox.width + 7,
            top: bbox.top
          };

          var menuItem = this.state.submenuShown;

          return _react2['default'].createElement(NestedContextMenu, {
            menuItems: menuItem.children,
            orientation: this.state.orientation,
            parentBbox: bbox,
            position: position,
            theme: this.props.theme
          });
        }
        return _react2['default'].createElement('div', null);
      }

      return getSubmenu;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {}

      return componentWillUnmount;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var menuItems = [];

        // iterate over the list

        var _loop = function () {
          function _loop(menuItemKey) {
            var menuItem = _this2.props.menuItems[menuItemKey];

            menuItems.push(_react2['default'].createElement(
              _ContextMenuItem2['default'],
              {
                key: menuItemKey,
                onClick: menuItem.handler ? menuItem.handler : function () {
                  return null;
                },
                onMouseEnter: menuItem.children ? function (e) {
                  return _this2.handleItemMouseEnter(e, menuItem);
                } : _this2.handleOtherMouseEnter.bind(_this2),
                onMouseLeave: _this2.handleMouseLeave
              },
              menuItem.name,
              menuItem.children && _react2['default'].createElement(
                'svg',
                { className: 'ContextMenu-module_play-icon-R4pIO' },
                _react2['default'].createElement('use', { xlinkHref: '#play' })
              )
            ));
          }

          return _loop;
        }();

        for (var menuItemKey in this.props.menuItems) {
          _loop(menuItemKey);
        }

        var styleNames = 'context-menu';
        if (this.props.theme === _configs.THEME_DARK) styleNames += ' context-menu-dark';

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this2.div = c;
              }

              return ref;
            }(),
            style: {
              left: this.state.left,
              top: this.state.top
            },
            className: (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
          },
          menuItems,
          this.getSubmenu()
        );
      }

      return render;
    }()
  }]);
  return NestedContextMenu;
}(_ContextMenuContainer3['default']);

exports['default'] = NestedContextMenu;

/***/ }),
/* 392 */
/***/ (function(module, exports, __nested_webpack_require_2153278__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2153278__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2153278__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2153278__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2153278__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2153278__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_2153278__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_2153278__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_2153278__(1);

var _react2 = _interopRequireDefault(_react);

var _d3Brush = __nested_webpack_require_2153278__(83);

var _d3Selection = __nested_webpack_require_2153278__(0);

var _slugid = __nested_webpack_require_2153278__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _ListWrapper = __nested_webpack_require_2153278__(393);

var _ListWrapper2 = _interopRequireDefault(_ListWrapper);

var _HorizontalItem = __nested_webpack_require_2153278__(667);

var _HorizontalItem2 = _interopRequireDefault(_HorizontalItem);

var _SortableList = __nested_webpack_require_2153278__(395);

var _SortableList2 = _interopRequireDefault(_SortableList);

var _utils = __nested_webpack_require_2153278__(10);

var _configs = __nested_webpack_require_2153278__(11);

var _HorizontalTiledPlotModule = __nested_webpack_require_2153278__(671);

var _HorizontalTiledPlotModule2 = _interopRequireDefault(_HorizontalTiledPlotModule);

var _TiledPlotModule = __nested_webpack_require_2153278__(176);

var _TiledPlotModule2 = _interopRequireDefault(_TiledPlotModule);

var _TrackModule = __nested_webpack_require_2153278__(175);

var _TrackModule2 = _interopRequireDefault(_TrackModule);

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

// eslint-disable-line no-unused-vars

// eslint-disable-line no-unused-vars


// Configs
var _styleModuleImportMap = {
  'styles': {
    'horizontal-tiled-plot': 'HorizontalTiledPlot-module_horizontal-tiled-plot-3EK65'
  },
  'stylesPlot': {
    'tiled-plot': 'TiledPlot-module_tiled-plot-uFHiB',
    'horizontalList': 'TiledPlot-module_horizontalList-1c1P8',
    'list': 'TiledPlot-module_list-24zgV',
    'stylizedList': 'TiledPlot-module_stylizedList-Mt4JL',
    'stylizedItem': 'TiledPlot-module_stylizedItem-2bQBK',
    'stylizedHelper': 'TiledPlot-module_stylizedHelper-3IVEu',
    'horizontalItem': 'TiledPlot-module_horizontalItem-2-ZjU',
    'resizable-track': 'TiledPlot-module_resizable-track-2oLT9',
    'domain': 'TiledPlot-module_domain-qYw6K'
  },
  'stylesTrack': {
    'track-range-selection': 'Track-module_track-range-selection-1yrDf',
    'track-range-selection-active': 'Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-active-primary': 'Track-module_track-range-selection-active-primary-29M73 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-active-secondary': 'Track-module_track-range-selection-active-secondary-1s0t5 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-group-inactive': 'Track-module_track-range-selection-group-inactive-YNRM4',
    'track-range-selection-group-brush-selection': 'Track-module_track-range-selection-group-brush-selection-2VYDl'
  }
}; // eslint-disable-line no-unused-vars


// Styles


// Utils

var HorizontalTiledPlot = function (_React$Component) {
  (0, _inherits3['default'])(HorizontalTiledPlot, _React$Component);

  function HorizontalTiledPlot(props) {
    (0, _classCallCheck3['default'])(this, HorizontalTiledPlot);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HorizontalTiledPlot.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTiledPlot)).call(this, props));

    _this.brushBehavior = (0, _d3Brush.brushX)(true).on('start', _this.brushStarted.bind(_this)).on('brush', _this.brushed.bind(_this)).on('end', _this.brushedEnded.bind(_this));
    return _this;
  }

  /* -------------------------- Life Cycle Methods -------------------------- */

  (0, _createClass3['default'])(HorizontalTiledPlot, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        if (this.props.isRangeSelectionActive) {
          this.addBrush();
        }
      }

      return componentDidMount;
    }()
  }, {
    key: 'shouldComponentUpdate',
    value: function () {
      function shouldComponentUpdate(nextProps, nextState) {
        if (this.rangeSelectionTriggered) {
          this.rangeSelectionTriggered = false;
          if (this.rangeSelectionTriggeredEnd && this.props.rangeSelection !== nextProps.rangeSelection) {
            this.moveBrush(nextProps.rangeSelection[0] ? nextProps.rangeSelection[0] : null, true);
          }
          this.rangeSelectionTriggeredEnd = false;
          return this.state !== nextState;
        }
        if (this.props.rangeSelection !== nextProps.rangeSelection) {
          this.moveBrush(nextProps.rangeSelection[0] ? nextProps.rangeSelection[0] : null, nextProps.rangeSelectionEnd);
          return this.state !== nextState;
        }
        return true;
      }

      return shouldComponentUpdate;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate() {
        if (this.props.isRangeSelectionActive) {
          this.addBrush();
        } else {
          this.removeBrush();
        }
      }

      return componentDidUpdate;
    }()

    /* --------------------------- Getter / Setter ---------------------------- */

  }, {
    key: 'addBrush',


    /* ---------------------------- Custom Methods ---------------------------- */

    value: function () {
      function addBrush() {
        if (!this.brushEl || this.brushElAddedBefore === this.brushEl) {
          return;
        }

        if (this.brushElAddedBefore) {
          // Remove event listener on old element to avoid memory leaks
          this.brushElAddedBefore.on('.brush', null);
        }

        this.brushEl.call(this.brushBehavior);
        this.brushElAddedBefore = this.brushEl;

        (0, _utils.resetD3BrushStyle)(this.brushEl, _TrackModule2['default']['track-range-selection-group-brush-selection']);
      }

      return addBrush;
    }()
  }, {
    key: 'brushed',
    value: function () {
      function brushed() {
        // Need to reassign variable to check after reset
        var rangeSelectionMoved = this.rangeSelectionMoved;
        this.rangeSelectionMoved = false;

        if (!this.sourceEvent || !this.props.onRangeSelection || rangeSelectionMoved) return;

        this.rangeSelectionTriggered = true;
        this.props.onRangeSelection(_d3Selection.event.selection);
      }

      return brushed;
    }()
  }, {
    key: 'brushStarted',
    value: function () {
      function brushStarted() {
        if (!this.sourceEvent || !_d3Selection.event.selection) return;

        this.props.onRangeSelectionStart();
      }

      return brushStarted;
    }()
  }, {
    key: 'brushedEnded',
    value: function () {
      function brushedEnded() {
        if (!this.props.is1dRangeSelection) return;

        var rangeSelectionMovedEnd = this.rangeSelectionMovedEnd;
        this.rangeSelectionMovedEnd = false;

        // Brush end event with a selection
        if (_d3Selection.event.selection && _d3Selection.event.sourceEvent && this.props.onRangeSelection && !rangeSelectionMovedEnd) {
          this.rangeSelectionTriggered = true;
          this.rangeSelectionTriggeredEnd = true;
          this.props.onRangeSelectionEnd(_d3Selection.event.selection);
        }

        // Brush end event with no selection, i.e., the selection is reset
        if (!_d3Selection.event.selection) {
          this.rangeSelectionTriggered = true;
          this.props.onRangeSelectionReset();
        }
      }

      return brushedEnded;
    }()
  }, {
    key: 'moveBrush',
    value: function () {
      function moveBrush(rangeSelection) {
        var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        if (!this.brushEl) {
          return;
        }

        var relRange = rangeSelection ? [this.props.scale(rangeSelection[0]), this.props.scale(rangeSelection[1])] : null;

        this.rangeSelectionMoved = true;
        this.rangeSelectionMovedEnd = true;
        if (animate) {
          this.brushEl.transition().call(this.brushBehavior.move, relRange);
        } else {
          this.brushEl.call(this.brushBehavior.move, relRange);
        }
      }

      return moveBrush;
    }()
  }, {
    key: 'removeBrush',
    value: function () {
      function removeBrush() {
        if (this.brushElAddedBefore) {
          // Reset brush selection
          this.brushElAddedBefore.call(this.brushBehavior.move, null);

          // Remove brush behavior
          this.brushElAddedBefore.on('.brush', null);
          this.brushElAddedBefore = undefined;

          this.props.onRangeSelectionReset();
        }
      }

      return removeBrush;
    }()

    /* ------------------------------ Rendering ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var height = this.props.tracks.map(function (x) {
          return x.height;
        }).reduce(_utils.sum, 0);

        var isBrushable = this.props.tracks.map(function (track) {
          return (0, _configs.IS_TRACK_RANGE_SELECTABLE)(track);
        }).reduce(_utils.or, false);

        var rangeSelectorClass = this.props.isRangeSelectionActive ? 'stylesTrack.track-range-selection-active' : 'stylesTrack.track-range-selection';

        return _react2['default'].createElement(
          'div',
          {
            className: 'horizontal-tiled-plot HorizontalTiledPlot-module_horizontal-tiled-plot-3EK65'
          },
          isBrushable && _react2['default'].createElement('svg', {
            ref: function () {
              function ref(el) {
                _this2.brushEl = (0, _d3Selection.select)(el);
              }

              return ref;
            }(),
            style: {
              height: height,
              width: this.props.width
            },

            xmlns: 'http://www.w3.org/2000/svg',
            className: (0, _getClassName3['default'])(rangeSelectorClass, _styleModuleImportMap)
          }),
          _react2['default'].createElement(_ListWrapper2['default'], {
            className: String(_TiledPlotModule2['default'].list) + ' ' + String(_TiledPlotModule2['default'].stylizedList),
            component: _SortableList2['default'],
            editable: this.props.editable,
            handleConfigTrack: this.props.handleConfigTrack,
            handleResizeTrack: this.props.handleResizeTrack,
            height: height,
            helperClass: _TiledPlotModule2['default'].stylizedHelper,
            itemClass: _TiledPlotModule2['default'].stylizedItem,
            itemReactClass: _HorizontalItem2['default'],
            items: this.props.tracks.map(function (d) {
              return {
                configMenuVisible: d.uid === _this2.props.configTrackMenuId,
                uid: d.uid || _slugid2['default'].nice(),
                width: _this2.props.width,
                height: d.height,
                value: d.value
              };
            }),
            onAddSeries: this.props.onAddSeries,
            onCloseTrack: this.props.onCloseTrack,
            onCloseTrackMenuOpened: this.props.onCloseTrackMenuOpened,
            onConfigTrackMenuOpened: this.props.onConfigTrackMenuOpened,
            onSortEnd: this.props.handleSortEnd,
            referenceAncestor: this.props.referenceAncestor,
            resizeHandles: this.props.resizeHandles,
            useDragHandle: true,
            width: this.props.width
          })
        );
      }

      return render;
    }()
  }, {
    key: 'sourceEvent',
    get: function () {
      function get() {
        return _d3Selection.event && _d3Selection.event.sourceEvent;
      }

      return get;
    }()
  }]);
  return HorizontalTiledPlot;
}(_react2['default'].Component);

HorizontalTiledPlot.propTypes = {
  configTrackMenuId: _propTypes2['default'].string,
  editable: _propTypes2['default'].bool,
  handleConfigTrack: _propTypes2['default'].func,
  handleResizeTrack: _propTypes2['default'].func,
  handleSortEnd: _propTypes2['default'].func,
  is1dRangeSelection: _propTypes2['default'].bool,
  isRangeSelectionActive: _propTypes2['default'].bool,
  onAddSeries: _propTypes2['default'].func,
  onCloseTrack: _propTypes2['default'].func,
  onCloseTrackMenuOpened: _propTypes2['default'].func,
  onConfigTrackMenuOpened: _propTypes2['default'].func,
  onRangeSelection: _propTypes2['default'].func,
  onRangeSelectionEnd: _propTypes2['default'].func,
  onRangeSelectionReset: _propTypes2['default'].func,
  onRangeSelectionStart: _propTypes2['default'].func,
  rangeSelection: _propTypes2['default'].array,
  rangeSelectionEnd: _propTypes2['default'].bool,
  referenceAncestor: _propTypes2['default'].func,
  resizeHandles: _propTypes2['default'].object,
  scale: _propTypes2['default'].func,
  tracks: _propTypes2['default'].array,
  width: _propTypes2['default'].number
};

exports['default'] = HorizontalTiledPlot;

/***/ }),
/* 393 */
/***/ (function(module, exports, __nested_webpack_require_2166970__) {

"use strict";


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

var _extends2 = __nested_webpack_require_2166970__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _getPrototypeOf = __nested_webpack_require_2166970__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2166970__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2166970__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2166970__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2166970__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_2166970__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_2166970__(1);

var _react2 = _interopRequireDefault(_react);

var _reactSortableHoc = __nested_webpack_require_2166970__(125);

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

var ListWrapper = function (_React$Component) {
  (0, _inherits3['default'])(ListWrapper, _React$Component);

  function ListWrapper(_ref) {
    var items = _ref.items;
    (0, _classCallCheck3['default'])(this, ListWrapper);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ListWrapper.__proto__ || (0, _getPrototypeOf2['default'])(ListWrapper)).call(this));

    _this.state = {
      items: items,
      isSorting: false
    };
    return _this;
  }

  // eslint-disable-next-line camelcase


  (0, _createClass3['default'])(ListWrapper, [{
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(nextProps) {
        this.setState({
          items: nextProps.items
        });
      }

      return UNSAFE_componentWillReceiveProps;
    }()
  }, {
    key: 'onSortStart',
    value: function () {
      function onSortStart(_ref2, e) {
        var node = _ref2.node,
            index = _ref2.index,
            collection = _ref2.collection;

        e.stopImmediatePropagation();
        var onSortStart = this.props.onSortStart;

        this.setState({ isSorting: true });

        if (onSortStart) {
          onSortStart(this.ref);
        }

        this.sortingIndex = index;

        this.sortStartTop = e.offsetTop;
        this.sortStartLeft = e.offsetLeft;
      }

      return onSortStart;
    }()
  }, {
    key: 'onSortMove',
    value: function () {
      function onSortMove() {}

      return onSortMove;
    }()
  }, {
    key: 'onSortEnd',
    value: function () {
      function onSortEnd(_ref3) {
        var oldIndex = _ref3.oldIndex,
            newIndex = _ref3.newIndex;
        var onSortEnd = this.props.onSortEnd;
        var items = this.state.items;


        this.setState({
          items: (0, _reactSortableHoc.arrayMove)(items, oldIndex, newIndex),
          isSorting: false
        });

        if (onSortEnd) {
          onSortEnd(this.state.items);
        }

        this.sortingIndex = null;
      }

      return onSortEnd;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var Component = this.props.component;
        var _state = this.state,
            items = _state.items,
            isSorting = _state.isSorting;

        var props = {
          isSorting: isSorting,
          items: items,
          onSortEnd: this.onSortEnd.bind(this),
          onSortStart: this.onSortStart.bind(this),
          onSortMove: this.onSortMove.bind(this)
        };

        return _react2['default'].createElement(Component, (0, _extends3['default'])({}, this.props, props, {
          ref: function () {
            function ref(element) {
              _this2.ref = element;
            }

            return ref;
          }()
        }));
      }

      return render;
    }()
  }]);
  return ListWrapper;
}(_react2['default'].Component);

ListWrapper.propTypes = {
  axis: _propTypes2['default'].string,
  className: _propTypes2['default'].string,
  component: _propTypes2['default'].func,
  editable: _propTypes2['default'].bool,
  handleConfigTrack: _propTypes2['default'].func,
  handleResizeTrack: _propTypes2['default'].func,
  height: _propTypes2['default'].number,
  helperClass: _propTypes2['default'].string,
  itemClass: _propTypes2['default'].string,
  itemControlAlignLeft: _propTypes2['default'].bool,
  itemReactClass: _propTypes2['default'].func,
  items: _propTypes2['default'].array,
  onAddSeries: _propTypes2['default'].func,
  onCloseTrack: _propTypes2['default'].func,
  onCloseTrackMenuOpened: _propTypes2['default'].func,
  onConfigTrackMenuOpened: _propTypes2['default'].func,
  onSortEnd: _propTypes2['default'].func,
  onSortStart: _propTypes2['default'].func,
  referenceAncestor: _propTypes2['default'].string,
  resizeHandles: _propTypes2['default'].object,
  useDragHandle: _propTypes2['default'].bool,
  width: _propTypes2['default'].number
};

ListWrapper.defaultProps = {
  className: 'list stylizedList',
  itemClass: 'item stylizedItem',
  width: 400,
  height: 600
};

exports['default'] = ListWrapper;

/***/ }),
/* 394 */
/***/ (function(module, exports, __nested_webpack_require_2172270__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2172270__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2172270__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2172270__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2172270__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2172270__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_2172270__(1);

var _react2 = _interopRequireDefault(_react);

var _MoveableTrack2 = __nested_webpack_require_2172270__(265);

var _MoveableTrack3 = _interopRequireDefault(_MoveableTrack2);

var _TrackControl = __nested_webpack_require_2172270__(174);

var _TrackControl2 = _interopRequireDefault(_TrackControl);

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

var STYLES = {
  pointerEvents: 'all'
};

var HorizontalTrack = function (_MoveableTrack) {
  (0, _inherits3['default'])(HorizontalTrack, _MoveableTrack);

  function HorizontalTrack() {
    (0, _classCallCheck3['default'])(this, HorizontalTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (HorizontalTrack.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(HorizontalTrack, [{
    key: 'getControls',
    value: function () {
      function getControls(isVisible) {
        return _react2['default'].createElement(_TrackControl2['default'], {
          configMenuVisible: this.props.item.configMenuVisible,
          imgStyleAdd: STYLES,
          imgStyleClose: STYLES,
          imgStyleMove: STYLES,
          imgStyleSettings: STYLES,
          isMoveable: this.moveable,
          isVisible: isVisible,
          onAddSeries: this.props.onAddSeries,
          onCloseTrackMenuOpened: this.props.onCloseTrackMenuOpened,
          onConfigTrackMenuOpened: this.props.onConfigTrackMenuOpened,
          uid: this.props.uid
        });
      }

      return getControls;
    }()
  }]);
  return HorizontalTrack;
}(_MoveableTrack3['default']);

exports['default'] = HorizontalTrack;

/***/ }),
/* 395 */
/***/ (function(module, exports, __nested_webpack_require_2174687__) {

"use strict";


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

var _extends2 = __nested_webpack_require_2174687__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _react = __nested_webpack_require_2174687__(1);

var _react2 = _interopRequireDefault(_react);

var _reactSortableHoc = __nested_webpack_require_2174687__(125);

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

var SortableList = (0, _reactSortableHoc.SortableContainer)(function (_ref) {
  var className = _ref.className,
      items = _ref.items,
      itemClass = _ref.itemClass,
      itemControlAlignLeft = _ref.itemControlAlignLeft,
      sortingIndex = _ref.sortingIndex,
      useDragHandle = _ref.useDragHandle,
      sortableHandlers = _ref.sortableHandlers,
      height = _ref.height,
      width = _ref.width,
      onCloseTrack = _ref.onCloseTrack,
      onCloseTrackMenuOpened = _ref.onCloseTrackMenuOpened,
      onConfigTrackMenuOpened = _ref.onConfigTrackMenuOpened,
      onAddSeries = _ref.onAddSeries,
      handleConfigTrack = _ref.handleConfigTrack,
      editable = _ref.editable,
      itemReactClass = _ref.itemReactClass,
      handleResizeTrack = _ref.handleResizeTrack,
      resizeHandles = _ref.resizeHandles;

  var itemElements = items.map(function (item, index) {
    return _react2['default'].createElement(itemReactClass, {
      key: 'sci-' + String(item.uid),
      className: itemClass,
      controlAlignLeft: itemControlAlignLeft,
      sortingIndex: sortingIndex,
      index: index,
      uid: item.uid,
      height: item.height,
      width: item.width,
      item: item,
      useDragHandle: useDragHandle,
      onCloseTrack: onCloseTrack,
      onCloseTrackMenuOpened: onCloseTrackMenuOpened,
      onConfigTrackMenuOpened: onConfigTrackMenuOpened,
      onAddSeries: onAddSeries,
      handleConfigTrack: handleConfigTrack,
      editable: editable,
      handleResizeTrack: handleResizeTrack,
      resizeHandles: resizeHandles
    });
  });

  return _react2['default'].createElement(
    'div',
    (0, _extends3['default'])({
      className: className,
      style: {
        height: height,
        width: width,
        background: 'transparent'
      }
    }, sortableHandlers),
    itemElements
  );
});

exports['default'] = SortableList;

/***/ }),
/* 396 */
/***/ (function(module, exports, __nested_webpack_require_2177063__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_2177063__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2177063__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2177063__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2177063__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2177063__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_2177063__(1);

var _react2 = _interopRequireDefault(_react);

var _MoveableTrack2 = __nested_webpack_require_2177063__(265);

var _MoveableTrack3 = _interopRequireDefault(_MoveableTrack2);

var _TrackControl = __nested_webpack_require_2177063__(174);

var _TrackControl2 = _interopRequireDefault(_TrackControl);

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

var STYLES = {
  pointerEvents: 'all'
};

var VerticalTrack = function (_MoveableTrack) {
  (0, _inherits3['default'])(VerticalTrack, _MoveableTrack);

  function VerticalTrack() {
    (0, _classCallCheck3['default'])(this, VerticalTrack);
    return (0, _possibleConstructorReturn3['default'])(this, (VerticalTrack.__proto__ || (0, _getPrototypeOf2['default'])(VerticalTrack)).apply(this, arguments));
  }

  (0, _createClass3['default'])(VerticalTrack, [{
    key: 'getControls',
    value: function () {
      function getControls(isVisible) {
        return _react2['default'].createElement(_TrackControl2['default'], {
          imgStyleAdd: STYLES,
          imgStyleClose: STYLES,
          imgStyleMove: STYLES,
          imgStyleSettings: STYLES,
          isAlignLeft: this.props.controlAlignLeft,
          isMoveable: this.moveable,
          isVertical: true,
          isVisible: isVisible,
          onAddSeries: this.props.onAddSeries,
          onCloseTrackMenuOpened: this.props.onCloseTrackMenuOpened,
          onConfigTrackMenuOpened: this.props.onConfigTrackMenuOpened,
          uid: this.props.uid
        });
      }

      return getControls;
    }()
  }]);
  return VerticalTrack;
}(_MoveableTrack3['default']);

exports['default'] = VerticalTrack;

/***/ }),
/* 397 */
/***/ (function(module, exports, __nested_webpack_require_2179478__) {

"use strict";


var compileSchema = __nested_webpack_require_2179478__(692)
  , resolve = __nested_webpack_require_2179478__(268)
  , Cache = __nested_webpack_require_2179478__(696)
  , SchemaObject = __nested_webpack_require_2179478__(398)
  , stableStringify = __nested_webpack_require_2179478__(399)
  , formats = __nested_webpack_require_2179478__(697)
  , rules = __nested_webpack_require_2179478__(698)
  , $dataMetaSchema = __nested_webpack_require_2179478__(719)
  , util = __nested_webpack_require_2179478__(117);

module.exports = Ajv;

Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;

Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;

Ajv.prototype.compileAsync = __nested_webpack_require_2179478__(720);
var customKeyword = __nested_webpack_require_2179478__(721);
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;

var errorClasses = __nested_webpack_require_2179478__(270);
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;

var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';

var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];

/**
 * Creates validator instance.
 * Usage: `Ajv(opts)`
 * @param {Object} opts optional options
 * @return {Object} ajv instance
 */
function Ajv(opts) {
  if (!(this instanceof Ajv)) return new Ajv(opts);
  opts = this._opts = util.copy(opts) || {};
  setLogger(this);
  this._schemas = {};
  this._refs = {};
  this._fragments = {};
  this._formats = formats(opts.format);

  this._cache = opts.cache || new Cache;
  this._loadingSchemas = {};
  this._compilations = [];
  this.RULES = rules();
  this._getId = chooseGetId(opts);

  opts.loopRequired = opts.loopRequired || Infinity;
  if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  if (opts.serialize === undefined) opts.serialize = stableStringify;
  this._metaOpts = getMetaSchemaOptions(this);

  if (opts.formats) addInitialFormats(this);
  addDefaultMetaSchema(this);
  if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
  if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
  addInitialSchemas(this);
}



/**
 * Validate data using schema
 * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
 * @this   Ajv
 * @param  {String|Object} schemaKeyRef key, ref or schema object
 * @param  {Any} data to be validated
 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
 */
function validate(schemaKeyRef, data) {
  var v;
  if (typeof schemaKeyRef == 'string') {
    v = this.getSchema(schemaKeyRef);
    if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  } else {
    var schemaObj = this._addSchema(schemaKeyRef);
    v = schemaObj.validate || this._compile(schemaObj);
  }

  var valid = v(data);
  if (v.$async !== true) this.errors = v.errors;
  return valid;
}


/**
 * Create validating function for passed schema.
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
 * @return {Function} validating function
 */
function compile(schema, _meta) {
  var schemaObj = this._addSchema(schema, undefined, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}


/**
 * Adds schema to the instance.
 * @this   Ajv
 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
 * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
 * @return {Ajv} this for method chaining
 */
function addSchema(schema, key, _skipValidation, _meta) {
  if (Array.isArray(schema)){
    for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
    return this;
  }
  var id = this._getId(schema);
  if (id !== undefined && typeof id != 'string')
    throw new Error('schema id must be string');
  key = resolve.normalizeId(key || id);
  checkUnique(this, key);
  this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
  return this;
}


/**
 * Add schema that will be used to validate other schemas
 * options in META_IGNORE_OPTIONS are alway set to false
 * @this   Ajv
 * @param {Object} schema schema object
 * @param {String} key optional schema key
 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
 * @return {Ajv} this for method chaining
 */
function addMetaSchema(schema, key, skipValidation) {
  this.addSchema(schema, key, skipValidation, true);
  return this;
}


/**
 * Validate schema
 * @this   Ajv
 * @param {Object} schema schema to validate
 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
 * @return {Boolean} true if schema is valid
 */
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    this.logger.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema, schema);
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') this.logger.error(message);
    else throw new Error(message);
  }
  return valid;
}


function defaultMeta(self) {
  var meta = self._opts.meta;
  self._opts.defaultMeta = typeof meta == 'object'
                            ? self._getId(meta) || meta
                            : self.getSchema(META_SCHEMA_ID)
                              ? META_SCHEMA_ID
                              : undefined;
  return self._opts.defaultMeta;
}


/**
 * Get compiled schema from the instance by `key` or `ref`.
 * @this   Ajv
 * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
 * @return {Function} schema validating function (with property `schema`).
 */
function getSchema(keyRef) {
  var schemaObj = _getSchemaObj(this, keyRef);
  switch (typeof schemaObj) {
    case 'object': return schemaObj.validate || this._compile(schemaObj);
    case 'string': return this.getSchema(schemaObj);
    case 'undefined': return _getSchemaFragment(this, keyRef);
  }
}


function _getSchemaFragment(self, ref) {
  var res = resolve.schema.call(self, { schema: {} }, ref);
  if (res) {
    var schema = res.schema
      , root = res.root
      , baseId = res.baseId;
    var v = compileSchema.call(self, schema, root, undefined, baseId);
    self._fragments[ref] = new SchemaObject({
      ref: ref,
      fragment: true,
      schema: schema,
      root: root,
      baseId: baseId,
      validate: v
    });
    return v;
  }
}


function _getSchemaObj(self, keyRef) {
  keyRef = resolve.normalizeId(keyRef);
  return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}


/**
 * Remove cached schema(s).
 * If no parameter is passed all schemas but meta-schemas are removed.
 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
 * @this   Ajv
 * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
 * @return {Ajv} this for method chaining
 */
function removeSchema(schemaKeyRef) {
  if (schemaKeyRef instanceof RegExp) {
    _removeAllSchemas(this, this._schemas, schemaKeyRef);
    _removeAllSchemas(this, this._refs, schemaKeyRef);
    return this;
  }
  switch (typeof schemaKeyRef) {
    case 'undefined':
      _removeAllSchemas(this, this._schemas);
      _removeAllSchemas(this, this._refs);
      this._cache.clear();
      return this;
    case 'string':
      var schemaObj = _getSchemaObj(this, schemaKeyRef);
      if (schemaObj) this._cache.del(schemaObj.cacheKey);
      delete this._schemas[schemaKeyRef];
      delete this._refs[schemaKeyRef];
      return this;
    case 'object':
      var serialize = this._opts.serialize;
      var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
      this._cache.del(cacheKey);
      var id = this._getId(schemaKeyRef);
      if (id) {
        id = resolve.normalizeId(id);
        delete this._schemas[id];
        delete this._refs[id];
      }
  }
  return this;
}


function _removeAllSchemas(self, schemas, regex) {
  for (var keyRef in schemas) {
    var schemaObj = schemas[keyRef];
    if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
      self._cache.del(schemaObj.cacheKey);
      delete schemas[keyRef];
    }
  }
}


/* @this   Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  if (typeof schema != 'object' && typeof schema != 'boolean')
    throw new Error('schema should be object or boolean');
  var serialize = this._opts.serialize;
  var cacheKey = serialize ? serialize(schema) : schema;
  var cached = this._cache.get(cacheKey);
  if (cached) return cached;

  shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;

  var id = resolve.normalizeId(this._getId(schema));
  if (id && shouldAddSchema) checkUnique(this, id);

  var willValidate = this._opts.validateSchema !== false && !skipValidation;
  var recursiveMeta;
  if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
    this.validateSchema(schema, true);

  var localRefs = resolve.ids.call(this, schema);

  var schemaObj = new SchemaObject({
    id: id,
    schema: schema,
    localRefs: localRefs,
    cacheKey: cacheKey,
    meta: meta
  });

  if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
  this._cache.put(cacheKey, schemaObj);

  if (willValidate && recursiveMeta) this.validateSchema(schema, true);

  return schemaObj;
}


/* @this   Ajv */
function _compile(schemaObj, root) {
  if (schemaObj.compiling) {
    schemaObj.validate = callValidate;
    callValidate.schema = schemaObj.schema;
    callValidate.errors = null;
    callValidate.root = root ? root : callValidate;
    if (schemaObj.schema.$async === true)
      callValidate.$async = true;
    return callValidate;
  }
  schemaObj.compiling = true;

  var currentOpts;
  if (schemaObj.meta) {
    currentOpts = this._opts;
    this._opts = this._metaOpts;
  }

  var v;
  try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
  catch(e) {
    delete schemaObj.validate;
    throw e;
  }
  finally {
    schemaObj.compiling = false;
    if (schemaObj.meta) this._opts = currentOpts;
  }

  schemaObj.validate = v;
  schemaObj.refs = v.refs;
  schemaObj.refVal = v.refVal;
  schemaObj.root = v.root;
  return v;


  /* @this   {*} - custom context, see passContext option */
  function callValidate() {
    /* jshint validthis: true */
    var _validate = schemaObj.validate;
    var result = _validate.apply(this, arguments);
    callValidate.errors = _validate.errors;
    return result;
  }
}


function chooseGetId(opts) {
  switch (opts.schemaId) {
    case 'auto': return _get$IdOrId;
    case 'id': return _getId;
    default: return _get$Id;
  }
}

/* @this   Ajv */
function _getId(schema) {
  if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
  return schema.id;
}

/* @this   Ajv */
function _get$Id(schema) {
  if (schema.id) this.logger.warn('schema id ignored', schema.id);
  return schema.$id;
}


function _get$IdOrId(schema) {
  if (schema.$id && schema.id && schema.$id != schema.id)
    throw new Error('schema $id is different from id');
  return schema.$id || schema.id;
}


/**
 * Convert array of error message objects to string
 * @this   Ajv
 * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
 * @param  {Object} options optional options with properties `separator` and `dataVar`.
 * @return {String} human readable string with all errors descriptions
 */
function errorsText(errors, options) {
  errors = errors || this.errors;
  if (!errors) return 'No errors';
  options = options || {};
  var separator = options.separator === undefined ? ', ' : options.separator;
  var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;

  var text = '';
  for (var i=0; i<errors.length; i++) {
    var e = errors[i];
    if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
  }
  return text.slice(0, -separator.length);
}


/**
 * Add custom format
 * @this   Ajv
 * @param {String} name format name
 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
 * @return {Ajv} this for method chaining
 */
function addFormat(name, format) {
  if (typeof format == 'string') format = new RegExp(format);
  this._formats[name] = format;
  return this;
}


function addDefaultMetaSchema(self) {
  var $dataSchema;
  if (self._opts.$data) {
    $dataSchema = __nested_webpack_require_2179478__(723);
    self.addMetaSchema($dataSchema, $dataSchema.$id, true);
  }
  if (self._opts.meta === false) return;
  var metaSchema = __nested_webpack_require_2179478__(405);
  if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
  self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
  self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}


function addInitialSchemas(self) {
  var optsSchemas = self._opts.schemas;
  if (!optsSchemas) return;
  if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
  else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}


function addInitialFormats(self) {
  for (var name in self._opts.formats) {
    var format = self._opts.formats[name];
    self.addFormat(name, format);
  }
}


function checkUnique(self, id) {
  if (self._schemas[id] || self._refs[id])
    throw new Error('schema with key or id "' + id + '" already exists');
}


function getMetaSchemaOptions(self) {
  var metaOpts = util.copy(self._opts);
  for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
    delete metaOpts[META_IGNORE_OPTIONS[i]];
  return metaOpts;
}


function setLogger(self) {
  var logger = self._opts.logger;
  if (logger === false) {
    self.logger = {log: noop, warn: noop, error: noop};
  } else {
    if (logger === undefined) logger = console;
    if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
      throw new Error('logger must implement log, warn and error methods');
    self.logger = logger;
  }
}


function noop() {}


/***/ }),
/* 398 */
/***/ (function(module, exports, __nested_webpack_require_2195137__) {

"use strict";


var util = __nested_webpack_require_2195137__(117);

module.exports = SchemaObject;

function SchemaObject(obj) {
  util.copy(obj, this);
}


/***/ }),
/* 399 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = function (data, opts) {
    if (!opts) opts = {};
    if (typeof opts === 'function') opts = { cmp: opts };
    var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;

    var cmp = opts.cmp && (function (f) {
        return function (node) {
            return function (a, b) {
                var aobj = { key: a, value: node[a] };
                var bobj = { key: b, value: node[b] };
                return f(aobj, bobj);
            };
        };
    })(opts.cmp);

    var seen = [];
    return (function stringify (node) {
        if (node && node.toJSON && typeof node.toJSON === 'function') {
            node = node.toJSON();
        }

        if (node === undefined) return;
        if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
        if (typeof node !== 'object') return JSON.stringify(node);

        var i, out;
        if (Array.isArray(node)) {
            out = '[';
            for (i = 0; i < node.length; i++) {
                if (i) out += ',';
                out += stringify(node[i]) || 'null';
            }
            return out + ']';
        }

        if (node === null) return 'null';

        if (seen.indexOf(node) !== -1) {
            if (cycles) return JSON.stringify('__cycle__');
            throw new TypeError('Converting circular structure to JSON');
        }

        var seenIndex = seen.push(node) - 1;
        var keys = Object.keys(node).sort(cmp && cmp(node));
        out = '';
        for (i = 0; i < keys.length; i++) {
            var key = keys[i];
            var value = stringify(node[key]);

            if (!value) continue;
            if (out) out += ',';
            out += JSON.stringify(key) + ':' + value;
        }
        seen.splice(seenIndex, 1);
        return '{' + out + '}';
    })(data);
};


/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_validate(it, $keyword, $ruleType) {
  var out = '';
  var $async = it.schema.$async === true,
    $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
    $id = it.self._getId(it.schema);
  if (it.opts.strictKeywords) {
    var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
    if ($unknownKwd) {
      var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
      if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
      else throw new Error($keywordsMsg);
    }
  }
  if (it.isTop) {
    out += ' var validate = ';
    if ($async) {
      it.async = true;
      out += 'async ';
    }
    out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
    if ($id && (it.opts.sourceCode || it.opts.processCode)) {
      out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
    }
  }
  if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
    var $keyword = 'false schema';
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = 'data' + ($dataLvl || '');
    var $valid = 'valid' + $lvl;
    if (it.schema === false) {
      if (it.isTop) {
        $breakOnError = true;
      } else {
        out += ' var ' + ($valid) + ' = false; ';
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
        if (it.opts.messages !== false) {
          out += ' , message: \'boolean schema is false\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
    } else {
      if (it.isTop) {
        if ($async) {
          out += ' return data; ';
        } else {
          out += ' validate.errors = null; return true; ';
        }
      } else {
        out += ' var ' + ($valid) + ' = true; ';
      }
    }
    if (it.isTop) {
      out += ' }; return validate; ';
    }
    return out;
  }
  if (it.isTop) {
    var $top = it.isTop,
      $lvl = it.level = 0,
      $dataLvl = it.dataLevel = 0,
      $data = 'data';
    it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
    it.baseId = it.baseId || it.rootId;
    delete it.isTop;
    it.dataPathArr = [undefined];
    if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
      var $defaultMsg = 'default is ignored in the schema root';
      if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
      else throw new Error($defaultMsg);
    }
    out += ' var vErrors = null; ';
    out += ' var errors = 0;     ';
    out += ' if (rootData === undefined) rootData = data; ';
  } else {
    var $lvl = it.level,
      $dataLvl = it.dataLevel,
      $data = 'data' + ($dataLvl || '');
    if ($id) it.baseId = it.resolve.url(it.baseId, $id);
    if ($async && !it.async) throw new Error('async schema in sync schema');
    out += ' var errs_' + ($lvl) + ' = errors;';
  }
  var $valid = 'valid' + $lvl,
    $breakOnError = !it.opts.allErrors,
    $closingBraces1 = '',
    $closingBraces2 = '';
  var $errorKeyword;
  var $typeSchema = it.schema.type,
    $typeIsArray = Array.isArray($typeSchema);
  if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
    if ($typeIsArray) {
      if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
    } else if ($typeSchema != 'null') {
      $typeSchema = [$typeSchema, 'null'];
      $typeIsArray = true;
    }
  }
  if ($typeIsArray && $typeSchema.length == 1) {
    $typeSchema = $typeSchema[0];
    $typeIsArray = false;
  }
  if (it.schema.$ref && $refKeywords) {
    if (it.opts.extendRefs == 'fail') {
      throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
    } else if (it.opts.extendRefs !== true) {
      $refKeywords = false;
      it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    }
  }
  if (it.schema.$comment && it.opts.$comment) {
    out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
  }
  if ($typeSchema) {
    if (it.opts.coerceTypes) {
      var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
    }
    var $rulesGroup = it.RULES.types[$typeSchema];
    if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type';
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type',
        $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
      out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
      if ($coerceToTypes) {
        var $dataType = 'dataType' + $lvl,
          $coerced = 'coerced' + $lvl;
        out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
        if (it.opts.coerceTypes == 'array') {
          out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
        }
        out += ' var ' + ($coerced) + ' = undefined; ';
        var $bracesCoercion = '';
        var arr1 = $coerceToTypes;
        if (arr1) {
          var $type, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $type = arr1[$i += 1];
            if ($i) {
              out += ' if (' + ($coerced) + ' === undefined) { ';
              $bracesCoercion += '}';
            }
            if (it.opts.coerceTypes == 'array' && $type != 'array') {
              out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + ';  } ';
            }
            if ($type == 'string') {
              out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
            } else if ($type == 'number' || $type == 'integer') {
              out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
              if ($type == 'integer') {
                out += ' && !(' + ($data) + ' % 1)';
              }
              out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
            } else if ($type == 'boolean') {
              out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
            } else if ($type == 'null') {
              out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
            } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
              out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
            }
          }
        }
        out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else {  ';
        var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
          $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
        out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
        if (!$dataLvl) {
          out += 'if (' + ($parentData) + ' !== undefined)';
        }
        out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
      } else {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      }
      out += ' } ';
    }
  }
  if (it.schema.$ref && !$refKeywords) {
    out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
    if ($breakOnError) {
      out += ' } if (errors === ';
      if ($top) {
        out += '0';
      } else {
        out += 'errs_' + ($lvl);
      }
      out += ') { ';
      $closingBraces2 += '}';
    }
  } else {
    var arr2 = it.RULES;
    if (arr2) {
      var $rulesGroup, i2 = -1,
        l2 = arr2.length - 1;
      while (i2 < l2) {
        $rulesGroup = arr2[i2 += 1];
        if ($shouldUseGroup($rulesGroup)) {
          if ($rulesGroup.type) {
            out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
          }
          if (it.opts.useDefaults) {
            if ($rulesGroup.type == 'object' && it.schema.properties) {
              var $schema = it.schema.properties,
                $schemaKeys = Object.keys($schema);
              var arr3 = $schemaKeys;
              if (arr3) {
                var $propertyKey, i3 = -1,
                  l3 = arr3.length - 1;
                while (i3 < l3) {
                  $propertyKey = arr3[i3 += 1];
                  var $sch = $schema[$propertyKey];
                  if ($sch.default !== undefined) {
                    var $passData = $data + it.util.getProperty($propertyKey);
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = 'default is ignored for: ' + $passData;
                        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
                        else throw new Error($defaultMsg);
                      }
                    } else {
                      out += ' if (' + ($passData) + ' === undefined ';
                      if (it.opts.useDefaults == 'empty') {
                        out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
                      }
                      out += ' ) ' + ($passData) + ' = ';
                      if (it.opts.useDefaults == 'shared') {
                        out += ' ' + (it.useDefault($sch.default)) + ' ';
                      } else {
                        out += ' ' + (JSON.stringify($sch.default)) + ' ';
                      }
                      out += '; ';
                    }
                  }
                }
              }
            } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
              var arr4 = it.schema.items;
              if (arr4) {
                var $sch, $i = -1,
                  l4 = arr4.length - 1;
                while ($i < l4) {
                  $sch = arr4[$i += 1];
                  if ($sch.default !== undefined) {
                    var $passData = $data + '[' + $i + ']';
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = 'default is ignored for: ' + $passData;
                        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
                        else throw new Error($defaultMsg);
                      }
                    } else {
                      out += ' if (' + ($passData) + ' === undefined ';
                      if (it.opts.useDefaults == 'empty') {
                        out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
                      }
                      out += ' ) ' + ($passData) + ' = ';
                      if (it.opts.useDefaults == 'shared') {
                        out += ' ' + (it.useDefault($sch.default)) + ' ';
                      } else {
                        out += ' ' + (JSON.stringify($sch.default)) + ' ';
                      }
                      out += '; ';
                    }
                  }
                }
              }
            }
          }
          var arr5 = $rulesGroup.rules;
          if (arr5) {
            var $rule, i5 = -1,
              l5 = arr5.length - 1;
            while (i5 < l5) {
              $rule = arr5[i5 += 1];
              if ($shouldUseRule($rule)) {
                var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                if ($code) {
                  out += ' ' + ($code) + ' ';
                  if ($breakOnError) {
                    $closingBraces1 += '}';
                  }
                }
              }
            }
          }
          if ($breakOnError) {
            out += ' ' + ($closingBraces1) + ' ';
            $closingBraces1 = '';
          }
          if ($rulesGroup.type) {
            out += ' } ';
            if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
              out += ' else { ';
              var $schemaPath = it.schemaPath + '.type',
                $errSchemaPath = it.errSchemaPath + '/type';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                if ($typeIsArray) {
                  out += '' + ($typeSchema.join(","));
                } else {
                  out += '' + ($typeSchema);
                }
                out += '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should be ';
                  if ($typeIsArray) {
                    out += '' + ($typeSchema.join(","));
                  } else {
                    out += '' + ($typeSchema);
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
          }
          if ($breakOnError) {
            out += ' if (errors === ';
            if ($top) {
              out += '0';
            } else {
              out += 'errs_' + ($lvl);
            }
            out += ') { ';
            $closingBraces2 += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces2) + ' ';
  }
  if ($top) {
    if ($async) {
      out += ' if (errors === 0) return data;           ';
      out += ' else throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; ';
      out += ' return errors === 0;       ';
    }
    out += ' }; return validate;';
  } else {
    out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  }
  out = it.util.cleanUpCode(out);
  if ($top) {
    out = it.util.finalCleanUpCode(out, $async);
  }

  function $shouldUseGroup($rulesGroup) {
    var rules = $rulesGroup.rules;
    for (var i = 0; i < rules.length; i++)
      if ($shouldUseRule(rules[i])) return true;
  }

  function $shouldUseRule($rule) {
    return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
  }

  function $ruleImplementsSomeKeyword($rule) {
    var impl = $rule.implements;
    for (var i = 0; i < impl.length; i++)
      if (it.schema[impl[i]] !== undefined) return true;
  }
  return out;
}


/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limit(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $isMax = $keyword == 'maximum',
    $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
    $schemaExcl = it.schema[$exclusiveKeyword],
    $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
    $op = $isMax ? '<' : '>',
    $notOp = $isMax ? '>' : '<',
    $errorKeyword = undefined;
  if ($isDataExcl) {
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
      $exclusive = 'exclusive' + $lvl,
      $exclType = 'exclType' + $lvl,
      $exclIsNumber = 'exclIsNumber' + $lvl,
      $opExpr = 'op' + $lvl,
      $opStr = '\' + ' + $opExpr + ' + \'';
    out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
    $schemaValueExcl = 'schemaExcl' + $lvl;
    out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
    var $errorKeyword = $exclusiveKeyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
    }
    out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
    if ($schema === undefined) {
      $errorKeyword = $exclusiveKeyword;
      $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
      $schemaValue = $schemaValueExcl;
      $isData = $isDataExcl;
    }
  } else {
    var $exclIsNumber = typeof $schemaExcl == 'number',
      $opStr = $op;
    if ($exclIsNumber && $isData) {
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
    } else {
      if ($exclIsNumber && $schema === undefined) {
        $exclusive = true;
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
        $schemaValue = $schemaExcl;
        $notOp += '=';
      } else {
        if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
        if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
          $exclusive = true;
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
          $notOp += '=';
        } else {
          $exclusive = false;
          $opStr += '=';
        }
      }
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
    }
  }
  $errorKeyword = $errorKeyword || $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be ' + ($opStr) + ' ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 402 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limitItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxItems' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxItems') {
        out += 'more';
      } else {
        out += 'fewer';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' items\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limitLength(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxLength' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  if (it.opts.unicode === false) {
    out += ' ' + ($data) + '.length ';
  } else {
    out += ' ucs2length(' + ($data) + ') ';
  }
  out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT be ';
      if ($keyword == 'maxLength') {
        out += 'longer';
      } else {
        out += 'shorter';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' characters\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 404 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $op = $keyword == 'maxProperties' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxProperties') {
        out += 'more';
      } else {
        out += 'fewer';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' properties\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 405 */
/***/ (function(module) {

module.exports = {"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true};

/***/ }),
/* 406 */
/***/ (function(module, exports, __nested_webpack_require_2235842__) {

/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

module.exports = freeGlobal;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2235842__(27)))

/***/ }),
/* 407 */
/***/ (function(module, exports, __nested_webpack_require_2236206__) {

var baseFor = __nested_webpack_require_2236206__(408),
    keys = __nested_webpack_require_2236206__(119);

/**
 * The base implementation of `_.forOwn` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Object} Returns `object`.
 */
function baseForOwn(object, iteratee) {
  return object && baseFor(object, iteratee, keys);
}

module.exports = baseForOwn;


/***/ }),
/* 408 */
/***/ (function(module, exports, __nested_webpack_require_2236751__) {

var createBaseFor = __nested_webpack_require_2236751__(737);

/**
 * The base implementation of `baseForOwn` which iterates over `object`
 * properties returned by `keysFunc` and invokes `iteratee` for each property.
 * Iteratee functions may exit iteration early by explicitly returning `false`.
 *
 * @private
 * @param {Object} object The object to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @returns {Object} Returns `object`.
 */
var baseFor = createBaseFor();

module.exports = baseFor;


/***/ }),
/* 409 */
/***/ (function(module, exports, __nested_webpack_require_2237420__) {

var baseTimes = __nested_webpack_require_2237420__(738),
    isArguments = __nested_webpack_require_2237420__(184),
    isArray = __nested_webpack_require_2237420__(31),
    isBuffer = __nested_webpack_require_2237420__(185),
    isIndex = __nested_webpack_require_2237420__(142),
    isTypedArray = __nested_webpack_require_2237420__(273);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates an array of the enumerable property names of the array-like `value`.
 *
 * @private
 * @param {*} value The value to query.
 * @param {boolean} inherited Specify returning inherited property names.
 * @returns {Array} Returns the array of property names.
 */
function arrayLikeKeys(value, inherited) {
  var isArr = isArray(value),
      isArg = !isArr && isArguments(value),
      isBuff = !isArr && !isArg && isBuffer(value),
      isType = !isArr && !isArg && !isBuff && isTypedArray(value),
      skipIndexes = isArr || isArg || isBuff || isType,
      result = skipIndexes ? baseTimes(value.length, String) : [],
      length = result.length;

  for (var key in value) {
    if ((inherited || hasOwnProperty.call(value, key)) &&
        !(skipIndexes && (
           // Safari 9 has enumerable `arguments.length` in strict mode.
           key == 'length' ||
           // Node.js 0.10 has enumerable non-index properties on buffers.
           (isBuff && (key == 'offset' || key == 'parent')) ||
           // PhantomJS 2 has enumerable non-index properties on typed arrays.
           (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
           // Skip index properties.
           isIndex(key, length)
        ))) {
      result.push(key);
    }
  }
  return result;
}

module.exports = arrayLikeKeys;


/***/ }),
/* 410 */
/***/ (function(module, exports) {

/**
 * Creates a unary function that invokes `func` with its argument transformed.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {Function} transform The argument transform.
 * @returns {Function} Returns the new function.
 */
function overArg(func, transform) {
  return function(arg) {
    return func(transform(arg));
  };
}

module.exports = overArg;


/***/ }),
/* 411 */
/***/ (function(module, exports, __nested_webpack_require_2239726__) {

var identity = __nested_webpack_require_2239726__(143);

/**
 * Casts `value` to `identity` if it's not a function.
 *
 * @private
 * @param {*} value The value to inspect.
 * @returns {Function} Returns cast function.
 */
function castFunction(value) {
  return typeof value == 'function' ? value : identity;
}

module.exports = castFunction;


/***/ }),
/* 412 */
/***/ (function(module, exports, __nested_webpack_require_2240134__) {

var baseGetTag = __nested_webpack_require_2240134__(97),
    getPrototype = __nested_webpack_require_2240134__(278),
    isObjectLike = __nested_webpack_require_2240134__(56);

/** `Object#toString` result references. */
var objectTag = '[object Object]';

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);

/**
 * Checks if `value` is a plain object, that is, an object created by the
 * `Object` constructor or one with a `[[Prototype]]` of `null`.
 *
 * @static
 * @memberOf _
 * @since 0.8.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * _.isPlainObject(new Foo);
 * // => false
 *
 * _.isPlainObject([1, 2, 3]);
 * // => false
 *
 * _.isPlainObject({ 'x': 0, 'y': 0 });
 * // => true
 *
 * _.isPlainObject(Object.create(null));
 * // => true
 */
function isPlainObject(value) {
  if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
    return false;
  }
  var proto = getPrototype(value);
  if (proto === null) {
    return true;
  }
  var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
  return typeof Ctor == 'function' && Ctor instanceof Ctor &&
    funcToString.call(Ctor) == objectCtorString;
}

module.exports = isPlainObject;


/***/ }),
/* 413 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.map` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function arrayMap(array, iteratee) {
  var index = -1,
      length = array == null ? 0 : array.length,
      result = Array(length);

  while (++index < length) {
    result[index] = iteratee(array[index], index, array);
  }
  return result;
}

module.exports = arrayMap;


/***/ }),
/* 414 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var funcProto = Function.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/**
 * Converts `func` to its source code.
 *
 * @private
 * @param {Function} func The function to convert.
 * @returns {string} Returns the source code.
 */
function toSource(func) {
  if (func != null) {
    try {
      return funcToString.call(func);
    } catch (e) {}
    try {
      return (func + '');
    } catch (e) {}
  }
  return '';
}

module.exports = toSource;


/***/ }),
/* 415 */
/***/ (function(module, exports, __nested_webpack_require_2243086__) {

var baseIsEqualDeep = __nested_webpack_require_2243086__(772),
    isObjectLike = __nested_webpack_require_2243086__(56);

/**
 * The base implementation of `_.isEqual` which supports partial comparisons
 * and tracks traversed objects.
 *
 * @private
 * @param {*} value The value to compare.
 * @param {*} other The other value to compare.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Unordered comparison
 *  2 - Partial comparison
 * @param {Function} [customizer] The function to customize comparisons.
 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
 */
function baseIsEqual(value, other, bitmask, customizer, stack) {
  if (value === other) {
    return true;
  }
  if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
    return value !== value && other !== other;
  }
  return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}

module.exports = baseIsEqual;


/***/ }),
/* 416 */
/***/ (function(module, exports, __nested_webpack_require_2244177__) {

var SetCache = __nested_webpack_require_2244177__(773),
    arraySome = __nested_webpack_require_2244177__(417),
    cacheHas = __nested_webpack_require_2244177__(776);

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * A specialized version of `baseIsEqualDeep` for arrays with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Array} array The array to compare.
 * @param {Array} other The other array to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `array` and `other` objects.
 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
 */
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      arrLength = array.length,
      othLength = other.length;

  if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
    return false;
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(array);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  var index = -1,
      result = true,
      seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;

  stack.set(array, other);
  stack.set(other, array);

  // Ignore non-index properties.
  while (++index < arrLength) {
    var arrValue = array[index],
        othValue = other[index];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, arrValue, index, other, array, stack)
        : customizer(arrValue, othValue, index, array, other, stack);
    }
    if (compared !== undefined) {
      if (compared) {
        continue;
      }
      result = false;
      break;
    }
    // Recursively compare arrays (susceptible to call stack limits).
    if (seen) {
      if (!arraySome(other, function(othValue, othIndex) {
            if (!cacheHas(seen, othIndex) &&
                (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
        result = false;
        break;
      }
    } else if (!(
          arrValue === othValue ||
            equalFunc(arrValue, othValue, bitmask, customizer, stack)
        )) {
      result = false;
      break;
    }
  }
  stack['delete'](array);
  stack['delete'](other);
  return result;
}

module.exports = equalArrays;


/***/ }),
/* 417 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.some` for arrays without support for iteratee
 * shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function arraySome(array, predicate) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (predicate(array[index], index, array)) {
      return true;
    }
  }
  return false;
}

module.exports = arraySome;


/***/ }),
/* 418 */
/***/ (function(module, exports, __nested_webpack_require_2247508__) {

var root = __nested_webpack_require_2247508__(41);

/** Built-in value references. */
var Uint8Array = root.Uint8Array;

module.exports = Uint8Array;


/***/ }),
/* 419 */
/***/ (function(module, exports, __nested_webpack_require_2247722__) {

var baseGetAllKeys = __nested_webpack_require_2247722__(420),
    getSymbols = __nested_webpack_require_2247722__(282),
    keys = __nested_webpack_require_2247722__(119);

/**
 * Creates an array of own enumerable property names and symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeys(object) {
  return baseGetAllKeys(object, keys, getSymbols);
}

module.exports = getAllKeys;


/***/ }),
/* 420 */
/***/ (function(module, exports, __nested_webpack_require_2248259__) {

var arrayPush = __nested_webpack_require_2248259__(281),
    isArray = __nested_webpack_require_2248259__(31);

/**
 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Function} keysFunc The function to get the keys of `object`.
 * @param {Function} symbolsFunc The function to get the symbols of `object`.
 * @returns {Array} Returns the array of property names and symbols.
 */
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  var result = keysFunc(object);
  return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}

module.exports = baseGetAllKeys;


/***/ }),
/* 421 */
/***/ (function(module, exports) {

/**
 * This method returns a new empty array.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {Array} Returns the new empty array.
 * @example
 *
 * var arrays = _.times(2, _.stubArray);
 *
 * console.log(arrays);
 * // => [[], []]
 *
 * console.log(arrays[0] === arrays[1]);
 * // => false
 */
function stubArray() {
  return [];
}

module.exports = stubArray;


/***/ }),
/* 422 */
/***/ (function(module, exports, __nested_webpack_require_2249529__) {

var getNative = __nested_webpack_require_2249529__(99),
    root = __nested_webpack_require_2249529__(41);

/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');

module.exports = WeakMap;


/***/ }),
/* 423 */
/***/ (function(module, exports, __nested_webpack_require_2249820__) {

var isObject = __nested_webpack_require_2249820__(45);

/**
 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` if suitable for strict
 *  equality comparisons, else `false`.
 */
function isStrictComparable(value) {
  return value === value && !isObject(value);
}

module.exports = isStrictComparable;


/***/ }),
/* 424 */
/***/ (function(module, exports) {

/**
 * A specialized version of `matchesProperty` for source values suitable
 * for strict equality comparisons, i.e. `===`.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function matchesStrictComparable(key, srcValue) {
  return function(object) {
    if (object == null) {
      return false;
    }
    return object[key] === srcValue &&
      (srcValue !== undefined || (key in Object(object)));
  };
}

module.exports = matchesStrictComparable;


/***/ }),
/* 425 */
/***/ (function(module, exports, __nested_webpack_require_2250947__) {

var baseHasIn = __nested_webpack_require_2250947__(792),
    hasPath = __nested_webpack_require_2250947__(793);

/**
 * Checks if `path` is a direct or inherited property of `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 * @example
 *
 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
 *
 * _.hasIn(object, 'a');
 * // => true
 *
 * _.hasIn(object, 'a.b');
 * // => true
 *
 * _.hasIn(object, ['a', 'b']);
 * // => true
 *
 * _.hasIn(object, 'b');
 * // => false
 */
function hasIn(object, path) {
  return object != null && hasPath(object, path, baseHasIn);
}

module.exports = hasIn;


/***/ }),
/* 426 */
/***/ (function(module, exports, __nested_webpack_require_2251783__) {

var getNative = __nested_webpack_require_2251783__(99);

var defineProperty = (function() {
  try {
    var func = getNative(Object, 'defineProperty');
    func({}, '', {});
    return func;
  } catch (e) {}
}());

module.exports = defineProperty;


/***/ }),
/* 427 */
/***/ (function(module, exports, __nested_webpack_require_2252095__) {

/* WEBPACK VAR INJECTION */(function(module) {var root = __nested_webpack_require_2252095__(41);

/** Detect free variable `exports`. */
var freeExports =   true && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
    allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;

/**
 * Creates a clone of  `buffer`.
 *
 * @private
 * @param {Buffer} buffer The buffer to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Buffer} Returns the cloned buffer.
 */
function cloneBuffer(buffer, isDeep) {
  if (isDeep) {
    return buffer.slice();
  }
  var length = buffer.length,
      result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);

  buffer.copy(result);
  return result;
}

module.exports = cloneBuffer;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2252095__(173)(module)))

/***/ }),
/* 428 */
/***/ (function(module, exports, __nested_webpack_require_2253335__) {

var arrayPush = __nested_webpack_require_2253335__(281),
    getPrototype = __nested_webpack_require_2253335__(278),
    getSymbols = __nested_webpack_require_2253335__(282),
    stubArray = __nested_webpack_require_2253335__(421);

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;

/**
 * Creates an array of the own and inherited enumerable symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of symbols.
 */
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
  var result = [];
  while (object) {
    arrayPush(result, getSymbols(object));
    object = getPrototype(object);
  }
  return result;
};

module.exports = getSymbolsIn;


/***/ }),
/* 429 */
/***/ (function(module, exports, __nested_webpack_require_2254169__) {

var cloneArrayBuffer = __nested_webpack_require_2254169__(288);

/**
 * Creates a clone of `typedArray`.
 *
 * @private
 * @param {Object} typedArray The typed array to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned typed array.
 */
function cloneTypedArray(typedArray, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}

module.exports = cloneTypedArray;


/***/ }),
/* 430 */
/***/ (function(module, exports, __nested_webpack_require_2254769__) {

var baseCreate = __nested_webpack_require_2254769__(197),
    getPrototype = __nested_webpack_require_2254769__(278),
    isPrototype = __nested_webpack_require_2254769__(186);

/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneObject(object) {
  return (typeof object.constructor == 'function' && !isPrototype(object))
    ? baseCreate(getPrototype(object))
    : {};
}

module.exports = initCloneObject;


/***/ }),
/* 431 */
/***/ (function(module, exports, __nested_webpack_require_2255331__) {

var baseAssignValue = __nested_webpack_require_2255331__(287),
    eq = __nested_webpack_require_2255331__(120);

/**
 * This function is like `assignValue` except that it doesn't assign
 * `undefined` values.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {string} key The key of the property to assign.
 * @param {*} value The value to assign.
 */
function assignMergeValue(object, key, value) {
  if ((value !== undefined && !eq(object[key], value)) ||
      (value === undefined && !(key in object))) {
    baseAssignValue(object, key, value);
  }
}

module.exports = assignMergeValue;


/***/ }),
/* 432 */
/***/ (function(module, exports) {

/**
 * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
 *
 * @private
 * @param {Object} object The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function safeGet(object, key) {
  if (key === 'constructor' && typeof object[key] === 'function') {
    return;
  }

  if (key == '__proto__') {
    return;
  }

  return object[key];
}

module.exports = safeGet;


/***/ }),
/* 433 */
/***/ (function(module, exports, __nested_webpack_require_2256510__) {

var apply = __nested_webpack_require_2256510__(292);

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * A specialized version of `baseRest` which transforms the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @param {number} [start=func.length-1] The start position of the rest parameter.
 * @param {Function} transform The rest array transform.
 * @returns {Function} Returns the new function.
 */
function overRest(func, start, transform) {
  start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  return function() {
    var args = arguments,
        index = -1,
        length = nativeMax(args.length - start, 0),
        array = Array(length);

    while (++index < length) {
      array[index] = args[start + index];
    }
    index = -1;
    var otherArgs = Array(start + 1);
    while (++index < start) {
      otherArgs[index] = args[index];
    }
    otherArgs[start] = transform(array);
    return apply(func, this, otherArgs);
  };
}

module.exports = overRest;


/***/ }),
/* 434 */
/***/ (function(module, exports) {

/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
    HOT_SPAN = 16;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;

/**
 * Creates a function that'll short out and invoke `identity` instead
 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
 * milliseconds.
 *
 * @private
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new shortable function.
 */
function shortOut(func) {
  var count = 0,
      lastCalled = 0;

  return function() {
    var stamp = nativeNow(),
        remaining = HOT_SPAN - (stamp - lastCalled);

    lastCalled = stamp;
    if (remaining > 0) {
      if (++count >= HOT_COUNT) {
        return arguments[0];
      }
    } else {
      count = 0;
    }
    return func.apply(undefined, arguments);
  };
}

module.exports = shortOut;


/***/ }),
/* 435 */
/***/ (function(module, exports, __nested_webpack_require_2258689__) {

var isObject = __nested_webpack_require_2258689__(45),
    now = __nested_webpack_require_2258689__(839),
    toNumber = __nested_webpack_require_2258689__(436);

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
    nativeMin = Math.min;

/**
 * Creates a debounced function that delays invoking `func` until after `wait`
 * milliseconds have elapsed since the last time the debounced function was
 * invoked. The debounced function comes with a `cancel` method to cancel
 * delayed `func` invocations and a `flush` method to immediately invoke them.
 * Provide `options` to indicate whether `func` should be invoked on the
 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
 * with the last arguments provided to the debounced function. Subsequent
 * calls to the debounced function return the result of the last `func`
 * invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the debounced function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.debounce` and `_.throttle`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to debounce.
 * @param {number} [wait=0] The number of milliseconds to delay.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=false]
 *  Specify invoking on the leading edge of the timeout.
 * @param {number} [options.maxWait]
 *  The maximum time `func` is allowed to be delayed before it's invoked.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new debounced function.
 * @example
 *
 * // Avoid costly calculations while the window size is in flux.
 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
 *
 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
 * jQuery(element).on('click', _.debounce(sendMail, 300, {
 *   'leading': true,
 *   'trailing': false
 * }));
 *
 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
 * var source = new EventSource('/stream');
 * jQuery(source).on('message', debounced);
 *
 * // Cancel the trailing debounced invocation.
 * jQuery(window).on('popstate', debounced.cancel);
 */
function debounce(func, wait, options) {
  var lastArgs,
      lastThis,
      maxWait,
      result,
      timerId,
      lastCallTime,
      lastInvokeTime = 0,
      leading = false,
      maxing = false,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  wait = toNumber(wait) || 0;
  if (isObject(options)) {
    leading = !!options.leading;
    maxing = 'maxWait' in options;
    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }

  function invokeFunc(time) {
    var args = lastArgs,
        thisArg = lastThis;

    lastArgs = lastThis = undefined;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    return result;
  }

  function leadingEdge(time) {
    // Reset any `maxWait` timer.
    lastInvokeTime = time;
    // Start the timer for the trailing edge.
    timerId = setTimeout(timerExpired, wait);
    // Invoke the leading edge.
    return leading ? invokeFunc(time) : result;
  }

  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime,
        timeWaiting = wait - timeSinceLastCall;

    return maxing
      ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
      : timeWaiting;
  }

  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime,
        timeSinceLastInvoke = time - lastInvokeTime;

    // Either this is the first call, activity has stopped and we're at the
    // trailing edge, the system time has gone backwards and we're treating
    // it as the trailing edge, or we've hit the `maxWait` limit.
    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
  }

  function timerExpired() {
    var time = now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    // Restart the timer.
    timerId = setTimeout(timerExpired, remainingWait(time));
  }

  function trailingEdge(time) {
    timerId = undefined;

    // Only invoke if we have `lastArgs` which means `func` has been
    // debounced at least once.
    if (trailing && lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = lastThis = undefined;
    return result;
  }

  function cancel() {
    if (timerId !== undefined) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = undefined;
  }

  function flush() {
    return timerId === undefined ? result : trailingEdge(now());
  }

  function debounced() {
    var time = now(),
        isInvoking = shouldInvoke(time);

    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time;

    if (isInvoking) {
      if (timerId === undefined) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        // Handle invocations in a tight loop.
        clearTimeout(timerId);
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === undefined) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}

module.exports = debounce;


/***/ }),
/* 436 */
/***/ (function(module, exports, __nested_webpack_require_2264881__) {

var isObject = __nested_webpack_require_2264881__(45),
    isSymbol = __nested_webpack_require_2264881__(194);

/** Used as references for various `Number` constants. */
var NAN = 0 / 0;

/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;

/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;

/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;

/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;

/**
 * Converts `value` to a number.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @example
 *
 * _.toNumber(3.2);
 * // => 3.2
 *
 * _.toNumber(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toNumber(Infinity);
 * // => Infinity
 *
 * _.toNumber('3.2');
 * // => 3.2
 */
function toNumber(value) {
  if (typeof value == 'number') {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
    value = isObject(other) ? (other + '') : other;
  }
  if (typeof value != 'string') {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, '');
  var isBinary = reIsBinary.test(value);
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value);
}

module.exports = toNumber;


/***/ }),
/* 437 */
/***/ (function(module, exports, __nested_webpack_require_2266537__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_2266537__(1);

var _react2 = _interopRequireDefault(_react);

var _debounce = __nested_webpack_require_2266537__(435);

var _debounce2 = _interopRequireDefault(_debounce);

var _color = __nested_webpack_require_2266537__(57);

var _color2 = _interopRequireDefault(_color);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ColorWrap = exports.ColorWrap = function ColorWrap(Picker) {
  var ColorPicker = function (_ref) {
    _inherits(ColorPicker, _ref);

    function ColorPicker(props) {
      _classCallCheck(this, ColorPicker);

      var _this = _possibleConstructorReturn(this, (ColorPicker.__proto__ || Object.getPrototypeOf(ColorPicker)).call(this));

      _this.handleChange = function (data, event) {
        var isValidColor = _color2.default.simpleCheckForValidColor(data);
        if (isValidColor) {
          var colors = _color2.default.toState(data, data.h || _this.state.oldHue);
          _this.setState(colors);
          _this.props.onChangeComplete && _this.debounce(_this.props.onChangeComplete, colors, event);
          _this.props.onChange && _this.props.onChange(colors, event);
        }
      };

      _this.handleSwatchHover = function (data, event) {
        var isValidColor = _color2.default.simpleCheckForValidColor(data);
        if (isValidColor) {
          var colors = _color2.default.toState(data, data.h || _this.state.oldHue);
          _this.setState(colors);
          _this.props.onSwatchHover && _this.props.onSwatchHover(colors, event);
        }
      };

      _this.state = _extends({}, _color2.default.toState(props.color, 0));

      _this.debounce = (0, _debounce2.default)(function (fn, data, event) {
        fn(data, event);
      }, 100);
      return _this;
    }

    _createClass(ColorPicker, [{
      key: 'componentWillReceiveProps',
      value: function componentWillReceiveProps(nextProps) {
        this.setState(_extends({}, _color2.default.toState(nextProps.color, this.state.oldHue)));
      }
    }, {
      key: 'render',
      value: function render() {
        var optionalEvents = {};
        if (this.props.onSwatchHover) {
          optionalEvents.onSwatchHover = this.handleSwatchHover;
        }

        return _react2.default.createElement(Picker, _extends({}, this.props, this.state, {
          onChange: this.handleChange
        }, optionalEvents));
      }
    }]);

    return ColorPicker;
  }(_react.PureComponent || _react.Component);

  ColorPicker.propTypes = _extends({}, Picker.propTypes);

  ColorPicker.defaultProps = _extends({}, Picker.defaultProps, {
    color: {
      h: 250,
      s: 0.50,
      l: 0.20,
      a: 1
    }
  });

  return ColorPicker;
};

exports.default = ColorWrap;

/***/ }),
/* 438 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_2271190__) {

"use strict";
__nested_webpack_require_2271190__.r(__webpack_exports__);
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "red", function() { return red; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "pink", function() { return pink; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "purple", function() { return purple; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "deepPurple", function() { return deepPurple; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "indigo", function() { return indigo; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "blue", function() { return blue; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "lightBlue", function() { return lightBlue; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "cyan", function() { return cyan; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "teal", function() { return teal; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "green", function() { return green; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "lightGreen", function() { return lightGreen; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "lime", function() { return lime; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "yellow", function() { return yellow; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "amber", function() { return amber; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "orange", function() { return orange; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "deepOrange", function() { return deepOrange; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "brown", function() { return brown; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "grey", function() { return grey; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "blueGrey", function() { return blueGrey; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "darkText", function() { return darkText; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "lightText", function() { return lightText; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "darkIcons", function() { return darkIcons; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "lightIcons", function() { return lightIcons; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "white", function() { return white; });
/* harmony export (binding) */ __nested_webpack_require_2271190__.d(__webpack_exports__, "black", function() { return black; });
var red = {"50":"#ffebee","100":"#ffcdd2","200":"#ef9a9a","300":"#e57373","400":"#ef5350","500":"#f44336","600":"#e53935","700":"#d32f2f","800":"#c62828","900":"#b71c1c","a100":"#ff8a80","a200":"#ff5252","a400":"#ff1744","a700":"#d50000"};
var pink = {"50":"#fce4ec","100":"#f8bbd0","200":"#f48fb1","300":"#f06292","400":"#ec407a","500":"#e91e63","600":"#d81b60","700":"#c2185b","800":"#ad1457","900":"#880e4f","a100":"#ff80ab","a200":"#ff4081","a400":"#f50057","a700":"#c51162"};
var purple = {"50":"#f3e5f5","100":"#e1bee7","200":"#ce93d8","300":"#ba68c8","400":"#ab47bc","500":"#9c27b0","600":"#8e24aa","700":"#7b1fa2","800":"#6a1b9a","900":"#4a148c","a100":"#ea80fc","a200":"#e040fb","a400":"#d500f9","a700":"#aa00ff"};
var deepPurple = {"50":"#ede7f6","100":"#d1c4e9","200":"#b39ddb","300":"#9575cd","400":"#7e57c2","500":"#673ab7","600":"#5e35b1","700":"#512da8","800":"#4527a0","900":"#311b92","a100":"#b388ff","a200":"#7c4dff","a400":"#651fff","a700":"#6200ea"};
var indigo = {"50":"#e8eaf6","100":"#c5cae9","200":"#9fa8da","300":"#7986cb","400":"#5c6bc0","500":"#3f51b5","600":"#3949ab","700":"#303f9f","800":"#283593","900":"#1a237e","a100":"#8c9eff","a200":"#536dfe","a400":"#3d5afe","a700":"#304ffe"};
var blue = {"50":"#e3f2fd","100":"#bbdefb","200":"#90caf9","300":"#64b5f6","400":"#42a5f5","500":"#2196f3","600":"#1e88e5","700":"#1976d2","800":"#1565c0","900":"#0d47a1","a100":"#82b1ff","a200":"#448aff","a400":"#2979ff","a700":"#2962ff"};
var lightBlue = {"50":"#e1f5fe","100":"#b3e5fc","200":"#81d4fa","300":"#4fc3f7","400":"#29b6f6","500":"#03a9f4","600":"#039be5","700":"#0288d1","800":"#0277bd","900":"#01579b","a100":"#80d8ff","a200":"#40c4ff","a400":"#00b0ff","a700":"#0091ea"};
var cyan = {"50":"#e0f7fa","100":"#b2ebf2","200":"#80deea","300":"#4dd0e1","400":"#26c6da","500":"#00bcd4","600":"#00acc1","700":"#0097a7","800":"#00838f","900":"#006064","a100":"#84ffff","a200":"#18ffff","a400":"#00e5ff","a700":"#00b8d4"};
var teal = {"50":"#e0f2f1","100":"#b2dfdb","200":"#80cbc4","300":"#4db6ac","400":"#26a69a","500":"#009688","600":"#00897b","700":"#00796b","800":"#00695c","900":"#004d40","a100":"#a7ffeb","a200":"#64ffda","a400":"#1de9b6","a700":"#00bfa5"};
var green = {"50":"#e8f5e9","100":"#c8e6c9","200":"#a5d6a7","300":"#81c784","400":"#66bb6a","500":"#4caf50","600":"#43a047","700":"#388e3c","800":"#2e7d32","900":"#1b5e20","a100":"#b9f6ca","a200":"#69f0ae","a400":"#00e676","a700":"#00c853"};
var lightGreen = {"50":"#f1f8e9","100":"#dcedc8","200":"#c5e1a5","300":"#aed581","400":"#9ccc65","500":"#8bc34a","600":"#7cb342","700":"#689f38","800":"#558b2f","900":"#33691e","a100":"#ccff90","a200":"#b2ff59","a400":"#76ff03","a700":"#64dd17"};
var lime = {"50":"#f9fbe7","100":"#f0f4c3","200":"#e6ee9c","300":"#dce775","400":"#d4e157","500":"#cddc39","600":"#c0ca33","700":"#afb42b","800":"#9e9d24","900":"#827717","a100":"#f4ff81","a200":"#eeff41","a400":"#c6ff00","a700":"#aeea00"};
var yellow = {"50":"#fffde7","100":"#fff9c4","200":"#fff59d","300":"#fff176","400":"#ffee58","500":"#ffeb3b","600":"#fdd835","700":"#fbc02d","800":"#f9a825","900":"#f57f17","a100":"#ffff8d","a200":"#ffff00","a400":"#ffea00","a700":"#ffd600"};
var amber = {"50":"#fff8e1","100":"#ffecb3","200":"#ffe082","300":"#ffd54f","400":"#ffca28","500":"#ffc107","600":"#ffb300","700":"#ffa000","800":"#ff8f00","900":"#ff6f00","a100":"#ffe57f","a200":"#ffd740","a400":"#ffc400","a700":"#ffab00"};
var orange = {"50":"#fff3e0","100":"#ffe0b2","200":"#ffcc80","300":"#ffb74d","400":"#ffa726","500":"#ff9800","600":"#fb8c00","700":"#f57c00","800":"#ef6c00","900":"#e65100","a100":"#ffd180","a200":"#ffab40","a400":"#ff9100","a700":"#ff6d00"};
var deepOrange = {"50":"#fbe9e7","100":"#ffccbc","200":"#ffab91","300":"#ff8a65","400":"#ff7043","500":"#ff5722","600":"#f4511e","700":"#e64a19","800":"#d84315","900":"#bf360c","a100":"#ff9e80","a200":"#ff6e40","a400":"#ff3d00","a700":"#dd2c00"};
var brown = {"50":"#efebe9","100":"#d7ccc8","200":"#bcaaa4","300":"#a1887f","400":"#8d6e63","500":"#795548","600":"#6d4c41","700":"#5d4037","800":"#4e342e","900":"#3e2723"};
var grey = {"50":"#fafafa","100":"#f5f5f5","200":"#eeeeee","300":"#e0e0e0","400":"#bdbdbd","500":"#9e9e9e","600":"#757575","700":"#616161","800":"#424242","900":"#212121"};
var blueGrey = {"50":"#eceff1","100":"#cfd8dc","200":"#b0bec5","300":"#90a4ae","400":"#78909c","500":"#607d8b","600":"#546e7a","700":"#455a64","800":"#37474f","900":"#263238"};
var darkText = {"primary":"rgba(0, 0, 0, 0.87)","secondary":"rgba(0, 0, 0, 0.54)","disabled":"rgba(0, 0, 0, 0.38)","dividers":"rgba(0, 0, 0, 0.12)"};
var lightText = {"primary":"rgba(255, 255, 255, 1)","secondary":"rgba(255, 255, 255, 0.7)","disabled":"rgba(255, 255, 255, 0.5)","dividers":"rgba(255, 255, 255, 0.12)"};
var darkIcons = {"active":"rgba(0, 0, 0, 0.54)","inactive":"rgba(0, 0, 0, 0.38)"};
var lightIcons = {"active":"rgba(255, 255, 255, 1)","inactive":"rgba(255, 255, 255, 0.5)"};
var white = "#ffffff";
var black = "#000000";

/* harmony default export */ __webpack_exports__["default"] = ({
  red: red,
  pink: pink,
  purple: purple,
  deepPurple: deepPurple,
  indigo: indigo,
  blue: blue,
  lightBlue: lightBlue,
  cyan: cyan,
  teal: teal,
  green: green,
  lightGreen: lightGreen,
  lime: lime,
  yellow: yellow,
  amber: amber,
  orange: orange,
  deepOrange: deepOrange,
  brown: brown,
  grey: grey,
  blueGrey: blueGrey,
  darkText: darkText,
  lightText: lightText,
  darkIcons: darkIcons,
  lightIcons: lightIcons,
  white: white,
  black: black
});


/***/ }),
/* 439 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Pure functional reducer. Can be used for currying stuff. Check out
 *   `flatten.js`.
 * @param   {function}  f  Reducer function.
 * @return  {array}  Curried function that accepts an array to be reduced.
 */
var reduce = function reduce(f) {
  return function (x) {
    return Array.prototype.reduce.call(x, f);
  };
};

exports["default"] = reduce;

/***/ }),
/* 440 */
/***/ (function(module, exports, __nested_webpack_require_2280253__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_2280253__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _slicedToArray2 = __nested_webpack_require_2280253__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _getXylofon3 = __nested_webpack_require_2280253__(441);

var _getXylofon4 = _interopRequireDefault(_getXylofon3);

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

var isInit = false;

var listen = function listen() {
  if (isInit) return;

  var _getXylofon = (0, _getXylofon4['default'])(),
      _getXylofon2 = (0, _slicedToArray3['default'])(_getXylofon, 2),
      o = _getXylofon2[0],
      x = _getXylofon2[1];

  var a = '102117110099116105111110040041123115101108' + '102046099111110115111108101046108111103040039';
  var b = '072';
  var c = '105';
  var d = '071';
  var e = '108097115115';
  var f = '032118';
  var g = '058032104116116112058047047104105103108097115115046105111039041125';
  var h = [String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(a.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase(), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(b.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(c.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase(), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(d.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(e.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase(), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(f.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase(), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(x.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase(), String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(g.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase()].join('');

  var i = '085082076';
  var j = '066076079066';
  var k = '087111114107101114'; // Worker
  var l = '099114101097116101079098106101099116085082076'; // createObjectURL
  var m = '114101118111107101079098106101099116085082076'; // revokeObjectURL

  var ca = function ca(s) {
    return s.charAt(0).toUpperCase() + s.slice(1);
  };
  var cb = function cb(s) {
    return s.slice(0, 6) + s.charAt(6).toUpperCase() + s.slice(7, 12) + s.slice(12).toUpperCase();
  };

  var ur = o[String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(i.match(/.{1,3}/g).map(function (y) {
    return +y;
  })))];
  var bl = o[ca(String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(j.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase())];
  var wo = o[ca(String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(k.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase())];
  var co = cb(String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(l.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase());
  var ro = cb(String.fromCharCode.apply(String, (0, _toConsumableArray3['default'])(m.match(/.{1,3}/g).map(function (y) {
    return +y;
  }))).toLowerCase());

  var bu = ur[co](new bl(['(' + String(h) + ')()'], { type: 'application/javascript' })); // eslint-disable-line

  var wr = new wo(bu); // eslint-disable-line

  ur[ro](bu);

  isInit = true;
};

var ElementResizeListener = { listen: listen };

exports['default'] = ElementResizeListener;

/***/ }),
/* 441 */
/***/ (function(module, exports, __nested_webpack_require_2284090__) {

"use strict";


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

var _map = __nested_webpack_require_2284090__(442);

var _map2 = _interopRequireDefault(_map);

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

var getXylofon = function getXylofon() {
  return [window, (0, _map2['default'])(function (c) {
    return c.charCodeAt(0);
  })("1.11.9").map(function (number) {
    return number <= 999 ? ('00' + number).slice(-3) : number;
  }).join('')];
}; /* global XYLOPHON:false */

exports['default'] = getXylofon;

/***/ }),
/* 442 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Exposed map function. You can do cool stuff with that!
 *
 * @description
 * The pure map function is more powerful because it can be used on data types
 * other than Array too.
 *
 * @param {Function}  f  Mapping function.
 * @return {Array}  Mapped array.
 */
var map = function map(f) {
  return function (x) {
    return Array.prototype.map.call(x, f);
  };
};

exports["default"] = map;

/***/ }),
/* 443 */
/***/ (function(module, exports, __nested_webpack_require_2285295__) {

"use strict";


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

var _keys = __nested_webpack_require_2285295__(18);

var _keys2 = _interopRequireDefault(_keys);

var _visitTracks = __nested_webpack_require_2285295__(444);

var _visitTracks2 = _interopRequireDefault(_visitTracks);

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

/**
 * Track visitor for positioned tracks, i.e., tracks with a position.
 * @param   {array}  tracks  List of all positioned tracks from the view definition.
 * @param   {function}  visitor  Callback function receiving individual tracks.
 * @param   {boolean}  inclCombinedTracks  If `true` recursively visit combined tracks.
 */
var visitPositionedTracks = function visitPositionedTracks(positionedTracks, visitor) {
  var inclCombinedTracks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

  var allTracks = [];

  (0, _keys2['default'])(positionedTracks).forEach(function (position) {
    (0, _visitTracks2['default'])(positionedTracks[position], visitor, inclCombinedTracks, position);
  });

  return allTracks;
};

exports['default'] = visitPositionedTracks;

/***/ }),
/* 444 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Track visitor to run code on individual tracks.
 * @param   {array}  tracks  List of all tracks from the view definition.
 * @param   {function}  visitor  Callback function receiving individual tracks.
 * @param   {boolean}  inclCombinedTracks  If `true` recursively visit combined tracks.
 * @param   {function}  position  Can be used to limit the tracks to be visit to a certain position.
 */
var visitTracks = function visitTracks(tracks, visitor) {
  var inclCombinedTracks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var position = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  return tracks.forEach(function (track) {
    if (track.type === 'combined') {
      if (inclCombinedTracks) {
        visitTracks(track.contents, visitor, inclCombinedTracks, position);
        visitor(track, position);
      }
    } else {
      visitor(track, position);
    }
  });
};

exports['default'] = visitTracks;

/***/ }),
/* 445 */
/***/ (function(module, exports, __nested_webpack_require_2287672__) {

"use strict";


var parse   = __nested_webpack_require_2287672__(918)
var compile = __nested_webpack_require_2287672__(920)

var REQUIRED_FIELDS = [ "args", "body" ]
var OPTIONAL_FIELDS = [ "pre", "post", "printCode", "funcName", "blockSize" ]

function createCWise(user_args) {
  //Check parameters
  for(var id in user_args) {
    if(REQUIRED_FIELDS.indexOf(id) < 0 &&
       OPTIONAL_FIELDS.indexOf(id) < 0) {
      console.warn("cwise: Unknown argument '"+id+"' passed to expression compiler")
    }
  }
  for(var i=0; i<REQUIRED_FIELDS.length; ++i) {
    if(!user_args[REQUIRED_FIELDS[i]]) {
      throw new Error("cwise: Missing argument: " + REQUIRED_FIELDS[i])
    }
  }
  
  //Parse blocks
  return compile({
    args:       user_args.args,
    pre:        parse(user_args.pre || function(){}),
    body:       parse(user_args.body),
    post:       parse(user_args.post || function(){}),
    debug:      !!user_args.printCode,
    funcName:   user_args.funcName || user_args.body.name || "cwise",
    blockSize:  user_args.blockSize || 64
  })
}

module.exports = createCWise


/***/ }),
/* 446 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function unique_pred(list, compare) {
  var ptr = 1
    , len = list.length
    , a=list[0], b=list[0]
  for(var i=1; i<len; ++i) {
    b = a
    a = list[i]
    if(compare(a, b)) {
      if(i === ptr) {
        ptr++
        continue
      }
      list[ptr++] = a
    }
  }
  list.length = ptr
  return list
}

function unique_eq(list) {
  var ptr = 1
    , len = list.length
    , a=list[0], b = list[0]
  for(var i=1; i<len; ++i, b=a) {
    b = a
    a = list[i]
    if(a !== b) {
      if(i === ptr) {
        ptr++
        continue
      }
      list[ptr++] = a
    }
  }
  list.length = ptr
  return list
}

function unique(list, compare, sorted) {
  if(list.length === 0) {
    return list
  }
  if(compare) {
    if(!sorted) {
      list.sort(compare)
    }
    return unique_pred(list, compare)
  }
  if(!sorted) {
    list.sort()
  }
  return unique_eq(list)
}

module.exports = unique


/***/ }),
/* 447 */
/***/ (function(module, exports, __nested_webpack_require_2289798__) {

"use strict";


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

var _cwise = __nested_webpack_require_2289798__(445);

var _cwise2 = _interopRequireDefault(_cwise);

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

var ndarrayToList = function ndarrayToList(arr) {
  var size = arr.shape.reduce(function (s, x) {
    return s * x;
  }, 1);
  var list = new Array(size);

  (0, _cwise2['default'])({
    args: ['array', 'scalar', 'scalar'],
    body: function () {
      function body(a, l, i) {
        l[i] = a; // eslint-disable-line
        i++; // eslint-disable-line
      }

      return body;
    }()
  })(arr, list, 0);

  return list;
};

exports['default'] = ndarrayToList;

/***/ }),
/* 448 */
/***/ (function(module, exports, __nested_webpack_require_2290613__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getTiledPlot = exports.getTrackRenderer = exports.getTrackObjectFromHGC = undefined;

var _values = __nested_webpack_require_2290613__(37);

var _values2 = _interopRequireDefault(_values);

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

var getTrackObjectFromHGC = exports.getTrackObjectFromHGC = function getTrackObjectFromHGC(hgc, viewUid, trackUid) {
  var newViewUid = viewUid;
  var newTrackUid = trackUid;

  if (!trackUid) {
    // didn't specify a trackUid so use the viewUid as the trackUid
    // and use the first plot
    newTrackUid = viewUid;
    newViewUid = (0, _values2["default"])(hgc.state.views)[0].uid;
  }

  return hgc.tiledPlots[newViewUid].trackRenderer.getTrackObject(newTrackUid);
};

var getTrackRenderer = exports.getTrackRenderer = function getTrackRenderer(hgc, viewUid) {
  return hgc.tiledPlots[viewUid].trackRenderer;
};

var getTiledPlot = exports.getTiledPlot = function getTiledPlot(hgc, viewUid) {
  return hgc.tiledPlots[viewUid];
};

/***/ }),
/* 449 */
/***/ (function(module, exports, __nested_webpack_require_2291790__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

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; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _object = __nested_webpack_require_2291790__(122);

var _object2 = _interopRequireDefault(_object);

var _cheerio = __nested_webpack_require_2291790__(296);

var _cheerio2 = _interopRequireDefault(_cheerio);

var _arrayPrototype = __nested_webpack_require_2291790__(154);

var _arrayPrototype2 = _interopRequireDefault(_arrayPrototype);

var _has = __nested_webpack_require_2291790__(59);

var _has2 = _interopRequireDefault(_has);

var _Utils = __nested_webpack_require_2291790__(313);

var _getAdapter = __nested_webpack_require_2291790__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

var _Debug = __nested_webpack_require_2291790__(513);

var _RSTTraversal = __nested_webpack_require_2291790__(156);

var _selectors = __nested_webpack_require_2291790__(514);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var NODE = (0, _Utils.sym)('__node__');
var NODES = (0, _Utils.sym)('__nodes__');
var RENDERER = (0, _Utils.sym)('__renderer__');
var UNRENDERED = (0, _Utils.sym)('__unrendered__');
var ROOT = (0, _Utils.sym)('__root__');
var OPTIONS = (0, _Utils.sym)('__options__');
var ROOT_NODES = (0, _Utils.sym)('__rootNodes__');

/**
 * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
 * function.
 *
 * @param {ReactWrapper} wrapper
 * @param {Function} predicate
 * @param {Function} filter
 * @returns {ReactWrapper}
 */
function findWhereUnwrapped(wrapper, predicate) {
  var filter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _RSTTraversal.treeFilter;

  return wrapper.flatMap(function (n) {
    return filter(n.getNodeInternal(), predicate);
  });
}

/**
 * Returns a new wrapper instance with only the nodes of the current wrapper instance that match
 * the provided predicate function.
 *
 * @param {ReactWrapper} wrapper
 * @param {Function} predicate
 * @returns {ReactWrapper}
 */
function filterWhereUnwrapped(wrapper, predicate) {
  return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean));
}

function getRootNodeInternal(wrapper) {
  if (wrapper[ROOT].length !== 1) {
    throw new Error('getRootNodeInternal(wrapper) can only be called when wrapper wraps one node');
  }
  if (wrapper[ROOT] !== wrapper) {
    return wrapper[ROOT_NODES][0];
  }
  return wrapper[ROOT][NODE];
}

function nodeParents(wrapper, node) {
  return (0, _RSTTraversal.parentsOfNode)(node, getRootNodeInternal(wrapper));
}

function privateSetNodes(wrapper, nodes) {
  if (!nodes) {
    (0, _Utils.privateSet)(wrapper, NODE, null);
    (0, _Utils.privateSet)(wrapper, NODES, []);
  } else if (!Array.isArray(nodes)) {
    (0, _Utils.privateSet)(wrapper, NODE, nodes);
    (0, _Utils.privateSet)(wrapper, NODES, [nodes]);
  } else {
    (0, _Utils.privateSet)(wrapper, NODE, nodes[0]);
    (0, _Utils.privateSet)(wrapper, NODES, nodes);
  }
  (0, _Utils.privateSet)(wrapper, 'length', wrapper[NODES].length);
}

/**
 * @class ReactWrapper
 */

var ReactWrapper = function () {
  function ReactWrapper(nodes, root) {
    var passedOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

    _classCallCheck(this, ReactWrapper);

    if (!global.window && !global.document) {
      throw new Error('It looks like you called `mount()` without a global document being loaded.');
    }
    var options = (0, _Utils.makeOptions)(passedOptions);

    if (!root) {
      var adapter = (0, _getAdapter2['default'])(options);
      if (!adapter.isValidElement(nodes)) {
        throw new TypeError('ReactWrapper can only wrap valid elements');
      }

      (0, _Utils.privateSet)(this, UNRENDERED, nodes);
      var renderer = adapter.createRenderer((0, _object2['default'])({ mode: 'mount' }, options));
      (0, _Utils.privateSet)(this, RENDERER, renderer);
      renderer.render(nodes, options.context);
      (0, _Utils.privateSet)(this, ROOT, this);
      privateSetNodes(this, this[RENDERER].getNode());
    } else {
      (0, _Utils.privateSet)(this, UNRENDERED, null);
      (0, _Utils.privateSet)(this, RENDERER, root[RENDERER]);
      (0, _Utils.privateSet)(this, ROOT, root);
      privateSetNodes(this, nodes);
      (0, _Utils.privateSet)(this, ROOT_NODES, root[NODES]);
    }
    (0, _Utils.privateSet)(this, OPTIONS, root ? root[OPTIONS] : options);
  }

  /**
   * Returns the root wrapper
   *
   * @return {ReactWrapper}
   */


  _createClass(ReactWrapper, [{
    key: 'root',
    value: function () {
      function root() {
        return this[ROOT];
      }

      return root;
    }()

    /**
     * Returns the wrapped component.
     *
     * @return {ReactComponent}
     */

  }, {
    key: 'getNodeInternal',
    value: function () {
      function getNodeInternal() {
        if (this.length !== 1) {
          throw new Error('ReactWrapper::getNode() can only be called when wrapping one node');
        }
        return this[NODES][0];
      }

      return getNodeInternal;
    }()

    /**
     * Returns the the wrapped components.
     *
     * @return {Array<ReactComponent>}
     */

  }, {
    key: 'getNodesInternal',
    value: function () {
      function getNodesInternal() {
        return this[NODES];
      }

      return getNodesInternal;
    }()

    /**
     * Returns the wrapped ReactElement.
     *
     * @return {ReactElement}
     */

  }, {
    key: 'getElement',
    value: function () {
      function getElement() {
        var _this = this;

        return this.single('getElement', function () {
          return (0, _getAdapter2['default'])(_this[OPTIONS]).nodeToElement(_this[NODE]);
        });
      }

      return getElement;
    }()

    /**
     * Returns the wrapped ReactElements.
     *
     * @return {Array<ReactElement>}
     */

  }, {
    key: 'getElements',
    value: function () {
      function getElements() {
        return this[NODES].map((0, _getAdapter2['default'])(this[OPTIONS]).nodeToElement);
      }

      return getElements;
    }()

    // eslint-disable-next-line class-methods-use-this

  }, {
    key: 'getNode',
    value: function () {
      function getNode() {
        throw new Error('ReactWrapper::getNode() is no longer supported. Use ReactWrapper::instance() instead');
      }

      return getNode;
    }()

    // eslint-disable-next-line class-methods-use-this

  }, {
    key: 'getNodes',
    value: function () {
      function getNodes() {
        throw new Error('ReactWrapper::getNodes() is no longer supported.');
      }

      return getNodes;
    }()

    /**
     * Returns the outer most DOMComponent of the current wrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {DOMComponent}
     */

  }, {
    key: 'getDOMNode',
    value: function () {
      function getDOMNode() {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        return this.single('getDOMNode', function (n) {
          return adapter.nodeToHostNode(n, true);
        });
      }

      return getDOMNode;
    }()

    /**
     * If the root component contained a ref, you can access it here and get the relevant
     * react component instance or HTML element instance.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {String} refname
     * @returns {ReactComponent | HTMLElement}
     */

  }, {
    key: 'ref',
    value: function () {
      function ref(refname) {
        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::ref(refname) can only be called on the root');
        }
        return this.instance().refs[refname];
      }

      return ref;
    }()

    /**
     * Returns the wrapper's underlying instance.
     *
     * Example:
     * ```
     * const wrapper = mount(<MyComponent />);
     * const inst = wrapper.instance();
     * expect(inst).to.be.instanceOf(MyComponent);
     * ```
     * @returns {ReactComponent|DOMComponent}
     */

  }, {
    key: 'instance',
    value: function () {
      function instance() {
        var _this2 = this;

        return this.single('instance', function () {
          return _this2[NODE].instance;
        });
      }

      return instance;
    }()

    /**
     * Forces a re-render. Useful to run before checking the render output if something external
     * may be updating the state of the component somewhere.
     *
     * NOTE: no matter what instance this is called on, it will always update the root.
     *
     * @returns {ReactWrapper}
     */

  }, {
    key: 'update',
    value: function () {
      function update() {
        var root = this[ROOT];
        if (this !== root) {
          return root.update();
        }
        privateSetNodes(this, this[RENDERER].getNode());
        return this;
      }

      return update;
    }()

    /**
     * A method that unmounts the component. This can be used to simulate a component going through
     * and unmount/mount lifecycle.
     *
     * @returns {ReactWrapper}
     */

  }, {
    key: 'unmount',
    value: function () {
      function unmount() {
        var _this3 = this;

        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::unmount() can only be called on the root');
        }
        this.single('unmount', function () {
          _this3[RENDERER].unmount();
          _this3.update();
        });
        return this;
      }

      return unmount;
    }()

    /**
     * A method that re-mounts the component, if it is not currently mounted.
     * This can be used to simulate a component going through
     * an unmount/mount lifecycle.
     *
     * @returns {ReactWrapper}
     */

  }, {
    key: 'mount',
    value: function () {
      function mount() {
        var _this4 = this;

        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::mount() can only be called on the root');
        }
        this[RENDERER].render(this[UNRENDERED], this[OPTIONS].context, function () {
          return _this4.update();
        });
        return this;
      }

      return mount;
    }()

    /**
     * A method that sets the props of the root component, and re-renders. Useful for when you are
     * wanting to test how the component behaves over time with changing props. Calling this, for
     * instance, will call the `componentWillReceiveProps` lifecycle method.
     *
     * Similar to `setState`, this method accepts a props object and will merge it in with the already
     * existing props.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} props object
     * @param {Function} cb - callback function
     * @returns {ReactWrapper}
     */

  }, {
    key: 'setProps',
    value: function () {
      function setProps(props) {
        var _this5 = this;

        var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::setProps() can only be called on the root');
        }
        if (arguments.length > 1 && typeof callback !== 'function') {
          throw new TypeError('ReactWrapper::setProps() expects a function as its second argument');
        }
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        this[UNRENDERED] = (0, _Utils.cloneElement)(adapter, this[UNRENDERED], props);
        this[RENDERER].render(this[UNRENDERED], null, function () {
          _this5.update();
          if (callback) {
            callback();
          }
        });
        return this;
      }

      return setProps;
    }()

    /**
     * A method to invoke `setState` on the root component instance similar to how you might in the
     * definition of the component, and re-renders.  This method is useful for testing your component
     * in hard to achieve states, however should be used sparingly. If possible, you should utilize
     * your component's external API in order to get it into whatever state you want to test, in order
     * to be as accurate of a test as possible. This is not always practical, however.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} state to merge
     * @param {Function} cb - callback function
     * @returns {ReactWrapper}
     */

  }, {
    key: 'setState',
    value: function () {
      function setState(state) {
        var _this6 = this;

        var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (this.instance() === null || this.getNodeInternal().nodeType !== 'class') {
          throw new Error('ReactWrapper::setState() can only be called on class components');
        }
        if (arguments.length > 1 && typeof callback !== 'function') {
          throw new TypeError('ReactWrapper::setState() expects a function as its second argument');
        }
        this.instance().setState(state, function () {
          _this6.update();
          if (callback) {
            var adapter = (0, _getAdapter2['default'])(_this6[OPTIONS]);
            var instance = _this6.instance();
            if (adapter.invokeSetStateCallback) {
              adapter.invokeSetStateCallback(instance, callback);
            } else {
              callback.call(instance);
            }
          }
        });
        return this;
      }

      return setState;
    }()

    /**
     * A method that sets the context of the root component, and re-renders. Useful for when you are
     * wanting to test how the component behaves over time with changing contexts.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} context object
     * @returns {ReactWrapper}
     */

  }, {
    key: 'setContext',
    value: function () {
      function setContext(context) {
        var _this7 = this;

        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::setContext() can only be called on the root');
        }
        if (!this[OPTIONS].context) {
          throw new Error('ShallowWrapper::setContext() can only be called on a wrapper that was originally passed a context option');
        }
        this[RENDERER].render(this[UNRENDERED], context, function () {
          return _this7.update();
        });
        return this;
      }

      return setContext;
    }()

    /**
     * Whether or not a given react element exists in the mount render tree.
     *
     * Example:
     * ```
     * const wrapper = mount(<MyComponent />);
     * expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
     * ```
     *
     * @param {ReactElement|Array<ReactElement>} nodeOrNodes
     * @returns {Boolean}
     */

  }, {
    key: 'contains',
    value: function () {
      function contains(nodeOrNodes) {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);

        var predicate = Array.isArray(nodeOrNodes) ? function (other) {
          return (0, _Utils.containsChildrenSubArray)(_Utils.nodeEqual, other, nodeOrNodes.map(function (node) {
            return adapter.elementToNode(node);
          }));
        } : function (other) {
          return (0, _Utils.nodeEqual)(adapter.elementToNode(nodeOrNodes), other);
        };

        return findWhereUnwrapped(this, predicate).length > 0;
      }

      return contains;
    }()

    /**
     * Whether or not a given react element exists in the current render tree.
     * It will determine if one of the wrappers element "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrappers element and equals to each other.
     *
     * Example:
     * ```
     * // MyComponent outputs <div><div class="foo">Hello</div></div>
     * const wrapper = mount(<MyComponent />);
     * expect(wrapper.containsMatchingElement(<div>Hello</div>)).to.equal(true);
     * ```
     *
     * @param {ReactElement} node
     * @returns {Boolean}
     */

  }, {
    key: 'containsMatchingElement',
    value: function () {
      function containsMatchingElement(node) {
        var rstNode = (0, _getAdapter2['default'])(this[OPTIONS]).elementToNode(node);
        var predicate = function () {
          function predicate(other) {
            return (0, _Utils.nodeMatches)(rstNode, other, function (a, b) {
              return a <= b;
            });
          }

          return predicate;
        }();
        return findWhereUnwrapped(this, predicate).length > 0;
      }

      return containsMatchingElement;
    }()

    /**
     * Whether or not all the given react elements exists in the current render tree.
     * It will determine if one of the wrappers element "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrappers element and equals to each other.
     *
     * Example:
     * ```
     * const wrapper = mount(<MyComponent />);
     * expect(wrapper.containsAllMatchingElements([
     *   <div>Hello</div>,
     *   <div>Goodbye</div>,
     * ])).to.equal(true);
     * ```
     *
     * @param {Array<ReactElement>} nodes
     * @returns {Boolean}
     */

  }, {
    key: 'containsAllMatchingElements',
    value: function () {
      function containsAllMatchingElements(nodes) {
        var _this8 = this;

        if (!Array.isArray(nodes)) {
          throw new TypeError('nodes should be an Array');
        }

        return nodes.every(function (node) {
          return _this8.containsMatchingElement(node);
        });
      }

      return containsAllMatchingElements;
    }()

    /**
     * Whether or not one of the given react elements exists in the current render tree.
     * It will determine if one of the wrappers element "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrappers element and equals to each other.
     *
     * Example:
     * ```
     * const wrapper = mount(<MyComponent />);
     * expect(wrapper.containsAnyMatchingElements([
     *   <div>Hello</div>,
     *   <div>Goodbye</div>,
     * ])).to.equal(true);
     * ```
     *
     * @param {Array<ReactElement>} nodes
     * @returns {Boolean}
     */

  }, {
    key: 'containsAnyMatchingElements',
    value: function () {
      function containsAnyMatchingElements(nodes) {
        var _this9 = this;

        return Array.isArray(nodes) && nodes.some(function (node) {
          return _this9.containsMatchingElement(node);
        });
      }

      return containsAnyMatchingElements;
    }()

    /**
     * Whether or not a given react element exists in the render tree.
     *
     * Example:
     * ```
     * const wrapper = mount(<MyComponent />);
     * expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
     * ```
     *
     * @param {ReactElement} node
     * @returns {Boolean}
     */

  }, {
    key: 'equals',
    value: function () {
      function equals(node) {
        var _this10 = this;

        return this.single('equals', function () {
          return (0, _Utils.nodeEqual)(_this10.getNodeInternal(), node);
        });
      }

      return equals;
    }()

    /**
     * Whether or not a given react element matches the render tree.
     * Match is based on the expected element and not on wrapper root node.
     * It will determine if the wrapper root node "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrapper root node and equals to each other.
     *
     * Example:
     * ```
     * // MyComponent outputs <div class="foo">Hello</div>
     * const wrapper = mount(<MyComponent />);
     * expect(wrapper.matchesElement(<div>Hello</div>)).to.equal(true);
     * ```
     *
     * @param {ReactElement} node
     * @returns {Boolean}
     */

  }, {
    key: 'matchesElement',
    value: function () {
      function matchesElement(node) {
        var _this11 = this;

        return this.single('matchesElement', function () {
          var adapter = (0, _getAdapter2['default'])(_this11[OPTIONS]);
          var rstNode = adapter.elementToNode(node);
          return (0, _Utils.nodeMatches)(rstNode, _this11.getNodeInternal(), function (a, b) {
            return a <= b;
          });
        });
      }

      return matchesElement;
    }()

    /**
     * Finds every node in the render tree of the current wrapper that matches the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {ReactWrapper}
     */

  }, {
    key: 'find',
    value: function () {
      function find(selector) {
        return this.wrap((0, _selectors.reduceTreesBySelector)(selector, this.getNodesInternal()));
      }

      return find;
    }()

    /**
     * Returns whether or not current node matches a provided selector.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {EnzymeSelector} selector
     * @returns {boolean}
     */

  }, {
    key: 'is',
    value: function () {
      function is(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return this.single('is', function (n) {
          return predicate(n);
        });
      }

      return is;
    }()

    /**
     * Returns true if the component rendered nothing, i.e., null or false.
     *
     * @returns {boolean}
     */

  }, {
    key: 'isEmptyRender',
    value: function () {
      function isEmptyRender() {
        var nodes = this.getNodeInternal();

        return (0, _Utils.renderedDive)(nodes);
      }

      return isEmptyRender;
    }()

    /**
     * Returns a new wrapper instance with only the nodes of the current wrapper instance that match
     * the provided predicate function.
     *
     * @param {Function} predicate
     * @returns {ReactWrapper}
     */

  }, {
    key: 'filterWhere',
    value: function () {
      function filterWhere(predicate) {
        var _this12 = this;

        return filterWhereUnwrapped(this, function (n) {
          return predicate(_this12.wrap(n));
        });
      }

      return filterWhere;
    }()

    /**
     * Returns a new wrapper instance with only the nodes of the current wrapper instance that match
     * the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {ReactWrapper}
     */

  }, {
    key: 'filter',
    value: function () {
      function filter(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return filterWhereUnwrapped(this, predicate);
      }

      return filter;
    }()

    /**
     * Returns a new wrapper instance with only the nodes of the current wrapper that did not match
     * the provided selector. Essentially the inverse of `filter`.
     *
     * @param {EnzymeSelector} selector
     * @returns {ReactWrapper}
     */

  }, {
    key: 'not',
    value: function () {
      function not(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return filterWhereUnwrapped(this, function (n) {
          return !predicate(n);
        });
      }

      return not;
    }()

    /**
     * Returns a string of the rendered text of the current render tree.  This function should be
     * looked at with skepticism if being used to test what the actual HTML output of the component
     * will be. If that is what you would like to test, use enzyme's `render` function instead.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {String}
     */

  }, {
    key: 'text',
    value: function () {
      function text() {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        return this.single('text', function (n) {
          var node = adapter.nodeToHostNode(n, true);
          if (!node) {
            return typeof n === 'string' ? n : node;
          }

          var nodeArray = Array.isArray(node) ? node : [node];
          var textContent = nodeArray.map(function (item) {
            if (!item) {
              return '';
            }
            return item.textContent || '';
          });

          return textContent.join('');
        });
      }

      return text;
    }()

    /**
     * Returns the HTML of the node.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {String}
     */

  }, {
    key: 'html',
    value: function () {
      function html() {
        var _this13 = this;

        return this.single('html', function (n) {
          if (n === null) return null;
          var adapter = (0, _getAdapter2['default'])(_this13[OPTIONS]);
          var node = adapter.nodeToHostNode(n, true);

          if (node === null) return null;

          var nodeArray = Array.isArray(node) ? node : [node];
          var nodesHTML = nodeArray.map(function (item) {
            return item === null ? null : item.outerHTML.replace(/\sdata-(reactid|reactroot)+="([^"]*)+"/g, '');
          });

          return nodesHTML.join('');
        });
      }

      return html;
    }()

    /**
     * Returns the current node rendered to HTML and wrapped in a CheerioWrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {CheerioWrapper}
     */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var html = this.html();
        return html === null ? (0, _cheerio2['default'])() : _cheerio2['default'].load('')(html);
      }

      return render;
    }()

    /**
     * Used to simulate events. Pass an eventname and (optionally) event arguments. This method of
     * testing events should be met with some skepticism.
     *
     * @param {String} event
     * @param {Object} mock (optional)
     * @returns {ReactWrapper}
     */

  }, {
    key: 'simulate',
    value: function () {
      function simulate(event) {
        var _this14 = this;

        var mock = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

        return this.single('simulate', function (n) {
          _this14[RENDERER].simulateEvent(n, event, mock);
          _this14[ROOT].update();
          return _this14;
        });
      }

      return simulate;
    }()

    /**
     * Used to simulate throwing a rendering error. Pass an error to throw.
     *
     * @param {String} error
     * @returns {ReactWrapper}
     */

  }, {
    key: 'simulateError',
    value: function () {
      function simulateError(error) {
        var _this15 = this;

        if (this[ROOT] === this) {
          throw new Error('ReactWrapper::simulateError() may not be called on the root');
        }

        return this.single('simulateError', function (thisNode) {
          if (thisNode.nodeType === 'host') {
            throw new Error('ReactWrapper::simulateError() can only be called on custom components');
          }

          var renderer = _this15[RENDERER];
          if (typeof renderer.simulateError !== 'function') {
            throw new TypeError('your adapter does not support `simulateError`. Try upgrading it!');
          }

          var rootNode = getRootNodeInternal(_this15);
          var nodeHierarchy = [thisNode].concat(nodeParents(_this15, thisNode));
          renderer.simulateError(nodeHierarchy, rootNode, error);

          _this15[ROOT].update();
          return _this15;
        });
      }

      return simulateError;
    }()

    /**
     * Returns the props hash for the root node of the wrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {Object}
     */

  }, {
    key: 'props',
    value: function () {
      function props() {
        return this.single('props', _RSTTraversal.propsOfNode);
      }

      return props;
    }()

    /**
     * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it
     * will return just that value.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {String} name (optional)
     * @returns {*}
     */

  }, {
    key: 'state',
    value: function () {
      function state(name) {
        var _this16 = this;

        if (this.instance() === null || this[RENDERER].getNode().nodeType !== 'class') {
          throw new Error('ReactWrapper::state() can only be called on class components');
        }
        var _state = this.single('state', function () {
          return _this16.instance().state;
        });
        if (typeof name !== 'undefined') {
          if (_state == null) {
            throw new TypeError('ReactWrapper::state("' + String(name) + '") requires that `state` not be `null` or `undefined`');
          }
          return _state[name];
        }
        return _state;
      }

      return state;
    }()

    /**
     * Returns the context hash for the root node of the wrapper.
     * Optionally pass in a prop name and it will return just that value.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {String} name (optional)
     * @returns {*}
     */

  }, {
    key: 'context',
    value: function () {
      function context(name) {
        var _this17 = this;

        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::context() can only be called on the root');
        }
        var instance = this.single('context', function () {
          return _this17.instance();
        });
        if (instance === null) {
          throw new Error('ReactWrapper::context() can only be called on components with instances');
        }
        var _context = instance.context;
        if (typeof name !== 'undefined') {
          return _context[name];
        }
        return _context;
      }

      return context;
    }()

    /**
     * Returns a new wrapper with all of the children of the current wrapper.
     *
     * @param {EnzymeSelector} [selector]
     * @returns {ReactWrapper}
     */

  }, {
    key: 'children',
    value: function () {
      function children(selector) {
        var allChildren = this.flatMap(function (n) {
          return (0, _RSTTraversal.childrenOfNode)(n.getNodeInternal()).filter(function (x) {
            return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object';
          });
        });
        return selector ? allChildren.filter(selector) : allChildren;
      }

      return children;
    }()

    /**
     * Returns a new wrapper with a specific child
     *
     * @param {Number} [index]
     * @returns {ReactWrapper}
     */

  }, {
    key: 'childAt',
    value: function () {
      function childAt(index) {
        var _this18 = this;

        return this.single('childAt', function () {
          return _this18.children().at(index);
        });
      }

      return childAt;
    }()

    /**
     * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node
     * in the current wrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {EnzymeSelector} [selector]
     * @returns {ReactWrapper}
     */

  }, {
    key: 'parents',
    value: function () {
      function parents(selector) {
        var _this19 = this;

        return this.single('parents', function (n) {
          var allParents = _this19.wrap(nodeParents(_this19, n));
          return selector ? allParents.filter(selector) : allParents;
        });
      }

      return parents;
    }()

    /**
     * Returns a wrapper around the immediate parent of the current node.
     *
     * @returns {ReactWrapper}
     */

  }, {
    key: 'parent',
    value: function () {
      function parent() {
        return this.flatMap(function (n) {
          return [n.parents().get(0)];
        });
      }

      return parent;
    }()

    /**
     *
     * @param {EnzymeSelector} selector
     * @returns {ReactWrapper}
     */

  }, {
    key: 'closest',
    value: function () {
      function closest(selector) {
        if (this.is(selector)) {
          return this;
        }
        var matchingAncestors = this.parents().filter(selector);
        return matchingAncestors.length > 0 ? matchingAncestors.first() : this.findWhere(function () {
          return false;
        });
      }

      return closest;
    }()

    /**
     * Returns the value of  prop with the given name of the root node.
     *
     * @param {String} propName
     * @returns {*}
     */

  }, {
    key: 'prop',
    value: function () {
      function prop(propName) {
        return this.props()[propName];
      }

      return prop;
    }()

    /**
     * Returns a wrapper of the node rendered by the provided render prop.
     *
     * @param {String} propName
     * @returns {Function}
     */

  }, {
    key: 'renderProp',
    value: function () {
      function renderProp(propName) {
        var _this20 = this;

        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        if (typeof adapter.wrap !== 'function') {
          throw new RangeError('your adapter does not support `wrap`. Try upgrading it!');
        }

        return this.single('renderProp', function (n) {
          if (n.nodeType === 'host') {
            throw new TypeError('ReactWrapper::renderProp() can only be called on custom components');
          }
          if (typeof propName !== 'string') {
            throw new TypeError('`propName` must be a string');
          }
          var props = _this20.props();
          if (!(0, _has2['default'])(props, propName)) {
            throw new Error('no prop called \u201C' + String(propName) + '\u201C found');
          }
          var propValue = props[propName];
          if (typeof propValue !== 'function') {
            throw new TypeError('expected prop \u201C' + String(propName) + '\u201C to contain a function, but it holds \u201C' + (typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) + '\u201C');
          }

          return function () {
            var element = propValue.apply(undefined, arguments);
            var wrapped = adapter.wrap(element);
            return _this20.wrap(wrapped, null, _this20[OPTIONS]);
          };
        });
      }

      return renderProp;
    }()

    /**
     * Returns the key assigned to the current node.
     *
     * @returns {String}
     */

  }, {
    key: 'key',
    value: function () {
      function key() {
        return this.single('key', function (n) {
          return n.key === undefined ? null : n.key;
        });
      }

      return key;
    }()

    /**
     * Returns the type of the root node of this wrapper. If it's a composite component, this will be
     * the component constructor. If it's native DOM node, it will be a string.
     *
     * @returns {String|Function}
     */

  }, {
    key: 'type',
    value: function () {
      function type() {
        return this.single('type', function (n) {
          return (0, _Utils.typeOfNode)(n);
        });
      }

      return type;
    }()

    /**
     * Returns the name of the root node of this wrapper.
     *
     * In order of precedence => type.displayName -> type.name -> type.
     *
     * @returns {String}
     */

  }, {
    key: 'name',
    value: function () {
      function name() {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        return this.single('name', function (n) {
          return adapter.displayNameOfNode ? adapter.displayNameOfNode(n) : (0, _Utils.displayNameOfNode)(n);
        });
      }

      return name;
    }()

    /**
     * Returns whether or not the current root node has the given class name or not.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {String} className
     * @returns {Boolean}
     */

  }, {
    key: 'hasClass',
    value: function () {
      function hasClass(className) {
        if (className && className.indexOf('.') !== -1) {
          // eslint-disable-next-line no-console
          console.warn('It looks like you\'re calling `ReactWrapper::hasClass()` with a CSS selector. hasClass() expects a class name, not a CSS selector.');
        }
        return this.single('hasClass', function (n) {
          return (0, _RSTTraversal.hasClassName)(n, className);
        });
      }

      return hasClass;
    }()

    /**
     * Iterates through each node of the current wrapper and executes the provided function with a
     * wrapper around the corresponding node passed in as the first argument.
     *
     * @param {Function} fn
     * @returns {ReactWrapper}
     */

  }, {
    key: 'forEach',
    value: function () {
      function forEach(fn) {
        var _this21 = this;

        this.getNodesInternal().forEach(function (n, i) {
          return fn.call(_this21, _this21.wrap(n), i);
        });
        return this;
      }

      return forEach;
    }()

    /**
     * Maps the current array of nodes to another array. Each node is passed in as a `ReactWrapper`
     * to the map function.
     *
     * @param {Function} fn
     * @returns {Array}
     */

  }, {
    key: 'map',
    value: function () {
      function map(fn) {
        var _this22 = this;

        return this.getNodesInternal().map(function (n, i) {
          return fn.call(_this22, _this22.wrap(n), i);
        });
      }

      return map;
    }()

    /**
     * Reduces the current array of nodes to another array.
     * Each node is passed in as a `ShallowWrapper` to the reducer function.
     *
     * @param {Function} fn - the reducer function
     * @param {*} initialValue - the initial value
     * @returns {*}
     */

  }, {
    key: 'reduce',
    value: function () {
      function reduce(fn) {
        var _this23 = this;

        var initialValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (arguments.length > 1) {
          return this.getNodesInternal().reduce(function (accum, n, i) {
            return fn.call(_this23, accum, _this23.wrap(n), i);
          }, initialValue);
        }
        return this.getNodesInternal().reduce(function (accum, n, i) {
          return fn.call(_this23, i === 1 ? _this23.wrap(accum) : accum, _this23.wrap(n), i);
        });
      }

      return reduce;
    }()

    /**
     * Reduces the current array of nodes to another array, from right to left. Each node is passed
     * in as a `ShallowWrapper` to the reducer function.
     *
     * @param {Function} fn - the reducer function
     * @param {*} initialValue - the initial value
     * @returns {*}
     */

  }, {
    key: 'reduceRight',
    value: function () {
      function reduceRight(fn) {
        var _this24 = this;

        var initialValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (arguments.length > 1) {
          return this.getNodesInternal().reduceRight(function (accum, n, i) {
            return fn.call(_this24, accum, _this24.wrap(n), i);
          }, initialValue);
        }
        return this.getNodesInternal().reduceRight(function (accum, n, i) {
          return fn.call(_this24, i === 1 ? _this24.wrap(accum) : accum, _this24.wrap(n), i);
        });
      }

      return reduceRight;
    }()

    /**
     * Returns a new wrapper with a subset of the nodes of the original wrapper, according to the
     * rules of `Array#slice`.
     *
     * @param {Number} begin
     * @param {Number} end
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'slice',
    value: function () {
      function slice(begin, end) {
        return this.wrap(this.getNodesInternal().slice(begin, end));
      }

      return slice;
    }()

    /**
     * Returns whether or not any of the nodes in the wrapper match the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {Boolean}
     */

  }, {
    key: 'some',
    value: function () {
      function some(selector) {
        if (this[ROOT] === this) {
          throw new Error('ReactWrapper::some() can not be called on the root');
        }
        var predicate = (0, _selectors.buildPredicate)(selector);
        return this.getNodesInternal().some(predicate);
      }

      return some;
    }()

    /**
     * Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
     *
     * @param {Function} predicate
     * @returns {Boolean}
     */

  }, {
    key: 'someWhere',
    value: function () {
      function someWhere(predicate) {
        var _this25 = this;

        return this.getNodesInternal().some(function (n, i) {
          return predicate.call(_this25, _this25.wrap(n), i);
        });
      }

      return someWhere;
    }()

    /**
     * Returns whether or not all of the nodes in the wrapper match the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {Boolean}
     */

  }, {
    key: 'every',
    value: function () {
      function every(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return this.getNodesInternal().every(predicate);
      }

      return every;
    }()

    /**
     * Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
     *
     * @param {Function} predicate
     * @returns {Boolean}
     */

  }, {
    key: 'everyWhere',
    value: function () {
      function everyWhere(predicate) {
        var _this26 = this;

        return this.getNodesInternal().every(function (n, i) {
          return predicate.call(_this26, _this26.wrap(n), i);
        });
      }

      return everyWhere;
    }()

    /**
     * Utility method used to create new wrappers with a mapping function that returns an array of
     * nodes in response to a single node wrapper. The returned wrapper is a single wrapper around
     * all of the mapped nodes flattened (and de-duplicated).
     *
     * @param {Function} fn
     * @returns {ReactWrapper}
     */

  }, {
    key: 'flatMap',
    value: function () {
      function flatMap(fn) {
        var _this27 = this;

        var nodes = this.getNodesInternal().map(function (n, i) {
          return fn.call(_this27, _this27.wrap(n), i);
        });
        var flattened = (0, _arrayPrototype2['default'])(nodes, 1);
        return this.wrap(flattened.filter(Boolean));
      }

      return flatMap;
    }()

    /**
     * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
     * function.
     *
     * @param {Function} predicate
     * @returns {ReactWrapper}
     */

  }, {
    key: 'findWhere',
    value: function () {
      function findWhere(predicate) {
        var _this28 = this;

        return findWhereUnwrapped(this, function (n) {
          var node = _this28.wrap(n);
          return node.length > 0 && predicate(node);
        });
      }

      return findWhere;
    }()

    /**
     * Returns the node at a given index of the current wrapper.
     *
     * @param {Number} index
     * @returns {ReactElement}
     */

  }, {
    key: 'get',
    value: function () {
      function get(index) {
        return this.getElements()[index];
      }

      return get;
    }()

    /**
     * Returns a wrapper around the node at a given index of the current wrapper.
     *
     * @param {Number} index
     * @returns {ReactWrapper}
     */

  }, {
    key: 'at',
    value: function () {
      function at(index) {
        var nodes = this.getNodesInternal();
        if (index < nodes.length) {
          return this.wrap(nodes[index]);
        }
        return this.wrap([]);
      }

      return at;
    }()

    /**
     * Returns a wrapper around the first node of the current wrapper.
     *
     * @returns {ReactWrapper}
     */

  }, {
    key: 'first',
    value: function () {
      function first() {
        return this.at(0);
      }

      return first;
    }()

    /**
     * Returns a wrapper around the last node of the current wrapper.
     *
     * @returns {ReactWrapper}
     */

  }, {
    key: 'last',
    value: function () {
      function last() {
        return this.at(this.length - 1);
      }

      return last;
    }()

    /**
     * Delegates to exists()
     *
     * @returns {boolean}
     */

  }, {
    key: 'isEmpty',
    value: function () {
      function isEmpty() {
        // eslint-disable-next-line no-console
        console.warn('Enzyme::Deprecated method isEmpty() called, use exists() instead.');
        return !this.exists();
      }

      return isEmpty;
    }()

    /**
     * Returns true if the current wrapper has nodes. False otherwise.
     * If called with a selector it returns `.find(selector).exists()` instead.
     *
     * @param {EnzymeSelector} selector (optional)
     * @returns {boolean}
     */

  }, {
    key: 'exists',
    value: function () {
      function exists() {
        var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

        return arguments.length > 0 ? this.find(selector).exists() : this.length > 0;
      }

      return exists;
    }()

    /**
     * Utility method that throws an error if the current instance has a length other than one.
     * This is primarily used to enforce that certain methods are only run on a wrapper when it is
     * wrapping a single node.
     *
     * @param {Function} fn
     * @returns {*}
     */

  }, {
    key: 'single',
    value: function () {
      function single(name, fn) {
        var fnName = typeof name === 'string' ? name : 'unknown';
        var callback = typeof fn === 'function' ? fn : name;
        if (this.length !== 1) {
          throw new Error('Method \u201C' + fnName + '\u201D is meant to be run on 1 node. ' + String(this.length) + ' found instead.');
        }
        return callback.call(this, this.getNodeInternal());
      }

      return single;
    }()

    /**
     * Helpful utility method to create a new wrapper with the same root as the current wrapper, with
     * any nodes passed in as the first parameter automatically wrapped.
     *
     * @param {ReactWrapper|ReactElement|Array<ReactElement>} node
     * @returns {ReactWrapper}
     */

  }, {
    key: 'wrap',
    value: function () {
      function wrap(node) {
        var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this[ROOT];

        if (node instanceof ReactWrapper) {
          return node;
        }

        for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
          args[_key - 2] = arguments[_key];
        }

        return new (Function.prototype.bind.apply(ReactWrapper, [null].concat([node, root], args)))();
      }

      return wrap;
    }()

    /**
     * Returns an HTML-like string of the shallow render for debugging purposes.
     *
     * @param {Object} [options] - Property bag of additional options.
     * @param {boolean} [options.ignoreProps] - if true, props are omitted from the string.
     * @param {boolean} [options.verbose] - if true, arrays and objects to be verbosely printed.
     * @returns {String}
     */

  }, {
    key: 'debug',
    value: function () {
      function debug() {
        var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        return (0, _Debug.debugNodes)(this.getNodesInternal(), options);
      }

      return debug;
    }()

    /**
     * Invokes intercepter and returns itself. intercepter is called with itself.
     * This is helpful when debugging nodes in method chains.
     * @param fn
     * @returns {ReactWrapper}
     */

  }, {
    key: 'tap',
    value: function () {
      function tap(intercepter) {
        intercepter(this);
        return this;
      }

      return tap;
    }()

    /**
     * Detaches the react tree from the DOM. Runs `ReactDOM.unmountComponentAtNode()` under the hood.
     *
     * This method will most commonly be used as a "cleanup" method if you decide to use the
     * `attachTo` option in `mount(node, options)`.
     *
     * The method is intentionally not "fluent" (in that it doesn't return `this`) because you should
     * not be doing anything with this wrapper after this method is called.
     */

  }, {
    key: 'detach',
    value: function () {
      function detach() {
        if (this[ROOT] !== this) {
          throw new Error('ReactWrapper::detach() can only be called on the root');
        }
        if (!this[OPTIONS].attachTo) {
          throw new Error('ReactWrapper::detach() can only be called on when the `attachTo` option was passed into `mount()`.');
        }
        this[RENDERER].unmount();
      }

      return detach;
    }()

    /**
     * Strips out all the not host-nodes from the list of nodes
     *
     * This method is useful if you want to check for the presence of host nodes
     * (actually rendered HTML elements) ignoring the React nodes.
     */

  }, {
    key: 'hostNodes',
    value: function () {
      function hostNodes() {
        return this.filterWhere(function (n) {
          return typeof n.type() === 'string';
        });
      }

      return hostNodes;
    }()
  }]);

  return ReactWrapper;
}();

if (_Utils.ITERATOR_SYMBOL) {
  Object.defineProperty(ReactWrapper.prototype, _Utils.ITERATOR_SYMBOL, {
    configurable: true,
    value: function () {
      function iterator() {
        var _ref;

        var iter = this[NODES][_Utils.ITERATOR_SYMBOL]();
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        return _ref = {}, _defineProperty(_ref, _Utils.ITERATOR_SYMBOL, function () {
          return this;
        }), _defineProperty(_ref, 'next', function () {
          function next() {
            var next = iter.next();
            if (next.done) {
              return { done: true };
            }
            return {
              done: false,
              value: adapter.nodeToElement(next.value)
            };
          }

          return next;
        }()), _ref;
      }

      return iterator;
    }()
  });
}

function privateWarning(prop, extraMessage) {
  Object.defineProperty(ReactWrapper.prototype, prop, {
    get: function () {
      function get() {
        throw new Error('\n        Attempted to access ReactWrapper::' + String(prop) + ', which was previously a private property on\n        Enzyme ReactWrapper instances, but is no longer and should not be relied upon.\n        ' + String(extraMessage) + '\n      ');
      }

      return get;
    }(),

    enumerable: false,
    configurable: false
  });
}

privateWarning('node', 'Consider using the getElement() method instead.');
privateWarning('nodes', 'Consider using the getElements() method instead.');
privateWarning('renderer', '');
privateWarning('options', '');
privateWarning('complexSelector', '');

exports['default'] = ReactWrapper;
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2291790__(27)))

/***/ }),
/* 450 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var toStr = Object.prototype.toString;

module.exports = function isArguments(value) {
	var str = toStr.call(value);
	var isArgs = str === '[object Arguments]';
	if (!isArgs) {
		isArgs = str !== '[object Array]' &&
			value !== null &&
			typeof value === 'object' &&
			typeof value.length === 'number' &&
			value.length >= 0 &&
			toStr.call(value.callee) === '[object Function]';
	}
	return isArgs;
};


/***/ }),
/* 451 */
/***/ (function(module, exports, __nested_webpack_require_2344613__) {

"use strict";


// modified from https://github.com/es-shims/es6-shim
var keys = __nested_webpack_require_2344613__(295);
var bind = __nested_webpack_require_2344613__(53);
var canBeObject = function (obj) {
	return typeof obj !== 'undefined' && obj !== null;
};
var hasSymbols = __nested_webpack_require_2344613__(452)();
var toObject = Object;
var push = bind.call(Function.call, Array.prototype.push);
var propIsEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);
var originalGetSymbols = hasSymbols ? Object.getOwnPropertySymbols : null;

module.exports = function assign(target, source1) {
	if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
	var objTarget = toObject(target);
	var s, source, i, props, syms, value, key;
	for (s = 1; s < arguments.length; ++s) {
		source = toObject(arguments[s]);
		props = keys(source);
		var getSymbols = hasSymbols && (Object.getOwnPropertySymbols || originalGetSymbols);
		if (getSymbols) {
			syms = getSymbols(source);
			for (i = 0; i < syms.length; ++i) {
				key = syms[i];
				if (propIsEnumerable(source, key)) {
					push(props, key);
				}
			}
		}
		for (i = 0; i < props.length; ++i) {
			key = props[i];
			value = source[key];
			if (propIsEnumerable(source, key)) {
				objTarget[key] = value;
			}
		}
	}
	return objTarget;
};


/***/ }),
/* 452 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* eslint complexity: [2, 17], max-statements: [2, 33] */
module.exports = function hasSymbols() {
	if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
	if (typeof Symbol.iterator === 'symbol') { return true; }

	var obj = {};
	var sym = Symbol('test');
	var symObj = Object(sym);
	if (typeof sym === 'string') { return false; }

	if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
	if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }

	// temp disabled per https://github.com/ljharb/object.assign/issues/17
	// if (sym instanceof Symbol) { return false; }
	// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
	// if (!(symObj instanceof Symbol)) { return false; }

	// if (typeof Symbol.prototype.toString !== 'function') { return false; }
	// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }

	var symVal = 42;
	obj[sym] = symVal;
	for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax
	if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }

	if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }

	var syms = Object.getOwnPropertySymbols(obj);
	if (syms.length !== 1 || syms[0] !== sym) { return false; }

	if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }

	if (typeof Object.getOwnPropertyDescriptor === 'function') {
		var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
		if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
	}

	return true;
};


/***/ }),
/* 453 */
/***/ (function(module, exports, __nested_webpack_require_2347806__) {

"use strict";


var implementation = __nested_webpack_require_2347806__(451);

var lacksProperEnumerationOrder = function () {
	if (!Object.assign) {
		return false;
	}
	// v8, specifically in node 4.x, has a bug with incorrect property enumeration order
	// note: this does not detect the bug unless there's 20 characters
	var str = 'abcdefghijklmnopqrst';
	var letters = str.split('');
	var map = {};
	for (var i = 0; i < letters.length; ++i) {
		map[letters[i]] = letters[i];
	}
	var obj = Object.assign({}, map);
	var actual = '';
	for (var k in obj) {
		actual += k;
	}
	return str !== actual;
};

var assignHasPendingExceptions = function () {
	if (!Object.assign || !Object.preventExtensions) {
		return false;
	}
	// Firefox 37 still has "pending exception" logic in its Object.assign implementation,
	// which is 72% slower than our shim, and Firefox 40's native implementation.
	var thrower = Object.preventExtensions({ 1: 2 });
	try {
		Object.assign(thrower, 'xy');
	} catch (e) {
		return thrower[1] === 'y';
	}
	return false;
};

module.exports = function getPolyfill() {
	if (!Object.assign) {
		return implementation;
	}
	if (lacksProperEnumerationOrder()) {
		return implementation;
	}
	if (assignHasPendingExceptions()) {
		return implementation;
	}
	return Object.assign;
};


/***/ }),
/* 454 */
/***/ (function(module, exports, __nested_webpack_require_2349164__) {

/*
  Module dependencies
*/

var parse = __nested_webpack_require_2349164__(198),
    defaultOptions = __nested_webpack_require_2349164__(204).default,
    flattenOptions = __nested_webpack_require_2349164__(204).flatten,
    isHtml = __nested_webpack_require_2349164__(152).isHtml,
    _ = {
      extend: __nested_webpack_require_2349164__(473),
      bind: __nested_webpack_require_2349164__(306),
      forEach: __nested_webpack_require_2349164__(147),
      defaults: __nested_webpack_require_2349164__(484)
    };

/*
 * The API
 */

var api = [
  __nested_webpack_require_2349164__(1020),
  __nested_webpack_require_2349164__(1030),
  __nested_webpack_require_2349164__(1037),
  __nested_webpack_require_2349164__(1040),
  __nested_webpack_require_2349164__(1046)
];

/*
 * Instance of cheerio
 */

var Cheerio = module.exports = function(selector, context, root, options) {
  if (!(this instanceof Cheerio)) return new Cheerio(selector, context, root, options);

  this.options = _.defaults(flattenOptions(options), this.options, defaultOptions);

  // $(), $(null), $(undefined), $(false)
  if (!selector) return this;

  if (root) {
    if (typeof root === 'string') root = parse(root, this.options, false);
    this._root = Cheerio.call(this, root);
  }

  // $($)
  if (selector.cheerio) return selector;

  // $(dom)
  if (isNode(selector))
    selector = [selector];

  // $([dom])
  if (Array.isArray(selector)) {
    _.forEach(selector, _.bind(function(elem, idx) {
      this[idx] = elem;
    }, this));
    this.length = selector.length;
    return this;
  }

  // $(<html>)
  if (typeof selector === 'string' && isHtml(selector)) {
    return Cheerio.call(this, parse(selector, this.options, false).children);
  }

  // If we don't have a context, maybe we have a root, from loading
  if (!context) {
    context = this._root;
  } else if (typeof context === 'string') {
    if (isHtml(context)) {
      // $('li', '<ul>...</ul>')
      context = parse(context, this.options, false);
      context = Cheerio.call(this, context);
    } else {
      // $('li', 'ul')
      selector = [context, selector].join(' ');
      context = this._root;
    }
  // $('li', node), $('li', [nodes])
  } else if (!context.cheerio) {
    context = Cheerio.call(this, context);
  }

  // If we still don't have a context, return
  if (!context) return this;

  // #id, .class, tag
  return context.find(selector);
};

/**
 * Mix in `static`
 */

_.extend(Cheerio, __nested_webpack_require_2349164__(310));

/*
 * Set a signature of the object
 */

Cheerio.prototype.cheerio = '[cheerio object]';

/*
 * Make cheerio an array-like object
 */

Cheerio.prototype.length = 0;
Cheerio.prototype.splice = Array.prototype.splice;

/*
 * Make a cheerio object
 *
 * @api private
 */

Cheerio.prototype._make = function(dom, context) {
  var cheerio = new this.constructor(dom, context, this._root, this.options);
  cheerio.prevObject = this;
  return cheerio;
};

/**
 * Turn a cheerio object into an array
 */

Cheerio.prototype.toArray = function() {
  return this.get();
};

/**
 * Plug in the API
 */
api.forEach(function(mod) {
  _.extend(Cheerio.prototype, mod);
});

var isNode = function(obj) {
  return obj.name || obj.type === 'text' || obj.type === 'comment';
};


/***/ }),
/* 455 */
/***/ (function(module, exports, __nested_webpack_require_2352300__) {

var Tokenizer = __nested_webpack_require_2352300__(456);

/*
	Options:

	xmlMode: Disables the special behavior for script/style tags (false by default)
	lowerCaseAttributeNames: call .toLowerCase for each attribute name (true if xmlMode is `false`)
	lowerCaseTags: call .toLowerCase for each tag name (true if xmlMode is `false`)
*/

/*
	Callbacks:

	oncdataend,
	oncdatastart,
	onclosetag,
	oncomment,
	oncommentend,
	onerror,
	onopentag,
	onprocessinginstruction,
	onreset,
	ontext
*/

var formTags = {
    input: true,
    option: true,
    optgroup: true,
    select: true,
    button: true,
    datalist: true,
    textarea: true
};

var openImpliesClose = {
    tr: { tr: true, th: true, td: true },
    th: { th: true },
    td: { thead: true, th: true, td: true },
    body: { head: true, link: true, script: true },
    li: { li: true },
    p: { p: true },
    h1: { p: true },
    h2: { p: true },
    h3: { p: true },
    h4: { p: true },
    h5: { p: true },
    h6: { p: true },
    select: formTags,
    input: formTags,
    output: formTags,
    button: formTags,
    datalist: formTags,
    textarea: formTags,
    option: { option: true },
    optgroup: { optgroup: true }
};

var voidElements = {
    __proto__: null,
    area: true,
    base: true,
    basefont: true,
    br: true,
    col: true,
    command: true,
    embed: true,
    frame: true,
    hr: true,
    img: true,
    input: true,
    isindex: true,
    keygen: true,
    link: true,
    meta: true,
    param: true,
    source: true,
    track: true,
    wbr: true
};

var foreignContextElements = {
    __proto__: null,
    math: true,
    svg: true
};
var htmlIntegrationElements = {
    __proto__: null,
    mi: true,
    mo: true,
    mn: true,
    ms: true,
    mtext: true,
    "annotation-xml": true,
    foreignObject: true,
    desc: true,
    title: true
};

var re_nameEnd = /\s|\//;

function Parser(cbs, options) {
    this._options = options || {};
    this._cbs = cbs || {};

    this._tagname = "";
    this._attribname = "";
    this._attribvalue = "";
    this._attribs = null;
    this._stack = [];
    this._foreignContext = [];

    this.startIndex = 0;
    this.endIndex = null;

    this._lowerCaseTagNames =
        "lowerCaseTags" in this._options
            ? !!this._options.lowerCaseTags
            : !this._options.xmlMode;
    this._lowerCaseAttributeNames =
        "lowerCaseAttributeNames" in this._options
            ? !!this._options.lowerCaseAttributeNames
            : !this._options.xmlMode;

    if (this._options.Tokenizer) {
        Tokenizer = this._options.Tokenizer;
    }
    this._tokenizer = new Tokenizer(this._options, this);

    if (this._cbs.onparserinit) this._cbs.onparserinit(this);
}

__nested_webpack_require_2352300__(58)(Parser, __nested_webpack_require_2352300__(199).EventEmitter);

Parser.prototype._updatePosition = function(initialOffset) {
    if (this.endIndex === null) {
        if (this._tokenizer._sectionStart <= initialOffset) {
            this.startIndex = 0;
        } else {
            this.startIndex = this._tokenizer._sectionStart - initialOffset;
        }
    } else this.startIndex = this.endIndex + 1;
    this.endIndex = this._tokenizer.getAbsoluteIndex();
};

//Tokenizer event handlers
Parser.prototype.ontext = function(data) {
    this._updatePosition(1);
    this.endIndex--;

    if (this._cbs.ontext) this._cbs.ontext(data);
};

Parser.prototype.onopentagname = function(name) {
    if (this._lowerCaseTagNames) {
        name = name.toLowerCase();
    }

    this._tagname = name;

    if (!this._options.xmlMode && name in openImpliesClose) {
        for (
            var el;
            (el = this._stack[this._stack.length - 1]) in
            openImpliesClose[name];
            this.onclosetag(el)
        );
    }

    if (this._options.xmlMode || !(name in voidElements)) {
        this._stack.push(name);
        if (name in foreignContextElements) this._foreignContext.push(true);
        else if (name in htmlIntegrationElements)
            this._foreignContext.push(false);
    }

    if (this._cbs.onopentagname) this._cbs.onopentagname(name);
    if (this._cbs.onopentag) this._attribs = {};
};

Parser.prototype.onopentagend = function() {
    this._updatePosition(1);

    if (this._attribs) {
        if (this._cbs.onopentag)
            this._cbs.onopentag(this._tagname, this._attribs);
        this._attribs = null;
    }

    if (
        !this._options.xmlMode &&
        this._cbs.onclosetag &&
        this._tagname in voidElements
    ) {
        this._cbs.onclosetag(this._tagname);
    }

    this._tagname = "";
};

Parser.prototype.onclosetag = function(name) {
    this._updatePosition(1);

    if (this._lowerCaseTagNames) {
        name = name.toLowerCase();
    }
    
    if (name in foreignContextElements || name in htmlIntegrationElements) {
        this._foreignContext.pop();
    }

    if (
        this._stack.length &&
        (!(name in voidElements) || this._options.xmlMode)
    ) {
        var pos = this._stack.lastIndexOf(name);
        if (pos !== -1) {
            if (this._cbs.onclosetag) {
                pos = this._stack.length - pos;
                while (pos--) this._cbs.onclosetag(this._stack.pop());
            } else this._stack.length = pos;
        } else if (name === "p" && !this._options.xmlMode) {
            this.onopentagname(name);
            this._closeCurrentTag();
        }
    } else if (!this._options.xmlMode && (name === "br" || name === "p")) {
        this.onopentagname(name);
        this._closeCurrentTag();
    }
};

Parser.prototype.onselfclosingtag = function() {
    if (
        this._options.xmlMode ||
        this._options.recognizeSelfClosing ||
        this._foreignContext[this._foreignContext.length - 1]
    ) {
        this._closeCurrentTag();
    } else {
        this.onopentagend();
    }
};

Parser.prototype._closeCurrentTag = function() {
    var name = this._tagname;

    this.onopentagend();

    //self-closing tags will be on the top of the stack
    //(cheaper check than in onclosetag)
    if (this._stack[this._stack.length - 1] === name) {
        if (this._cbs.onclosetag) {
            this._cbs.onclosetag(name);
        }
        this._stack.pop();
        
    }
};

Parser.prototype.onattribname = function(name) {
    if (this._lowerCaseAttributeNames) {
        name = name.toLowerCase();
    }
    this._attribname = name;
};

Parser.prototype.onattribdata = function(value) {
    this._attribvalue += value;
};

Parser.prototype.onattribend = function() {
    if (this._cbs.onattribute)
        this._cbs.onattribute(this._attribname, this._attribvalue);
    if (
        this._attribs &&
        !Object.prototype.hasOwnProperty.call(this._attribs, this._attribname)
    ) {
        this._attribs[this._attribname] = this._attribvalue;
    }
    this._attribname = "";
    this._attribvalue = "";
};

Parser.prototype._getInstructionName = function(value) {
    var idx = value.search(re_nameEnd),
        name = idx < 0 ? value : value.substr(0, idx);

    if (this._lowerCaseTagNames) {
        name = name.toLowerCase();
    }

    return name;
};

Parser.prototype.ondeclaration = function(value) {
    if (this._cbs.onprocessinginstruction) {
        var name = this._getInstructionName(value);
        this._cbs.onprocessinginstruction("!" + name, "!" + value);
    }
};

Parser.prototype.onprocessinginstruction = function(value) {
    if (this._cbs.onprocessinginstruction) {
        var name = this._getInstructionName(value);
        this._cbs.onprocessinginstruction("?" + name, "?" + value);
    }
};

Parser.prototype.oncomment = function(value) {
    this._updatePosition(4);

    if (this._cbs.oncomment) this._cbs.oncomment(value);
    if (this._cbs.oncommentend) this._cbs.oncommentend();
};

Parser.prototype.oncdata = function(value) {
    this._updatePosition(1);

    if (this._options.xmlMode || this._options.recognizeCDATA) {
        if (this._cbs.oncdatastart) this._cbs.oncdatastart();
        if (this._cbs.ontext) this._cbs.ontext(value);
        if (this._cbs.oncdataend) this._cbs.oncdataend();
    } else {
        this.oncomment("[CDATA[" + value + "]]");
    }
};

Parser.prototype.onerror = function(err) {
    if (this._cbs.onerror) this._cbs.onerror(err);
};

Parser.prototype.onend = function() {
    if (this._cbs.onclosetag) {
        for (
            var i = this._stack.length;
            i > 0;
            this._cbs.onclosetag(this._stack[--i])
        );
    }
    if (this._cbs.onend) this._cbs.onend();
};

//Resets the parser to a blank state, ready to parse a new HTML document
Parser.prototype.reset = function() {
    if (this._cbs.onreset) this._cbs.onreset();
    this._tokenizer.reset();

    this._tagname = "";
    this._attribname = "";
    this._attribs = null;
    this._stack = [];

    if (this._cbs.onparserinit) this._cbs.onparserinit(this);
};

//Parses a complete HTML document and pushes it to the handler
Parser.prototype.parseComplete = function(data) {
    this.reset();
    this.end(data);
};

Parser.prototype.write = function(chunk) {
    this._tokenizer.write(chunk);
};

Parser.prototype.end = function(chunk) {
    this._tokenizer.end(chunk);
};

Parser.prototype.pause = function() {
    this._tokenizer.pause();
};

Parser.prototype.resume = function() {
    this._tokenizer.resume();
};

//alias for backwards compat
Parser.prototype.parseChunk = Parser.prototype.write;
Parser.prototype.done = Parser.prototype.end;

module.exports = Parser;


/***/ }),
/* 456 */
/***/ (function(module, exports, __nested_webpack_require_2361870__) {

module.exports = Tokenizer;

var decodeCodePoint = __nested_webpack_require_2361870__(457);
var entityMap = __nested_webpack_require_2361870__(297);
var legacyMap = __nested_webpack_require_2361870__(458);
var xmlMap = __nested_webpack_require_2361870__(298);

var i = 0;

var TEXT = i++;
var BEFORE_TAG_NAME = i++; //after <
var IN_TAG_NAME = i++;
var IN_SELF_CLOSING_TAG = i++;
var BEFORE_CLOSING_TAG_NAME = i++;
var IN_CLOSING_TAG_NAME = i++;
var AFTER_CLOSING_TAG_NAME = i++;

//attributes
var BEFORE_ATTRIBUTE_NAME = i++;
var IN_ATTRIBUTE_NAME = i++;
var AFTER_ATTRIBUTE_NAME = i++;
var BEFORE_ATTRIBUTE_VALUE = i++;
var IN_ATTRIBUTE_VALUE_DQ = i++; // "
var IN_ATTRIBUTE_VALUE_SQ = i++; // '
var IN_ATTRIBUTE_VALUE_NQ = i++;

//declarations
var BEFORE_DECLARATION = i++; // !
var IN_DECLARATION = i++;

//processing instructions
var IN_PROCESSING_INSTRUCTION = i++; // ?

//comments
var BEFORE_COMMENT = i++;
var IN_COMMENT = i++;
var AFTER_COMMENT_1 = i++;
var AFTER_COMMENT_2 = i++;

//cdata
var BEFORE_CDATA_1 = i++; // [
var BEFORE_CDATA_2 = i++; // C
var BEFORE_CDATA_3 = i++; // D
var BEFORE_CDATA_4 = i++; // A
var BEFORE_CDATA_5 = i++; // T
var BEFORE_CDATA_6 = i++; // A
var IN_CDATA = i++; // [
var AFTER_CDATA_1 = i++; // ]
var AFTER_CDATA_2 = i++; // ]

//special tags
var BEFORE_SPECIAL = i++; //S
var BEFORE_SPECIAL_END = i++; //S

var BEFORE_SCRIPT_1 = i++; //C
var BEFORE_SCRIPT_2 = i++; //R
var BEFORE_SCRIPT_3 = i++; //I
var BEFORE_SCRIPT_4 = i++; //P
var BEFORE_SCRIPT_5 = i++; //T
var AFTER_SCRIPT_1 = i++; //C
var AFTER_SCRIPT_2 = i++; //R
var AFTER_SCRIPT_3 = i++; //I
var AFTER_SCRIPT_4 = i++; //P
var AFTER_SCRIPT_5 = i++; //T

var BEFORE_STYLE_1 = i++; //T
var BEFORE_STYLE_2 = i++; //Y
var BEFORE_STYLE_3 = i++; //L
var BEFORE_STYLE_4 = i++; //E
var AFTER_STYLE_1 = i++; //T
var AFTER_STYLE_2 = i++; //Y
var AFTER_STYLE_3 = i++; //L
var AFTER_STYLE_4 = i++; //E

var BEFORE_ENTITY = i++; //&
var BEFORE_NUMERIC_ENTITY = i++; //#
var IN_NAMED_ENTITY = i++;
var IN_NUMERIC_ENTITY = i++;
var IN_HEX_ENTITY = i++; //X

var j = 0;

var SPECIAL_NONE = j++;
var SPECIAL_SCRIPT = j++;
var SPECIAL_STYLE = j++;

function whitespace(c) {
    return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}

function ifElseState(upper, SUCCESS, FAILURE) {
    var lower = upper.toLowerCase();

    if (upper === lower) {
        return function(c) {
            if (c === lower) {
                this._state = SUCCESS;
            } else {
                this._state = FAILURE;
                this._index--;
            }
        };
    } else {
        return function(c) {
            if (c === lower || c === upper) {
                this._state = SUCCESS;
            } else {
                this._state = FAILURE;
                this._index--;
            }
        };
    }
}

function consumeSpecialNameChar(upper, NEXT_STATE) {
    var lower = upper.toLowerCase();

    return function(c) {
        if (c === lower || c === upper) {
            this._state = NEXT_STATE;
        } else {
            this._state = IN_TAG_NAME;
            this._index--; //consume the token again
        }
    };
}

function Tokenizer(options, cbs) {
    this._state = TEXT;
    this._buffer = "";
    this._sectionStart = 0;
    this._index = 0;
    this._bufferOffset = 0; //chars removed from _buffer
    this._baseState = TEXT;
    this._special = SPECIAL_NONE;
    this._cbs = cbs;
    this._running = true;
    this._ended = false;
    this._xmlMode = !!(options && options.xmlMode);
    this._decodeEntities = !!(options && options.decodeEntities);
}

Tokenizer.prototype._stateText = function(c) {
    if (c === "<") {
        if (this._index > this._sectionStart) {
            this._cbs.ontext(this._getSection());
        }
        this._state = BEFORE_TAG_NAME;
        this._sectionStart = this._index;
    } else if (
        this._decodeEntities &&
        this._special === SPECIAL_NONE &&
        c === "&"
    ) {
        if (this._index > this._sectionStart) {
            this._cbs.ontext(this._getSection());
        }
        this._baseState = TEXT;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateBeforeTagName = function(c) {
    if (c === "/") {
        this._state = BEFORE_CLOSING_TAG_NAME;
    } else if (c === "<") {
        this._cbs.ontext(this._getSection());
        this._sectionStart = this._index;
    } else if (c === ">" || this._special !== SPECIAL_NONE || whitespace(c)) {
        this._state = TEXT;
    } else if (c === "!") {
        this._state = BEFORE_DECLARATION;
        this._sectionStart = this._index + 1;
    } else if (c === "?") {
        this._state = IN_PROCESSING_INSTRUCTION;
        this._sectionStart = this._index + 1;
    } else {
        this._state =
            !this._xmlMode && (c === "s" || c === "S")
                ? BEFORE_SPECIAL
                : IN_TAG_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInTagName = function(c) {
    if (c === "/" || c === ">" || whitespace(c)) {
        this._emitToken("onopentagname");
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateBeforeCloseingTagName = function(c) {
    if (whitespace(c));
    else if (c === ">") {
        this._state = TEXT;
    } else if (this._special !== SPECIAL_NONE) {
        if (c === "s" || c === "S") {
            this._state = BEFORE_SPECIAL_END;
        } else {
            this._state = TEXT;
            this._index--;
        }
    } else {
        this._state = IN_CLOSING_TAG_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInCloseingTagName = function(c) {
    if (c === ">" || whitespace(c)) {
        this._emitToken("onclosetag");
        this._state = AFTER_CLOSING_TAG_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateAfterCloseingTagName = function(c) {
    //skip everything until ">"
    if (c === ">") {
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    }
};

Tokenizer.prototype._stateBeforeAttributeName = function(c) {
    if (c === ">") {
        this._cbs.onopentagend();
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (c === "/") {
        this._state = IN_SELF_CLOSING_TAG;
    } else if (!whitespace(c)) {
        this._state = IN_ATTRIBUTE_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInSelfClosingTag = function(c) {
    if (c === ">") {
        this._cbs.onselfclosingtag();
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (!whitespace(c)) {
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateInAttributeName = function(c) {
    if (c === "=" || c === "/" || c === ">" || whitespace(c)) {
        this._cbs.onattribname(this._getSection());
        this._sectionStart = -1;
        this._state = AFTER_ATTRIBUTE_NAME;
        this._index--;
    }
};

Tokenizer.prototype._stateAfterAttributeName = function(c) {
    if (c === "=") {
        this._state = BEFORE_ATTRIBUTE_VALUE;
    } else if (c === "/" || c === ">") {
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    } else if (!whitespace(c)) {
        this._cbs.onattribend();
        this._state = IN_ATTRIBUTE_NAME;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateBeforeAttributeValue = function(c) {
    if (c === '"') {
        this._state = IN_ATTRIBUTE_VALUE_DQ;
        this._sectionStart = this._index + 1;
    } else if (c === "'") {
        this._state = IN_ATTRIBUTE_VALUE_SQ;
        this._sectionStart = this._index + 1;
    } else if (!whitespace(c)) {
        this._state = IN_ATTRIBUTE_VALUE_NQ;
        this._sectionStart = this._index;
        this._index--; //reconsume token
    }
};

Tokenizer.prototype._stateInAttributeValueDoubleQuotes = function(c) {
    if (c === '"') {
        this._emitToken("onattribdata");
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
    } else if (this._decodeEntities && c === "&") {
        this._emitToken("onattribdata");
        this._baseState = this._state;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInAttributeValueSingleQuotes = function(c) {
    if (c === "'") {
        this._emitToken("onattribdata");
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
    } else if (this._decodeEntities && c === "&") {
        this._emitToken("onattribdata");
        this._baseState = this._state;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateInAttributeValueNoQuotes = function(c) {
    if (whitespace(c) || c === ">") {
        this._emitToken("onattribdata");
        this._cbs.onattribend();
        this._state = BEFORE_ATTRIBUTE_NAME;
        this._index--;
    } else if (this._decodeEntities && c === "&") {
        this._emitToken("onattribdata");
        this._baseState = this._state;
        this._state = BEFORE_ENTITY;
        this._sectionStart = this._index;
    }
};

Tokenizer.prototype._stateBeforeDeclaration = function(c) {
    this._state =
        c === "["
            ? BEFORE_CDATA_1
            : c === "-"
                ? BEFORE_COMMENT
                : IN_DECLARATION;
};

Tokenizer.prototype._stateInDeclaration = function(c) {
    if (c === ">") {
        this._cbs.ondeclaration(this._getSection());
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    }
};

Tokenizer.prototype._stateInProcessingInstruction = function(c) {
    if (c === ">") {
        this._cbs.onprocessinginstruction(this._getSection());
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    }
};

Tokenizer.prototype._stateBeforeComment = function(c) {
    if (c === "-") {
        this._state = IN_COMMENT;
        this._sectionStart = this._index + 1;
    } else {
        this._state = IN_DECLARATION;
    }
};

Tokenizer.prototype._stateInComment = function(c) {
    if (c === "-") this._state = AFTER_COMMENT_1;
};

Tokenizer.prototype._stateAfterComment1 = function(c) {
    if (c === "-") {
        this._state = AFTER_COMMENT_2;
    } else {
        this._state = IN_COMMENT;
    }
};

Tokenizer.prototype._stateAfterComment2 = function(c) {
    if (c === ">") {
        //remove 2 trailing chars
        this._cbs.oncomment(
            this._buffer.substring(this._sectionStart, this._index - 2)
        );
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (c !== "-") {
        this._state = IN_COMMENT;
    }
    // else: stay in AFTER_COMMENT_2 (`--->`)
};

Tokenizer.prototype._stateBeforeCdata1 = ifElseState(
    "C",
    BEFORE_CDATA_2,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata2 = ifElseState(
    "D",
    BEFORE_CDATA_3,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata3 = ifElseState(
    "A",
    BEFORE_CDATA_4,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata4 = ifElseState(
    "T",
    BEFORE_CDATA_5,
    IN_DECLARATION
);
Tokenizer.prototype._stateBeforeCdata5 = ifElseState(
    "A",
    BEFORE_CDATA_6,
    IN_DECLARATION
);

Tokenizer.prototype._stateBeforeCdata6 = function(c) {
    if (c === "[") {
        this._state = IN_CDATA;
        this._sectionStart = this._index + 1;
    } else {
        this._state = IN_DECLARATION;
        this._index--;
    }
};

Tokenizer.prototype._stateInCdata = function(c) {
    if (c === "]") this._state = AFTER_CDATA_1;
};

Tokenizer.prototype._stateAfterCdata1 = function(c) {
    if (c === "]") this._state = AFTER_CDATA_2;
    else this._state = IN_CDATA;
};

Tokenizer.prototype._stateAfterCdata2 = function(c) {
    if (c === ">") {
        //remove 2 trailing chars
        this._cbs.oncdata(
            this._buffer.substring(this._sectionStart, this._index - 2)
        );
        this._state = TEXT;
        this._sectionStart = this._index + 1;
    } else if (c !== "]") {
        this._state = IN_CDATA;
    }
    //else: stay in AFTER_CDATA_2 (`]]]>`)
};

Tokenizer.prototype._stateBeforeSpecial = function(c) {
    if (c === "c" || c === "C") {
        this._state = BEFORE_SCRIPT_1;
    } else if (c === "t" || c === "T") {
        this._state = BEFORE_STYLE_1;
    } else {
        this._state = IN_TAG_NAME;
        this._index--; //consume the token again
    }
};

Tokenizer.prototype._stateBeforeSpecialEnd = function(c) {
    if (this._special === SPECIAL_SCRIPT && (c === "c" || c === "C")) {
        this._state = AFTER_SCRIPT_1;
    } else if (this._special === SPECIAL_STYLE && (c === "t" || c === "T")) {
        this._state = AFTER_STYLE_1;
    } else this._state = TEXT;
};

Tokenizer.prototype._stateBeforeScript1 = consumeSpecialNameChar(
    "R",
    BEFORE_SCRIPT_2
);
Tokenizer.prototype._stateBeforeScript2 = consumeSpecialNameChar(
    "I",
    BEFORE_SCRIPT_3
);
Tokenizer.prototype._stateBeforeScript3 = consumeSpecialNameChar(
    "P",
    BEFORE_SCRIPT_4
);
Tokenizer.prototype._stateBeforeScript4 = consumeSpecialNameChar(
    "T",
    BEFORE_SCRIPT_5
);

Tokenizer.prototype._stateBeforeScript5 = function(c) {
    if (c === "/" || c === ">" || whitespace(c)) {
        this._special = SPECIAL_SCRIPT;
    }
    this._state = IN_TAG_NAME;
    this._index--; //consume the token again
};

Tokenizer.prototype._stateAfterScript1 = ifElseState("R", AFTER_SCRIPT_2, TEXT);
Tokenizer.prototype._stateAfterScript2 = ifElseState("I", AFTER_SCRIPT_3, TEXT);
Tokenizer.prototype._stateAfterScript3 = ifElseState("P", AFTER_SCRIPT_4, TEXT);
Tokenizer.prototype._stateAfterScript4 = ifElseState("T", AFTER_SCRIPT_5, TEXT);

Tokenizer.prototype._stateAfterScript5 = function(c) {
    if (c === ">" || whitespace(c)) {
        this._special = SPECIAL_NONE;
        this._state = IN_CLOSING_TAG_NAME;
        this._sectionStart = this._index - 6;
        this._index--; //reconsume the token
    } else this._state = TEXT;
};

Tokenizer.prototype._stateBeforeStyle1 = consumeSpecialNameChar(
    "Y",
    BEFORE_STYLE_2
);
Tokenizer.prototype._stateBeforeStyle2 = consumeSpecialNameChar(
    "L",
    BEFORE_STYLE_3
);
Tokenizer.prototype._stateBeforeStyle3 = consumeSpecialNameChar(
    "E",
    BEFORE_STYLE_4
);

Tokenizer.prototype._stateBeforeStyle4 = function(c) {
    if (c === "/" || c === ">" || whitespace(c)) {
        this._special = SPECIAL_STYLE;
    }
    this._state = IN_TAG_NAME;
    this._index--; //consume the token again
};

Tokenizer.prototype._stateAfterStyle1 = ifElseState("Y", AFTER_STYLE_2, TEXT);
Tokenizer.prototype._stateAfterStyle2 = ifElseState("L", AFTER_STYLE_3, TEXT);
Tokenizer.prototype._stateAfterStyle3 = ifElseState("E", AFTER_STYLE_4, TEXT);

Tokenizer.prototype._stateAfterStyle4 = function(c) {
    if (c === ">" || whitespace(c)) {
        this._special = SPECIAL_NONE;
        this._state = IN_CLOSING_TAG_NAME;
        this._sectionStart = this._index - 5;
        this._index--; //reconsume the token
    } else this._state = TEXT;
};

Tokenizer.prototype._stateBeforeEntity = ifElseState(
    "#",
    BEFORE_NUMERIC_ENTITY,
    IN_NAMED_ENTITY
);
Tokenizer.prototype._stateBeforeNumericEntity = ifElseState(
    "X",
    IN_HEX_ENTITY,
    IN_NUMERIC_ENTITY
);

//for entities terminated with a semicolon
Tokenizer.prototype._parseNamedEntityStrict = function() {
    //offset = 1
    if (this._sectionStart + 1 < this._index) {
        var entity = this._buffer.substring(
                this._sectionStart + 1,
                this._index
            ),
            map = this._xmlMode ? xmlMap : entityMap;

        if (map.hasOwnProperty(entity)) {
            this._emitPartial(map[entity]);
            this._sectionStart = this._index + 1;
        }
    }
};

//parses legacy entities (without trailing semicolon)
Tokenizer.prototype._parseLegacyEntity = function() {
    var start = this._sectionStart + 1,
        limit = this._index - start;

    if (limit > 6) limit = 6; //the max length of legacy entities is 6

    while (limit >= 2) {
        //the min length of legacy entities is 2
        var entity = this._buffer.substr(start, limit);

        if (legacyMap.hasOwnProperty(entity)) {
            this._emitPartial(legacyMap[entity]);
            this._sectionStart += limit + 1;
            return;
        } else {
            limit--;
        }
    }
};

Tokenizer.prototype._stateInNamedEntity = function(c) {
    if (c === ";") {
        this._parseNamedEntityStrict();
        if (this._sectionStart + 1 < this._index && !this._xmlMode) {
            this._parseLegacyEntity();
        }
        this._state = this._baseState;
    } else if (
        (c < "a" || c > "z") &&
        (c < "A" || c > "Z") &&
        (c < "0" || c > "9")
    ) {
        if (this._xmlMode);
        else if (this._sectionStart + 1 === this._index);
        else if (this._baseState !== TEXT) {
            if (c !== "=") {
                this._parseNamedEntityStrict();
            }
        } else {
            this._parseLegacyEntity();
        }

        this._state = this._baseState;
        this._index--;
    }
};

Tokenizer.prototype._decodeNumericEntity = function(offset, base) {
    var sectionStart = this._sectionStart + offset;

    if (sectionStart !== this._index) {
        //parse entity
        var entity = this._buffer.substring(sectionStart, this._index);
        var parsed = parseInt(entity, base);

        this._emitPartial(decodeCodePoint(parsed));
        this._sectionStart = this._index;
    } else {
        this._sectionStart--;
    }

    this._state = this._baseState;
};

Tokenizer.prototype._stateInNumericEntity = function(c) {
    if (c === ";") {
        this._decodeNumericEntity(2, 10);
        this._sectionStart++;
    } else if (c < "0" || c > "9") {
        if (!this._xmlMode) {
            this._decodeNumericEntity(2, 10);
        } else {
            this._state = this._baseState;
        }
        this._index--;
    }
};

Tokenizer.prototype._stateInHexEntity = function(c) {
    if (c === ";") {
        this._decodeNumericEntity(3, 16);
        this._sectionStart++;
    } else if (
        (c < "a" || c > "f") &&
        (c < "A" || c > "F") &&
        (c < "0" || c > "9")
    ) {
        if (!this._xmlMode) {
            this._decodeNumericEntity(3, 16);
        } else {
            this._state = this._baseState;
        }
        this._index--;
    }
};

Tokenizer.prototype._cleanup = function() {
    if (this._sectionStart < 0) {
        this._buffer = "";
        this._bufferOffset += this._index;
        this._index = 0;
    } else if (this._running) {
        if (this._state === TEXT) {
            if (this._sectionStart !== this._index) {
                this._cbs.ontext(this._buffer.substr(this._sectionStart));
            }
            this._buffer = "";
            this._bufferOffset += this._index;
            this._index = 0;
        } else if (this._sectionStart === this._index) {
            //the section just started
            this._buffer = "";
            this._bufferOffset += this._index;
            this._index = 0;
        } else {
            //remove everything unnecessary
            this._buffer = this._buffer.substr(this._sectionStart);
            this._index -= this._sectionStart;
            this._bufferOffset += this._sectionStart;
        }

        this._sectionStart = 0;
    }
};

//TODO make events conditional
Tokenizer.prototype.write = function(chunk) {
    if (this._ended) this._cbs.onerror(Error(".write() after done!"));

    this._buffer += chunk;
    this._parse();
};

Tokenizer.prototype._parse = function() {
    while (this._index < this._buffer.length && this._running) {
        var c = this._buffer.charAt(this._index);
        if (this._state === TEXT) {
            this._stateText(c);
        } else if (this._state === BEFORE_TAG_NAME) {
            this._stateBeforeTagName(c);
        } else if (this._state === IN_TAG_NAME) {
            this._stateInTagName(c);
        } else if (this._state === BEFORE_CLOSING_TAG_NAME) {
            this._stateBeforeCloseingTagName(c);
        } else if (this._state === IN_CLOSING_TAG_NAME) {
            this._stateInCloseingTagName(c);
        } else if (this._state === AFTER_CLOSING_TAG_NAME) {
            this._stateAfterCloseingTagName(c);
        } else if (this._state === IN_SELF_CLOSING_TAG) {
            this._stateInSelfClosingTag(c);
        } else if (this._state === BEFORE_ATTRIBUTE_NAME) {

        /*
		*	attributes
		*/
            this._stateBeforeAttributeName(c);
        } else if (this._state === IN_ATTRIBUTE_NAME) {
            this._stateInAttributeName(c);
        } else if (this._state === AFTER_ATTRIBUTE_NAME) {
            this._stateAfterAttributeName(c);
        } else if (this._state === BEFORE_ATTRIBUTE_VALUE) {
            this._stateBeforeAttributeValue(c);
        } else if (this._state === IN_ATTRIBUTE_VALUE_DQ) {
            this._stateInAttributeValueDoubleQuotes(c);
        } else if (this._state === IN_ATTRIBUTE_VALUE_SQ) {
            this._stateInAttributeValueSingleQuotes(c);
        } else if (this._state === IN_ATTRIBUTE_VALUE_NQ) {
            this._stateInAttributeValueNoQuotes(c);
        } else if (this._state === BEFORE_DECLARATION) {

        /*
		*	declarations
		*/
            this._stateBeforeDeclaration(c);
        } else if (this._state === IN_DECLARATION) {
            this._stateInDeclaration(c);
        } else if (this._state === IN_PROCESSING_INSTRUCTION) {

        /*
		*	processing instructions
		*/
            this._stateInProcessingInstruction(c);
        } else if (this._state === BEFORE_COMMENT) {

        /*
		*	comments
		*/
            this._stateBeforeComment(c);
        } else if (this._state === IN_COMMENT) {
            this._stateInComment(c);
        } else if (this._state === AFTER_COMMENT_1) {
            this._stateAfterComment1(c);
        } else if (this._state === AFTER_COMMENT_2) {
            this._stateAfterComment2(c);
        } else if (this._state === BEFORE_CDATA_1) {

        /*
		*	cdata
		*/
            this._stateBeforeCdata1(c);
        } else if (this._state === BEFORE_CDATA_2) {
            this._stateBeforeCdata2(c);
        } else if (this._state === BEFORE_CDATA_3) {
            this._stateBeforeCdata3(c);
        } else if (this._state === BEFORE_CDATA_4) {
            this._stateBeforeCdata4(c);
        } else if (this._state === BEFORE_CDATA_5) {
            this._stateBeforeCdata5(c);
        } else if (this._state === BEFORE_CDATA_6) {
            this._stateBeforeCdata6(c);
        } else if (this._state === IN_CDATA) {
            this._stateInCdata(c);
        } else if (this._state === AFTER_CDATA_1) {
            this._stateAfterCdata1(c);
        } else if (this._state === AFTER_CDATA_2) {
            this._stateAfterCdata2(c);
        } else if (this._state === BEFORE_SPECIAL) {

        /*
		* special tags
		*/
            this._stateBeforeSpecial(c);
        } else if (this._state === BEFORE_SPECIAL_END) {
            this._stateBeforeSpecialEnd(c);
        } else if (this._state === BEFORE_SCRIPT_1) {

        /*
		* script
		*/
            this._stateBeforeScript1(c);
        } else if (this._state === BEFORE_SCRIPT_2) {
            this._stateBeforeScript2(c);
        } else if (this._state === BEFORE_SCRIPT_3) {
            this._stateBeforeScript3(c);
        } else if (this._state === BEFORE_SCRIPT_4) {
            this._stateBeforeScript4(c);
        } else if (this._state === BEFORE_SCRIPT_5) {
            this._stateBeforeScript5(c);
        } else if (this._state === AFTER_SCRIPT_1) {
            this._stateAfterScript1(c);
        } else if (this._state === AFTER_SCRIPT_2) {
            this._stateAfterScript2(c);
        } else if (this._state === AFTER_SCRIPT_3) {
            this._stateAfterScript3(c);
        } else if (this._state === AFTER_SCRIPT_4) {
            this._stateAfterScript4(c);
        } else if (this._state === AFTER_SCRIPT_5) {
            this._stateAfterScript5(c);
        } else if (this._state === BEFORE_STYLE_1) {

        /*
		* style
		*/
            this._stateBeforeStyle1(c);
        } else if (this._state === BEFORE_STYLE_2) {
            this._stateBeforeStyle2(c);
        } else if (this._state === BEFORE_STYLE_3) {
            this._stateBeforeStyle3(c);
        } else if (this._state === BEFORE_STYLE_4) {
            this._stateBeforeStyle4(c);
        } else if (this._state === AFTER_STYLE_1) {
            this._stateAfterStyle1(c);
        } else if (this._state === AFTER_STYLE_2) {
            this._stateAfterStyle2(c);
        } else if (this._state === AFTER_STYLE_3) {
            this._stateAfterStyle3(c);
        } else if (this._state === AFTER_STYLE_4) {
            this._stateAfterStyle4(c);
        } else if (this._state === BEFORE_ENTITY) {

        /*
		* entities
		*/
            this._stateBeforeEntity(c);
        } else if (this._state === BEFORE_NUMERIC_ENTITY) {
            this._stateBeforeNumericEntity(c);
        } else if (this._state === IN_NAMED_ENTITY) {
            this._stateInNamedEntity(c);
        } else if (this._state === IN_NUMERIC_ENTITY) {
            this._stateInNumericEntity(c);
        } else if (this._state === IN_HEX_ENTITY) {
            this._stateInHexEntity(c);
        } else {
            this._cbs.onerror(Error("unknown _state"), this._state);
        }

        this._index++;
    }

    this._cleanup();
};

Tokenizer.prototype.pause = function() {
    this._running = false;
};
Tokenizer.prototype.resume = function() {
    this._running = true;

    if (this._index < this._buffer.length) {
        this._parse();
    }
    if (this._ended) {
        this._finish();
    }
};

Tokenizer.prototype.end = function(chunk) {
    if (this._ended) this._cbs.onerror(Error(".end() after done!"));
    if (chunk) this.write(chunk);

    this._ended = true;

    if (this._running) this._finish();
};

Tokenizer.prototype._finish = function() {
    //if there is remaining data, emit it in a reasonable way
    if (this._sectionStart < this._index) {
        this._handleTrailingData();
    }

    this._cbs.onend();
};

Tokenizer.prototype._handleTrailingData = function() {
    var data = this._buffer.substr(this._sectionStart);

    if (
        this._state === IN_CDATA ||
        this._state === AFTER_CDATA_1 ||
        this._state === AFTER_CDATA_2
    ) {
        this._cbs.oncdata(data);
    } else if (
        this._state === IN_COMMENT ||
        this._state === AFTER_COMMENT_1 ||
        this._state === AFTER_COMMENT_2
    ) {
        this._cbs.oncomment(data);
    } else if (this._state === IN_NAMED_ENTITY && !this._xmlMode) {
        this._parseLegacyEntity();
        if (this._sectionStart < this._index) {
            this._state = this._baseState;
            this._handleTrailingData();
        }
    } else if (this._state === IN_NUMERIC_ENTITY && !this._xmlMode) {
        this._decodeNumericEntity(2, 10);
        if (this._sectionStart < this._index) {
            this._state = this._baseState;
            this._handleTrailingData();
        }
    } else if (this._state === IN_HEX_ENTITY && !this._xmlMode) {
        this._decodeNumericEntity(3, 16);
        if (this._sectionStart < this._index) {
            this._state = this._baseState;
            this._handleTrailingData();
        }
    } else if (
        this._state !== IN_TAG_NAME &&
        this._state !== BEFORE_ATTRIBUTE_NAME &&
        this._state !== BEFORE_ATTRIBUTE_VALUE &&
        this._state !== AFTER_ATTRIBUTE_NAME &&
        this._state !== IN_ATTRIBUTE_NAME &&
        this._state !== IN_ATTRIBUTE_VALUE_SQ &&
        this._state !== IN_ATTRIBUTE_VALUE_DQ &&
        this._state !== IN_ATTRIBUTE_VALUE_NQ &&
        this._state !== IN_CLOSING_TAG_NAME
    ) {
        this._cbs.ontext(data);
    }
    //else, ignore remaining data
    //TODO add a way to remove current tag
};

Tokenizer.prototype.reset = function() {
    Tokenizer.call(
        this,
        { xmlMode: this._xmlMode, decodeEntities: this._decodeEntities },
        this._cbs
    );
};

Tokenizer.prototype.getAbsoluteIndex = function() {
    return this._bufferOffset + this._index;
};

Tokenizer.prototype._getSection = function() {
    return this._buffer.substring(this._sectionStart, this._index);
};

Tokenizer.prototype._emitToken = function(name) {
    this._cbs[name](this._getSection());
    this._sectionStart = -1;
};

Tokenizer.prototype._emitPartial = function(value) {
    if (this._baseState !== TEXT) {
        this._cbs.onattribdata(value); //TODO implement the new event
    } else {
        this._cbs.ontext(value);
    }
};


/***/ }),
/* 457 */
/***/ (function(module, exports, __nested_webpack_require_2390785__) {

var decodeMap = __nested_webpack_require_2390785__(956);

module.exports = decodeCodePoint;

// modified version of https://github.com/mathiasbynens/he/blob/master/src/he.js#L94-L119
function decodeCodePoint(codePoint) {
    if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) {
        return "\uFFFD";
    }

    if (codePoint in decodeMap) {
        codePoint = decodeMap[codePoint];
    }

    var output = "";

    if (codePoint > 0xffff) {
        codePoint -= 0x10000;
        output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800);
        codePoint = 0xdc00 | (codePoint & 0x3ff);
    }

    output += String.fromCharCode(codePoint);
    return output;
}


/***/ }),
/* 458 */
/***/ (function(module) {

module.exports = {"Aacute":"Á","aacute":"á","Acirc":"Â","acirc":"â","acute":"´","AElig":"Æ","aelig":"æ","Agrave":"À","agrave":"à","amp":"&","AMP":"&","Aring":"Å","aring":"å","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","brvbar":"¦","Ccedil":"Ç","ccedil":"ç","cedil":"¸","cent":"¢","copy":"©","COPY":"©","curren":"¤","deg":"°","divide":"÷","Eacute":"É","eacute":"é","Ecirc":"Ê","ecirc":"ê","Egrave":"È","egrave":"è","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","frac12":"½","frac14":"¼","frac34":"¾","gt":">","GT":">","Iacute":"Í","iacute":"í","Icirc":"Î","icirc":"î","iexcl":"¡","Igrave":"Ì","igrave":"ì","iquest":"¿","Iuml":"Ï","iuml":"ï","laquo":"«","lt":"<","LT":"<","macr":"¯","micro":"µ","middot":"·","nbsp":" ","not":"¬","Ntilde":"Ñ","ntilde":"ñ","Oacute":"Ó","oacute":"ó","Ocirc":"Ô","ocirc":"ô","Ograve":"Ò","ograve":"ò","ordf":"ª","ordm":"º","Oslash":"Ø","oslash":"ø","Otilde":"Õ","otilde":"õ","Ouml":"Ö","ouml":"ö","para":"¶","plusmn":"±","pound":"£","quot":"\"","QUOT":"\"","raquo":"»","reg":"®","REG":"®","sect":"§","shy":"­","sup1":"¹","sup2":"²","sup3":"³","szlig":"ß","THORN":"Þ","thorn":"þ","times":"×","Uacute":"Ú","uacute":"ú","Ucirc":"Û","ucirc":"û","Ugrave":"Ù","ugrave":"ù","uml":"¨","Uuml":"Ü","uuml":"ü","Yacute":"Ý","yacute":"ý","yen":"¥","yuml":"ÿ"};

/***/ }),
/* 459 */
/***/ (function(module, exports, __nested_webpack_require_2392873__) {

var ElementType = __nested_webpack_require_2392873__(123);

var re_whitespace = /\s+/g;
var NodePrototype = __nested_webpack_require_2392873__(460);
var ElementPrototype = __nested_webpack_require_2392873__(957);

function DomHandler(callback, options, elementCB){
	if(typeof callback === "object"){
		elementCB = options;
		options = callback;
		callback = null;
	} else if(typeof options === "function"){
		elementCB = options;
		options = defaultOpts;
	}
	this._callback = callback;
	this._options = options || defaultOpts;
	this._elementCB = elementCB;
	this.dom = [];
	this._done = false;
	this._tagStack = [];
	this._parser = this._parser || null;
}

//default options
var defaultOpts = {
	normalizeWhitespace: false, //Replace all whitespace with single spaces
	withStartIndices: false, //Add startIndex properties to nodes
	withEndIndices: false, //Add endIndex properties to nodes
};

DomHandler.prototype.onparserinit = function(parser){
	this._parser = parser;
};

//Resets the handler back to starting state
DomHandler.prototype.onreset = function(){
	DomHandler.call(this, this._callback, this._options, this._elementCB);
};

//Signals the handler that parsing is done
DomHandler.prototype.onend = function(){
	if(this._done) return;
	this._done = true;
	this._parser = null;
	this._handleCallback(null);
};

DomHandler.prototype._handleCallback =
DomHandler.prototype.onerror = function(error){
	if(typeof this._callback === "function"){
		this._callback(error, this.dom);
	} else {
		if(error) throw error;
	}
};

DomHandler.prototype.onclosetag = function(){
	//if(this._tagStack.pop().name !== name) this._handleCallback(Error("Tagname didn't match!"));
	
	var elem = this._tagStack.pop();

	if(this._options.withEndIndices && elem){
		elem.endIndex = this._parser.endIndex;
	}

	if(this._elementCB) this._elementCB(elem);
};

DomHandler.prototype._createDomElement = function(properties){
	if (!this._options.withDomLvl1) return properties;

	var element;
	if (properties.type === "tag") {
		element = Object.create(ElementPrototype);
	} else {
		element = Object.create(NodePrototype);
	}

	for (var key in properties) {
		if (properties.hasOwnProperty(key)) {
			element[key] = properties[key];
		}
	}

	return element;
};

DomHandler.prototype._addDomElement = function(element){
	var parent = this._tagStack[this._tagStack.length - 1];
	var siblings = parent ? parent.children : this.dom;
	var previousSibling = siblings[siblings.length - 1];

	element.next = null;

	if(this._options.withStartIndices){
		element.startIndex = this._parser.startIndex;
	}
	if(this._options.withEndIndices){
		element.endIndex = this._parser.endIndex;
	}

	if(previousSibling){
		element.prev = previousSibling;
		previousSibling.next = element;
	} else {
		element.prev = null;
	}

	siblings.push(element);
	element.parent = parent || null;
};

DomHandler.prototype.onopentag = function(name, attribs){
	var properties = {
		type: name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag,
		name: name,
		attribs: attribs,
		children: []
	};

	var element = this._createDomElement(properties);

	this._addDomElement(element);

	this._tagStack.push(element);
};

DomHandler.prototype.ontext = function(data){
	//the ignoreWhitespace is officially dropped, but for now,
	//it's an alias for normalizeWhitespace
	var normalize = this._options.normalizeWhitespace || this._options.ignoreWhitespace;

	var lastTag;

	if(!this._tagStack.length && this.dom.length && (lastTag = this.dom[this.dom.length-1]).type === ElementType.Text){
		if(normalize){
			lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
		} else {
			lastTag.data += data;
		}
	} else {
		if(
			this._tagStack.length &&
			(lastTag = this._tagStack[this._tagStack.length - 1]) &&
			(lastTag = lastTag.children[lastTag.children.length - 1]) &&
			lastTag.type === ElementType.Text
		){
			if(normalize){
				lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
			} else {
				lastTag.data += data;
			}
		} else {
			if(normalize){
				data = data.replace(re_whitespace, " ");
			}

			var element = this._createDomElement({
				data: data,
				type: ElementType.Text
			});

			this._addDomElement(element);
		}
	}
};

DomHandler.prototype.oncomment = function(data){
	var lastTag = this._tagStack[this._tagStack.length - 1];

	if(lastTag && lastTag.type === ElementType.Comment){
		lastTag.data += data;
		return;
	}

	var properties = {
		data: data,
		type: ElementType.Comment
	};

	var element = this._createDomElement(properties);

	this._addDomElement(element);
	this._tagStack.push(element);
};

DomHandler.prototype.oncdatastart = function(){
	var properties = {
		children: [{
			data: "",
			type: ElementType.Text
		}],
		type: ElementType.CDATA
	};

	var element = this._createDomElement(properties);

	this._addDomElement(element);
	this._tagStack.push(element);
};

DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function(){
	this._tagStack.pop();
};

DomHandler.prototype.onprocessinginstruction = function(name, data){
	var element = this._createDomElement({
		name: name,
		data: data,
		type: ElementType.Directive
	});

	this._addDomElement(element);
};

module.exports = DomHandler;


/***/ }),
/* 460 */
/***/ (function(module, exports) {

// This object will be used as the prototype for Nodes when creating a
// DOM-Level-1-compliant structure.
var NodePrototype = module.exports = {
	get firstChild() {
		var children = this.children;
		return children && children[0] || null;
	},
	get lastChild() {
		var children = this.children;
		return children && children[children.length - 1] || null;
	},
	get nodeType() {
		return nodeTypes[this.type] || nodeTypes.element;
	}
};

var domLvl1 = {
	tagName: "name",
	childNodes: "children",
	parentNode: "parent",
	previousSibling: "prev",
	nextSibling: "next",
	nodeValue: "data"
};

var nodeTypes = {
	element: 1,
	text: 3,
	cdata: 4,
	comment: 8
};

Object.keys(domLvl1).forEach(function(key) {
	var shorthand = domLvl1[key];
	Object.defineProperty(NodePrototype, key, {
		get: function() {
			return this[shorthand] || null;
		},
		set: function(val) {
			this[shorthand] = val;
			return val;
		}
	});
});


/***/ }),
/* 461 */
/***/ (function(module, exports, __nested_webpack_require_2399144__) {

module.exports = Stream;

var Parser = __nested_webpack_require_2399144__(455);
var WritableStream = __nested_webpack_require_2399144__(969).Writable;
var StringDecoder = __nested_webpack_require_2399144__(300).StringDecoder;
var Buffer = __nested_webpack_require_2399144__(113).Buffer;

function Stream(cbs, options) {
    var parser = (this._parser = new Parser(cbs, options));
    var decoder = (this._decoder = new StringDecoder());

    WritableStream.call(this, { decodeStrings: false });

    this.once("finish", function() {
        parser.end(decoder.end());
    });
}

__nested_webpack_require_2399144__(58)(Stream, WritableStream);

Stream.prototype._write = function(chunk, encoding, cb) {
    if (chunk instanceof Buffer) chunk = this._decoder.write(chunk);
    this._parser.write(chunk);
    cb();
};


/***/ }),
/* 462 */
/***/ (function(module, exports, __nested_webpack_require_2399963__) {

"use strict";


var Tokenizer = __nested_webpack_require_2399963__(124),
    OpenElementStack = __nested_webpack_require_2399963__(975),
    FormattingElementList = __nested_webpack_require_2399963__(976),
    LocationInfoParserMixin = __nested_webpack_require_2399963__(977),
    defaultTreeAdapter = __nested_webpack_require_2399963__(301),
    mergeOptions = __nested_webpack_require_2399963__(302),
    doctype = __nested_webpack_require_2399963__(303),
    foreignContent = __nested_webpack_require_2399963__(465),
    UNICODE = __nested_webpack_require_2399963__(149),
    HTML = __nested_webpack_require_2399963__(64);

//Aliases
var $ = HTML.TAG_NAMES,
    NS = HTML.NAMESPACES,
    ATTRS = HTML.ATTRS;

var DEFAULT_OPTIONS = {
    locationInfo: false,
    treeAdapter: defaultTreeAdapter
};

//Misc constants
var HIDDEN_INPUT_TYPE = 'hidden';

//Adoption agency loops iteration count
var AA_OUTER_LOOP_ITER = 8,
    AA_INNER_LOOP_ITER = 3;

//Insertion modes
var INITIAL_MODE = 'INITIAL_MODE',
    BEFORE_HTML_MODE = 'BEFORE_HTML_MODE',
    BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE',
    IN_HEAD_MODE = 'IN_HEAD_MODE',
    AFTER_HEAD_MODE = 'AFTER_HEAD_MODE',
    IN_BODY_MODE = 'IN_BODY_MODE',
    TEXT_MODE = 'TEXT_MODE',
    IN_TABLE_MODE = 'IN_TABLE_MODE',
    IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE',
    IN_CAPTION_MODE = 'IN_CAPTION_MODE',
    IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE',
    IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE',
    IN_ROW_MODE = 'IN_ROW_MODE',
    IN_CELL_MODE = 'IN_CELL_MODE',
    IN_SELECT_MODE = 'IN_SELECT_MODE',
    IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE',
    IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE',
    AFTER_BODY_MODE = 'AFTER_BODY_MODE',
    IN_FRAMESET_MODE = 'IN_FRAMESET_MODE',
    AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE',
    AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE',
    AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE';

//Insertion mode reset map
var INSERTION_MODE_RESET_MAP = Object.create(null);

INSERTION_MODE_RESET_MAP[$.TR] = IN_ROW_MODE;
INSERTION_MODE_RESET_MAP[$.TBODY] =
INSERTION_MODE_RESET_MAP[$.THEAD] =
INSERTION_MODE_RESET_MAP[$.TFOOT] = IN_TABLE_BODY_MODE;
INSERTION_MODE_RESET_MAP[$.CAPTION] = IN_CAPTION_MODE;
INSERTION_MODE_RESET_MAP[$.COLGROUP] = IN_COLUMN_GROUP_MODE;
INSERTION_MODE_RESET_MAP[$.TABLE] = IN_TABLE_MODE;
INSERTION_MODE_RESET_MAP[$.BODY] = IN_BODY_MODE;
INSERTION_MODE_RESET_MAP[$.FRAMESET] = IN_FRAMESET_MODE;

//Template insertion mode switch map
var TEMPLATE_INSERTION_MODE_SWITCH_MAP = Object.create(null);

TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.CAPTION] =
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.COLGROUP] =
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.TBODY] =
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.TFOOT] =
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.THEAD] = IN_TABLE_MODE;
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.COL] = IN_COLUMN_GROUP_MODE;
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.TR] = IN_TABLE_BODY_MODE;
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.TD] =
TEMPLATE_INSERTION_MODE_SWITCH_MAP[$.TH] = IN_ROW_MODE;

//Token handlers map for insertion modes
var _ = Object.create(null);

_[INITIAL_MODE] = Object.create(null);
_[INITIAL_MODE][Tokenizer.CHARACTER_TOKEN] =
_[INITIAL_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenInInitialMode;
_[INITIAL_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = ignoreToken;
_[INITIAL_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[INITIAL_MODE][Tokenizer.DOCTYPE_TOKEN] = doctypeInInitialMode;
_[INITIAL_MODE][Tokenizer.START_TAG_TOKEN] =
_[INITIAL_MODE][Tokenizer.END_TAG_TOKEN] =
_[INITIAL_MODE][Tokenizer.EOF_TOKEN] = tokenInInitialMode;

_[BEFORE_HTML_MODE] = Object.create(null);
_[BEFORE_HTML_MODE][Tokenizer.CHARACTER_TOKEN] =
_[BEFORE_HTML_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenBeforeHtml;
_[BEFORE_HTML_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = ignoreToken;
_[BEFORE_HTML_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[BEFORE_HTML_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[BEFORE_HTML_MODE][Tokenizer.START_TAG_TOKEN] = startTagBeforeHtml;
_[BEFORE_HTML_MODE][Tokenizer.END_TAG_TOKEN] = endTagBeforeHtml;
_[BEFORE_HTML_MODE][Tokenizer.EOF_TOKEN] = tokenBeforeHtml;

_[BEFORE_HEAD_MODE] = Object.create(null);
_[BEFORE_HEAD_MODE][Tokenizer.CHARACTER_TOKEN] =
_[BEFORE_HEAD_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenBeforeHead;
_[BEFORE_HEAD_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = ignoreToken;
_[BEFORE_HEAD_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[BEFORE_HEAD_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[BEFORE_HEAD_MODE][Tokenizer.START_TAG_TOKEN] = startTagBeforeHead;
_[BEFORE_HEAD_MODE][Tokenizer.END_TAG_TOKEN] = endTagBeforeHead;
_[BEFORE_HEAD_MODE][Tokenizer.EOF_TOKEN] = tokenBeforeHead;

_[IN_HEAD_MODE] = Object.create(null);
_[IN_HEAD_MODE][Tokenizer.CHARACTER_TOKEN] =
_[IN_HEAD_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenInHead;
_[IN_HEAD_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[IN_HEAD_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_HEAD_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_HEAD_MODE][Tokenizer.START_TAG_TOKEN] = startTagInHead;
_[IN_HEAD_MODE][Tokenizer.END_TAG_TOKEN] = endTagInHead;
_[IN_HEAD_MODE][Tokenizer.EOF_TOKEN] = tokenInHead;

_[AFTER_HEAD_MODE] = Object.create(null);
_[AFTER_HEAD_MODE][Tokenizer.CHARACTER_TOKEN] =
_[AFTER_HEAD_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenAfterHead;
_[AFTER_HEAD_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[AFTER_HEAD_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[AFTER_HEAD_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[AFTER_HEAD_MODE][Tokenizer.START_TAG_TOKEN] = startTagAfterHead;
_[AFTER_HEAD_MODE][Tokenizer.END_TAG_TOKEN] = endTagAfterHead;
_[AFTER_HEAD_MODE][Tokenizer.EOF_TOKEN] = tokenAfterHead;

_[IN_BODY_MODE] = Object.create(null);
_[IN_BODY_MODE][Tokenizer.CHARACTER_TOKEN] = characterInBody;
_[IN_BODY_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_BODY_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[IN_BODY_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_BODY_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_BODY_MODE][Tokenizer.START_TAG_TOKEN] = startTagInBody;
_[IN_BODY_MODE][Tokenizer.END_TAG_TOKEN] = endTagInBody;
_[IN_BODY_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[TEXT_MODE] = Object.create(null);
_[TEXT_MODE][Tokenizer.CHARACTER_TOKEN] =
_[TEXT_MODE][Tokenizer.NULL_CHARACTER_TOKEN] =
_[TEXT_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[TEXT_MODE][Tokenizer.COMMENT_TOKEN] =
_[TEXT_MODE][Tokenizer.DOCTYPE_TOKEN] =
_[TEXT_MODE][Tokenizer.START_TAG_TOKEN] = ignoreToken;
_[TEXT_MODE][Tokenizer.END_TAG_TOKEN] = endTagInText;
_[TEXT_MODE][Tokenizer.EOF_TOKEN] = eofInText;

_[IN_TABLE_MODE] = Object.create(null);
_[IN_TABLE_MODE][Tokenizer.CHARACTER_TOKEN] =
_[IN_TABLE_MODE][Tokenizer.NULL_CHARACTER_TOKEN] =
_[IN_TABLE_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = characterInTable;
_[IN_TABLE_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_TABLE_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_TABLE_MODE][Tokenizer.START_TAG_TOKEN] = startTagInTable;
_[IN_TABLE_MODE][Tokenizer.END_TAG_TOKEN] = endTagInTable;
_[IN_TABLE_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_TABLE_TEXT_MODE] = Object.create(null);
_[IN_TABLE_TEXT_MODE][Tokenizer.CHARACTER_TOKEN] = characterInTableText;
_[IN_TABLE_TEXT_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_TABLE_TEXT_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInTableText;
_[IN_TABLE_TEXT_MODE][Tokenizer.COMMENT_TOKEN] =
_[IN_TABLE_TEXT_MODE][Tokenizer.DOCTYPE_TOKEN] =
_[IN_TABLE_TEXT_MODE][Tokenizer.START_TAG_TOKEN] =
_[IN_TABLE_TEXT_MODE][Tokenizer.END_TAG_TOKEN] =
_[IN_TABLE_TEXT_MODE][Tokenizer.EOF_TOKEN] = tokenInTableText;

_[IN_CAPTION_MODE] = Object.create(null);
_[IN_CAPTION_MODE][Tokenizer.CHARACTER_TOKEN] = characterInBody;
_[IN_CAPTION_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_CAPTION_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[IN_CAPTION_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_CAPTION_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_CAPTION_MODE][Tokenizer.START_TAG_TOKEN] = startTagInCaption;
_[IN_CAPTION_MODE][Tokenizer.END_TAG_TOKEN] = endTagInCaption;
_[IN_CAPTION_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_COLUMN_GROUP_MODE] = Object.create(null);
_[IN_COLUMN_GROUP_MODE][Tokenizer.CHARACTER_TOKEN] =
_[IN_COLUMN_GROUP_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenInColumnGroup;
_[IN_COLUMN_GROUP_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[IN_COLUMN_GROUP_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_COLUMN_GROUP_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_COLUMN_GROUP_MODE][Tokenizer.START_TAG_TOKEN] = startTagInColumnGroup;
_[IN_COLUMN_GROUP_MODE][Tokenizer.END_TAG_TOKEN] = endTagInColumnGroup;
_[IN_COLUMN_GROUP_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_TABLE_BODY_MODE] = Object.create(null);
_[IN_TABLE_BODY_MODE][Tokenizer.CHARACTER_TOKEN] =
_[IN_TABLE_BODY_MODE][Tokenizer.NULL_CHARACTER_TOKEN] =
_[IN_TABLE_BODY_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = characterInTable;
_[IN_TABLE_BODY_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_TABLE_BODY_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_TABLE_BODY_MODE][Tokenizer.START_TAG_TOKEN] = startTagInTableBody;
_[IN_TABLE_BODY_MODE][Tokenizer.END_TAG_TOKEN] = endTagInTableBody;
_[IN_TABLE_BODY_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_ROW_MODE] = Object.create(null);
_[IN_ROW_MODE][Tokenizer.CHARACTER_TOKEN] =
_[IN_ROW_MODE][Tokenizer.NULL_CHARACTER_TOKEN] =
_[IN_ROW_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = characterInTable;
_[IN_ROW_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_ROW_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_ROW_MODE][Tokenizer.START_TAG_TOKEN] = startTagInRow;
_[IN_ROW_MODE][Tokenizer.END_TAG_TOKEN] = endTagInRow;
_[IN_ROW_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_CELL_MODE] = Object.create(null);
_[IN_CELL_MODE][Tokenizer.CHARACTER_TOKEN] = characterInBody;
_[IN_CELL_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_CELL_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[IN_CELL_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_CELL_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_CELL_MODE][Tokenizer.START_TAG_TOKEN] = startTagInCell;
_[IN_CELL_MODE][Tokenizer.END_TAG_TOKEN] = endTagInCell;
_[IN_CELL_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_SELECT_MODE] = Object.create(null);
_[IN_SELECT_MODE][Tokenizer.CHARACTER_TOKEN] = insertCharacters;
_[IN_SELECT_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_SELECT_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[IN_SELECT_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_SELECT_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_SELECT_MODE][Tokenizer.START_TAG_TOKEN] = startTagInSelect;
_[IN_SELECT_MODE][Tokenizer.END_TAG_TOKEN] = endTagInSelect;
_[IN_SELECT_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_SELECT_IN_TABLE_MODE] = Object.create(null);
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.CHARACTER_TOKEN] = insertCharacters;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.START_TAG_TOKEN] = startTagInSelectInTable;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.END_TAG_TOKEN] = endTagInSelectInTable;
_[IN_SELECT_IN_TABLE_MODE][Tokenizer.EOF_TOKEN] = eofInBody;

_[IN_TEMPLATE_MODE] = Object.create(null);
_[IN_TEMPLATE_MODE][Tokenizer.CHARACTER_TOKEN] = characterInBody;
_[IN_TEMPLATE_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_TEMPLATE_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[IN_TEMPLATE_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_TEMPLATE_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_TEMPLATE_MODE][Tokenizer.START_TAG_TOKEN] = startTagInTemplate;
_[IN_TEMPLATE_MODE][Tokenizer.END_TAG_TOKEN] = endTagInTemplate;
_[IN_TEMPLATE_MODE][Tokenizer.EOF_TOKEN] = eofInTemplate;

_[AFTER_BODY_MODE] = Object.create(null);
_[AFTER_BODY_MODE][Tokenizer.CHARACTER_TOKEN] =
_[AFTER_BODY_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenAfterBody;
_[AFTER_BODY_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[AFTER_BODY_MODE][Tokenizer.COMMENT_TOKEN] = appendCommentToRootHtmlElement;
_[AFTER_BODY_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[AFTER_BODY_MODE][Tokenizer.START_TAG_TOKEN] = startTagAfterBody;
_[AFTER_BODY_MODE][Tokenizer.END_TAG_TOKEN] = endTagAfterBody;
_[AFTER_BODY_MODE][Tokenizer.EOF_TOKEN] = stopParsing;

_[IN_FRAMESET_MODE] = Object.create(null);
_[IN_FRAMESET_MODE][Tokenizer.CHARACTER_TOKEN] =
_[IN_FRAMESET_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[IN_FRAMESET_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[IN_FRAMESET_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[IN_FRAMESET_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[IN_FRAMESET_MODE][Tokenizer.START_TAG_TOKEN] = startTagInFrameset;
_[IN_FRAMESET_MODE][Tokenizer.END_TAG_TOKEN] = endTagInFrameset;
_[IN_FRAMESET_MODE][Tokenizer.EOF_TOKEN] = stopParsing;

_[AFTER_FRAMESET_MODE] = Object.create(null);
_[AFTER_FRAMESET_MODE][Tokenizer.CHARACTER_TOKEN] =
_[AFTER_FRAMESET_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[AFTER_FRAMESET_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = insertCharacters;
_[AFTER_FRAMESET_MODE][Tokenizer.COMMENT_TOKEN] = appendComment;
_[AFTER_FRAMESET_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[AFTER_FRAMESET_MODE][Tokenizer.START_TAG_TOKEN] = startTagAfterFrameset;
_[AFTER_FRAMESET_MODE][Tokenizer.END_TAG_TOKEN] = endTagAfterFrameset;
_[AFTER_FRAMESET_MODE][Tokenizer.EOF_TOKEN] = stopParsing;

_[AFTER_AFTER_BODY_MODE] = Object.create(null);
_[AFTER_AFTER_BODY_MODE][Tokenizer.CHARACTER_TOKEN] = tokenAfterAfterBody;
_[AFTER_AFTER_BODY_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = tokenAfterAfterBody;
_[AFTER_AFTER_BODY_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[AFTER_AFTER_BODY_MODE][Tokenizer.COMMENT_TOKEN] = appendCommentToDocument;
_[AFTER_AFTER_BODY_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[AFTER_AFTER_BODY_MODE][Tokenizer.START_TAG_TOKEN] = startTagAfterAfterBody;
_[AFTER_AFTER_BODY_MODE][Tokenizer.END_TAG_TOKEN] = tokenAfterAfterBody;
_[AFTER_AFTER_BODY_MODE][Tokenizer.EOF_TOKEN] = stopParsing;

_[AFTER_AFTER_FRAMESET_MODE] = Object.create(null);
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.CHARACTER_TOKEN] =
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.NULL_CHARACTER_TOKEN] = ignoreToken;
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.WHITESPACE_CHARACTER_TOKEN] = whitespaceCharacterInBody;
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.COMMENT_TOKEN] = appendCommentToDocument;
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.DOCTYPE_TOKEN] = ignoreToken;
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.START_TAG_TOKEN] = startTagAfterAfterFrameset;
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.END_TAG_TOKEN] = ignoreToken;
_[AFTER_AFTER_FRAMESET_MODE][Tokenizer.EOF_TOKEN] = stopParsing;


//Parser
var Parser = module.exports = function (options) {
    this.options = mergeOptions(DEFAULT_OPTIONS, options);

    this.treeAdapter = this.options.treeAdapter;
    this.pendingScript = null;

    if (this.options.locationInfo)
        new LocationInfoParserMixin(this);
};

// API
Parser.prototype.parse = function (html) {
    var document = this.treeAdapter.createDocument();

    this._bootstrap(document, null);
    this.tokenizer.write(html, true);
    this._runParsingLoop(null);

    return document;
};

Parser.prototype.parseFragment = function (html, fragmentContext) {
    //NOTE: use <template> element as a fragment context if context element was not provided,
    //so we will parse in "forgiving" manner
    if (!fragmentContext)
        fragmentContext = this.treeAdapter.createElement($.TEMPLATE, NS.HTML, []);

    //NOTE: create fake element which will be used as 'document' for fragment parsing.
    //This is important for jsdom there 'document' can't be recreated, therefore
    //fragment parsing causes messing of the main `document`.
    var documentMock = this.treeAdapter.createElement('documentmock', NS.HTML, []);

    this._bootstrap(documentMock, fragmentContext);

    if (this.treeAdapter.getTagName(fragmentContext) === $.TEMPLATE)
        this._pushTmplInsertionMode(IN_TEMPLATE_MODE);

    this._initTokenizerForFragmentParsing();
    this._insertFakeRootElement();
    this._resetInsertionMode();
    this._findFormInFragmentContext();
    this.tokenizer.write(html, true);
    this._runParsingLoop(null);

    var rootElement = this.treeAdapter.getFirstChild(documentMock),
        fragment = this.treeAdapter.createDocumentFragment();

    this._adoptNodes(rootElement, fragment);

    return fragment;
};

//Bootstrap parser
Parser.prototype._bootstrap = function (document, fragmentContext) {
    this.tokenizer = new Tokenizer(this.options);

    this.stopped = false;

    this.insertionMode = INITIAL_MODE;
    this.originalInsertionMode = '';

    this.document = document;
    this.fragmentContext = fragmentContext;

    this.headElement = null;
    this.formElement = null;

    this.openElements = new OpenElementStack(this.document, this.treeAdapter);
    this.activeFormattingElements = new FormattingElementList(this.treeAdapter);

    this.tmplInsertionModeStack = [];
    this.tmplInsertionModeStackTop = -1;
    this.currentTmplInsertionMode = null;

    this.pendingCharacterTokens = [];
    this.hasNonWhitespacePendingCharacterToken = false;

    this.framesetOk = true;
    this.skipNextNewLine = false;
    this.fosterParentingEnabled = false;
};

//Parsing loop
Parser.prototype._runParsingLoop  = function (scriptHandler) {
    while (!this.stopped) {
        this._setupTokenizerCDATAMode();

        var token = this.tokenizer.getNextToken();

        if (token.type === Tokenizer.HIBERNATION_TOKEN)
            break;

        if (this.skipNextNewLine) {
            this.skipNextNewLine = false;

            if (token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN && token.chars[0] === '\n') {
                if (token.chars.length === 1)
                    continue;

                token.chars = token.chars.substr(1);
            }
        }

        this._processInputToken(token);

        if (scriptHandler && this.pendingScript)
            break;
    }
};

Parser.prototype.runParsingLoopForCurrentChunk = function (writeCallback, scriptHandler) {
    this._runParsingLoop(scriptHandler);

    if (scriptHandler && this.pendingScript) {
        var script = this.pendingScript;

        this.pendingScript = null;

        scriptHandler(script);

        return;
    }

    if (writeCallback)
        writeCallback();
};

//Text parsing
Parser.prototype._setupTokenizerCDATAMode = function () {
    var current = this._getAdjustedCurrentElement();

    this.tokenizer.allowCDATA = current && current !== this.document &&
                                this.treeAdapter.getNamespaceURI(current) !== NS.HTML && !this._isIntegrationPoint(current);
};

Parser.prototype._switchToTextParsing = function (currentToken, nextTokenizerState) {
    this._insertElement(currentToken, NS.HTML);
    this.tokenizer.state = nextTokenizerState;
    this.originalInsertionMode = this.insertionMode;
    this.insertionMode = TEXT_MODE;
};

Parser.prototype.switchToPlaintextParsing = function () {
    this.insertionMode = TEXT_MODE;
    this.originalInsertionMode = IN_BODY_MODE;
    this.tokenizer.state = Tokenizer.MODE.PLAINTEXT;
};

//Fragment parsing
Parser.prototype._getAdjustedCurrentElement = function () {
    return this.openElements.stackTop === 0 && this.fragmentContext ?
        this.fragmentContext :
        this.openElements.current;
};

Parser.prototype._findFormInFragmentContext = function () {
    var node = this.fragmentContext;

    do {
        if (this.treeAdapter.getTagName(node) === $.FORM) {
            this.formElement = node;
            break;
        }

        node = this.treeAdapter.getParentNode(node);
    } while (node);
};

Parser.prototype._initTokenizerForFragmentParsing = function () {
    if (this.treeAdapter.getNamespaceURI(this.fragmentContext) === NS.HTML) {
        var tn = this.treeAdapter.getTagName(this.fragmentContext);

        if (tn === $.TITLE || tn === $.TEXTAREA)
            this.tokenizer.state = Tokenizer.MODE.RCDATA;

        else if (tn === $.STYLE || tn === $.XMP || tn === $.IFRAME ||
                 tn === $.NOEMBED || tn === $.NOFRAMES || tn === $.NOSCRIPT)
            this.tokenizer.state = Tokenizer.MODE.RAWTEXT;

        else if (tn === $.SCRIPT)
            this.tokenizer.state = Tokenizer.MODE.SCRIPT_DATA;

        else if (tn === $.PLAINTEXT)
            this.tokenizer.state = Tokenizer.MODE.PLAINTEXT;
    }
};

//Tree mutation
Parser.prototype._setDocumentType = function (token) {
    this.treeAdapter.setDocumentType(this.document, token.name, token.publicId, token.systemId);
};

Parser.prototype._attachElementToTree = function (element) {
    if (this._shouldFosterParentOnInsertion())
        this._fosterParentElement(element);

    else {
        var parent = this.openElements.currentTmplContent || this.openElements.current;

        this.treeAdapter.appendChild(parent, element);
    }
};

Parser.prototype._appendElement = function (token, namespaceURI) {
    var element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);

    this._attachElementToTree(element);
};

Parser.prototype._insertElement = function (token, namespaceURI) {
    var element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);

    this._attachElementToTree(element);
    this.openElements.push(element);
};

Parser.prototype._insertFakeElement = function (tagName) {
    var element = this.treeAdapter.createElement(tagName, NS.HTML, []);

    this._attachElementToTree(element);
    this.openElements.push(element);
};

Parser.prototype._insertTemplate = function (token) {
    var tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs),
        content = this.treeAdapter.createDocumentFragment();

    this.treeAdapter.setTemplateContent(tmpl, content);
    this._attachElementToTree(tmpl);
    this.openElements.push(tmpl);
};

Parser.prototype._insertFakeRootElement = function () {
    var element = this.treeAdapter.createElement($.HTML, NS.HTML, []);

    this.treeAdapter.appendChild(this.openElements.current, element);
    this.openElements.push(element);
};

Parser.prototype._appendCommentNode = function (token, parent) {
    var commentNode = this.treeAdapter.createCommentNode(token.data);

    this.treeAdapter.appendChild(parent, commentNode);
};

Parser.prototype._insertCharacters = function (token) {
    if (this._shouldFosterParentOnInsertion())
        this._fosterParentText(token.chars);

    else {
        var parent = this.openElements.currentTmplContent || this.openElements.current;

        this.treeAdapter.insertText(parent, token.chars);
    }
};

Parser.prototype._adoptNodes = function (donor, recipient) {
    while (true) {
        var child = this.treeAdapter.getFirstChild(donor);

        if (!child)
            break;

        this.treeAdapter.detachNode(child);
        this.treeAdapter.appendChild(recipient, child);
    }
};

//Token processing
Parser.prototype._shouldProcessTokenInForeignContent = function (token) {
    var current = this._getAdjustedCurrentElement();

    if (!current || current === this.document)
        return false;

    var ns = this.treeAdapter.getNamespaceURI(current);

    if (ns === NS.HTML)
        return false;

    if (this.treeAdapter.getTagName(current) === $.ANNOTATION_XML && ns === NS.MATHML &&
        token.type === Tokenizer.START_TAG_TOKEN && token.tagName === $.SVG)
        return false;

    var isCharacterToken = token.type === Tokenizer.CHARACTER_TOKEN ||
                           token.type === Tokenizer.NULL_CHARACTER_TOKEN ||
                           token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN,
        isMathMLTextStartTag = token.type === Tokenizer.START_TAG_TOKEN &&
                               token.tagName !== $.MGLYPH &&
                               token.tagName !== $.MALIGNMARK;

    if ((isMathMLTextStartTag || isCharacterToken) && this._isIntegrationPoint(current, NS.MATHML))
        return false;

    if ((token.type === Tokenizer.START_TAG_TOKEN || isCharacterToken) && this._isIntegrationPoint(current, NS.HTML))
        return false;

    return token.type !== Tokenizer.EOF_TOKEN;
};

Parser.prototype._processToken = function (token) {
    _[this.insertionMode][token.type](this, token);
};

Parser.prototype._processTokenInBodyMode = function (token) {
    _[IN_BODY_MODE][token.type](this, token);
};

Parser.prototype._processTokenInForeignContent = function (token) {
    if (token.type === Tokenizer.CHARACTER_TOKEN)
        characterInForeignContent(this, token);

    else if (token.type === Tokenizer.NULL_CHARACTER_TOKEN)
        nullCharacterInForeignContent(this, token);

    else if (token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN)
        insertCharacters(this, token);

    else if (token.type === Tokenizer.COMMENT_TOKEN)
        appendComment(this, token);

    else if (token.type === Tokenizer.START_TAG_TOKEN)
        startTagInForeignContent(this, token);

    else if (token.type === Tokenizer.END_TAG_TOKEN)
        endTagInForeignContent(this, token);
};

Parser.prototype._processInputToken = function (token) {
    if (this._shouldProcessTokenInForeignContent(token))
        this._processTokenInForeignContent(token);

    else
        this._processToken(token);
};

//Integration points
Parser.prototype._isIntegrationPoint = function (element, foreignNS) {
    var tn = this.treeAdapter.getTagName(element),
        ns = this.treeAdapter.getNamespaceURI(element),
        attrs = this.treeAdapter.getAttrList(element);

    return foreignContent.isIntegrationPoint(tn, ns, attrs, foreignNS);
};

//Active formatting elements reconstruction
Parser.prototype._reconstructActiveFormattingElements = function () {
    var listLength = this.activeFormattingElements.length;

    if (listLength) {
        var unopenIdx = listLength,
            entry = null;

        do {
            unopenIdx--;
            entry = this.activeFormattingElements.entries[unopenIdx];

            if (entry.type === FormattingElementList.MARKER_ENTRY || this.openElements.contains(entry.element)) {
                unopenIdx++;
                break;
            }
        } while (unopenIdx > 0);

        for (var i = unopenIdx; i < listLength; i++) {
            entry = this.activeFormattingElements.entries[i];
            this._insertElement(entry.token, this.treeAdapter.getNamespaceURI(entry.element));
            entry.element = this.openElements.current;
        }
    }
};

//Close elements
Parser.prototype._closeTableCell = function () {
    this.openElements.generateImpliedEndTags();
    this.openElements.popUntilTableCellPopped();
    this.activeFormattingElements.clearToLastMarker();
    this.insertionMode = IN_ROW_MODE;
};

Parser.prototype._closePElement = function () {
    this.openElements.generateImpliedEndTagsWithExclusion($.P);
    this.openElements.popUntilTagNamePopped($.P);
};

//Insertion modes
Parser.prototype._resetInsertionMode = function () {
    for (var i = this.openElements.stackTop, last = false; i >= 0; i--) {
        var element = this.openElements.items[i];

        if (i === 0) {
            last = true;

            if (this.fragmentContext)
                element = this.fragmentContext;
        }

        var tn = this.treeAdapter.getTagName(element),
            newInsertionMode = INSERTION_MODE_RESET_MAP[tn];

        if (newInsertionMode) {
            this.insertionMode = newInsertionMode;
            break;
        }

        else if (!last && (tn === $.TD || tn === $.TH)) {
            this.insertionMode = IN_CELL_MODE;
            break;
        }

        else if (!last && tn === $.HEAD) {
            this.insertionMode = IN_HEAD_MODE;
            break;
        }

        else if (tn === $.SELECT) {
            this._resetInsertionModeForSelect(i);
            break;
        }

        else if (tn === $.TEMPLATE) {
            this.insertionMode = this.currentTmplInsertionMode;
            break;
        }

        else if (tn === $.HTML) {
            this.insertionMode = this.headElement ? AFTER_HEAD_MODE : BEFORE_HEAD_MODE;
            break;
        }

        else if (last) {
            this.insertionMode = IN_BODY_MODE;
            break;
        }
    }
};

Parser.prototype._resetInsertionModeForSelect = function (selectIdx) {
    if (selectIdx > 0) {
        for (var i = selectIdx - 1; i > 0; i--) {
            var ancestor = this.openElements.items[i],
                tn = this.treeAdapter.getTagName(ancestor);

            if (tn === $.TEMPLATE)
                break;

            else if (tn === $.TABLE) {
                this.insertionMode = IN_SELECT_IN_TABLE_MODE;
                return;
            }
        }
    }

    this.insertionMode = IN_SELECT_MODE;
};

Parser.prototype._pushTmplInsertionMode = function (mode) {
    this.tmplInsertionModeStack.push(mode);
    this.tmplInsertionModeStackTop++;
    this.currentTmplInsertionMode = mode;
};

Parser.prototype._popTmplInsertionMode = function () {
    this.tmplInsertionModeStack.pop();
    this.tmplInsertionModeStackTop--;
    this.currentTmplInsertionMode = this.tmplInsertionModeStack[this.tmplInsertionModeStackTop];
};

//Foster parenting
Parser.prototype._isElementCausesFosterParenting = function (element) {
    var tn = this.treeAdapter.getTagName(element);

    return tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR;
};

Parser.prototype._shouldFosterParentOnInsertion = function () {
    return this.fosterParentingEnabled && this._isElementCausesFosterParenting(this.openElements.current);
};

Parser.prototype._findFosterParentingLocation = function () {
    var location = {
        parent: null,
        beforeElement: null
    };

    for (var i = this.openElements.stackTop; i >= 0; i--) {
        var openElement = this.openElements.items[i],
            tn = this.treeAdapter.getTagName(openElement),
            ns = this.treeAdapter.getNamespaceURI(openElement);

        if (tn === $.TEMPLATE && ns === NS.HTML) {
            location.parent = this.treeAdapter.getTemplateContent(openElement);
            break;
        }

        else if (tn === $.TABLE) {
            location.parent = this.treeAdapter.getParentNode(openElement);

            if (location.parent)
                location.beforeElement = openElement;
            else
                location.parent = this.openElements.items[i - 1];

            break;
        }
    }

    if (!location.parent)
        location.parent = this.openElements.items[0];

    return location;
};

Parser.prototype._fosterParentElement = function (element) {
    var location = this._findFosterParentingLocation();

    if (location.beforeElement)
        this.treeAdapter.insertBefore(location.parent, element, location.beforeElement);
    else
        this.treeAdapter.appendChild(location.parent, element);
};

Parser.prototype._fosterParentText = function (chars) {
    var location = this._findFosterParentingLocation();

    if (location.beforeElement)
        this.treeAdapter.insertTextBefore(location.parent, chars, location.beforeElement);
    else
        this.treeAdapter.insertText(location.parent, chars);
};

//Special elements
Parser.prototype._isSpecialElement = function (element) {
    var tn = this.treeAdapter.getTagName(element),
        ns = this.treeAdapter.getNamespaceURI(element);

    return HTML.SPECIAL_ELEMENTS[ns][tn];
};

//Adoption agency algorithm
//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#adoptionAgency)
//------------------------------------------------------------------

//Steps 5-8 of the algorithm
function aaObtainFormattingElementEntry(p, token) {
    var formattingElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName);

    if (formattingElementEntry) {
        if (!p.openElements.contains(formattingElementEntry.element)) {
            p.activeFormattingElements.removeEntry(formattingElementEntry);
            formattingElementEntry = null;
        }

        else if (!p.openElements.hasInScope(token.tagName))
            formattingElementEntry = null;
    }

    else
        genericEndTagInBody(p, token);

    return formattingElementEntry;
}

//Steps 9 and 10 of the algorithm
function aaObtainFurthestBlock(p, formattingElementEntry) {
    var furthestBlock = null;

    for (var i = p.openElements.stackTop; i >= 0; i--) {
        var element = p.openElements.items[i];

        if (element === formattingElementEntry.element)
            break;

        if (p._isSpecialElement(element))
            furthestBlock = element;
    }

    if (!furthestBlock) {
        p.openElements.popUntilElementPopped(formattingElementEntry.element);
        p.activeFormattingElements.removeEntry(formattingElementEntry);
    }

    return furthestBlock;
}

//Step 13 of the algorithm
function aaInnerLoop(p, furthestBlock, formattingElement) {
    var lastElement = furthestBlock,
        nextElement = p.openElements.getCommonAncestor(furthestBlock);

    for (var i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
        //NOTE: store next element for the next loop iteration (it may be deleted from the stack by step 9.5)
        nextElement = p.openElements.getCommonAncestor(element);

        var elementEntry = p.activeFormattingElements.getElementEntry(element),
            counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER,
            shouldRemoveFromOpenElements = !elementEntry || counterOverflow;

        if (shouldRemoveFromOpenElements) {
            if (counterOverflow)
                p.activeFormattingElements.removeEntry(elementEntry);

            p.openElements.remove(element);
        }

        else {
            element = aaRecreateElementFromEntry(p, elementEntry);

            if (lastElement === furthestBlock)
                p.activeFormattingElements.bookmark = elementEntry;

            p.treeAdapter.detachNode(lastElement);
            p.treeAdapter.appendChild(element, lastElement);
            lastElement = element;
        }
    }

    return lastElement;
}

//Step 13.7 of the algorithm
function aaRecreateElementFromEntry(p, elementEntry) {
    var ns = p.treeAdapter.getNamespaceURI(elementEntry.element),
        newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);

    p.openElements.replace(elementEntry.element, newElement);
    elementEntry.element = newElement;

    return newElement;
}

//Step 14 of the algorithm
function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
    if (p._isElementCausesFosterParenting(commonAncestor))
        p._fosterParentElement(lastElement);

    else {
        var tn = p.treeAdapter.getTagName(commonAncestor),
            ns = p.treeAdapter.getNamespaceURI(commonAncestor);

        if (tn === $.TEMPLATE && ns === NS.HTML)
            commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);

        p.treeAdapter.appendChild(commonAncestor, lastElement);
    }
}

//Steps 15-19 of the algorithm
function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
    var ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element),
        token = formattingElementEntry.token,
        newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);

    p._adoptNodes(furthestBlock, newElement);
    p.treeAdapter.appendChild(furthestBlock, newElement);

    p.activeFormattingElements.insertElementAfterBookmark(newElement, formattingElementEntry.token);
    p.activeFormattingElements.removeEntry(formattingElementEntry);

    p.openElements.remove(formattingElementEntry.element);
    p.openElements.insertAfter(furthestBlock, newElement);
}

//Algorithm entry point
function callAdoptionAgency(p, token) {
    var formattingElementEntry;

    for (var i = 0; i < AA_OUTER_LOOP_ITER; i++) {
        formattingElementEntry = aaObtainFormattingElementEntry(p, token, formattingElementEntry);

        if (!formattingElementEntry)
            break;

        var furthestBlock = aaObtainFurthestBlock(p, formattingElementEntry);

        if (!furthestBlock)
            break;

        p.activeFormattingElements.bookmark = formattingElementEntry;

        var lastElement = aaInnerLoop(p, furthestBlock, formattingElementEntry.element),
            commonAncestor = p.openElements.getCommonAncestor(formattingElementEntry.element);

        p.treeAdapter.detachNode(lastElement);
        aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement);
        aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry);
    }
}


//Generic token handlers
//------------------------------------------------------------------
function ignoreToken() {
    //NOTE: do nothing =)
}

function appendComment(p, token) {
    p._appendCommentNode(token, p.openElements.currentTmplContent || p.openElements.current);
}

function appendCommentToRootHtmlElement(p, token) {
    p._appendCommentNode(token, p.openElements.items[0]);
}

function appendCommentToDocument(p, token) {
    p._appendCommentNode(token, p.document);
}

function insertCharacters(p, token) {
    p._insertCharacters(token);
}

function stopParsing(p) {
    p.stopped = true;
}

//12.2.5.4.1 The "initial" insertion mode
//------------------------------------------------------------------
function doctypeInInitialMode(p, token) {
    p._setDocumentType(token);

    var mode = token.forceQuirks ?
        HTML.DOCUMENT_MODE.QUIRKS :
        doctype.getDocumentMode(token.name, token.publicId, token.systemId);

    p.treeAdapter.setDocumentMode(p.document, mode);

    p.insertionMode = BEFORE_HTML_MODE;
}

function tokenInInitialMode(p, token) {
    p.treeAdapter.setDocumentMode(p.document, HTML.DOCUMENT_MODE.QUIRKS);
    p.insertionMode = BEFORE_HTML_MODE;
    p._processToken(token);
}


//12.2.5.4.2 The "before html" insertion mode
//------------------------------------------------------------------
function startTagBeforeHtml(p, token) {
    if (token.tagName === $.HTML) {
        p._insertElement(token, NS.HTML);
        p.insertionMode = BEFORE_HEAD_MODE;
    }

    else
        tokenBeforeHtml(p, token);
}

function endTagBeforeHtml(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML || tn === $.HEAD || tn === $.BODY || tn === $.BR)
        tokenBeforeHtml(p, token);
}

function tokenBeforeHtml(p, token) {
    p._insertFakeRootElement();
    p.insertionMode = BEFORE_HEAD_MODE;
    p._processToken(token);
}


//12.2.5.4.3 The "before head" insertion mode
//------------------------------------------------------------------
function startTagBeforeHead(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.HEAD) {
        p._insertElement(token, NS.HTML);
        p.headElement = p.openElements.current;
        p.insertionMode = IN_HEAD_MODE;
    }

    else
        tokenBeforeHead(p, token);
}

function endTagBeforeHead(p, token) {
    var tn = token.tagName;

    if (tn === $.HEAD || tn === $.BODY || tn === $.HTML || tn === $.BR)
        tokenBeforeHead(p, token);
}

function tokenBeforeHead(p, token) {
    p._insertFakeElement($.HEAD);
    p.headElement = p.openElements.current;
    p.insertionMode = IN_HEAD_MODE;
    p._processToken(token);
}


//12.2.5.4.4 The "in head" insertion mode
//------------------------------------------------------------------
function startTagInHead(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.BASE || tn === $.BASEFONT || tn === $.BGSOUND || tn === $.LINK || tn === $.META)
        p._appendElement(token, NS.HTML);

    else if (tn === $.TITLE)
        p._switchToTextParsing(token, Tokenizer.MODE.RCDATA);

    //NOTE: here we assume that we always act as an interactive user agent with enabled scripting, so we parse
    //<noscript> as a rawtext.
    else if (tn === $.NOSCRIPT || tn === $.NOFRAMES || tn === $.STYLE)
        p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT);

    else if (tn === $.SCRIPT)
        p._switchToTextParsing(token, Tokenizer.MODE.SCRIPT_DATA);

    else if (tn === $.TEMPLATE) {
        p._insertTemplate(token, NS.HTML);
        p.activeFormattingElements.insertMarker();
        p.framesetOk = false;
        p.insertionMode = IN_TEMPLATE_MODE;
        p._pushTmplInsertionMode(IN_TEMPLATE_MODE);
    }

    else if (tn !== $.HEAD)
        tokenInHead(p, token);
}

function endTagInHead(p, token) {
    var tn = token.tagName;

    if (tn === $.HEAD) {
        p.openElements.pop();
        p.insertionMode = AFTER_HEAD_MODE;
    }

    else if (tn === $.BODY || tn === $.BR || tn === $.HTML)
        tokenInHead(p, token);

    else if (tn === $.TEMPLATE && p.openElements.tmplCount > 0) {
        p.openElements.generateImpliedEndTags();
        p.openElements.popUntilTagNamePopped($.TEMPLATE);
        p.activeFormattingElements.clearToLastMarker();
        p._popTmplInsertionMode();
        p._resetInsertionMode();
    }
}

function tokenInHead(p, token) {
    p.openElements.pop();
    p.insertionMode = AFTER_HEAD_MODE;
    p._processToken(token);
}


//12.2.5.4.6 The "after head" insertion mode
//------------------------------------------------------------------
function startTagAfterHead(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.BODY) {
        p._insertElement(token, NS.HTML);
        p.framesetOk = false;
        p.insertionMode = IN_BODY_MODE;
    }

    else if (tn === $.FRAMESET) {
        p._insertElement(token, NS.HTML);
        p.insertionMode = IN_FRAMESET_MODE;
    }

    else if (tn === $.BASE || tn === $.BASEFONT || tn === $.BGSOUND || tn === $.LINK || tn === $.META ||
             tn === $.NOFRAMES || tn === $.SCRIPT || tn === $.STYLE || tn === $.TEMPLATE || tn === $.TITLE) {
        p.openElements.push(p.headElement);
        startTagInHead(p, token);
        p.openElements.remove(p.headElement);
    }

    else if (tn !== $.HEAD)
        tokenAfterHead(p, token);
}

function endTagAfterHead(p, token) {
    var tn = token.tagName;

    if (tn === $.BODY || tn === $.HTML || tn === $.BR)
        tokenAfterHead(p, token);

    else if (tn === $.TEMPLATE)
        endTagInHead(p, token);
}

function tokenAfterHead(p, token) {
    p._insertFakeElement($.BODY);
    p.insertionMode = IN_BODY_MODE;
    p._processToken(token);
}


//12.2.5.4.7 The "in body" insertion mode
//------------------------------------------------------------------
function whitespaceCharacterInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._insertCharacters(token);
}

function characterInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._insertCharacters(token);
    p.framesetOk = false;
}

function htmlStartTagInBody(p, token) {
    if (p.openElements.tmplCount === 0)
        p.treeAdapter.adoptAttributes(p.openElements.items[0], token.attrs);
}

function bodyStartTagInBody(p, token) {
    var bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();

    if (bodyElement && p.openElements.tmplCount === 0) {
        p.framesetOk = false;
        p.treeAdapter.adoptAttributes(bodyElement, token.attrs);
    }
}

function framesetStartTagInBody(p, token) {
    var bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();

    if (p.framesetOk && bodyElement) {
        p.treeAdapter.detachNode(bodyElement);
        p.openElements.popAllUpToHtmlElement();
        p._insertElement(token, NS.HTML);
        p.insertionMode = IN_FRAMESET_MODE;
    }
}

function addressStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    p._insertElement(token, NS.HTML);
}

function numberedHeaderStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    var tn = p.openElements.currentTagName;

    if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6)
        p.openElements.pop();

    p._insertElement(token, NS.HTML);
}

function preStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    p._insertElement(token, NS.HTML);
    //NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move
    //on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)
    p.skipNextNewLine = true;
    p.framesetOk = false;
}

function formStartTagInBody(p, token) {
    var inTemplate = p.openElements.tmplCount > 0;

    if (!p.formElement || inTemplate) {
        if (p.openElements.hasInButtonScope($.P))
            p._closePElement();

        p._insertElement(token, NS.HTML);

        if (!inTemplate)
            p.formElement = p.openElements.current;
    }
}

function listItemStartTagInBody(p, token) {
    p.framesetOk = false;

    var tn = token.tagName;

    for (var i = p.openElements.stackTop; i >= 0; i--) {
        var element = p.openElements.items[i],
            elementTn = p.treeAdapter.getTagName(element),
            closeTn = null;

        if (tn === $.LI && elementTn === $.LI)
            closeTn = $.LI;

        else if ((tn === $.DD || tn === $.DT) && (elementTn === $.DD || elementTn === $.DT))
            closeTn = elementTn;

        if (closeTn) {
            p.openElements.generateImpliedEndTagsWithExclusion(closeTn);
            p.openElements.popUntilTagNamePopped(closeTn);
            break;
        }

        if (elementTn !== $.ADDRESS && elementTn !== $.DIV && elementTn !== $.P && p._isSpecialElement(element))
            break;
    }

    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    p._insertElement(token, NS.HTML);
}

function plaintextStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    p._insertElement(token, NS.HTML);
    p.tokenizer.state = Tokenizer.MODE.PLAINTEXT;
}

function buttonStartTagInBody(p, token) {
    if (p.openElements.hasInScope($.BUTTON)) {
        p.openElements.generateImpliedEndTags();
        p.openElements.popUntilTagNamePopped($.BUTTON);
    }

    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
    p.framesetOk = false;
}

function aStartTagInBody(p, token) {
    var activeElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName($.A);

    if (activeElementEntry) {
        callAdoptionAgency(p, token);
        p.openElements.remove(activeElementEntry.element);
        p.activeFormattingElements.removeEntry(activeElementEntry);
    }

    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
    p.activeFormattingElements.pushElement(p.openElements.current, token);
}

function bStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
    p.activeFormattingElements.pushElement(p.openElements.current, token);
}

function nobrStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();

    if (p.openElements.hasInScope($.NOBR)) {
        callAdoptionAgency(p, token);
        p._reconstructActiveFormattingElements();
    }

    p._insertElement(token, NS.HTML);
    p.activeFormattingElements.pushElement(p.openElements.current, token);
}

function appletStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
    p.activeFormattingElements.insertMarker();
    p.framesetOk = false;
}

function tableStartTagInBody(p, token) {
    if (p.treeAdapter.getDocumentMode(p.document) !== HTML.DOCUMENT_MODE.QUIRKS && p.openElements.hasInButtonScope($.P))
        p._closePElement();

    p._insertElement(token, NS.HTML);
    p.framesetOk = false;
    p.insertionMode = IN_TABLE_MODE;
}

function areaStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._appendElement(token, NS.HTML);
    p.framesetOk = false;
}

function inputStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._appendElement(token, NS.HTML);

    var inputType = Tokenizer.getTokenAttr(token, ATTRS.TYPE);

    if (!inputType || inputType.toLowerCase() !== HIDDEN_INPUT_TYPE)
        p.framesetOk = false;

}

function paramStartTagInBody(p, token) {
    p._appendElement(token, NS.HTML);
}

function hrStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    if (p.openElements.currentTagName === $.MENUITEM)
        p.openElements.pop();

    p._appendElement(token, NS.HTML);
    p.framesetOk = false;
}

function imageStartTagInBody(p, token) {
    token.tagName = $.IMG;
    areaStartTagInBody(p, token);
}

function textareaStartTagInBody(p, token) {
    p._insertElement(token, NS.HTML);
    //NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move
    //on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
    p.skipNextNewLine = true;
    p.tokenizer.state = Tokenizer.MODE.RCDATA;
    p.originalInsertionMode = p.insertionMode;
    p.framesetOk = false;
    p.insertionMode = TEXT_MODE;
}

function xmpStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    p._reconstructActiveFormattingElements();
    p.framesetOk = false;
    p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT);
}

function iframeStartTagInBody(p, token) {
    p.framesetOk = false;
    p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT);
}

//NOTE: here we assume that we always act as an user agent with enabled plugins, so we parse
//<noembed> as a rawtext.
function noembedStartTagInBody(p, token) {
    p._switchToTextParsing(token, Tokenizer.MODE.RAWTEXT);
}

function selectStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
    p.framesetOk = false;

    if (p.insertionMode === IN_TABLE_MODE ||
        p.insertionMode === IN_CAPTION_MODE ||
        p.insertionMode === IN_TABLE_BODY_MODE ||
        p.insertionMode === IN_ROW_MODE ||
        p.insertionMode === IN_CELL_MODE)

        p.insertionMode = IN_SELECT_IN_TABLE_MODE;

    else
        p.insertionMode = IN_SELECT_MODE;
}

function optgroupStartTagInBody(p, token) {
    if (p.openElements.currentTagName === $.OPTION)
        p.openElements.pop();

    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
}

function rbStartTagInBody(p, token) {
    if (p.openElements.hasInScope($.RUBY))
        p.openElements.generateImpliedEndTags();

    p._insertElement(token, NS.HTML);
}

function rtStartTagInBody(p, token) {
    if (p.openElements.hasInScope($.RUBY))
        p.openElements.generateImpliedEndTagsWithExclusion($.RTC);

    p._insertElement(token, NS.HTML);
}

function menuitemStartTagInBody(p, token) {
    if (p.openElements.currentTagName === $.MENUITEM)
        p.openElements.pop();

    // TODO needs clarification, see https://github.com/whatwg/html/pull/907/files#r73505877
    p._reconstructActiveFormattingElements();

    p._insertElement(token, NS.HTML);
}

function menuStartTagInBody(p, token) {
    if (p.openElements.hasInButtonScope($.P))
        p._closePElement();

    if (p.openElements.currentTagName === $.MENUITEM)
        p.openElements.pop();

    p._insertElement(token, NS.HTML);
}

function mathStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();

    foreignContent.adjustTokenMathMLAttrs(token);
    foreignContent.adjustTokenXMLAttrs(token);

    if (token.selfClosing)
        p._appendElement(token, NS.MATHML);
    else
        p._insertElement(token, NS.MATHML);
}

function svgStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();

    foreignContent.adjustTokenSVGAttrs(token);
    foreignContent.adjustTokenXMLAttrs(token);

    if (token.selfClosing)
        p._appendElement(token, NS.SVG);
    else
        p._insertElement(token, NS.SVG);
}

function genericStartTagInBody(p, token) {
    p._reconstructActiveFormattingElements();
    p._insertElement(token, NS.HTML);
}

//OPTIMIZATION: Integer comparisons are low-cost, so we can use very fast tag name length filters here.
//It's faster than using dictionary.
function startTagInBody(p, token) {
    var tn = token.tagName;

    switch (tn.length) {
        case 1:
            if (tn === $.I || tn === $.S || tn === $.B || tn === $.U)
                bStartTagInBody(p, token);

            else if (tn === $.P)
                addressStartTagInBody(p, token);

            else if (tn === $.A)
                aStartTagInBody(p, token);

            else
                genericStartTagInBody(p, token);

            break;

        case 2:
            if (tn === $.DL || tn === $.OL || tn === $.UL)
                addressStartTagInBody(p, token);

            else if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6)
                numberedHeaderStartTagInBody(p, token);

            else if (tn === $.LI || tn === $.DD || tn === $.DT)
                listItemStartTagInBody(p, token);

            else if (tn === $.EM || tn === $.TT)
                bStartTagInBody(p, token);

            else if (tn === $.BR)
                areaStartTagInBody(p, token);

            else if (tn === $.HR)
                hrStartTagInBody(p, token);

            else if (tn === $.RB)
                rbStartTagInBody(p, token);

            else if (tn === $.RT || tn === $.RP)
                rtStartTagInBody(p, token);

            else if (tn !== $.TH && tn !== $.TD && tn !== $.TR)
                genericStartTagInBody(p, token);

            break;

        case 3:
            if (tn === $.DIV || tn === $.DIR || tn === $.NAV)
                addressStartTagInBody(p, token);

            else if (tn === $.PRE)
                preStartTagInBody(p, token);

            else if (tn === $.BIG)
                bStartTagInBody(p, token);

            else if (tn === $.IMG || tn === $.WBR)
                areaStartTagInBody(p, token);

            else if (tn === $.XMP)
                xmpStartTagInBody(p, token);

            else if (tn === $.SVG)
                svgStartTagInBody(p, token);

            else if (tn === $.RTC)
                rbStartTagInBody(p, token);

            else if (tn !== $.COL)
                genericStartTagInBody(p, token);

            break;

        case 4:
            if (tn === $.HTML)
                htmlStartTagInBody(p, token);

            else if (tn === $.BASE || tn === $.LINK || tn === $.META)
                startTagInHead(p, token);

            else if (tn === $.BODY)
                bodyStartTagInBody(p, token);

            else if (tn === $.MAIN)
                addressStartTagInBody(p, token);

            else if (tn === $.FORM)
                formStartTagInBody(p, token);

            else if (tn === $.CODE || tn === $.FONT)
                bStartTagInBody(p, token);

            else if (tn === $.NOBR)
                nobrStartTagInBody(p, token);

            else if (tn === $.AREA)
                areaStartTagInBody(p, token);

            else if (tn === $.MATH)
                mathStartTagInBody(p, token);

            else if (tn === $.MENU)
                menuStartTagInBody(p, token);

            else if (tn !== $.HEAD)
                genericStartTagInBody(p, token);

            break;

        case 5:
            if (tn === $.STYLE || tn === $.TITLE)
                startTagInHead(p, token);

            else if (tn === $.ASIDE)
                addressStartTagInBody(p, token);

            else if (tn === $.SMALL)
                bStartTagInBody(p, token);

            else if (tn === $.TABLE)
                tableStartTagInBody(p, token);

            else if (tn === $.EMBED)
                areaStartTagInBody(p, token);

            else if (tn === $.INPUT)
                inputStartTagInBody(p, token);

            else if (tn === $.PARAM || tn === $.TRACK)
                paramStartTagInBody(p, token);

            else if (tn === $.IMAGE)
                imageStartTagInBody(p, token);

            else if (tn !== $.FRAME && tn !== $.TBODY && tn !== $.TFOOT && tn !== $.THEAD)
                genericStartTagInBody(p, token);

            break;

        case 6:
            if (tn === $.SCRIPT)
                startTagInHead(p, token);

            else if (tn === $.CENTER || tn === $.FIGURE || tn === $.FOOTER || tn === $.HEADER || tn === $.HGROUP)
                addressStartTagInBody(p, token);

            else if (tn === $.BUTTON)
                buttonStartTagInBody(p, token);

            else if (tn === $.STRIKE || tn === $.STRONG)
                bStartTagInBody(p, token);

            else if (tn === $.APPLET || tn === $.OBJECT)
                appletStartTagInBody(p, token);

            else if (tn === $.KEYGEN)
                areaStartTagInBody(p, token);

            else if (tn === $.SOURCE)
                paramStartTagInBody(p, token);

            else if (tn === $.IFRAME)
                iframeStartTagInBody(p, token);

            else if (tn === $.SELECT)
                selectStartTagInBody(p, token);

            else if (tn === $.OPTION)
                optgroupStartTagInBody(p, token);

            else
                genericStartTagInBody(p, token);

            break;

        case 7:
            if (tn === $.BGSOUND)
                startTagInHead(p, token);

            else if (tn === $.DETAILS || tn === $.ADDRESS || tn === $.ARTICLE || tn === $.SECTION || tn === $.SUMMARY)
                addressStartTagInBody(p, token);

            else if (tn === $.LISTING)
                preStartTagInBody(p, token);

            else if (tn === $.MARQUEE)
                appletStartTagInBody(p, token);

            else if (tn === $.NOEMBED)
                noembedStartTagInBody(p, token);

            else if (tn !== $.CAPTION)
                genericStartTagInBody(p, token);

            break;

        case 8:
            if (tn === $.BASEFONT)
                startTagInHead(p, token);

            else if (tn === $.MENUITEM)
                menuitemStartTagInBody(p, token);

            else if (tn === $.FRAMESET)
                framesetStartTagInBody(p, token);

            else if (tn === $.FIELDSET)
                addressStartTagInBody(p, token);

            else if (tn === $.TEXTAREA)
                textareaStartTagInBody(p, token);

            else if (tn === $.TEMPLATE)
                startTagInHead(p, token);

            else if (tn === $.NOSCRIPT)
                noembedStartTagInBody(p, token);

            else if (tn === $.OPTGROUP)
                optgroupStartTagInBody(p, token);

            else if (tn !== $.COLGROUP)
                genericStartTagInBody(p, token);

            break;

        case 9:
            if (tn === $.PLAINTEXT)
                plaintextStartTagInBody(p, token);

            else
                genericStartTagInBody(p, token);

            break;

        case 10:
            if (tn === $.BLOCKQUOTE || tn === $.FIGCAPTION)
                addressStartTagInBody(p, token);

            else
                genericStartTagInBody(p, token);

            break;

        default:
            genericStartTagInBody(p, token);
    }
}

function bodyEndTagInBody(p) {
    if (p.openElements.hasInScope($.BODY))
        p.insertionMode = AFTER_BODY_MODE;
}

function htmlEndTagInBody(p, token) {
    if (p.openElements.hasInScope($.BODY)) {
        p.insertionMode = AFTER_BODY_MODE;
        p._processToken(token);
    }
}

function addressEndTagInBody(p, token) {
    var tn = token.tagName;

    if (p.openElements.hasInScope(tn)) {
        p.openElements.generateImpliedEndTags();
        p.openElements.popUntilTagNamePopped(tn);
    }
}

function formEndTagInBody(p) {
    var inTemplate = p.openElements.tmplCount > 0,
        formElement = p.formElement;

    if (!inTemplate)
        p.formElement = null;

    if ((formElement || inTemplate) && p.openElements.hasInScope($.FORM)) {
        p.openElements.generateImpliedEndTags();

        if (inTemplate)
            p.openElements.popUntilTagNamePopped($.FORM);

        else
            p.openElements.remove(formElement);
    }
}

function pEndTagInBody(p) {
    if (!p.openElements.hasInButtonScope($.P))
        p._insertFakeElement($.P);

    p._closePElement();
}

function liEndTagInBody(p) {
    if (p.openElements.hasInListItemScope($.LI)) {
        p.openElements.generateImpliedEndTagsWithExclusion($.LI);
        p.openElements.popUntilTagNamePopped($.LI);
    }
}

function ddEndTagInBody(p, token) {
    var tn = token.tagName;

    if (p.openElements.hasInScope(tn)) {
        p.openElements.generateImpliedEndTagsWithExclusion(tn);
        p.openElements.popUntilTagNamePopped(tn);
    }
}

function numberedHeaderEndTagInBody(p) {
    if (p.openElements.hasNumberedHeaderInScope()) {
        p.openElements.generateImpliedEndTags();
        p.openElements.popUntilNumberedHeaderPopped();
    }
}

function appletEndTagInBody(p, token) {
    var tn = token.tagName;

    if (p.openElements.hasInScope(tn)) {
        p.openElements.generateImpliedEndTags();
        p.openElements.popUntilTagNamePopped(tn);
        p.activeFormattingElements.clearToLastMarker();
    }
}

function brEndTagInBody(p) {
    p._reconstructActiveFormattingElements();
    p._insertFakeElement($.BR);
    p.openElements.pop();
    p.framesetOk = false;
}

function genericEndTagInBody(p, token) {
    var tn = token.tagName;

    for (var i = p.openElements.stackTop; i > 0; i--) {
        var element = p.openElements.items[i];

        if (p.treeAdapter.getTagName(element) === tn) {
            p.openElements.generateImpliedEndTagsWithExclusion(tn);
            p.openElements.popUntilElementPopped(element);
            break;
        }

        if (p._isSpecialElement(element))
            break;
    }
}

//OPTIMIZATION: Integer comparisons are low-cost, so we can use very fast tag name length filters here.
//It's faster than using dictionary.
function endTagInBody(p, token) {
    var tn = token.tagName;

    switch (tn.length) {
        case 1:
            if (tn === $.A || tn === $.B || tn === $.I || tn === $.S || tn === $.U)
                callAdoptionAgency(p, token);

            else if (tn === $.P)
                pEndTagInBody(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 2:
            if (tn === $.DL || tn === $.UL || tn === $.OL)
                addressEndTagInBody(p, token);

            else if (tn === $.LI)
                liEndTagInBody(p, token);

            else if (tn === $.DD || tn === $.DT)
                ddEndTagInBody(p, token);

            else if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6)
                numberedHeaderEndTagInBody(p, token);

            else if (tn === $.BR)
                brEndTagInBody(p, token);

            else if (tn === $.EM || tn === $.TT)
                callAdoptionAgency(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 3:
            if (tn === $.BIG)
                callAdoptionAgency(p, token);

            else if (tn === $.DIR || tn === $.DIV || tn === $.NAV)
                addressEndTagInBody(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 4:
            if (tn === $.BODY)
                bodyEndTagInBody(p, token);

            else if (tn === $.HTML)
                htmlEndTagInBody(p, token);

            else if (tn === $.FORM)
                formEndTagInBody(p, token);

            else if (tn === $.CODE || tn === $.FONT || tn === $.NOBR)
                callAdoptionAgency(p, token);

            else if (tn === $.MAIN || tn === $.MENU)
                addressEndTagInBody(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 5:
            if (tn === $.ASIDE)
                addressEndTagInBody(p, token);

            else if (tn === $.SMALL)
                callAdoptionAgency(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 6:
            if (tn === $.CENTER || tn === $.FIGURE || tn === $.FOOTER || tn === $.HEADER || tn === $.HGROUP)
                addressEndTagInBody(p, token);

            else if (tn === $.APPLET || tn === $.OBJECT)
                appletEndTagInBody(p, token);

            else if (tn === $.STRIKE || tn === $.STRONG)
                callAdoptionAgency(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 7:
            if (tn === $.ADDRESS || tn === $.ARTICLE || tn === $.DETAILS || tn === $.SECTION || tn === $.SUMMARY)
                addressEndTagInBody(p, token);

            else if (tn === $.MARQUEE)
                appletEndTagInBody(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 8:
            if (tn === $.FIELDSET)
                addressEndTagInBody(p, token);

            else if (tn === $.TEMPLATE)
                endTagInHead(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        case 10:
            if (tn === $.BLOCKQUOTE || tn === $.FIGCAPTION)
                addressEndTagInBody(p, token);

            else
                genericEndTagInBody(p, token);

            break;

        default :
            genericEndTagInBody(p, token);
    }
}

function eofInBody(p, token) {
    if (p.tmplInsertionModeStackTop > -1)
        eofInTemplate(p, token);

    else
        p.stopped = true;
}

//12.2.5.4.8 The "text" insertion mode
//------------------------------------------------------------------
function endTagInText(p, token) {
    if (token.tagName === $.SCRIPT)
        p.pendingScript = p.openElements.current;

    p.openElements.pop();
    p.insertionMode = p.originalInsertionMode;
}


function eofInText(p, token) {
    p.openElements.pop();
    p.insertionMode = p.originalInsertionMode;
    p._processToken(token);
}


//12.2.5.4.9 The "in table" insertion mode
//------------------------------------------------------------------
function characterInTable(p, token) {
    var curTn = p.openElements.currentTagName;

    if (curTn === $.TABLE || curTn === $.TBODY || curTn === $.TFOOT || curTn === $.THEAD || curTn === $.TR) {
        p.pendingCharacterTokens = [];
        p.hasNonWhitespacePendingCharacterToken = false;
        p.originalInsertionMode = p.insertionMode;
        p.insertionMode = IN_TABLE_TEXT_MODE;
        p._processToken(token);
    }

    else
        tokenInTable(p, token);
}

function captionStartTagInTable(p, token) {
    p.openElements.clearBackToTableContext();
    p.activeFormattingElements.insertMarker();
    p._insertElement(token, NS.HTML);
    p.insertionMode = IN_CAPTION_MODE;
}

function colgroupStartTagInTable(p, token) {
    p.openElements.clearBackToTableContext();
    p._insertElement(token, NS.HTML);
    p.insertionMode = IN_COLUMN_GROUP_MODE;
}

function colStartTagInTable(p, token) {
    p.openElements.clearBackToTableContext();
    p._insertFakeElement($.COLGROUP);
    p.insertionMode = IN_COLUMN_GROUP_MODE;
    p._processToken(token);
}

function tbodyStartTagInTable(p, token) {
    p.openElements.clearBackToTableContext();
    p._insertElement(token, NS.HTML);
    p.insertionMode = IN_TABLE_BODY_MODE;
}

function tdStartTagInTable(p, token) {
    p.openElements.clearBackToTableContext();
    p._insertFakeElement($.TBODY);
    p.insertionMode = IN_TABLE_BODY_MODE;
    p._processToken(token);
}

function tableStartTagInTable(p, token) {
    if (p.openElements.hasInTableScope($.TABLE)) {
        p.openElements.popUntilTagNamePopped($.TABLE);
        p._resetInsertionMode();
        p._processToken(token);
    }
}

function inputStartTagInTable(p, token) {
    var inputType = Tokenizer.getTokenAttr(token, ATTRS.TYPE);

    if (inputType && inputType.toLowerCase() === HIDDEN_INPUT_TYPE)
        p._appendElement(token, NS.HTML);

    else
        tokenInTable(p, token);
}

function formStartTagInTable(p, token) {
    if (!p.formElement && p.openElements.tmplCount === 0) {
        p._insertElement(token, NS.HTML);
        p.formElement = p.openElements.current;
        p.openElements.pop();
    }
}

function startTagInTable(p, token) {
    var tn = token.tagName;

    switch (tn.length) {
        case 2:
            if (tn === $.TD || tn === $.TH || tn === $.TR)
                tdStartTagInTable(p, token);

            else
                tokenInTable(p, token);

            break;

        case 3:
            if (tn === $.COL)
                colStartTagInTable(p, token);

            else
                tokenInTable(p, token);

            break;

        case 4:
            if (tn === $.FORM)
                formStartTagInTable(p, token);

            else
                tokenInTable(p, token);

            break;

        case 5:
            if (tn === $.TABLE)
                tableStartTagInTable(p, token);

            else if (tn === $.STYLE)
                startTagInHead(p, token);

            else if (tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD)
                tbodyStartTagInTable(p, token);

            else if (tn === $.INPUT)
                inputStartTagInTable(p, token);

            else
                tokenInTable(p, token);

            break;

        case 6:
            if (tn === $.SCRIPT)
                startTagInHead(p, token);

            else
                tokenInTable(p, token);

            break;

        case 7:
            if (tn === $.CAPTION)
                captionStartTagInTable(p, token);

            else
                tokenInTable(p, token);

            break;

        case 8:
            if (tn === $.COLGROUP)
                colgroupStartTagInTable(p, token);

            else if (tn === $.TEMPLATE)
                startTagInHead(p, token);

            else
                tokenInTable(p, token);

            break;

        default:
            tokenInTable(p, token);
    }

}

function endTagInTable(p, token) {
    var tn = token.tagName;

    if (tn === $.TABLE) {
        if (p.openElements.hasInTableScope($.TABLE)) {
            p.openElements.popUntilTagNamePopped($.TABLE);
            p._resetInsertionMode();
        }
    }

    else if (tn === $.TEMPLATE)
        endTagInHead(p, token);

    else if (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP && tn !== $.HTML &&
             tn !== $.TBODY && tn !== $.TD && tn !== $.TFOOT && tn !== $.TH && tn !== $.THEAD && tn !== $.TR)
        tokenInTable(p, token);
}

function tokenInTable(p, token) {
    var savedFosterParentingState = p.fosterParentingEnabled;

    p.fosterParentingEnabled = true;
    p._processTokenInBodyMode(token);
    p.fosterParentingEnabled = savedFosterParentingState;
}


//12.2.5.4.10 The "in table text" insertion mode
//------------------------------------------------------------------
function whitespaceCharacterInTableText(p, token) {
    p.pendingCharacterTokens.push(token);
}

function characterInTableText(p, token) {
    p.pendingCharacterTokens.push(token);
    p.hasNonWhitespacePendingCharacterToken = true;
}

function tokenInTableText(p, token) {
    var i = 0;

    if (p.hasNonWhitespacePendingCharacterToken) {
        for (; i < p.pendingCharacterTokens.length; i++)
            tokenInTable(p, p.pendingCharacterTokens[i]);
    }

    else {
        for (; i < p.pendingCharacterTokens.length; i++)
            p._insertCharacters(p.pendingCharacterTokens[i]);
    }

    p.insertionMode = p.originalInsertionMode;
    p._processToken(token);
}


//12.2.5.4.11 The "in caption" insertion mode
//------------------------------------------------------------------
function startTagInCaption(p, token) {
    var tn = token.tagName;

    if (tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY ||
        tn === $.TD || tn === $.TFOOT || tn === $.TH || tn === $.THEAD || tn === $.TR) {
        if (p.openElements.hasInTableScope($.CAPTION)) {
            p.openElements.generateImpliedEndTags();
            p.openElements.popUntilTagNamePopped($.CAPTION);
            p.activeFormattingElements.clearToLastMarker();
            p.insertionMode = IN_TABLE_MODE;
            p._processToken(token);
        }
    }

    else
        startTagInBody(p, token);
}

function endTagInCaption(p, token) {
    var tn = token.tagName;

    if (tn === $.CAPTION || tn === $.TABLE) {
        if (p.openElements.hasInTableScope($.CAPTION)) {
            p.openElements.generateImpliedEndTags();
            p.openElements.popUntilTagNamePopped($.CAPTION);
            p.activeFormattingElements.clearToLastMarker();
            p.insertionMode = IN_TABLE_MODE;

            if (tn === $.TABLE)
                p._processToken(token);
        }
    }

    else if (tn !== $.BODY && tn !== $.COL && tn !== $.COLGROUP && tn !== $.HTML && tn !== $.TBODY &&
             tn !== $.TD && tn !== $.TFOOT && tn !== $.TH && tn !== $.THEAD && tn !== $.TR)
        endTagInBody(p, token);
}


//12.2.5.4.12 The "in column group" insertion mode
//------------------------------------------------------------------
function startTagInColumnGroup(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.COL)
        p._appendElement(token, NS.HTML);

    else if (tn === $.TEMPLATE)
        startTagInHead(p, token);

    else
        tokenInColumnGroup(p, token);
}

function endTagInColumnGroup(p, token) {
    var tn = token.tagName;

    if (tn === $.COLGROUP) {
        if (p.openElements.currentTagName === $.COLGROUP) {
            p.openElements.pop();
            p.insertionMode = IN_TABLE_MODE;
        }
    }

    else if (tn === $.TEMPLATE)
        endTagInHead(p, token);

    else if (tn !== $.COL)
        tokenInColumnGroup(p, token);
}

function tokenInColumnGroup(p, token) {
    if (p.openElements.currentTagName === $.COLGROUP) {
        p.openElements.pop();
        p.insertionMode = IN_TABLE_MODE;
        p._processToken(token);
    }
}

//12.2.5.4.13 The "in table body" insertion mode
//------------------------------------------------------------------
function startTagInTableBody(p, token) {
    var tn = token.tagName;

    if (tn === $.TR) {
        p.openElements.clearBackToTableBodyContext();
        p._insertElement(token, NS.HTML);
        p.insertionMode = IN_ROW_MODE;
    }

    else if (tn === $.TH || tn === $.TD) {
        p.openElements.clearBackToTableBodyContext();
        p._insertFakeElement($.TR);
        p.insertionMode = IN_ROW_MODE;
        p._processToken(token);
    }

    else if (tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP ||
             tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD) {

        if (p.openElements.hasTableBodyContextInTableScope()) {
            p.openElements.clearBackToTableBodyContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_MODE;
            p._processToken(token);
        }
    }

    else
        startTagInTable(p, token);
}

function endTagInTableBody(p, token) {
    var tn = token.tagName;

    if (tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD) {
        if (p.openElements.hasInTableScope(tn)) {
            p.openElements.clearBackToTableBodyContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_MODE;
        }
    }

    else if (tn === $.TABLE) {
        if (p.openElements.hasTableBodyContextInTableScope()) {
            p.openElements.clearBackToTableBodyContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_MODE;
            p._processToken(token);
        }
    }

    else if (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP ||
             tn !== $.HTML && tn !== $.TD && tn !== $.TH && tn !== $.TR)
        endTagInTable(p, token);
}

//12.2.5.4.14 The "in row" insertion mode
//------------------------------------------------------------------
function startTagInRow(p, token) {
    var tn = token.tagName;

    if (tn === $.TH || tn === $.TD) {
        p.openElements.clearBackToTableRowContext();
        p._insertElement(token, NS.HTML);
        p.insertionMode = IN_CELL_MODE;
        p.activeFormattingElements.insertMarker();
    }

    else if (tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY ||
             tn === $.TFOOT || tn === $.THEAD || tn === $.TR) {
        if (p.openElements.hasInTableScope($.TR)) {
            p.openElements.clearBackToTableRowContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_BODY_MODE;
            p._processToken(token);
        }
    }

    else
        startTagInTable(p, token);
}

function endTagInRow(p, token) {
    var tn = token.tagName;

    if (tn === $.TR) {
        if (p.openElements.hasInTableScope($.TR)) {
            p.openElements.clearBackToTableRowContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_BODY_MODE;
        }
    }

    else if (tn === $.TABLE) {
        if (p.openElements.hasInTableScope($.TR)) {
            p.openElements.clearBackToTableRowContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_BODY_MODE;
            p._processToken(token);
        }
    }

    else if (tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD) {
        if (p.openElements.hasInTableScope(tn) || p.openElements.hasInTableScope($.TR)) {
            p.openElements.clearBackToTableRowContext();
            p.openElements.pop();
            p.insertionMode = IN_TABLE_BODY_MODE;
            p._processToken(token);
        }
    }

    else if (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP ||
             tn !== $.HTML && tn !== $.TD && tn !== $.TH)
        endTagInTable(p, token);
}


//12.2.5.4.15 The "in cell" insertion mode
//------------------------------------------------------------------
function startTagInCell(p, token) {
    var tn = token.tagName;

    if (tn === $.CAPTION || tn === $.COL || tn === $.COLGROUP || tn === $.TBODY ||
        tn === $.TD || tn === $.TFOOT || tn === $.TH || tn === $.THEAD || tn === $.TR) {

        if (p.openElements.hasInTableScope($.TD) || p.openElements.hasInTableScope($.TH)) {
            p._closeTableCell();
            p._processToken(token);
        }
    }

    else
        startTagInBody(p, token);
}

function endTagInCell(p, token) {
    var tn = token.tagName;

    if (tn === $.TD || tn === $.TH) {
        if (p.openElements.hasInTableScope(tn)) {
            p.openElements.generateImpliedEndTags();
            p.openElements.popUntilTagNamePopped(tn);
            p.activeFormattingElements.clearToLastMarker();
            p.insertionMode = IN_ROW_MODE;
        }
    }

    else if (tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT || tn === $.THEAD || tn === $.TR) {
        if (p.openElements.hasInTableScope(tn)) {
            p._closeTableCell();
            p._processToken(token);
        }
    }

    else if (tn !== $.BODY && tn !== $.CAPTION && tn !== $.COL && tn !== $.COLGROUP && tn !== $.HTML)
        endTagInBody(p, token);
}

//12.2.5.4.16 The "in select" insertion mode
//------------------------------------------------------------------
function startTagInSelect(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.OPTION) {
        if (p.openElements.currentTagName === $.OPTION)
            p.openElements.pop();

        p._insertElement(token, NS.HTML);
    }

    else if (tn === $.OPTGROUP) {
        if (p.openElements.currentTagName === $.OPTION)
            p.openElements.pop();

        if (p.openElements.currentTagName === $.OPTGROUP)
            p.openElements.pop();

        p._insertElement(token, NS.HTML);
    }

    else if (tn === $.INPUT || tn === $.KEYGEN || tn === $.TEXTAREA || tn === $.SELECT) {
        if (p.openElements.hasInSelectScope($.SELECT)) {
            p.openElements.popUntilTagNamePopped($.SELECT);
            p._resetInsertionMode();

            if (tn !== $.SELECT)
                p._processToken(token);
        }
    }

    else if (tn === $.SCRIPT || tn === $.TEMPLATE)
        startTagInHead(p, token);
}

function endTagInSelect(p, token) {
    var tn = token.tagName;

    if (tn === $.OPTGROUP) {
        var prevOpenElement = p.openElements.items[p.openElements.stackTop - 1],
            prevOpenElementTn = prevOpenElement && p.treeAdapter.getTagName(prevOpenElement);

        if (p.openElements.currentTagName === $.OPTION && prevOpenElementTn === $.OPTGROUP)
            p.openElements.pop();

        if (p.openElements.currentTagName === $.OPTGROUP)
            p.openElements.pop();
    }

    else if (tn === $.OPTION) {
        if (p.openElements.currentTagName === $.OPTION)
            p.openElements.pop();
    }

    else if (tn === $.SELECT && p.openElements.hasInSelectScope($.SELECT)) {
        p.openElements.popUntilTagNamePopped($.SELECT);
        p._resetInsertionMode();
    }

    else if (tn === $.TEMPLATE)
        endTagInHead(p, token);
}

//12.2.5.4.17 The "in select in table" insertion mode
//------------------------------------------------------------------
function startTagInSelectInTable(p, token) {
    var tn = token.tagName;

    if (tn === $.CAPTION || tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT ||
        tn === $.THEAD || tn === $.TR || tn === $.TD || tn === $.TH) {
        p.openElements.popUntilTagNamePopped($.SELECT);
        p._resetInsertionMode();
        p._processToken(token);
    }

    else
        startTagInSelect(p, token);
}

function endTagInSelectInTable(p, token) {
    var tn = token.tagName;

    if (tn === $.CAPTION || tn === $.TABLE || tn === $.TBODY || tn === $.TFOOT ||
        tn === $.THEAD || tn === $.TR || tn === $.TD || tn === $.TH) {
        if (p.openElements.hasInTableScope(tn)) {
            p.openElements.popUntilTagNamePopped($.SELECT);
            p._resetInsertionMode();
            p._processToken(token);
        }
    }

    else
        endTagInSelect(p, token);
}

//12.2.5.4.18 The "in template" insertion mode
//------------------------------------------------------------------
function startTagInTemplate(p, token) {
    var tn = token.tagName;

    if (tn === $.BASE || tn === $.BASEFONT || tn === $.BGSOUND || tn === $.LINK || tn === $.META ||
        tn === $.NOFRAMES || tn === $.SCRIPT || tn === $.STYLE || tn === $.TEMPLATE || tn === $.TITLE)
        startTagInHead(p, token);

    else {
        var newInsertionMode = TEMPLATE_INSERTION_MODE_SWITCH_MAP[tn] || IN_BODY_MODE;

        p._popTmplInsertionMode();
        p._pushTmplInsertionMode(newInsertionMode);
        p.insertionMode = newInsertionMode;
        p._processToken(token);
    }
}

function endTagInTemplate(p, token) {
    if (token.tagName === $.TEMPLATE)
        endTagInHead(p, token);
}

function eofInTemplate(p, token) {
    if (p.openElements.tmplCount > 0) {
        p.openElements.popUntilTagNamePopped($.TEMPLATE);
        p.activeFormattingElements.clearToLastMarker();
        p._popTmplInsertionMode();
        p._resetInsertionMode();
        p._processToken(token);
    }

    else
        p.stopped = true;
}


//12.2.5.4.19 The "after body" insertion mode
//------------------------------------------------------------------
function startTagAfterBody(p, token) {
    if (token.tagName === $.HTML)
        startTagInBody(p, token);

    else
        tokenAfterBody(p, token);
}

function endTagAfterBody(p, token) {
    if (token.tagName === $.HTML) {
        if (!p.fragmentContext)
            p.insertionMode = AFTER_AFTER_BODY_MODE;
    }

    else
        tokenAfterBody(p, token);
}

function tokenAfterBody(p, token) {
    p.insertionMode = IN_BODY_MODE;
    p._processToken(token);
}

//12.2.5.4.20 The "in frameset" insertion mode
//------------------------------------------------------------------
function startTagInFrameset(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.FRAMESET)
        p._insertElement(token, NS.HTML);

    else if (tn === $.FRAME)
        p._appendElement(token, NS.HTML);

    else if (tn === $.NOFRAMES)
        startTagInHead(p, token);
}

function endTagInFrameset(p, token) {
    if (token.tagName === $.FRAMESET && !p.openElements.isRootHtmlElementCurrent()) {
        p.openElements.pop();

        if (!p.fragmentContext && p.openElements.currentTagName !== $.FRAMESET)
            p.insertionMode = AFTER_FRAMESET_MODE;
    }
}

//12.2.5.4.21 The "after frameset" insertion mode
//------------------------------------------------------------------
function startTagAfterFrameset(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.NOFRAMES)
        startTagInHead(p, token);
}

function endTagAfterFrameset(p, token) {
    if (token.tagName === $.HTML)
        p.insertionMode = AFTER_AFTER_FRAMESET_MODE;
}

//12.2.5.4.22 The "after after body" insertion mode
//------------------------------------------------------------------
function startTagAfterAfterBody(p, token) {
    if (token.tagName === $.HTML)
        startTagInBody(p, token);

    else
        tokenAfterAfterBody(p, token);
}

function tokenAfterAfterBody(p, token) {
    p.insertionMode = IN_BODY_MODE;
    p._processToken(token);
}

//12.2.5.4.23 The "after after frameset" insertion mode
//------------------------------------------------------------------
function startTagAfterAfterFrameset(p, token) {
    var tn = token.tagName;

    if (tn === $.HTML)
        startTagInBody(p, token);

    else if (tn === $.NOFRAMES)
        startTagInHead(p, token);
}


//12.2.5.5 The rules for parsing tokens in foreign content
//------------------------------------------------------------------
function nullCharacterInForeignContent(p, token) {
    token.chars = UNICODE.REPLACEMENT_CHARACTER;
    p._insertCharacters(token);
}

function characterInForeignContent(p, token) {
    p._insertCharacters(token);
    p.framesetOk = false;
}

function startTagInForeignContent(p, token) {
    if (foreignContent.causesExit(token) && !p.fragmentContext) {
        while (p.treeAdapter.getNamespaceURI(p.openElements.current) !== NS.HTML && !p._isIntegrationPoint(p.openElements.current))
            p.openElements.pop();

        p._processToken(token);
    }

    else {
        var current = p._getAdjustedCurrentElement(),
            currentNs = p.treeAdapter.getNamespaceURI(current);

        if (currentNs === NS.MATHML)
            foreignContent.adjustTokenMathMLAttrs(token);

        else if (currentNs === NS.SVG) {
            foreignContent.adjustTokenSVGTagName(token);
            foreignContent.adjustTokenSVGAttrs(token);
        }

        foreignContent.adjustTokenXMLAttrs(token);

        if (token.selfClosing)
            p._appendElement(token, currentNs);
        else
            p._insertElement(token, currentNs);
    }
}

function endTagInForeignContent(p, token) {
    for (var i = p.openElements.stackTop; i > 0; i--) {
        var element = p.openElements.items[i];

        if (p.treeAdapter.getNamespaceURI(element) === NS.HTML) {
            p._processToken(token);
            break;
        }

        if (p.treeAdapter.getTagName(element).toLowerCase() === token.tagName) {
            p.openElements.popUntilElementPopped(element);
            break;
        }
    }
}


/***/ }),
/* 463 */
/***/ (function(module, exports, __nested_webpack_require_2488504__) {

"use strict";


var Mixin = __nested_webpack_require_2488504__(201),
    Tokenizer = __nested_webpack_require_2488504__(124),
    PositionTrackingPreprocessorMixin = __nested_webpack_require_2488504__(464),
    inherits = __nested_webpack_require_2488504__(71).inherits;

var LocationInfoTokenizerMixin = module.exports = function (tokenizer) {
    Mixin.call(this, tokenizer);

    this.tokenizer = tokenizer;
    this.posTracker = new PositionTrackingPreprocessorMixin(tokenizer.preprocessor);
    this.currentAttrLocation = null;
    this.currentTokenLocation = null;
};

inherits(LocationInfoTokenizerMixin, Mixin);

LocationInfoTokenizerMixin.prototype._getCurrentLocation = function () {
    return {
        line: this.posTracker.line,
        col: this.posTracker.col,
        startOffset: this.posTracker.offset,
        endOffset: -1
    };
};

LocationInfoTokenizerMixin.prototype._attachCurrentAttrLocationInfo = function () {
    this.currentAttrLocation.endOffset = this.posTracker.offset;

    var currentToken = this.tokenizer.currentToken,
        currentAttr = this.tokenizer.currentAttr;

    if (!currentToken.location.attrs)
        currentToken.location.attrs = Object.create(null);

    currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation;
};

LocationInfoTokenizerMixin.prototype._getOverriddenMethods = function (mxn, orig) {
    var methods = {
        _createStartTagToken: function () {
            orig._createStartTagToken.call(this);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createEndTagToken: function () {
            orig._createEndTagToken.call(this);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createCommentToken: function () {
            orig._createCommentToken.call(this);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createDoctypeToken: function (initialName) {
            orig._createDoctypeToken.call(this, initialName);
            this.currentToken.location = mxn.currentTokenLocation;
        },

        _createCharacterToken: function (type, ch) {
            orig._createCharacterToken.call(this, type, ch);
            this.currentCharacterToken.location = mxn.currentTokenLocation;
        },

        _createAttr: function (attrNameFirstCh) {
            orig._createAttr.call(this, attrNameFirstCh);
            mxn.currentAttrLocation = mxn._getCurrentLocation();
        },

        _leaveAttrName: function (toState) {
            orig._leaveAttrName.call(this, toState);
            mxn._attachCurrentAttrLocationInfo();
        },

        _leaveAttrValue: function (toState) {
            orig._leaveAttrValue.call(this, toState);
            mxn._attachCurrentAttrLocationInfo();
        },

        _emitCurrentToken: function () {
            //NOTE: if we have pending character token make it's end location equal to the
            //current token's start location.
            if (this.currentCharacterToken)
                this.currentCharacterToken.location.endOffset = this.currentToken.location.startOffset;

            this.currentToken.location.endOffset = mxn.posTracker.offset + 1;
            orig._emitCurrentToken.call(this);
        },

        _emitCurrentCharacterToken: function () {
            //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(),
            //then set it's location at the current preprocessor position.
            //We don't need to increment preprocessor position, since character token
            //emission is always forced by the start of the next character token here.
            //So, we already have advanced position.
            if (this.currentCharacterToken && this.currentCharacterToken.location.endOffset === -1)
                this.currentCharacterToken.location.endOffset = mxn.posTracker.offset;

            orig._emitCurrentCharacterToken.call(this);
        }
    };

    //NOTE: patch initial states for each mode to obtain token start position
    Object.keys(Tokenizer.MODE).forEach(function (modeName) {
        var state = Tokenizer.MODE[modeName];

        methods[state] = function (cp) {
            mxn.currentTokenLocation = mxn._getCurrentLocation();
            orig[state].call(this, cp);
        };
    });

    return methods;
};



/***/ }),
/* 464 */
/***/ (function(module, exports, __nested_webpack_require_2492891__) {

"use strict";


var Mixin = __nested_webpack_require_2492891__(201),
    inherits = __nested_webpack_require_2492891__(71).inherits,
    UNICODE = __nested_webpack_require_2492891__(149);

//Aliases
var $ = UNICODE.CODE_POINTS;

var PositionTrackingPreprocessorMixin = module.exports = function (preprocessor) {
    // NOTE: avoid installing tracker twice
    if (!preprocessor.__locTracker) {
        preprocessor.__locTracker = this;

        Mixin.call(this, preprocessor);

        this.preprocessor = preprocessor;
        this.isEol = false;
        this.lineStartPos = 0;
        this.droppedBufferSize = 0;

        this.col = -1;
        this.line = 1;
    }

    return preprocessor.__locTracker;
};

inherits(PositionTrackingPreprocessorMixin, Mixin);

Object.defineProperty(PositionTrackingPreprocessorMixin.prototype, 'offset', {
    get: function () {
        return this.droppedBufferSize + this.preprocessor.pos;
    }
});

PositionTrackingPreprocessorMixin.prototype._getOverriddenMethods = function (mxn, orig) {
    return {
        advance: function () {
            var cp = orig.advance.call(this);

            //NOTE: LF should be in the last column of the line
            if (mxn.isEol) {
                mxn.isEol = false;
                mxn.line++;
                mxn.lineStartPos = mxn.offset;
            }

            if (cp === $.LINE_FEED)
                mxn.isEol = true;

            mxn.col = mxn.offset - mxn.lineStartPos + 1;

            return cp;
        },

        retreat: function () {
            orig.retreat.call(this);
            mxn.isEol = false;

            mxn.col = mxn.offset - mxn.lineStartPos + 1;
        },

        dropParsedChunk: function () {
            var prevPos = this.pos;

            orig.dropParsedChunk.call(this);

            mxn.droppedBufferSize += prevPos - this.pos;
        }
    };
};


/***/ }),
/* 465 */
/***/ (function(module, exports, __nested_webpack_require_2494797__) {

"use strict";


var Tokenizer = __nested_webpack_require_2494797__(124),
    HTML = __nested_webpack_require_2494797__(64);

//Aliases
var $ = HTML.TAG_NAMES,
    NS = HTML.NAMESPACES,
    ATTRS = HTML.ATTRS;


//MIME types
var MIME_TYPES = {
    TEXT_HTML: 'text/html',
    APPLICATION_XML: 'application/xhtml+xml'
};

//Attributes
var DEFINITION_URL_ATTR = 'definitionurl',
    ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL',
    SVG_ATTRS_ADJUSTMENT_MAP = {
        'attributename': 'attributeName',
        'attributetype': 'attributeType',
        'basefrequency': 'baseFrequency',
        'baseprofile': 'baseProfile',
        'calcmode': 'calcMode',
        'clippathunits': 'clipPathUnits',
        'diffuseconstant': 'diffuseConstant',
        'edgemode': 'edgeMode',
        'filterunits': 'filterUnits',
        'glyphref': 'glyphRef',
        'gradienttransform': 'gradientTransform',
        'gradientunits': 'gradientUnits',
        'kernelmatrix': 'kernelMatrix',
        'kernelunitlength': 'kernelUnitLength',
        'keypoints': 'keyPoints',
        'keysplines': 'keySplines',
        'keytimes': 'keyTimes',
        'lengthadjust': 'lengthAdjust',
        'limitingconeangle': 'limitingConeAngle',
        'markerheight': 'markerHeight',
        'markerunits': 'markerUnits',
        'markerwidth': 'markerWidth',
        'maskcontentunits': 'maskContentUnits',
        'maskunits': 'maskUnits',
        'numoctaves': 'numOctaves',
        'pathlength': 'pathLength',
        'patterncontentunits': 'patternContentUnits',
        'patterntransform': 'patternTransform',
        'patternunits': 'patternUnits',
        'pointsatx': 'pointsAtX',
        'pointsaty': 'pointsAtY',
        'pointsatz': 'pointsAtZ',
        'preservealpha': 'preserveAlpha',
        'preserveaspectratio': 'preserveAspectRatio',
        'primitiveunits': 'primitiveUnits',
        'refx': 'refX',
        'refy': 'refY',
        'repeatcount': 'repeatCount',
        'repeatdur': 'repeatDur',
        'requiredextensions': 'requiredExtensions',
        'requiredfeatures': 'requiredFeatures',
        'specularconstant': 'specularConstant',
        'specularexponent': 'specularExponent',
        'spreadmethod': 'spreadMethod',
        'startoffset': 'startOffset',
        'stddeviation': 'stdDeviation',
        'stitchtiles': 'stitchTiles',
        'surfacescale': 'surfaceScale',
        'systemlanguage': 'systemLanguage',
        'tablevalues': 'tableValues',
        'targetx': 'targetX',
        'targety': 'targetY',
        'textlength': 'textLength',
        'viewbox': 'viewBox',
        'viewtarget': 'viewTarget',
        'xchannelselector': 'xChannelSelector',
        'ychannelselector': 'yChannelSelector',
        'zoomandpan': 'zoomAndPan'
    },
    XML_ATTRS_ADJUSTMENT_MAP = {
        'xlink:actuate': {prefix: 'xlink', name: 'actuate', namespace: NS.XLINK},
        'xlink:arcrole': {prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK},
        'xlink:href': {prefix: 'xlink', name: 'href', namespace: NS.XLINK},
        'xlink:role': {prefix: 'xlink', name: 'role', namespace: NS.XLINK},
        'xlink:show': {prefix: 'xlink', name: 'show', namespace: NS.XLINK},
        'xlink:title': {prefix: 'xlink', name: 'title', namespace: NS.XLINK},
        'xlink:type': {prefix: 'xlink', name: 'type', namespace: NS.XLINK},
        'xml:base': {prefix: 'xml', name: 'base', namespace: NS.XML},
        'xml:lang': {prefix: 'xml', name: 'lang', namespace: NS.XML},
        'xml:space': {prefix: 'xml', name: 'space', namespace: NS.XML},
        'xmlns': {prefix: '', name: 'xmlns', namespace: NS.XMLNS},
        'xmlns:xlink': {prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS}

    };

//SVG tag names adjustment map
var SVG_TAG_NAMES_ADJUSTMENT_MAP = exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = {
    'altglyph': 'altGlyph',
    'altglyphdef': 'altGlyphDef',
    'altglyphitem': 'altGlyphItem',
    'animatecolor': 'animateColor',
    'animatemotion': 'animateMotion',
    'animatetransform': 'animateTransform',
    'clippath': 'clipPath',
    'feblend': 'feBlend',
    'fecolormatrix': 'feColorMatrix',
    'fecomponenttransfer': 'feComponentTransfer',
    'fecomposite': 'feComposite',
    'feconvolvematrix': 'feConvolveMatrix',
    'fediffuselighting': 'feDiffuseLighting',
    'fedisplacementmap': 'feDisplacementMap',
    'fedistantlight': 'feDistantLight',
    'feflood': 'feFlood',
    'fefunca': 'feFuncA',
    'fefuncb': 'feFuncB',
    'fefuncg': 'feFuncG',
    'fefuncr': 'feFuncR',
    'fegaussianblur': 'feGaussianBlur',
    'feimage': 'feImage',
    'femerge': 'feMerge',
    'femergenode': 'feMergeNode',
    'femorphology': 'feMorphology',
    'feoffset': 'feOffset',
    'fepointlight': 'fePointLight',
    'fespecularlighting': 'feSpecularLighting',
    'fespotlight': 'feSpotLight',
    'fetile': 'feTile',
    'feturbulence': 'feTurbulence',
    'foreignobject': 'foreignObject',
    'glyphref': 'glyphRef',
    'lineargradient': 'linearGradient',
    'radialgradient': 'radialGradient',
    'textpath': 'textPath'
};

//Tags that causes exit from foreign content
var EXITS_FOREIGN_CONTENT = Object.create(null);

EXITS_FOREIGN_CONTENT[$.B] = true;
EXITS_FOREIGN_CONTENT[$.BIG] = true;
EXITS_FOREIGN_CONTENT[$.BLOCKQUOTE] = true;
EXITS_FOREIGN_CONTENT[$.BODY] = true;
EXITS_FOREIGN_CONTENT[$.BR] = true;
EXITS_FOREIGN_CONTENT[$.CENTER] = true;
EXITS_FOREIGN_CONTENT[$.CODE] = true;
EXITS_FOREIGN_CONTENT[$.DD] = true;
EXITS_FOREIGN_CONTENT[$.DIV] = true;
EXITS_FOREIGN_CONTENT[$.DL] = true;
EXITS_FOREIGN_CONTENT[$.DT] = true;
EXITS_FOREIGN_CONTENT[$.EM] = true;
EXITS_FOREIGN_CONTENT[$.EMBED] = true;
EXITS_FOREIGN_CONTENT[$.H1] = true;
EXITS_FOREIGN_CONTENT[$.H2] = true;
EXITS_FOREIGN_CONTENT[$.H3] = true;
EXITS_FOREIGN_CONTENT[$.H4] = true;
EXITS_FOREIGN_CONTENT[$.H5] = true;
EXITS_FOREIGN_CONTENT[$.H6] = true;
EXITS_FOREIGN_CONTENT[$.HEAD] = true;
EXITS_FOREIGN_CONTENT[$.HR] = true;
EXITS_FOREIGN_CONTENT[$.I] = true;
EXITS_FOREIGN_CONTENT[$.IMG] = true;
EXITS_FOREIGN_CONTENT[$.LI] = true;
EXITS_FOREIGN_CONTENT[$.LISTING] = true;
EXITS_FOREIGN_CONTENT[$.MENU] = true;
EXITS_FOREIGN_CONTENT[$.META] = true;
EXITS_FOREIGN_CONTENT[$.NOBR] = true;
EXITS_FOREIGN_CONTENT[$.OL] = true;
EXITS_FOREIGN_CONTENT[$.P] = true;
EXITS_FOREIGN_CONTENT[$.PRE] = true;
EXITS_FOREIGN_CONTENT[$.RUBY] = true;
EXITS_FOREIGN_CONTENT[$.S] = true;
EXITS_FOREIGN_CONTENT[$.SMALL] = true;
EXITS_FOREIGN_CONTENT[$.SPAN] = true;
EXITS_FOREIGN_CONTENT[$.STRONG] = true;
EXITS_FOREIGN_CONTENT[$.STRIKE] = true;
EXITS_FOREIGN_CONTENT[$.SUB] = true;
EXITS_FOREIGN_CONTENT[$.SUP] = true;
EXITS_FOREIGN_CONTENT[$.TABLE] = true;
EXITS_FOREIGN_CONTENT[$.TT] = true;
EXITS_FOREIGN_CONTENT[$.U] = true;
EXITS_FOREIGN_CONTENT[$.UL] = true;
EXITS_FOREIGN_CONTENT[$.VAR] = true;

//Check exit from foreign content
exports.causesExit = function (startTagToken) {
    var tn = startTagToken.tagName;
    var isFontWithAttrs = tn === $.FONT && (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null ||
                                            Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null ||
                                            Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null);

    return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn];
};

//Token adjustments
exports.adjustTokenMathMLAttrs = function (token) {
    for (var i = 0; i < token.attrs.length; i++) {
        if (token.attrs[i].name === DEFINITION_URL_ATTR) {
            token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;
            break;
        }
    }
};

exports.adjustTokenSVGAttrs = function (token) {
    for (var i = 0; i < token.attrs.length; i++) {
        var adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];

        if (adjustedAttrName)
            token.attrs[i].name = adjustedAttrName;
    }
};

exports.adjustTokenXMLAttrs = function (token) {
    for (var i = 0; i < token.attrs.length; i++) {
        var adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];

        if (adjustedAttrEntry) {
            token.attrs[i].prefix = adjustedAttrEntry.prefix;
            token.attrs[i].name = adjustedAttrEntry.name;
            token.attrs[i].namespace = adjustedAttrEntry.namespace;
        }
    }
};

exports.adjustTokenSVGTagName = function (token) {
    var adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName];

    if (adjustedTagName)
        token.tagName = adjustedTagName;
};

//Integration points
function isMathMLTextIntegrationPoint(tn, ns) {
    return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT);
}

function isHtmlIntegrationPoint(tn, ns, attrs) {
    if (ns === NS.MATHML && tn === $.ANNOTATION_XML) {
        for (var i = 0; i < attrs.length; i++) {
            if (attrs[i].name === ATTRS.ENCODING) {
                var value = attrs[i].value.toLowerCase();

                return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
            }
        }
    }

    return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE);
}

exports.isIntegrationPoint = function (tn, ns, attrs, foreignNS) {
    if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs))
        return true;

    if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns))
        return true;

    return false;
};


/***/ }),
/* 466 */
/***/ (function(module, exports, __nested_webpack_require_2504286__) {

"use strict";


var defaultTreeAdapter = __nested_webpack_require_2504286__(301),
    mergeOptions = __nested_webpack_require_2504286__(302),
    doctype = __nested_webpack_require_2504286__(303),
    HTML = __nested_webpack_require_2504286__(64);

//Aliases
var $ = HTML.TAG_NAMES,
    NS = HTML.NAMESPACES;

//Default serializer options
var DEFAULT_OPTIONS = {
    treeAdapter: defaultTreeAdapter
};

//Escaping regexes
var AMP_REGEX = /&/g,
    NBSP_REGEX = /\u00a0/g,
    DOUBLE_QUOTE_REGEX = /"/g,
    LT_REGEX = /</g,
    GT_REGEX = />/g;

//Serializer
var Serializer = module.exports = function (node, options) {
    this.options = mergeOptions(DEFAULT_OPTIONS, options);
    this.treeAdapter = this.options.treeAdapter;

    this.html = '';
    this.startNode = node;
};

// NOTE: exported as static method for the testing purposes
Serializer.escapeString = function (str, attrMode) {
    str = str
        .replace(AMP_REGEX, '&amp;')
        .replace(NBSP_REGEX, '&nbsp;');

    if (attrMode)
        str = str.replace(DOUBLE_QUOTE_REGEX, '&quot;');

    else {
        str = str
            .replace(LT_REGEX, '&lt;')
            .replace(GT_REGEX, '&gt;');
    }

    return str;
};


//API
Serializer.prototype.serialize = function () {
    this._serializeChildNodes(this.startNode);

    return this.html;
};


//Internals
Serializer.prototype._serializeChildNodes = function (parentNode) {
    var childNodes = this.treeAdapter.getChildNodes(parentNode);

    if (childNodes) {
        for (var i = 0, cnLength = childNodes.length; i < cnLength; i++) {
            var currentNode = childNodes[i];

            if (this.treeAdapter.isElementNode(currentNode))
                this._serializeElement(currentNode);

            else if (this.treeAdapter.isTextNode(currentNode))
                this._serializeTextNode(currentNode);

            else if (this.treeAdapter.isCommentNode(currentNode))
                this._serializeCommentNode(currentNode);

            else if (this.treeAdapter.isDocumentTypeNode(currentNode))
                this._serializeDocumentTypeNode(currentNode);
        }
    }
};

Serializer.prototype._serializeElement = function (node) {
    var tn = this.treeAdapter.getTagName(node),
        ns = this.treeAdapter.getNamespaceURI(node);

    this.html += '<' + tn;
    this._serializeAttributes(node);
    this.html += '>';

    if (tn !== $.AREA && tn !== $.BASE && tn !== $.BASEFONT && tn !== $.BGSOUND && tn !== $.BR && tn !== $.BR &&
        tn !== $.COL && tn !== $.EMBED && tn !== $.FRAME && tn !== $.HR && tn !== $.IMG && tn !== $.INPUT &&
        tn !== $.KEYGEN && tn !== $.LINK && tn !== $.MENUITEM && tn !== $.META && tn !== $.PARAM && tn !== $.SOURCE &&
        tn !== $.TRACK && tn !== $.WBR) {

        var childNodesHolder = tn === $.TEMPLATE && ns === NS.HTML ?
            this.treeAdapter.getTemplateContent(node) :
            node;

        this._serializeChildNodes(childNodesHolder);
        this.html += '</' + tn + '>';
    }
};

Serializer.prototype._serializeAttributes = function (node) {
    var attrs = this.treeAdapter.getAttrList(node);

    for (var i = 0, attrsLength = attrs.length; i < attrsLength; i++) {
        var attr = attrs[i],
            value = Serializer.escapeString(attr.value, true);

        this.html += ' ';

        if (!attr.namespace)
            this.html += attr.name;

        else if (attr.namespace === NS.XML)
            this.html += 'xml:' + attr.name;

        else if (attr.namespace === NS.XMLNS) {
            if (attr.name !== 'xmlns')
                this.html += 'xmlns:';

            this.html += attr.name;
        }

        else if (attr.namespace === NS.XLINK)
            this.html += 'xlink:' + attr.name;

        else
            this.html += attr.namespace + ':' + attr.name;

        this.html += '="' + value + '"';
    }
};

Serializer.prototype._serializeTextNode = function (node) {
    var content = this.treeAdapter.getTextNodeContent(node),
        parent = this.treeAdapter.getParentNode(node),
        parentTn = void 0;

    if (parent && this.treeAdapter.isElementNode(parent))
        parentTn = this.treeAdapter.getTagName(parent);

    if (parentTn === $.STYLE || parentTn === $.SCRIPT || parentTn === $.XMP || parentTn === $.IFRAME ||
        parentTn === $.NOEMBED || parentTn === $.NOFRAMES || parentTn === $.PLAINTEXT || parentTn === $.NOSCRIPT)

        this.html += content;

    else
        this.html += Serializer.escapeString(content, false);
};

Serializer.prototype._serializeCommentNode = function (node) {
    this.html += '<!--' + this.treeAdapter.getCommentNodeContent(node) + '-->';
};

Serializer.prototype._serializeDocumentTypeNode = function (node) {
    var name = this.treeAdapter.getDocumentTypeNodeName(node);

    this.html += '<' + doctype.serializeContent(name, null, null) + '>';
};


/***/ }),
/* 467 */
/***/ (function(module, exports, __nested_webpack_require_2509160__) {

"use strict";


var WritableStream = __nested_webpack_require_2509160__(202).Writable,
    inherits = __nested_webpack_require_2509160__(71).inherits,
    Parser = __nested_webpack_require_2509160__(462);

var ParserStream = module.exports = function (options) {
    WritableStream.call(this);

    this.parser = new Parser(options);

    this.lastChunkWritten = false;
    this.writeCallback = null;
    this.pausedByScript = false;

    this.document = this.parser.treeAdapter.createDocument();

    this.pendingHtmlInsertions = [];

    this._resume = this._resume.bind(this);
    this._documentWrite = this._documentWrite.bind(this);
    this._scriptHandler = this._scriptHandler.bind(this);

    this.parser._bootstrap(this.document, null);
};

inherits(ParserStream, WritableStream);

//WritableStream implementation
ParserStream.prototype._write = function (chunk, encoding, callback) {
    this.writeCallback = callback;
    this.parser.tokenizer.write(chunk.toString('utf8'), this.lastChunkWritten);
    this._runParsingLoop();
};

ParserStream.prototype.end = function (chunk, encoding, callback) {
    this.lastChunkWritten = true;
    WritableStream.prototype.end.call(this, chunk || '', encoding, callback);
};

//Scriptable parser implementation
ParserStream.prototype._runParsingLoop = function () {
    this.parser.runParsingLoopForCurrentChunk(this.writeCallback, this._scriptHandler);
};

ParserStream.prototype._resume = function () {
    if (!this.pausedByScript)
        throw new Error('Parser was already resumed');

    while (this.pendingHtmlInsertions.length) {
        var html = this.pendingHtmlInsertions.pop();

        this.parser.tokenizer.insertHtmlAtCurrentPos(html);
    }

    this.pausedByScript = false;

    //NOTE: keep parsing if we don't wait for the next input chunk
    if (this.parser.tokenizer.active)
        this._runParsingLoop();
};

ParserStream.prototype._documentWrite = function (html) {
    if (!this.parser.stopped)
        this.pendingHtmlInsertions.push(html);
};

ParserStream.prototype._scriptHandler = function (scriptElement) {
    if (this.listeners('script').length) {
        this.pausedByScript = true;
        this.emit('script', scriptElement, this._documentWrite, this._resume);
    }
    else
        this._runParsingLoop();
};



/***/ }),
/* 468 */
/***/ (function(module, exports, __nested_webpack_require_2511493__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



/*<replacement>*/

var pna = __nested_webpack_require_2511493__(203);
/*</replacement>*/

module.exports = Readable;

/*<replacement>*/
var isArray = __nested_webpack_require_2511493__(338);
/*</replacement>*/

/*<replacement>*/
var Duplex;
/*</replacement>*/

Readable.ReadableState = ReadableState;

/*<replacement>*/
var EE = __nested_webpack_require_2511493__(199).EventEmitter;

var EElistenerCount = function (emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/

/*<replacement>*/
var Stream = __nested_webpack_require_2511493__(469);
/*</replacement>*/

/*<replacement>*/

var Buffer = __nested_webpack_require_2511493__(200).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
  return Buffer.from(chunk);
}
function _isUint8Array(obj) {
  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}

/*</replacement>*/

/*<replacement>*/
var util = __nested_webpack_require_2511493__(151);
util.inherits = __nested_webpack_require_2511493__(58);
/*</replacement>*/

/*<replacement>*/
var debugUtil = __nested_webpack_require_2511493__(981);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
  debug = debugUtil.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/

var BufferList = __nested_webpack_require_2511493__(982);
var destroyImpl = __nested_webpack_require_2511493__(470);
var StringDecoder;

util.inherits(Readable, Stream);

var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];

function prependListener(emitter, event, fn) {
  // Sadly this is not cacheable as some libraries bundle their own
  // event emitter implementation with them.
  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);

  // This is a hack to make sure that our error handler is attached before any
  // userland ones.  NEVER DO THIS. This is here only because this code needs
  // to continue to work with older versions of Node.js that do not include
  // the prependListener() method. The goal is to eventually remove this hack.
  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}

function ReadableState(options, stream) {
  Duplex = Duplex || __nested_webpack_require_2511493__(102);

  options = options || {};

  // Duplex streams are both readable and writable, but share
  // the same options object.
  // However, some cases require setting options to different
  // values for the readable and the writable sides of the duplex stream.
  // These options can be provided separately as readableXXX and writableXXX.
  var isDuplex = stream instanceof Duplex;

  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;

  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var readableHwm = options.readableHighWaterMark;
  var defaultHwm = this.objectMode ? 16 : 16 * 1024;

  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;

  // cast to ints.
  this.highWaterMark = Math.floor(this.highWaterMark);

  // A linked list is used to store data chunks instead of an array because the
  // linked list can remove elements from the beginning faster than
  // array.shift()
  this.buffer = new BufferList();
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // a flag to be able to tell if the event 'readable'/'data' is emitted
  // immediately, or on a later tick.  We set this to true at first, because
  // any actions that shouldn't happen until "later" should generally also
  // not happen before the first read call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
  this.resumeScheduled = false;

  // has it been destroyed
  this.destroyed = false;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;

  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder) StringDecoder = __nested_webpack_require_2511493__(300).StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}

function Readable(options) {
  Duplex = Duplex || __nested_webpack_require_2511493__(102);

  if (!(this instanceof Readable)) return new Readable(options);

  this._readableState = new ReadableState(options, this);

  // legacy
  this.readable = true;

  if (options) {
    if (typeof options.read === 'function') this._read = options.read;

    if (typeof options.destroy === 'function') this._destroy = options.destroy;
  }

  Stream.call(this);
}

Object.defineProperty(Readable.prototype, 'destroyed', {
  get: function () {
    if (this._readableState === undefined) {
      return false;
    }
    return this._readableState.destroyed;
  },
  set: function (value) {
    // we ignore the value if the stream
    // has not been initialized yet
    if (!this._readableState) {
      return;
    }

    // backward compatibility, the user is explicitly
    // managing destroyed
    this._readableState.destroyed = value;
  }
});

Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
  this.push(null);
  cb(err);
};

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
  var state = this._readableState;
  var skipChunkCheck;

  if (!state.objectMode) {
    if (typeof chunk === 'string') {
      encoding = encoding || state.defaultEncoding;
      if (encoding !== state.encoding) {
        chunk = Buffer.from(chunk, encoding);
        encoding = '';
      }
      skipChunkCheck = true;
    }
  } else {
    skipChunkCheck = true;
  }

  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
  return readableAddChunk(this, chunk, null, true, false);
};

function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  var state = stream._readableState;
  if (chunk === null) {
    state.reading = false;
    onEofChunk(stream, state);
  } else {
    var er;
    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
    if (er) {
      stream.emit('error', er);
    } else if (state.objectMode || chunk && chunk.length > 0) {
      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
        chunk = _uint8ArrayToBuffer(chunk);
      }

      if (addToFront) {
        if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
      } else if (state.ended) {
        stream.emit('error', new Error('stream.push() after EOF'));
      } else {
        state.reading = false;
        if (state.decoder && !encoding) {
          chunk = state.decoder.write(chunk);
          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
        } else {
          addChunk(stream, state, chunk, false);
        }
      }
    } else if (!addToFront) {
      state.reading = false;
    }
  }

  return needMoreData(state);
}

function addChunk(stream, state, chunk, addToFront) {
  if (state.flowing && state.length === 0 && !state.sync) {
    stream.emit('data', chunk);
    stream.read(0);
  } else {
    // update the buffer info.
    state.length += state.objectMode ? 1 : chunk.length;
    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);

    if (state.needReadable) emitReadable(stream);
  }
  maybeReadMore(stream, state);
}

function chunkInvalid(state, chunk) {
  var er;
  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}

// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}

Readable.prototype.isPaused = function () {
  return this._readableState.flowing === false;
};

// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
  if (!StringDecoder) StringDecoder = __nested_webpack_require_2511493__(300).StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
  return this;
};

// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2 to prevent increasing hwm excessively in
    // tiny amounts
    n--;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n++;
  }
  return n;
}

// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
  if (n <= 0 || state.length === 0 && state.ended) return 0;
  if (state.objectMode) return 1;
  if (n !== n) {
    // Only flow one buffer at a time
    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  }
  // If we're asking for more than the current hwm, then raise the hwm.
  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  if (n <= state.length) return n;
  // Don't have enough
  if (!state.ended) {
    state.needReadable = true;
    return 0;
  }
  return state.length;
}

// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
  debug('read', n);
  n = parseInt(n, 10);
  var state = this._readableState;
  var nOrig = n;

  if (n !== 0) state.emittedReadable = false;

  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
    return null;
  }

  n = howMuchToRead(n, state);

  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0) endReadable(this);
    return null;
  }

  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.

  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);

  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }

  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  } else if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0) state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
    // If _read pushed data synchronously, then `reading` will be false,
    // and we need to re-evaluate how much data we can return to the user.
    if (!state.reading) n = howMuchToRead(nOrig, state);
  }

  var ret;
  if (n > 0) ret = fromList(n, state);else ret = null;

  if (ret === null) {
    state.needReadable = true;
    n = 0;
  } else {
    state.length -= n;
  }

  if (state.length === 0) {
    // If we have nothing in the buffer, then we want to know
    // as soon as we *do* get something into the buffer.
    if (!state.ended) state.needReadable = true;

    // If we tried to read() past the EOF, then emit end on the next tick.
    if (nOrig !== n && state.ended) endReadable(this);
  }

  if (ret !== null) this.emit('data', ret);

  return ret;
};

function onEofChunk(stream, state) {
  if (state.ended) return;
  if (state.decoder) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;

  // emit 'readable' now to make sure it gets picked up.
  emitReadable(stream);
}

// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  }
}

function emitReadable_(stream) {
  debug('emit readable');
  stream.emit('readable');
  flow(stream);
}

// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    pna.nextTick(maybeReadMore_, stream, state);
  }
}

function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;else len = state.length;
  }
  state.readingMore = false;
}

// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
  this.emit('error', new Error('_read() is not implemented'));
};

Readable.prototype.pipe = function (dest, pipeOpts) {
  var src = this;
  var state = this._readableState;

  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);

  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;

  var endFn = doEnd ? onend : unpipe;
  if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);

  dest.on('unpipe', onunpipe);
  function onunpipe(readable, unpipeInfo) {
    debug('onunpipe');
    if (readable === src) {
      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
        unpipeInfo.hasUnpiped = true;
        cleanup();
      }
    }
  }

  function onend() {
    debug('onend');
    dest.end();
  }

  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);

  var cleanedUp = false;
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', unpipe);
    src.removeListener('data', ondata);

    cleanedUp = true;

    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  }

  // If the user pushes more data while we're writing to dest then we'll end up
  // in ondata again. However, we only want to increase awaitDrain once because
  // dest will only emit one 'drain' event for the multiple writes.
  // => Introduce a guard on increasing awaitDrain.
  var increasedAwaitDrain = false;
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    increasedAwaitDrain = false;
    var ret = dest.write(chunk);
    if (false === ret && !increasedAwaitDrain) {
      // If the user unpiped during `dest.write()`, it is possible
      // to get stuck in a permanently paused state if that write
      // also returned false.
      // => Check whether `dest` is still a piping destination.
      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
        debug('false write response, pause', src._readableState.awaitDrain);
        src._readableState.awaitDrain++;
        increasedAwaitDrain = true;
      }
      src.pause();
    }
  }

  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  }

  // Make sure our error handler is attached before userland ones.
  prependListener(dest, 'error', onerror);

  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);

  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }

  // tell the dest that it's being piped to
  dest.emit('pipe', src);

  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }

  return dest;
};

function pipeOnDrain(src) {
  return function () {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain) state.awaitDrain--;
    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}

Readable.prototype.unpipe = function (dest) {
  var state = this._readableState;
  var unpipeInfo = { hasUnpiped: false };

  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0) return this;

  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes) return this;

    if (!dest) dest = state.pipes;

    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest) dest.emit('unpipe', this, unpipeInfo);
    return this;
  }

  // slow case. multiple pipe destinations.

  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;

    for (var i = 0; i < len; i++) {
      dests[i].emit('unpipe', this, unpipeInfo);
    }return this;
  }

  // try to find the right one.
  var index = indexOf(state.pipes, dest);
  if (index === -1) return this;

  state.pipes.splice(index, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1) state.pipes = state.pipes[0];

  dest.emit('unpipe', this, unpipeInfo);

  return this;
};

// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);

  if (ev === 'data') {
    // Start flowing on next tick if stream isn't explicitly paused
    if (this._readableState.flowing !== false) this.resume();
  } else if (ev === 'readable') {
    var state = this._readableState;
    if (!state.endEmitted && !state.readableListening) {
      state.readableListening = state.needReadable = true;
      state.emittedReadable = false;
      if (!state.reading) {
        pna.nextTick(nReadingNextTick, this);
      } else if (state.length) {
        emitReadable(this);
      }
    }
  }

  return res;
};
Readable.prototype.addListener = Readable.prototype.on;

function nReadingNextTick(self) {
  debug('readable nexttick read 0');
  self.read(0);
}

// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    state.flowing = true;
    resume(this, state);
  }
  return this;
};

function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    pna.nextTick(resume_, stream, state);
  }
}

function resume_(stream, state) {
  if (!state.reading) {
    debug('resume read 0');
    stream.read(0);
  }

  state.resumeScheduled = false;
  state.awaitDrain = 0;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading) stream.read(0);
}

Readable.prototype.pause = function () {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (false !== this._readableState.flowing) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  return this;
};

function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  while (state.flowing && stream.read() !== null) {}
}

// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
  var _this = this;

  var state = this._readableState;
  var paused = false;

  stream.on('end', function () {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) _this.push(chunk);
    }

    _this.push(null);
  });

  stream.on('data', function (chunk) {
    debug('wrapped data');
    if (state.decoder) chunk = state.decoder.write(chunk);

    // don't skip over falsy values in objectMode
    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;

    var ret = _this.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });

  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (this[i] === undefined && typeof stream[i] === 'function') {
      this[i] = function (method) {
        return function () {
          return stream[method].apply(stream, arguments);
        };
      }(i);
    }
  }

  // proxy certain important events.
  for (var n = 0; n < kProxyEvents.length; n++) {
    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  }

  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  this._read = function (n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };

  return this;
};

Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  // making it explicit this property is not enumerable
  // because otherwise some prototype manipulation in
  // userland will fail
  enumerable: false,
  get: function () {
    return this._readableState.highWaterMark;
  }
});

// exposed for testing purposes only.
Readable._fromList = fromList;

// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
  // nothing buffered
  if (state.length === 0) return null;

  var ret;
  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
    // read it all, truncate the list
    if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
    state.buffer.clear();
  } else {
    // read part of list
    ret = fromListPartial(n, state.buffer, state.decoder);
  }

  return ret;
}

// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
  var ret;
  if (n < list.head.data.length) {
    // slice is the same for buffers and strings
    ret = list.head.data.slice(0, n);
    list.head.data = list.head.data.slice(n);
  } else if (n === list.head.data.length) {
    // first chunk is a perfect match
    ret = list.shift();
  } else {
    // result spans more than one buffer
    ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  }
  return ret;
}

// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
  var p = list.head;
  var c = 1;
  var ret = p.data;
  n -= ret.length;
  while (p = p.next) {
    var str = p.data;
    var nb = n > str.length ? str.length : n;
    if (nb === str.length) ret += str;else ret += str.slice(0, n);
    n -= nb;
    if (n === 0) {
      if (nb === str.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = str.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}

// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
  var ret = Buffer.allocUnsafe(n);
  var p = list.head;
  var c = 1;
  p.data.copy(ret);
  n -= p.data.length;
  while (p = p.next) {
    var buf = p.data;
    var nb = n > buf.length ? buf.length : n;
    buf.copy(ret, ret.length - n, 0, nb);
    n -= nb;
    if (n === 0) {
      if (nb === buf.length) {
        ++c;
        if (p.next) list.head = p.next;else list.head = list.tail = null;
      } else {
        list.head = p;
        p.data = buf.slice(nb);
      }
      break;
    }
    ++c;
  }
  list.length -= c;
  return ret;
}

function endReadable(stream) {
  var state = stream._readableState;

  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');

  if (!state.endEmitted) {
    state.ended = true;
    pna.nextTick(endReadableNT, state, stream);
  }
}

function endReadableNT(state, stream) {
  // Check that we didn't get one last unshift.
  if (!state.endEmitted && state.length === 0) {
    state.endEmitted = true;
    stream.readable = false;
    stream.emit('end');
  }
}

function indexOf(xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2511493__(27), __nested_webpack_require_2511493__(150)))

/***/ }),
/* 469 */
/***/ (function(module, exports, __nested_webpack_require_2543000__) {

module.exports = __nested_webpack_require_2543000__(199).EventEmitter;


/***/ }),
/* 470 */
/***/ (function(module, exports, __nested_webpack_require_2543135__) {

"use strict";


/*<replacement>*/

var pna = __nested_webpack_require_2543135__(203);
/*</replacement>*/

// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
  var _this = this;

  var readableDestroyed = this._readableState && this._readableState.destroyed;
  var writableDestroyed = this._writableState && this._writableState.destroyed;

  if (readableDestroyed || writableDestroyed) {
    if (cb) {
      cb(err);
    } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
      pna.nextTick(emitErrorNT, this, err);
    }
    return this;
  }

  // we set destroyed to true before firing error callbacks in order
  // to make it re-entrance safe in case destroy() is called within callbacks

  if (this._readableState) {
    this._readableState.destroyed = true;
  }

  // if this is a duplex stream mark the writable part as destroyed as well
  if (this._writableState) {
    this._writableState.destroyed = true;
  }

  this._destroy(err || null, function (err) {
    if (!cb && err) {
      pna.nextTick(emitErrorNT, _this, err);
      if (_this._writableState) {
        _this._writableState.errorEmitted = true;
      }
    } else if (cb) {
      cb(err);
    }
  });

  return this;
}

function undestroy() {
  if (this._readableState) {
    this._readableState.destroyed = false;
    this._readableState.reading = false;
    this._readableState.ended = false;
    this._readableState.endEmitted = false;
  }

  if (this._writableState) {
    this._writableState.destroyed = false;
    this._writableState.ended = false;
    this._writableState.ending = false;
    this._writableState.finished = false;
    this._writableState.errorEmitted = false;
  }
}

function emitErrorNT(self, err) {
  self.emit('error', err);
}

module.exports = {
  destroy: destroy,
  undestroy: undestroy
};

/***/ }),
/* 471 */
/***/ (function(module, exports, __nested_webpack_require_2545057__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.



module.exports = Transform;

var Duplex = __nested_webpack_require_2545057__(102);

/*<replacement>*/
var util = __nested_webpack_require_2545057__(151);
util.inherits = __nested_webpack_require_2545057__(58);
/*</replacement>*/

util.inherits(Transform, Duplex);

function afterTransform(er, data) {
  var ts = this._transformState;
  ts.transforming = false;

  var cb = ts.writecb;

  if (!cb) {
    return this.emit('error', new Error('write callback called multiple times'));
  }

  ts.writechunk = null;
  ts.writecb = null;

  if (data != null) // single equals check for both `null` and `undefined`
    this.push(data);

  cb(er);

  var rs = this._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    this._read(rs.highWaterMark);
  }
}

function Transform(options) {
  if (!(this instanceof Transform)) return new Transform(options);

  Duplex.call(this, options);

  this._transformState = {
    afterTransform: afterTransform.bind(this),
    needTransform: false,
    transforming: false,
    writecb: null,
    writechunk: null,
    writeencoding: null
  };

  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;

  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;

  if (options) {
    if (typeof options.transform === 'function') this._transform = options.transform;

    if (typeof options.flush === 'function') this._flush = options.flush;
  }

  // When the writable side finishes, then flush out anything remaining.
  this.on('prefinish', prefinish);
}

function prefinish() {
  var _this = this;

  if (typeof this._flush === 'function') {
    this._flush(function (er, data) {
      done(_this, er, data);
    });
  } else {
    done(this, null, null);
  }
}

Transform.prototype.push = function (chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
  throw new Error('_transform() is not implemented');
};

Transform.prototype._write = function (chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  }
};

// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
  var ts = this._transformState;

  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};

Transform.prototype._destroy = function (err, cb) {
  var _this2 = this;

  Duplex.prototype._destroy.call(this, err, function (err2) {
    cb(err2);
    _this2.emit('close');
  });
};

function done(stream, er, data) {
  if (er) return stream.emit('error', er);

  if (data != null) // single equals check for both `null` and `undefined`
    stream.push(data);

  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');

  if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');

  return stream.push(null);
}

/***/ }),
/* 472 */
/***/ (function(module, exports, __nested_webpack_require_2552866__) {

var assignValue = __nested_webpack_require_2552866__(195),
    copyObject = __nested_webpack_require_2552866__(100),
    createAssigner = __nested_webpack_require_2552866__(290),
    isArrayLike = __nested_webpack_require_2552866__(98),
    isPrototype = __nested_webpack_require_2552866__(186),
    keys = __nested_webpack_require_2552866__(119);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Assigns own enumerable string keyed properties of source objects to the
 * destination object. Source objects are applied from left to right.
 * Subsequent sources overwrite property assignments of previous sources.
 *
 * **Note:** This method mutates `object` and is loosely based on
 * [`Object.assign`](https://mdn.io/Object/assign).
 *
 * @static
 * @memberOf _
 * @since 0.10.0
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.assignIn
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * function Bar() {
 *   this.c = 3;
 * }
 *
 * Foo.prototype.b = 2;
 * Bar.prototype.d = 4;
 *
 * _.assign({ 'a': 0 }, new Foo, new Bar);
 * // => { 'a': 1, 'c': 3 }
 */
var assign = createAssigner(function(object, source) {
  if (isPrototype(source) || isArrayLike(source)) {
    copyObject(source, keys(source), object);
    return;
  }
  for (var key in source) {
    if (hasOwnProperty.call(source, key)) {
      assignValue(object, key, source[key]);
    }
  }
});

module.exports = assign;


/***/ }),
/* 473 */
/***/ (function(module, exports, __nested_webpack_require_2554511__) {

var copyObject = __nested_webpack_require_2554511__(100),
    createAssigner = __nested_webpack_require_2554511__(290),
    keysIn = __nested_webpack_require_2554511__(121);

/**
 * This method is like `_.assign` except that it iterates over own and
 * inherited source properties.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @alias extend
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.assign
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 * }
 *
 * function Bar() {
 *   this.c = 3;
 * }
 *
 * Foo.prototype.b = 2;
 * Bar.prototype.d = 4;
 *
 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
 */
var assignIn = createAssigner(function(object, source) {
  copyObject(source, keysIn(source), object);
});

module.exports = assignIn;


/***/ }),
/* 474 */
/***/ (function(module, exports, __nested_webpack_require_2555497__) {

var identity = __nested_webpack_require_2555497__(143),
    metaMap = __nested_webpack_require_2555497__(475);

/**
 * The base implementation of `setData` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to associate metadata with.
 * @param {*} data The metadata.
 * @returns {Function} Returns `func`.
 */
var baseSetData = !metaMap ? identity : function(func, data) {
  metaMap.set(func, data);
  return func;
};

module.exports = baseSetData;


/***/ }),
/* 475 */
/***/ (function(module, exports, __nested_webpack_require_2556038__) {

var WeakMap = __nested_webpack_require_2556038__(422);

/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;

module.exports = metaMap;


/***/ }),
/* 476 */
/***/ (function(module, exports, __nested_webpack_require_2556263__) {

var composeArgs = __nested_webpack_require_2556263__(477),
    composeArgsRight = __nested_webpack_require_2556263__(478),
    countHolders = __nested_webpack_require_2556263__(1000),
    createCtor = __nested_webpack_require_2556263__(205),
    createRecurry = __nested_webpack_require_2556263__(479),
    getHolder = __nested_webpack_require_2556263__(309),
    reorder = __nested_webpack_require_2556263__(1015),
    replaceHolders = __nested_webpack_require_2556263__(206),
    root = __nested_webpack_require_2556263__(41);

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_FLAG = 8,
    WRAP_CURRY_RIGHT_FLAG = 16,
    WRAP_ARY_FLAG = 128,
    WRAP_FLIP_FLAG = 512;

/**
 * Creates a function that wraps `func` to invoke it with optional `this`
 * binding of `thisArg`, partial application, and currying.
 *
 * @private
 * @param {Function|string} func The function or method name to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to prepend to those provided to
 *  the new function.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [partialsRight] The arguments to append to those provided
 *  to the new function.
 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
  var isAry = bitmask & WRAP_ARY_FLAG,
      isBind = bitmask & WRAP_BIND_FLAG,
      isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
      isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
      isFlip = bitmask & WRAP_FLIP_FLAG,
      Ctor = isBindKey ? undefined : createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length;

    while (index--) {
      args[index] = arguments[index];
    }
    if (isCurried) {
      var placeholder = getHolder(wrapper),
          holdersCount = countHolders(args, placeholder);
    }
    if (partials) {
      args = composeArgs(args, partials, holders, isCurried);
    }
    if (partialsRight) {
      args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
    }
    length -= holdersCount;
    if (isCurried && length < arity) {
      var newHolders = replaceHolders(args, placeholder);
      return createRecurry(
        func, bitmask, createHybrid, wrapper.placeholder, thisArg,
        args, newHolders, argPos, ary, arity - length
      );
    }
    var thisBinding = isBind ? thisArg : this,
        fn = isBindKey ? thisBinding[func] : func;

    length = args.length;
    if (argPos) {
      args = reorder(args, argPos);
    } else if (isFlip && length > 1) {
      args.reverse();
    }
    if (isAry && ary < length) {
      args.length = ary;
    }
    if (this && this !== root && this instanceof wrapper) {
      fn = Ctor || createCtor(fn);
    }
    return fn.apply(thisBinding, args);
  }
  return wrapper;
}

module.exports = createHybrid;


/***/ }),
/* 477 */
/***/ (function(module, exports) {

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * Creates an array that is the composition of partially applied arguments,
 * placeholders, and provided arguments into a single array of arguments.
 *
 * @private
 * @param {Array} args The provided arguments.
 * @param {Array} partials The arguments to prepend to those provided.
 * @param {Array} holders The `partials` placeholder indexes.
 * @params {boolean} [isCurried] Specify composing for a curried function.
 * @returns {Array} Returns the new array of composed arguments.
 */
function composeArgs(args, partials, holders, isCurried) {
  var argsIndex = -1,
      argsLength = args.length,
      holdersLength = holders.length,
      leftIndex = -1,
      leftLength = partials.length,
      rangeLength = nativeMax(argsLength - holdersLength, 0),
      result = Array(leftLength + rangeLength),
      isUncurried = !isCurried;

  while (++leftIndex < leftLength) {
    result[leftIndex] = partials[leftIndex];
  }
  while (++argsIndex < holdersLength) {
    if (isUncurried || argsIndex < argsLength) {
      result[holders[argsIndex]] = args[argsIndex];
    }
  }
  while (rangeLength--) {
    result[leftIndex++] = args[argsIndex++];
  }
  return result;
}

module.exports = composeArgs;


/***/ }),
/* 478 */
/***/ (function(module, exports) {

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * This function is like `composeArgs` except that the arguments composition
 * is tailored for `_.partialRight`.
 *
 * @private
 * @param {Array} args The provided arguments.
 * @param {Array} partials The arguments to append to those provided.
 * @param {Array} holders The `partials` placeholder indexes.
 * @params {boolean} [isCurried] Specify composing for a curried function.
 * @returns {Array} Returns the new array of composed arguments.
 */
function composeArgsRight(args, partials, holders, isCurried) {
  var argsIndex = -1,
      argsLength = args.length,
      holdersIndex = -1,
      holdersLength = holders.length,
      rightIndex = -1,
      rightLength = partials.length,
      rangeLength = nativeMax(argsLength - holdersLength, 0),
      result = Array(rangeLength + rightLength),
      isUncurried = !isCurried;

  while (++argsIndex < rangeLength) {
    result[argsIndex] = args[argsIndex];
  }
  var offset = argsIndex;
  while (++rightIndex < rightLength) {
    result[offset + rightIndex] = partials[rightIndex];
  }
  while (++holdersIndex < holdersLength) {
    if (isUncurried || argsIndex < argsLength) {
      result[offset + holders[holdersIndex]] = args[argsIndex++];
    }
  }
  return result;
}

module.exports = composeArgsRight;


/***/ }),
/* 479 */
/***/ (function(module, exports, __nested_webpack_require_2562416__) {

var isLaziable = __nested_webpack_require_2562416__(1001),
    setData = __nested_webpack_require_2562416__(482),
    setWrapToString = __nested_webpack_require_2562416__(483);

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_BOUND_FLAG = 4,
    WRAP_CURRY_FLAG = 8,
    WRAP_PARTIAL_FLAG = 32,
    WRAP_PARTIAL_RIGHT_FLAG = 64;

/**
 * Creates a function that wraps `func` to continue currying.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {Function} wrapFunc The function to create the `func` wrapper.
 * @param {*} placeholder The placeholder value.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to prepend to those provided to
 *  the new function.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
  var isCurry = bitmask & WRAP_CURRY_FLAG,
      newHolders = isCurry ? holders : undefined,
      newHoldersRight = isCurry ? undefined : holders,
      newPartials = isCurry ? partials : undefined,
      newPartialsRight = isCurry ? undefined : partials;

  bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
  bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);

  if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
    bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
  }
  var newData = [
    func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
    newHoldersRight, argPos, ary, arity
  ];

  var result = wrapFunc.apply(undefined, newData);
  if (isLaziable(func)) {
    setData(result, newData);
  }
  result.placeholder = placeholder;
  return setWrapToString(result, func, bitmask);
}

module.exports = createRecurry;


/***/ }),
/* 480 */
/***/ (function(module, exports, __nested_webpack_require_2564611__) {

var metaMap = __nested_webpack_require_2564611__(475),
    noop = __nested_webpack_require_2564611__(1002);

/**
 * Gets metadata for `func`.
 *
 * @private
 * @param {Function} func The function to query.
 * @returns {*} Returns the metadata for `func`.
 */
var getData = !metaMap ? noop : function(func) {
  return metaMap.get(func);
};

module.exports = getData;


/***/ }),
/* 481 */
/***/ (function(module, exports, __nested_webpack_require_2565026__) {

var baseCreate = __nested_webpack_require_2565026__(197),
    baseLodash = __nested_webpack_require_2565026__(308);

/**
 * The base constructor for creating `lodash` wrapper objects.
 *
 * @private
 * @param {*} value The value to wrap.
 * @param {boolean} [chainAll] Enable explicit method chain sequences.
 */
function LodashWrapper(value, chainAll) {
  this.__wrapped__ = value;
  this.__actions__ = [];
  this.__chain__ = !!chainAll;
  this.__index__ = 0;
  this.__values__ = undefined;
}

LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;

module.exports = LodashWrapper;


/***/ }),
/* 482 */
/***/ (function(module, exports, __nested_webpack_require_2565716__) {

var baseSetData = __nested_webpack_require_2565716__(474),
    shortOut = __nested_webpack_require_2565716__(434);

/**
 * Sets metadata for `func`.
 *
 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
 * period of time, it will trip its breaker and transition to an identity
 * function to avoid garbage collection pauses in V8. See
 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
 * for more details.
 *
 * @private
 * @param {Function} func The function to associate metadata with.
 * @param {*} data The metadata.
 * @returns {Function} Returns `func`.
 */
var setData = shortOut(baseSetData);

module.exports = setData;


/***/ }),
/* 483 */
/***/ (function(module, exports, __nested_webpack_require_2566441__) {

var getWrapDetails = __nested_webpack_require_2566441__(1007),
    insertWrapDetails = __nested_webpack_require_2566441__(1008),
    setToString = __nested_webpack_require_2566441__(293),
    updateWrapDetails = __nested_webpack_require_2566441__(1009);

/**
 * Sets the `toString` method of `wrapper` to mimic the source of `reference`
 * with wrapper details in a comment at the top of the source body.
 *
 * @private
 * @param {Function} wrapper The function to modify.
 * @param {Function} reference The reference function.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @returns {Function} Returns `wrapper`.
 */
function setWrapToString(wrapper, reference, bitmask) {
  var source = (reference + '');
  return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}

module.exports = setWrapToString;


/***/ }),
/* 484 */
/***/ (function(module, exports, __nested_webpack_require_2567351__) {

var baseRest = __nested_webpack_require_2567351__(291),
    eq = __nested_webpack_require_2567351__(120),
    isIterateeCall = __nested_webpack_require_2567351__(294),
    keysIn = __nested_webpack_require_2567351__(121);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Assigns own and inherited enumerable string keyed properties of source
 * objects to the destination object for all destination properties that
 * resolve to `undefined`. Source objects are applied from left to right.
 * Once a property is set, additional values of the same property are ignored.
 *
 * **Note:** This method mutates `object`.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The destination object.
 * @param {...Object} [sources] The source objects.
 * @returns {Object} Returns `object`.
 * @see _.defaultsDeep
 * @example
 *
 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
 * // => { 'a': 1, 'b': 2 }
 */
var defaults = baseRest(function(object, sources) {
  object = Object(object);

  var index = -1;
  var length = sources.length;
  var guard = length > 2 ? sources[2] : undefined;

  if (guard && isIterateeCall(sources[0], sources[1], guard)) {
    length = 1;
  }

  while (++index < length) {
    var source = sources[index];
    var props = keysIn(source);
    var propsIndex = -1;
    var propsLength = props.length;

    while (++propsIndex < propsLength) {
      var key = props[propsIndex];
      var value = object[key];

      if (value === undefined ||
          (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
        object[key] = source[key];
      }
    }
  }

  return object;
});

module.exports = defaults;


/***/ }),
/* 485 */
/***/ (function(module, exports, __nested_webpack_require_2569196__) {

"use strict";


module.exports = CSSselect;

var Pseudos       = __nested_webpack_require_2569196__(311),
    DomUtils      = __nested_webpack_require_2569196__(101),
    findOne       = DomUtils.findOne,
    findAll       = DomUtils.findAll,
    getChildren   = DomUtils.getChildren,
    removeSubsets = DomUtils.removeSubsets,
    falseFunc     = __nested_webpack_require_2569196__(153).falseFunc,
    compile       = __nested_webpack_require_2569196__(1024),
    compileUnsafe = compile.compileUnsafe,
    compileToken  = compile.compileToken;

function getSelectorFunc(searchFunc){
	return function select(query, elems, options){
        if(typeof query !== "function") query = compileUnsafe(query, options, elems);
        if(!Array.isArray(elems)) elems = getChildren(elems);
		else elems = removeSubsets(elems);
		return searchFunc(query, elems);
	};
}

var selectAll = getSelectorFunc(function selectAll(query, elems){
	return (query === falseFunc || !elems || elems.length === 0) ? [] : findAll(query, elems);
});

var selectOne = getSelectorFunc(function selectOne(query, elems){
	return (query === falseFunc || !elems || elems.length === 0) ? null : findOne(query, elems);
});

function is(elem, query, options){
	return (typeof query === "function" ? query : compile(query, options))(elem);
}

/*
	the exported interface
*/
function CSSselect(query, elems, options){
	return selectAll(query, elems, options);
}

CSSselect.compile = compile;
CSSselect.filters = Pseudos.filters;
CSSselect.pseudos = Pseudos.pseudos;

CSSselect.selectAll = selectAll;
CSSselect.selectOne = selectOne;

CSSselect.is = is;

//legacy methods (might be removed)
CSSselect.parse = compile;
CSSselect.iterate = selectAll;

//hooks
CSSselect._compileUnsafe = compileUnsafe;
CSSselect._compileToken = compileToken;


/***/ }),
/* 486 */
/***/ (function(module, exports, __nested_webpack_require_2571015__) {

var DomUtils  = __nested_webpack_require_2571015__(101),
    hasAttrib = DomUtils.hasAttrib,
    getAttributeValue = DomUtils.getAttributeValue,
    falseFunc = __nested_webpack_require_2571015__(153).falseFunc;

//https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js#L469
var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g;

/*
	attribute selectors
*/

var attributeRules = {
	__proto__: null,
	equals: function(next, data){
		var name  = data.name,
		    value = data.value;

		if(data.ignoreCase){
			value = value.toLowerCase();

			return function equalsIC(elem){
				var attr = getAttributeValue(elem, name);
				return attr != null && attr.toLowerCase() === value && next(elem);
			};
		}

		return function equals(elem){
			return getAttributeValue(elem, name) === value && next(elem);
		};
	},
	hyphen: function(next, data){
		var name  = data.name,
		    value = data.value,
		    len = value.length;

		if(data.ignoreCase){
			value = value.toLowerCase();

			return function hyphenIC(elem){
				var attr = getAttributeValue(elem, name);
				return attr != null &&
						(attr.length === len || attr.charAt(len) === "-") &&
						attr.substr(0, len).toLowerCase() === value &&
						next(elem);
			};
		}

		return function hyphen(elem){
			var attr = getAttributeValue(elem, name);
			return attr != null &&
					attr.substr(0, len) === value &&
					(attr.length === len || attr.charAt(len) === "-") &&
					next(elem);
		};
	},
	element: function(next, data){
		var name = data.name,
		    value = data.value;

		if(/\s/.test(value)){
			return falseFunc;
		}

		value = value.replace(reChars, "\\$&");

		var pattern = "(?:^|\\s)" + value + "(?:$|\\s)",
		    flags = data.ignoreCase ? "i" : "",
		    regex = new RegExp(pattern, flags);

		return function element(elem){
			var attr = getAttributeValue(elem, name);
			return attr != null && regex.test(attr) && next(elem);
		};
	},
	exists: function(next, data){
		var name = data.name;
		return function exists(elem){
			return hasAttrib(elem, name) && next(elem);
		};
	},
	start: function(next, data){
		var name  = data.name,
		    value = data.value,
		    len = value.length;

		if(len === 0){
			return falseFunc;
		}
		
		if(data.ignoreCase){
			value = value.toLowerCase();

			return function startIC(elem){
				var attr = getAttributeValue(elem, name);
				return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem);
			};
		}

		return function start(elem){
			var attr = getAttributeValue(elem, name);
			return attr != null && attr.substr(0, len) === value && next(elem);
		};
	},
	end: function(next, data){
		var name  = data.name,
		    value = data.value,
		    len   = -value.length;

		if(len === 0){
			return falseFunc;
		}

		if(data.ignoreCase){
			value = value.toLowerCase();

			return function endIC(elem){
				var attr = getAttributeValue(elem, name);
				return attr != null && attr.substr(len).toLowerCase() === value && next(elem);
			};
		}

		return function end(elem){
			var attr = getAttributeValue(elem, name);
			return attr != null && attr.substr(len) === value && next(elem);
		};
	},
	any: function(next, data){
		var name  = data.name,
		    value = data.value;

		if(value === ""){
			return falseFunc;
		}

		if(data.ignoreCase){
			var regex = new RegExp(value.replace(reChars, "\\$&"), "i");

			return function anyIC(elem){
				var attr = getAttributeValue(elem, name);
				return attr != null && regex.test(attr) && next(elem);
			};
		}

		return function any(elem){
			var attr = getAttributeValue(elem, name);
			return attr != null && attr.indexOf(value) >= 0 && next(elem);
		};
	},
	not: function(next, data){
		var name  = data.name,
		    value = data.value;

		if(value === ""){
			return function notEmpty(elem){
				return !!getAttributeValue(elem, name) && next(elem);
			};
		} else if(data.ignoreCase){
			value = value.toLowerCase();

			return function notIC(elem){
				var attr = getAttributeValue(elem, name);
				return attr != null && attr.toLowerCase() !== value && next(elem);
			};
		}

		return function not(elem){
			return getAttributeValue(elem, name) !== value && next(elem);
		};
	}
};

module.exports = {
	compile: function(next, data, options){
		if(options && options.strict && (
			data.ignoreCase || data.action === "not"
		)) throw SyntaxError("Unsupported attribute selector");
		return attributeRules[data.action](next, data);
	},
	rules: attributeRules
};


/***/ }),
/* 487 */
/***/ (function(module) {

module.exports = {"universal":50,"tag":30,"attribute":1,"pseudo":0,"descendant":-1,"child":-1,"parent":-1,"sibling":-1,"adjacent":-1};

/***/ }),
/* 488 */
/***/ (function(module, exports, __nested_webpack_require_2575680__) {

var baseEach = __nested_webpack_require_2575680__(146);

/**
 * The base implementation of `_.filter` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 */
function baseFilter(collection, predicate) {
  var result = [];
  baseEach(collection, function(value, index, collection) {
    if (predicate(value, index, collection)) {
      result.push(value);
    }
  });
  return result;
}

module.exports = baseFilter;


/***/ }),
/* 489 */
/***/ (function(module, exports, __nested_webpack_require_2576351__) {

var baseFlatten = __nested_webpack_require_2576351__(1038);

/**
 * Flattens `array` a single level deep.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Array
 * @param {Array} array The array to flatten.
 * @returns {Array} Returns the new flattened array.
 * @example
 *
 * _.flatten([1, [2, [3, [4]], 5]]);
 * // => [1, 2, [3, [4]], 5]
 */
function flatten(array) {
  var length = array == null ? 0 : array.length;
  return length ? baseFlatten(array, 1) : [];
}

module.exports = flatten;


/***/ }),
/* 490 */
/***/ (function(module, exports, __nested_webpack_require_2576919__) {

"use strict";


var ES = __nested_webpack_require_2576919__(1048);

var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || (Math.pow(2, 53) - 1);

// eslint-disable-next-line max-params, max-statements
var FlattenIntoArray = function FlattenIntoArray(target, source, sourceLen, start, depth) {
	var targetIndex = start;
	var sourceIndex = 0;

	/*
	var mapperFunction;
	if (arguments.length > 5) {
		mapperFunction = arguments[5];
	}
	*/

	while (sourceIndex < sourceLen) {
		var P = ES.ToString(sourceIndex);
		var exists = ES.HasProperty(source, P);
		if (exists) {
			var element = ES.Get(source, P);
			/*
			if (typeof mapperFunction !== 'undefined') {
				if (arguments.length <= 6) {
					throw new TypeError('Assertion failed: thisArg is required when mapperFunction is provided');
				}
				element = ES.Call(mapperFunction, arguments[6], [element, sourceIndex, source]);
			}
			*/
			var shouldFlatten = false;
			if (depth > 0) {
				shouldFlatten = ES.IsArray(element);
			}
			if (shouldFlatten) {
				var elementLen = ES.ToLength(ES.Get(element, 'length'));
				targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1);
			} else {
				if (targetIndex >= MAX_SAFE_INTEGER) {
					throw new TypeError('index too large');
				}
				ES.CreateDataPropertyOrThrow(target, ES.ToString(targetIndex), element);
				targetIndex += 1;
			}
		}
		sourceIndex += 1;
	}

	return targetIndex;
};

module.exports = function flat() {
	var O = ES.ToObject(this);
	var sourceLen = ES.ToLength(ES.Get(O, 'length'));

	var depthNum = 1;
	if (arguments.length > 0 && typeof arguments[0] !== 'undefined') {
		depthNum = ES.ToInteger(arguments[0]);
	}

	var A = ES.ArraySpeciesCreate(O, 0);
	FlattenIntoArray(A, O, sourceLen, 0, depthNum);
	return A;
};


/***/ }),
/* 491 */
/***/ (function(module, exports, __nested_webpack_require_2578750__) {

"use strict";


var ES2015 = __nested_webpack_require_2578750__(1049);
var assign = __nested_webpack_require_2578750__(312);

var ES2016 = assign(assign({}, ES2015), {
	// https://github.com/tc39/ecma262/pull/60
	SameValueNonNumber: function SameValueNonNumber(x, y) {
		if (typeof x === 'number' || typeof x !== typeof y) {
			throw new TypeError('SameValueNonNumber requires two non-number values of the same type.');
		}
		return this.SameValue(x, y);
	}
});

module.exports = ES2016;


/***/ }),
/* 492 */
/***/ (function(module, exports) {

module.exports = function isPrimitive(value) {
	return value === null || (typeof value !== 'function' && typeof value !== 'object');
};


/***/ }),
/* 493 */
/***/ (function(module, exports, __nested_webpack_require_2579481__) {

"use strict";


var GetIntrinsic = __nested_webpack_require_2579481__(207);

var $TypeError = GetIntrinsic('%TypeError%');
var $SyntaxError = GetIntrinsic('%SyntaxError%');

var has = __nested_webpack_require_2579481__(59);

var predicates = {
  // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
  'Property Descriptor': function isPropertyDescriptor(ES, Desc) {
    if (ES.Type(Desc) !== 'Object') {
      return false;
    }
    var allowed = {
      '[[Configurable]]': true,
      '[[Enumerable]]': true,
      '[[Get]]': true,
      '[[Set]]': true,
      '[[Value]]': true,
      '[[Writable]]': true
    };

    for (var key in Desc) { // eslint-disable-line
      if (has(Desc, key) && !allowed[key]) {
        return false;
      }
    }

    var isData = has(Desc, '[[Value]]');
    var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
    if (isData && IsAccessor) {
      throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
    }
    return true;
  }
};

module.exports = function assertRecord(ES, recordType, argumentName, value) {
  var predicate = predicates[recordType];
  if (typeof predicate !== 'function') {
    throw new $SyntaxError('unknown record type: ' + recordType);
  }
  if (!predicate(ES, value)) {
    throw new $TypeError(argumentName + ' must be a ' + recordType);
  }
  console.log(predicate(ES, value), value);
};


/***/ }),
/* 494 */
/***/ (function(module, exports) {

module.exports = Number.isNaN || function isNaN(a) {
	return a !== a;
};


/***/ }),
/* 495 */
/***/ (function(module, exports) {

var $isNaN = Number.isNaN || function (a) { return a !== a; };

module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };


/***/ }),
/* 496 */
/***/ (function(module, exports) {

module.exports = function sign(number) {
	return number >= 0 ? 1 : -1;
};


/***/ }),
/* 497 */
/***/ (function(module, exports) {

module.exports = function mod(number, modulo) {
	var remain = number % modulo;
	return Math.floor(remain >= 0 ? remain : remain + modulo);
};


/***/ }),
/* 498 */
/***/ (function(module, exports, __nested_webpack_require_2581690__) {

"use strict";


var GetIntrinsic = __nested_webpack_require_2581690__(207);

var $Object = GetIntrinsic('%Object%');
var $TypeError = GetIntrinsic('%TypeError%');
var $String = GetIntrinsic('%String%');

var assertRecord = __nested_webpack_require_2581690__(493);
var $isNaN = __nested_webpack_require_2581690__(494);
var $isFinite = __nested_webpack_require_2581690__(495);

var sign = __nested_webpack_require_2581690__(496);
var mod = __nested_webpack_require_2581690__(497);

var IsCallable = __nested_webpack_require_2581690__(155);
var toPrimitive = __nested_webpack_require_2581690__(1056);

var has = __nested_webpack_require_2581690__(59);

// https://es5.github.io/#x9
var ES5 = {
	ToPrimitive: toPrimitive,

	ToBoolean: function ToBoolean(value) {
		return !!value;
	},
	ToNumber: function ToNumber(value) {
		return +value; // eslint-disable-line no-implicit-coercion
	},
	ToInteger: function ToInteger(value) {
		var number = this.ToNumber(value);
		if ($isNaN(number)) { return 0; }
		if (number === 0 || !$isFinite(number)) { return number; }
		return sign(number) * Math.floor(Math.abs(number));
	},
	ToInt32: function ToInt32(x) {
		return this.ToNumber(x) >> 0;
	},
	ToUint32: function ToUint32(x) {
		return this.ToNumber(x) >>> 0;
	},
	ToUint16: function ToUint16(value) {
		var number = this.ToNumber(value);
		if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
		var posInt = sign(number) * Math.floor(Math.abs(number));
		return mod(posInt, 0x10000);
	},
	ToString: function ToString(value) {
		return $String(value);
	},
	ToObject: function ToObject(value) {
		this.CheckObjectCoercible(value);
		return $Object(value);
	},
	CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
		/* jshint eqnull:true */
		if (value == null) {
			throw new $TypeError(optMessage || 'Cannot call method on ' + value);
		}
		return value;
	},
	IsCallable: IsCallable,
	SameValue: function SameValue(x, y) {
		if (x === y) { // 0 === -0, but they are not identical.
			if (x === 0) { return 1 / x === 1 / y; }
			return true;
		}
		return $isNaN(x) && $isNaN(y);
	},

	// https://www.ecma-international.org/ecma-262/5.1/#sec-8
	Type: function Type(x) {
		if (x === null) {
			return 'Null';
		}
		if (typeof x === 'undefined') {
			return 'Undefined';
		}
		if (typeof x === 'function' || typeof x === 'object') {
			return 'Object';
		}
		if (typeof x === 'number') {
			return 'Number';
		}
		if (typeof x === 'boolean') {
			return 'Boolean';
		}
		if (typeof x === 'string') {
			return 'String';
		}
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
	IsPropertyDescriptor: function IsPropertyDescriptor(Desc) {
		if (this.Type(Desc) !== 'Object') {
			return false;
		}
		var allowed = {
			'[[Configurable]]': true,
			'[[Enumerable]]': true,
			'[[Get]]': true,
			'[[Set]]': true,
			'[[Value]]': true,
			'[[Writable]]': true
		};

		for (var key in Desc) { // eslint-disable-line
			if (has(Desc, key) && !allowed[key]) {
				return false;
			}
		}

		var isData = has(Desc, '[[Value]]');
		var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
		if (isData && IsAccessor) {
			throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
		}
		return true;
	},

	// https://ecma-international.org/ecma-262/5.1/#sec-8.10.1
	IsAccessorDescriptor: function IsAccessorDescriptor(Desc) {
		if (typeof Desc === 'undefined') {
			return false;
		}

		assertRecord(this, 'Property Descriptor', 'Desc', Desc);

		if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
			return false;
		}

		return true;
	},

	// https://ecma-international.org/ecma-262/5.1/#sec-8.10.2
	IsDataDescriptor: function IsDataDescriptor(Desc) {
		if (typeof Desc === 'undefined') {
			return false;
		}

		assertRecord(this, 'Property Descriptor', 'Desc', Desc);

		if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
			return false;
		}

		return true;
	},

	// https://ecma-international.org/ecma-262/5.1/#sec-8.10.3
	IsGenericDescriptor: function IsGenericDescriptor(Desc) {
		if (typeof Desc === 'undefined') {
			return false;
		}

		assertRecord(this, 'Property Descriptor', 'Desc', Desc);

		if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) {
			return true;
		}

		return false;
	},

	// https://ecma-international.org/ecma-262/5.1/#sec-8.10.4
	FromPropertyDescriptor: function FromPropertyDescriptor(Desc) {
		if (typeof Desc === 'undefined') {
			return Desc;
		}

		assertRecord(this, 'Property Descriptor', 'Desc', Desc);

		if (this.IsDataDescriptor(Desc)) {
			return {
				value: Desc['[[Value]]'],
				writable: !!Desc['[[Writable]]'],
				enumerable: !!Desc['[[Enumerable]]'],
				configurable: !!Desc['[[Configurable]]']
			};
		} else if (this.IsAccessorDescriptor(Desc)) {
			return {
				get: Desc['[[Get]]'],
				set: Desc['[[Set]]'],
				enumerable: !!Desc['[[Enumerable]]'],
				configurable: !!Desc['[[Configurable]]']
			};
		} else {
			throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');
		}
	},

	// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5
	ToPropertyDescriptor: function ToPropertyDescriptor(Obj) {
		if (this.Type(Obj) !== 'Object') {
			throw new $TypeError('ToPropertyDescriptor requires an object');
		}

		var desc = {};
		if (has(Obj, 'enumerable')) {
			desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable);
		}
		if (has(Obj, 'configurable')) {
			desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable);
		}
		if (has(Obj, 'value')) {
			desc['[[Value]]'] = Obj.value;
		}
		if (has(Obj, 'writable')) {
			desc['[[Writable]]'] = this.ToBoolean(Obj.writable);
		}
		if (has(Obj, 'get')) {
			var getter = Obj.get;
			if (typeof getter !== 'undefined' && !this.IsCallable(getter)) {
				throw new TypeError('getter must be a function');
			}
			desc['[[Get]]'] = getter;
		}
		if (has(Obj, 'set')) {
			var setter = Obj.set;
			if (typeof setter !== 'undefined' && !this.IsCallable(setter)) {
				throw new $TypeError('setter must be a function');
			}
			desc['[[Set]]'] = setter;
		}

		if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
			throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
		}
		return desc;
	}
};

module.exports = ES5;


/***/ }),
/* 499 */
/***/ (function(module, exports, __nested_webpack_require_2588060__) {

"use strict";


var has = __nested_webpack_require_2588060__(59);
var regexExec = RegExp.prototype.exec;
var gOPD = Object.getOwnPropertyDescriptor;

var tryRegexExecCall = function tryRegexExec(value) {
	try {
		var lastIndex = value.lastIndex;
		value.lastIndex = 0;

		regexExec.call(value);
		return true;
	} catch (e) {
		return false;
	} finally {
		value.lastIndex = lastIndex;
	}
};
var toStr = Object.prototype.toString;
var regexClass = '[object RegExp]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isRegex(value) {
	if (!value || typeof value !== 'object') {
		return false;
	}
	if (!hasToStringTag) {
		return toStr.call(value) === regexClass;
	}

	var descriptor = gOPD(value, 'lastIndex');
	var hasLastIndexDataProperty = descriptor && has(descriptor, 'value');
	if (!hasLastIndexDataProperty) {
		return false;
	}

	return tryRegexExecCall(value);
};


/***/ }),
/* 500 */
/***/ (function(module, exports, __nested_webpack_require_2589067__) {

"use strict";


var implementation = __nested_webpack_require_2589067__(490);

module.exports = function getPolyfill() {
	return Array.prototype.flat || implementation;
};


/***/ }),
/* 501 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.is */

var NumberIsNaN = function (value) {
	return value !== value;
};

module.exports = function is(a, b) {
	if (a === 0 && b === 0) {
		return 1 / a === 1 / b;
	} else if (a === b) {
		return true;
	} else if (NumberIsNaN(a) && NumberIsNaN(b)) {
		return true;
	}
	return false;
};



/***/ }),
/* 502 */
/***/ (function(module, exports, __nested_webpack_require_2589752__) {

"use strict";


var define = __nested_webpack_require_2589752__(52);

var implementation = __nested_webpack_require_2589752__(503);
var getPolyfill = __nested_webpack_require_2589752__(505);
var shim = __nested_webpack_require_2589752__(1059);

var polyfill = getPolyfill();

define(polyfill, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = polyfill;


/***/ }),
/* 503 */
/***/ (function(module, exports, __nested_webpack_require_2590170__) {

"use strict";


var ES = __nested_webpack_require_2590170__(504);
var has = __nested_webpack_require_2590170__(59);
var bind = __nested_webpack_require_2590170__(53);
var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);

module.exports = function entries(O) {
	var obj = ES.RequireObjectCoercible(O);
	var entrys = [];
	for (var key in obj) {
		if (has(obj, key) && isEnumerable(obj, key)) {
			entrys.push([key, obj[key]]);
		}
	}
	return entrys;
};


/***/ }),
/* 504 */
/***/ (function(module, exports, __nested_webpack_require_2590686__) {

"use strict";


module.exports = __nested_webpack_require_2590686__(491);


/***/ }),
/* 505 */
/***/ (function(module, exports, __nested_webpack_require_2590824__) {

"use strict";


var implementation = __nested_webpack_require_2590824__(503);

module.exports = function getPolyfill() {
	return typeof Object.entries === 'function' ? Object.entries : implementation;
};


/***/ }),
/* 506 */
/***/ (function(module, exports, __nested_webpack_require_2591092__) {

"use strict";


var isCallable = __nested_webpack_require_2591092__(155);
var functionsHaveNames = __nested_webpack_require_2591092__(507);
var bind = __nested_webpack_require_2591092__(53);
var functionToString = bind.call(Function.call, Function.prototype.toString);
var stringMatch = bind.call(Function.call, String.prototype.match);

var classRegex = /^class /;

var isClass = function isClassConstructor(fn) {
	if (isCallable(fn)) {
		return false;
	}
	if (typeof fn !== 'function') {
		return false;
	}
	try {
		var match = stringMatch(functionToString(fn), classRegex);
		return !!match;
	} catch (e) {}
	return false;
};

var regex = /\s*function\s+([^(\s]*)\s*/;

var functionProto = Function.prototype;

module.exports = function getName() {
	if (!isClass(this) && !isCallable(this)) {
		throw new TypeError('Function.prototype.name sham getter called on non-function');
	}
	if (functionsHaveNames) {
		return this.name;
	}
	if (this === functionProto) {
		return '';
	}
	var str = functionToString(this);
	var match = stringMatch(str, regex);
	var name = match && match[1];
	return name;
};


/***/ }),
/* 507 */
/***/ (function(module, exports) {

module.exports = typeof function foo() {}.name === 'string'; // when function names are minified, checking for "foo" would break


/***/ }),
/* 508 */
/***/ (function(module, exports, __nested_webpack_require_2592415__) {

"use strict";


var implementation = __nested_webpack_require_2592415__(506);

module.exports = function getPolyfill() {
	return implementation;
};


/***/ }),
/* 509 */
/***/ (function(module, exports, __nested_webpack_require_2592627__) {

"use strict";


var bind = __nested_webpack_require_2592627__(53);
var ES = __nested_webpack_require_2592627__(498);
var replace = bind.call(Function.call, String.prototype.replace);

var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/;
var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+$/;

module.exports = function trim() {
	var S = ES.ToString(ES.CheckObjectCoercible(this));
	return replace(replace(S, leftWhitespace, ''), rightWhitespace, '');
};


/***/ }),
/* 510 */
/***/ (function(module, exports, __nested_webpack_require_2593365__) {

"use strict";


var implementation = __nested_webpack_require_2593365__(509);

var zeroWidthSpace = '\u200b';

module.exports = function getPolyfill() {
	if (String.prototype.trim && zeroWidthSpace.trim() === zeroWidthSpace) {
		return String.prototype.trim;
	}
	return implementation;
};


/***/ }),
/* 511 */
/***/ (function(module, exports, __nested_webpack_require_2593718__) {

"use strict";


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

var _EnzymeAdapter = __nested_webpack_require_2593718__(512);

var _EnzymeAdapter2 = _interopRequireDefault(_EnzymeAdapter);

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

function validateAdapter(adapter) {
  if (!adapter) {
    throw new Error('\n      Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.\n      To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`\n      before using any of Enzyme\'s top level APIs, where `Adapter` is the adapter\n      corresponding to the library currently being tested. For example:\n\n      import Adapter from \'enzyme-adapter-react-15\';\n\n      To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html\n    ');
  }
  if (typeof adapter === 'function') {
    if (Object.getPrototypeOf(adapter) === _EnzymeAdapter2['default']) {
      throw new Error('\n        Enzyme Internal Error: Enzyme expects an adapter instance to be configured -\n        you provided an adapter *constructor*.\n        To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`\n        before using any of Enzyme\'s top level APIs, where `Adapter` is the adapter\n        corresponding to the library currently being tested. For example:\n\n        import Adapter from \'enzyme-adapter-react-15\';\n\n        To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html\n      ');
    }
    throw new Error('\n      Enzyme Internal Error: Enzyme expects an adapter to be configured -\n      an enzyme adapter must be an object instance; you provided a function.\n      To configure an adapter, you should call `Enzyme.configure({ adapter: new Adapter() })`\n      before using any of Enzyme\'s top level APIs, where `Adapter` is the adapter\n      corresponding to the library currently being tested. For example:\n\n      import Adapter from \'enzyme-adapter-react-15\';\n\n      To find out more about this, see http://airbnb.io/enzyme/docs/installation/index.html\n    ');
  }
  if (!(adapter instanceof _EnzymeAdapter2['default'])) {
    throw new Error('Enzyme Internal Error: configured enzyme adapter did not inherit from the EnzymeAdapter base class');
  }
}

/***/ }),
/* 512 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function unimplementedError(methodName, classname) {
  return new Error(String(methodName) + ' is a required method of ' + String(classname) + ', but was not implemented.');
}

var EnzymeAdapter = function () {
  function EnzymeAdapter() {
    _classCallCheck(this, EnzymeAdapter);

    this.options = {};
  }

  // Provided a bag of options, return an `EnzymeRenderer`. Some options can be implementation
  // specific, like `attach` etc. for React, but not part of this interface explicitly.
  // eslint-disable-next-line class-methods-use-this, no-unused-vars


  _createClass(EnzymeAdapter, [{
    key: 'createRenderer',
    value: function () {
      function createRenderer(options) {
        throw unimplementedError('createRenderer', 'EnzymeAdapter');
      }

      return createRenderer;
    }()

    // converts an RSTNode to the corresponding JSX Pragma Element. This will be needed
    // in order to implement the `Wrapper.mount()` and `Wrapper.shallow()` methods, but should
    // be pretty straightforward for people to implement.
    // eslint-disable-next-line class-methods-use-this, no-unused-vars

  }, {
    key: 'nodeToElement',
    value: function () {
      function nodeToElement(node) {
        throw unimplementedError('nodeToElement', 'EnzymeAdapter');
      }

      return nodeToElement;
    }()

    // eslint-disable-next-line class-methods-use-this, no-unused-vars

  }, {
    key: 'isValidElement',
    value: function () {
      function isValidElement(element) {
        throw unimplementedError('isValidElement', 'EnzymeAdapter');
      }

      return isValidElement;
    }()

    // eslint-disable-next-line class-methods-use-this, no-unused-vars

  }, {
    key: 'createElement',
    value: function () {
      function createElement(type, props) {
        throw unimplementedError('createElement', 'EnzymeAdapter');
      }

      return createElement;
    }()

    // eslint-disable-next-line class-methods-use-this

  }, {
    key: 'invokeSetStateCallback',
    value: function () {
      function invokeSetStateCallback(instance, callback) {
        callback.call(instance);
      }

      return invokeSetStateCallback;
    }()
  }]);

  return EnzymeAdapter;
}();

EnzymeAdapter.MODES = {
  STRING: 'string',
  MOUNT: 'mount',
  SHALLOW: 'shallow'
};

module.exports = EnzymeAdapter;

/***/ }),
/* 513 */
/***/ (function(module, exports, __nested_webpack_require_2599339__) {

"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; };

exports.typeName = typeName;
exports.spaces = spaces;
exports.indent = indent;
exports.debugNode = debugNode;
exports.debugNodes = debugNodes;

var _lodash = __nested_webpack_require_2599339__(1064);

var _lodash2 = _interopRequireDefault(_lodash);

var _functionPrototype = __nested_webpack_require_2599339__(314);

var _functionPrototype2 = _interopRequireDefault(_functionPrototype);

var _isString = __nested_webpack_require_2599339__(1065);

var _isString2 = _interopRequireDefault(_isString);

var _isNumberObject = __nested_webpack_require_2599339__(1066);

var _isNumberObject2 = _interopRequireDefault(_isNumberObject);

var _isCallable = __nested_webpack_require_2599339__(155);

var _isCallable2 = _interopRequireDefault(_isCallable);

var _isBooleanObject = __nested_webpack_require_2599339__(1067);

var _isBooleanObject2 = _interopRequireDefault(_isBooleanObject);

var _objectInspect = __nested_webpack_require_2599339__(1068);

var _objectInspect2 = _interopRequireDefault(_objectInspect);

var _has = __nested_webpack_require_2599339__(59);

var _has2 = _interopRequireDefault(_has);

var _RSTTraversal = __nested_webpack_require_2599339__(156);

var _getAdapter = __nested_webpack_require_2599339__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

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

var booleanValue = Function.bind.call(Function.call, Boolean.prototype.valueOf);

function typeName(node) {
  var adapter = (0, _getAdapter2['default'])();
  if (adapter.displayNameOfNode) {
    return (0, _getAdapter2['default'])().displayNameOfNode(node) || 'Component';
  }
  return typeof node.type === 'function' ? node.type.displayName || (0, _functionPrototype2['default'])(node.type) || 'Component' : node.type;
}

function spaces(n) {
  return Array(n + 1).join(' ');
}

function indent(depth, string) {
  return string.split('\n').map(function (x) {
    return '' + String(spaces(depth)) + String(x);
  }).join('\n');
}

function propString(prop, options) {
  if ((0, _isString2['default'])(prop)) {
    return (0, _objectInspect2['default'])(String(prop), { quoteStyle: 'double' });
  }
  if ((0, _isNumberObject2['default'])(prop)) {
    return '{' + String((0, _objectInspect2['default'])(Number(prop))) + '}';
  }
  if ((0, _isBooleanObject2['default'])(prop)) {
    return '{' + String((0, _objectInspect2['default'])(booleanValue(prop))) + '}';
  }
  if ((0, _isCallable2['default'])(prop)) {
    return '{' + String((0, _objectInspect2['default'])(prop)) + '}';
  }
  if ((typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) === 'object') {
    if (options.verbose) {
      return '{' + String((0, _objectInspect2['default'])(prop)) + '}';
    }

    return '{{...}}';
  }
  return '{[' + (typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) + ']}';
}

function propsString(node, options) {
  var props = (0, _RSTTraversal.propsOfNode)(node);
  var keys = Object.keys(props).filter(function (x) {
    return x !== 'children';
  });
  return keys.map(function (key) {
    return String(key) + '=' + String(propString(props[key], options));
  }).join(' ');
}

function indentChildren(childrenStrs, indentLength) {
  return childrenStrs.length ? '\n' + String(childrenStrs.map(function (x) {
    return indent(indentLength, x);
  }).join('\n')) + '\n' : '';
}

function isRSTNodeLike(node) {
  return (0, _has2['default'])(node, 'nodeType') && typeof node.nodeType === 'string' && (0, _has2['default'])(node, 'type') && (0, _has2['default'])(node, 'key') && (0, _has2['default'])(node, 'ref') && (0, _has2['default'])(node, 'instance') && (0, _has2['default'])(node, 'rendered');
}

function debugNode(node) {
  var indentLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  if (typeof node === 'string' || typeof node === 'number') return (0, _lodash2['default'])(node);
  if (typeof node === 'function') {
    var name = (0, _functionPrototype2['default'])(node);
    return '[function' + (name ? ' ' + String(name) : '') + ']';
  }
  if (!node) return '';

  var adapter = (0, _getAdapter2['default'])();
  if (!adapter.isValidElement(node) && !isRSTNodeLike(node)) {
    return '{' + String((0, _objectInspect2['default'])(node)) + '}';
  }

  var childrenStrs = (0, _RSTTraversal.childrenOfNode)(node).map(function (n) {
    return debugNode(n, indentLength, options);
  }).filter(Boolean);
  var type = typeName(node);

  var props = options.ignoreProps ? '' : propsString(node, options);
  var beforeProps = props ? ' ' : '';
  var afterProps = childrenStrs.length ? '>' : ' ';
  var childrenIndented = indentChildren(childrenStrs, indentLength);
  var nodeClose = childrenStrs.length ? '</' + String(type) + '>' : '/>';
  return '<' + String(type) + beforeProps + String(props) + afterProps + String(childrenIndented) + nodeClose;
}

function debugNodes(nodes) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  return nodes.map(function (node) {
    return debugNode(node, undefined, options);
  }).join('\n\n\n');
}

/***/ }),
/* 514 */
/***/ (function(module, exports, __nested_webpack_require_2604814__) {

"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; };

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.buildPredicate = buildPredicate;
exports.reduceTreeBySelector = reduceTreeBySelector;
exports.reduceTreesBySelector = reduceTreesBySelector;

var _rstSelectorParser = __nested_webpack_require_2604814__(1070);

var _object = __nested_webpack_require_2604814__(1076);

var _object2 = _interopRequireDefault(_object);

var _arrayPrototype = __nested_webpack_require_2604814__(154);

var _arrayPrototype2 = _interopRequireDefault(_arrayPrototype);

var _objectIs = __nested_webpack_require_2604814__(501);

var _objectIs2 = _interopRequireDefault(_objectIs);

var _has = __nested_webpack_require_2604814__(59);

var _has2 = _interopRequireDefault(_has);

var _byConstructor = __nested_webpack_require_2604814__(1078);

var _byConstructor2 = _interopRequireDefault(_byConstructor);

var _RSTTraversal = __nested_webpack_require_2604814__(156);

var _Utils = __nested_webpack_require_2604814__(313);

var _getAdapter = __nested_webpack_require_2604814__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': 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); } }

// our CSS selector parser instance
var parser = (0, _rstSelectorParser.createParser)();

// Combinators that allow you to chance selectors
var CHILD = 'childCombinator';
var ADJACENT_SIBLING = 'adjacentSiblingCombinator';
var GENERAL_SIBLING = 'generalSiblingCombinator';
var DESCENDANT = 'descendantCombinator';

// Selectors for targeting elements
var SELECTOR = 'selector';
var TYPE_SELECTOR = 'typeSelector';
var CLASS_SELECTOR = 'classSelector';
var ID_SELECTOR = 'idSelector';
var UNIVERSAL_SELECTOR = 'universalSelector';
var ATTRIBUTE_PRESENCE = 'attributePresenceSelector';
var ATTRIBUTE_VALUE = 'attributeValueSelector';
// @TODO we dont support these, throw if they are used
var PSEUDO_CLASS = 'pseudoClassSelector';
var PSEUDO_ELEMENT = 'pseudoElementSelector';

var EXACT_ATTRIBUTE_OPERATOR = '=';
var WHITELIST_ATTRIBUTE_OPERATOR = '~=';
var HYPHENATED_ATTRIBUTE_OPERATOR = '|=';
var PREFIX_ATTRIBUTE_OPERATOR = '^=';
var SUFFIX_ATTRIBUTE_OPERATOR = '$=';
var SUBSTRING_ATTRIBUTE_OPERATOR = '*=';

function unique(arr) {
  return [].concat(_toConsumableArray(new Set(arr)));
}

/**
 * Calls reduce on a array of nodes with the passed
 * function, returning only unique results.
 * @param {Function} fn
 * @param {Array<Node>} nodes
 */
function uniqueReduce(fn, nodes) {
  return unique(nodes.reduce(fn, []));
}

/**
 * Takes a CSS selector and returns a set of tokens parsed
 * by scalpel.
 * @param {String} selector
 */
function safelyGenerateTokens(selector) {
  try {
    return parser.parse(selector);
  } catch (err) {
    throw new Error('Failed to parse selector: ' + String(selector));
  }
}

function matchAttributeSelector(node, token) {
  var operator = token.operator,
      value = token.value,
      name = token.name;

  var nodeProps = (0, _Utils.propsOfNode)(node);
  var descriptor = Object.getOwnPropertyDescriptor(nodeProps, name);
  if (descriptor && descriptor.get) {
    return false;
  }
  var nodePropValue = nodeProps[name];
  if (typeof nodePropValue === 'undefined') {
    return false;
  }
  if (token.type === ATTRIBUTE_PRESENCE) {
    return (0, _has2['default'])(nodeProps, token.name);
  }
  // Only the exact value operator ("=") can match non-strings
  if (typeof nodePropValue !== 'string' || typeof value !== 'string') {
    if (operator !== EXACT_ATTRIBUTE_OPERATOR) {
      return false;
    }
  }
  switch (operator) {
    /**
     * Represents an element with the att attribute whose value is exactly "val".
     * @example
     * [attr="val"] matches attr="val"
     */
    case EXACT_ATTRIBUTE_OPERATOR:
      return (0, _objectIs2['default'])(nodePropValue, value);
    /**
     * Represents an element with the att attribute whose value is a whitespace-separated
     * list of words, one of which is exactly
     * @example
     *  [rel~="copyright"] matches rel="copyright other"
     */
    case WHITELIST_ATTRIBUTE_OPERATOR:
      return nodePropValue.split(' ').indexOf(value) !== -1;
    /**
     * Represents an element with the att attribute, its value either being exactly the
     * value or beginning with the value immediately followed by "-"
     * @example
     * [hreflang|="en"] matches hreflang="en-US"
     */
    case HYPHENATED_ATTRIBUTE_OPERATOR:
      return nodePropValue === value || nodePropValue.startsWith(String(value) + '-');
    /**
     * Represents an element with the att attribute whose value begins with the prefix value.
     * If the value is the empty string then the selector does not represent anything.
     * @example
     * [type^="image"] matches type="imageobject"
     */
    case PREFIX_ATTRIBUTE_OPERATOR:
      return value === '' ? false : nodePropValue.slice(0, value.length) === value;
    /**
     * Represents an element with the att attribute whose value ends with the suffix value.
     * If the value is the empty string then the selector does not represent anything.
     * @example
     * [type$="image"] matches type="imageobject"
     */
    case SUFFIX_ATTRIBUTE_OPERATOR:
      return value === '' ? false : nodePropValue.slice(-value.length) === value;
    /**
     * Represents an element with the att attribute whose value contains at least one
     * instance of the value. If value is the empty string then the
     * selector does not represent anything.
     * @example
     * [title*="hello"] matches title="well hello there"
     */
    case SUBSTRING_ATTRIBUTE_OPERATOR:
      return value === '' ? false : nodePropValue.indexOf(value) !== -1;
    default:
      throw new Error('Enzyme::Selector: Unknown attribute selector operator "' + String(operator) + '"');
  }
}

function matchPseudoSelector(node, token, root) {
  var name = token.name,
      parameters = token.parameters;

  if (name === 'not') {
    // eslint-disable-next-line no-use-before-define
    return parameters.every(function (selector) {
      return reduceTreeBySelector(selector, node).length === 0;
    });
  }
  if (name === 'empty') {
    return (0, _RSTTraversal.treeFilter)(node, function (n) {
      return n !== node;
    }).length === 0;
  }
  if (name === 'first-child') {
    var _findParentNode = (0, _RSTTraversal.findParentNode)(root, node),
        rendered = _findParentNode.rendered;

    var _rendered = _slicedToArray(rendered, 1),
        firstChild = _rendered[0];

    return firstChild === node;
  }
  if (name === 'last-child') {
    var _findParentNode2 = (0, _RSTTraversal.findParentNode)(root, node),
        _rendered2 = _findParentNode2.rendered;

    return _rendered2[_rendered2.length - 1] === node;
  }
  if (name === 'focus') {
    if (typeof document === 'undefined') {
      throw new Error('Enzyme::Selector does not support the ":focus" pseudo-element without a global `document`.');
    }
    var adapter = (0, _getAdapter2['default'])();
    /* eslint-env browser */
    return document.activeElement && adapter.nodeToHostNode(node) === document.activeElement;
  }

  throw new TypeError('Enzyme::Selector does not support the "' + String(token.name) + '" pseudo-element or pseudo-class selectors.');
}

/**
 * Takes a node and a token and determines if the node
 * matches the predicate defined by the token.
 * @param {Node} node
 * @param {Token} token
 */
function nodeMatchesToken(node, token, root) {
  if (node === null || typeof node === 'string') {
    return false;
  }
  switch (token.type) {
    /**
     * Match every node
     * @example '*' matches every node
     */
    case UNIVERSAL_SELECTOR:
      return true;
    /**
     * Match against the className prop
     * @example '.active' matches <div className='active' />
     */
    case CLASS_SELECTOR:
      return (0, _RSTTraversal.hasClassName)(node, token.name);
    /**
     * Simple type matching
     * @example 'div' matches <div />
     */
    case TYPE_SELECTOR:
      return (0, _Utils.nodeHasType)(node, token.name);
    /**
     * Match against the `id` prop
     * @example '#nav' matches <ul id="nav" />
     */
    case ID_SELECTOR:
      return (0, _RSTTraversal.nodeHasId)(node, token.name);
    /**
     * Matches if an attribute is present, regardless
     * of its value
     * @example '[disabled]' matches <a disabled />
     */
    case ATTRIBUTE_PRESENCE:
      return matchAttributeSelector(node, token);
    /**
     * Matches if an attribute is present with the
     * provided value
     * @example '[data-foo=foo]' matches <div data-foo="foo" />
     */
    case ATTRIBUTE_VALUE:
      return matchAttributeSelector(node, token);
    case PSEUDO_ELEMENT:
    case PSEUDO_CLASS:
      return matchPseudoSelector(node, token, root);
    default:
      throw new Error('Unknown token type: ' + String(token.type));
  }
}

/**
 * Returns a predicate function that checks if a
 * node matches every token in the body of a selector
 * token.
 * @param {Token} token
 */
function buildPredicateFromToken(token, root) {
  return function (node) {
    return token.body.every(function (bodyToken) {
      return nodeMatchesToken(node, bodyToken, root);
    });
  };
}

/**
 * Returns whether a parsed selector is a complex selector, which
 * is defined as a selector that contains combinators.
 * @param {Array<Token>} tokens
 */
function isComplexSelector(tokens) {
  return tokens.some(function (token) {
    return token.type !== SELECTOR;
  });
}

/**
 * Takes a component constructor, object, or string representing
 * a simple selector and returns a predicate function that can
 * be applied to a single node.
 * @param {EnzymeSelector} selector
 */
function buildPredicate(selector) {
  // If the selector is a string, parse it as a simple CSS selector
  if (typeof selector === 'string') {
    var tokens = safelyGenerateTokens(selector);
    if (isComplexSelector(tokens)) {
      throw new TypeError('This method does not support complex CSS selectors');
    }
    // Simple selectors only have a single selector token
    return buildPredicateFromToken(tokens[0]);
  }

  // If the selector is an element type, check if the node's type matches
  var adapter = (0, _getAdapter2['default'])();
  var isElementType = adapter.isValidElementType ? adapter.isValidElementType(selector) : typeof selector === 'function';
  if (isElementType) {
    return function (node) {
      return node && node.type === selector;
    };
  }
  // If the selector is an non-empty object, treat the keys/values as props
  if ((typeof selector === 'undefined' ? 'undefined' : _typeof(selector)) === 'object') {
    if (!Array.isArray(selector) && selector !== null && Object.keys(selector).length > 0) {
      var hasUndefinedValues = (0, _object2['default'])(selector).some(function (value) {
        return typeof value === 'undefined';
      });
      if (hasUndefinedValues) {
        throw new TypeError('Enzyme::Props can’t have `undefined` values. Try using ‘findWhere()’ instead.');
      }
      return function (node) {
        return (0, _RSTTraversal.nodeMatchesObjectProps)(node, selector);
      };
    }
    throw new TypeError('Enzyme::Selector does not support an array, null, or empty object as a selector');
  }

  throw new TypeError('Enzyme::Selector expects a string, object, or valid element type (Component Constructor)');
}

/**
 * Matches only nodes which are adjacent siblings (direct next sibling)
 * against a predicate, returning those that match.
 * @param {Array<Node>} nodes
 * @param {Function} predicate
 * @param {Node} root
 */
function matchAdjacentSiblings(nodes, predicate, root) {
  return nodes.reduce(function (matches, node) {
    var parent = (0, _RSTTraversal.findParentNode)(root, node);
    // If there's no parent, there's no siblings
    if (!parent) {
      return matches;
    }
    var parentChildren = (0, _RSTTraversal.childrenOfNode)(parent);
    var nodeIndex = parentChildren.indexOf(node);
    var adjacentSibling = parentChildren[nodeIndex + 1];
    // No sibling
    if (!adjacentSibling) {
      return matches;
    }
    if (predicate(adjacentSibling)) {
      matches.push(adjacentSibling);
    }
    return matches;
  }, []);
}

/**
 * Matches only nodes which are general siblings (any sibling *after*)
 * against a predicate, returning those that match.
 * @param {Array<Node>} nodes
 * @param {Function} predicate
 * @param {Node} root
 */
function matchGeneralSibling(nodes, predicate, root) {
  return uniqueReduce(function (matches, node) {
    var parent = (0, _RSTTraversal.findParentNode)(root, node);
    if (!parent) {
      return matches;
    }
    var parentChildren = (0, _RSTTraversal.childrenOfNode)(parent);
    var nodeIndex = parentChildren.indexOf(node);
    var youngerSiblings = parentChildren.slice(nodeIndex + 1);
    return matches.concat(youngerSiblings.filter(predicate));
  }, nodes);
}

/**
 * Matches only nodes which are direct children (not grandchildren, etc.)
 * against a predicate, returning those that match.
 * @param {Array<Node>} nodes
 * @param {Function} predicate
 */
function matchDirectChild(nodes, predicate) {
  return uniqueReduce(function (matches, node) {
    return matches.concat((0, _RSTTraversal.childrenOfNode)(node).filter(predicate));
  }, nodes);
}

/**
 * Matches all descendant nodes against a predicate,
 * returning those that match.
 * @param {Array<Node>} nodes
 * @param {Function} predicate
 */
function matchDescendant(nodes, predicate) {
  return uniqueReduce(function (matches, node) {
    return matches.concat((0, _RSTTraversal.treeFilter)(node, predicate));
  }, (0, _arrayPrototype2['default'])(nodes.map(_RSTTraversal.childrenOfNode)));
}

/**
 * Takes an RST and reduces it to a set of nodes matching
 * the selector. The selector can be a simple selector, which
 * is handled by `buildPredicate`, or a complex CSS selector which
 * reduceTreeBySelector parses and reduces the tree based on the combinators.
 *
 * @param {EnzymeSelector} selector
 * @param {RSTNode} root
 */
function reduceTreeBySelector(selector, root) {
  if (typeof selector !== 'string') {
    var elements = (0, _byConstructor2['default'])(selector);
    if (elements.length > 0) {
      return (0, _arrayPrototype2['default'])(elements.map(function (x) {
        return reduceTreeBySelector(x.tag, root);
      }));

      // when https://github.com/aweary/rst-selector-parser/issues/15 is resolved
      // const htmlTagNames = elements.map(x => x.tag).join(', ');
      // return reduceTreeBySelector(htmlTagNames, root);
    }
  }

  if (typeof selector === 'function' || (typeof selector === 'undefined' ? 'undefined' : _typeof(selector)) === 'object') {
    return (0, _RSTTraversal.treeFilter)(root, buildPredicate(selector));
  }

  var results = [];
  if (typeof selector === 'string') {
    var tokens = safelyGenerateTokens(selector);
    var index = 0;
    while (index < tokens.length) {
      var token = tokens[index];
      /**
       * There are two types of tokens in a CSS selector:
       *
       * 1. Selector tokens. These target nodes directly, like
       *    type or attribute selectors. These are easy to apply
       *    because we can traverse the tree and return only
       *    the nodes that match the predicate.
       *
       * 2. Combinator tokens. These tokens chain together
       *    selector nodes. For example > for children, or +
       *    for adjacent siblings. These are harder to match
       *    as we have to track where in the tree we are
       *    to determine if a selector node applies or not.
       */
      if (token.type === SELECTOR) {
        var predicate = buildPredicateFromToken(token, root);
        results = results.concat((0, _RSTTraversal.treeFilter)(root, predicate));
      } else {
        // We can assume there always all previously matched tokens since selectors
        // cannot start with combinators.
        var type = token.type;
        // We assume the next token is a selector, so move the index
        // forward and build the predicate.

        index += 1;
        var _predicate = buildPredicateFromToken(tokens[index], root);
        // We match against only the nodes which have already been matched,
        // since a combinator is meant to refine a previous selector.
        switch (type) {
          // The + combinator
          case ADJACENT_SIBLING:
            results = matchAdjacentSiblings(results, _predicate, root);
            break;
          // The ~ combinator
          case GENERAL_SIBLING:
            results = matchGeneralSibling(results, _predicate, root);
            break;
          // The > combinator
          case CHILD:
            results = matchDirectChild(results, _predicate);
            break;
          // The ' ' (whitespace) combinator
          case DESCENDANT:
            {
              results = matchDescendant(results, _predicate);
              break;
            }
          default:
            throw new Error('Unknown combinator selector: ' + String(type));
        }
      }
      index += 1;
    }
  } else {
    throw new TypeError('Enzyme::Selector expects a string, object, or Component Constructor');
  }
  return results;
}

function reduceTreesBySelector(selector, roots) {
  var results = roots.map(function (n) {
    return reduceTreeBySelector(selector, n);
  });
  return unique((0, _arrayPrototype2['default'])(results, 1));
}

/***/ }),
/* 515 */
/***/ (function(module, exports, __nested_webpack_require_2623325__) {

"use strict";


var ES = __nested_webpack_require_2623325__(504);
var has = __nested_webpack_require_2623325__(59);
var bind = __nested_webpack_require_2623325__(53);
var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable);

module.exports = function values(O) {
	var obj = ES.RequireObjectCoercible(O);
	var vals = [];
	for (var key in obj) {
		if (has(obj, key) && isEnumerable(obj, key)) {
			vals.push(obj[key]);
		}
	}
	return vals;
};


/***/ }),
/* 516 */
/***/ (function(module, exports, __nested_webpack_require_2623827__) {

"use strict";


var implementation = __nested_webpack_require_2623827__(515);

module.exports = function getPolyfill() {
	return typeof Object.values === 'function' ? Object.values : implementation;
};


/***/ }),
/* 517 */
/***/ (function(module, exports, __nested_webpack_require_2624093__) {

"use strict";


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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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; };

var _object = __nested_webpack_require_2624093__(122);

var _object2 = _interopRequireDefault(_object);

var _arrayPrototype = __nested_webpack_require_2624093__(154);

var _arrayPrototype2 = _interopRequireDefault(_arrayPrototype);

var _cheerio = __nested_webpack_require_2624093__(296);

var _cheerio2 = _interopRequireDefault(_cheerio);

var _has = __nested_webpack_require_2624093__(59);

var _has2 = _interopRequireDefault(_has);

var _Utils = __nested_webpack_require_2624093__(313);

var _getAdapter = __nested_webpack_require_2624093__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

var _Debug = __nested_webpack_require_2624093__(513);

var _RSTTraversal = __nested_webpack_require_2624093__(156);

var _selectors = __nested_webpack_require_2624093__(514);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var NODE = (0, _Utils.sym)('__node__');
var NODES = (0, _Utils.sym)('__nodes__');
var RENDERER = (0, _Utils.sym)('__renderer__');
var UNRENDERED = (0, _Utils.sym)('__unrendered__');
var ROOT = (0, _Utils.sym)('__root__');
var OPTIONS = (0, _Utils.sym)('__options__');
var SET_STATE = (0, _Utils.sym)('__setState__');
var ROOT_NODES = (0, _Utils.sym)('__rootNodes__');
var CHILD_CONTEXT = (0, _Utils.sym)('__childContext__');

/**
 * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
 * function.
 *
 * @param {ShallowWrapper} wrapper
 * @param {Function} predicate
 * @param {Function} filter
 * @returns {ShallowWrapper}
 */
function findWhereUnwrapped(wrapper, predicate) {
  var filter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _RSTTraversal.treeFilter;

  return wrapper.flatMap(function (n) {
    return filter(n.getNodeInternal(), predicate);
  });
}

/**
 * Returns a new wrapper instance with only the nodes of the current wrapper instance that match
 * the provided predicate function.
 *
 * @param {ShallowWrapper} wrapper
 * @param {Function} predicate
 * @returns {ShallowWrapper}
 */
function filterWhereUnwrapped(wrapper, predicate) {
  return wrapper.wrap(wrapper.getNodesInternal().filter(predicate).filter(Boolean));
}

/**
 * Ensure options passed to ShallowWrapper are valid. Throws otherwise.
 * @param {Object} options
 */
function validateOptions(options) {
  var lifecycleExperimental = options.lifecycleExperimental,
      disableLifecycleMethods = options.disableLifecycleMethods,
      enableComponentDidUpdateOnSetState = options.enableComponentDidUpdateOnSetState,
      supportPrevContextArgumentOfComponentDidUpdate = options.supportPrevContextArgumentOfComponentDidUpdate,
      lifecycles = options.lifecycles;

  if (typeof lifecycleExperimental !== 'undefined' && typeof lifecycleExperimental !== 'boolean') {
    throw new Error('lifecycleExperimental must be either true or false if provided');
  }

  if (typeof disableLifecycleMethods !== 'undefined' && typeof disableLifecycleMethods !== 'boolean') {
    throw new Error('disableLifecycleMethods must be either true or false if provided');
  }

  if (lifecycleExperimental != null && disableLifecycleMethods != null && lifecycleExperimental === disableLifecycleMethods) {
    throw new Error('lifecycleExperimental and disableLifecycleMethods cannot be set to the same value');
  }

  if (typeof enableComponentDidUpdateOnSetState !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState !== enableComponentDidUpdateOnSetState) {
    throw new TypeError('the legacy enableComponentDidUpdateOnSetState option should be matched by `lifecycles: { componentDidUpdate: { onSetState: true } }`, for compatibility');
  }

  if (typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined' && lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.prevContext !== supportPrevContextArgumentOfComponentDidUpdate) {
    throw new TypeError('the legacy supportPrevContextArgumentOfComponentDidUpdate option should be matched by `lifecycles: { componentDidUpdate: { prevContext: true } }`, for compatibility');
  }
}

function getAdapterLifecycles(_ref) {
  var options = _ref.options;
  var _options$lifecycles = options.lifecycles,
      lifecycles = _options$lifecycles === undefined ? {} : _options$lifecycles,
      enableComponentDidUpdateOnSetState = options.enableComponentDidUpdateOnSetState,
      supportPrevContextArgumentOfComponentDidUpdate = options.supportPrevContextArgumentOfComponentDidUpdate;


  var hasLegacySetStateArg = typeof enableComponentDidUpdateOnSetState !== 'undefined';
  var hasLegacyPrevContextArg = typeof supportPrevContextArgumentOfComponentDidUpdate !== 'undefined';
  var componentDidUpdate = hasLegacySetStateArg || hasLegacyPrevContextArg ? (0, _object2['default'])({}, hasLegacySetStateArg && {
    onSetState: !!enableComponentDidUpdateOnSetState
  }, hasLegacyPrevContextArg && {
    prevContext: !!supportPrevContextArgumentOfComponentDidUpdate
  }) : null;

  return (0, _object2['default'])({}, lifecycles, {
    setState: (0, _object2['default'])({}, lifecycles.setState),
    getChildContext: (0, _object2['default'])({
      calledByRenderer: true
    }, lifecycles.getChildContext)
  }, componentDidUpdate && { componentDidUpdate: componentDidUpdate });
}

function getRootNode(node) {
  if (node.nodeType === 'host') {
    return node;
  }
  return node.rendered;
}

function getRootNodeInternal(wrapper) {
  if (wrapper[ROOT].length !== 1) {
    throw new Error('getRootNodeInternal(wrapper) can only be called when wrapper wraps one node');
  }
  if (wrapper[ROOT] !== wrapper) {
    return wrapper[ROOT_NODES][0];
  }
  return wrapper[ROOT][NODE];
}

function nodeParents(wrapper, node) {
  return (0, _RSTTraversal.parentsOfNode)(node, getRootNodeInternal(wrapper));
}

function privateSetNodes(wrapper, nodes) {
  if (!Array.isArray(nodes)) {
    (0, _Utils.privateSet)(wrapper, NODE, nodes);
    (0, _Utils.privateSet)(wrapper, NODES, [nodes]);
  } else {
    (0, _Utils.privateSet)(wrapper, NODE, nodes[0]);
    (0, _Utils.privateSet)(wrapper, NODES, nodes);
  }
  (0, _Utils.privateSet)(wrapper, 'length', wrapper[NODES].length);
}

function pureComponentShouldComponentUpdate(prevProps, props, prevState, state) {
  return !(0, _Utils.shallowEqual)(prevProps, props) || !(0, _Utils.shallowEqual)(prevState, state);
}

function isPureComponent(instance) {
  return instance && instance.isPureReactComponent;
}

function getChildContext(node, hierarchy, renderer) {
  var instance = node.instance,
      Component = node.type;

  var componentName = (0, _Utils.displayNameOfNode)(node);
  // Warn like react if childContextTypes is not defined:
  // https://github.com/facebook/react/blob/1454a8be03794f5e0b23a7e7696cbbbdcf8b0f5d/packages/react-dom/src/server/ReactPartialRenderer.js#L639-L646
  if (_typeof(Component.childContextTypes) !== 'object') {
    // eslint-disable-next-line no-console
    console.warn(String(componentName) + '.getChildContext(): childContextTypes must be defined in order to use getChildContext().');
    return {};
  }
  // Check childContextTypes like react:
  // https://github.com/facebook/react/blob/1454a8be03794f5e0b23a7e7696cbbbdcf8b0f5d/packages/react-dom/src/server/ReactPartialRenderer.js#L630-L637
  var childContext = instance.getChildContext();
  Object.keys(childContext).forEach(function (key) {
    if (!(key in Component.childContextTypes)) {
      throw new Error(String(componentName) + '.getChildContext(): key "' + String(key) + '" is not defined in childContextTypes.');
    }
  });
  if (typeof renderer.checkPropTypes === 'function') {
    renderer.checkPropTypes(Component.childContextTypes, childContext, 'child context', hierarchy);
  }
  return childContext;
}

function spyOnGetChildContextInitialRender(nodes, adapter) {
  if (!(0, _Utils.isCustomComponentElement)(nodes, adapter) || !nodes.type.prototype || typeof nodes.type.prototype.getChildContext !== 'function') {
    return null;
  }

  return (0, _Utils.spyMethod)(nodes.type.prototype, 'getChildContext');
}

function privateSetChildContext(adapter, wrapper, instance, renderedNode, getChildContextSpy) {
  var renderer = wrapper[RENDERER];
  // We only support parent-based context.
  if (adapter.options.legacyContextMode !== 'parent') {
    return;
  }
  if (getChildContextSpy) {
    (0, _Utils.privateSet)(wrapper, CHILD_CONTEXT, getChildContextSpy.getLastReturnValue());
    getChildContextSpy.restore();
  } else if (typeof instance.getChildContext === 'function') {
    // If there's no spy but getChildContext is a function, that means our renderer
    // is not going to call it for us, so we need to call it ourselves.
    var nodeHierarchy = [wrapper[NODE]].concat(nodeParents(wrapper, wrapper[NODE]));
    var childContext = getChildContext(renderedNode, nodeHierarchy, renderer);
    (0, _Utils.privateSet)(wrapper, CHILD_CONTEXT, childContext);
  } else {
    (0, _Utils.privateSet)(wrapper, CHILD_CONTEXT, null);
  }
}

/**
 * @class ShallowWrapper
 */

var ShallowWrapper = function () {
  function ShallowWrapper(nodes, root) {
    var _this = this;

    var passedOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

    _classCallCheck(this, ShallowWrapper);

    validateOptions(passedOptions);

    var options = (0, _Utils.makeOptions)(passedOptions);
    var adapter = (0, _getAdapter2['default'])(options);
    var lifecycles = getAdapterLifecycles(adapter);

    // mounting a ShallowRender component
    if (!root) {
      if (!adapter.isValidElement(nodes)) {
        throw new TypeError('ShallowWrapper can only wrap valid elements');
      }

      var getChildContextSpy = lifecycles.getChildContext.calledByRenderer ? spyOnGetChildContextInitialRender(nodes, adapter) : null;
      (0, _Utils.privateSet)(this, ROOT, this);
      (0, _Utils.privateSet)(this, UNRENDERED, nodes);
      var renderer = adapter.createRenderer((0, _object2['default'])({ mode: 'shallow' }, options));
      (0, _Utils.privateSet)(this, RENDERER, renderer);
      this[RENDERER].render(nodes, options.context);
      var renderedNode = this[RENDERER].getNode();
      privateSetNodes(this, getRootNode(renderedNode));
      (0, _Utils.privateSet)(this, OPTIONS, options);

      var instance = renderedNode.instance;

      if (instance && !options.disableLifecycleMethods) {
        // Ensure to call componentDidUpdate when instance.setState is called
        if (lifecycles.componentDidUpdate.onSetState && !instance[SET_STATE]) {
          (0, _Utils.privateSet)(instance, SET_STATE, instance.setState);
          instance.setState = function (updater) {
            var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
            return _this.setState.apply(_this, _toConsumableArray(callback == null ? [updater] : [updater, callback]));
          };
        }

        if (typeof instance.componentDidMount === 'function') {
          this[RENDERER].batchedUpdates(function () {
            instance.componentDidMount();
          });
        }
        privateSetChildContext(adapter, this, instance, renderedNode, getChildContextSpy);
      }
      // creating a child component through enzyme's ShallowWrapper APIs.
    } else {
      (0, _Utils.privateSet)(this, ROOT, root);
      (0, _Utils.privateSet)(this, UNRENDERED, null);
      (0, _Utils.privateSet)(this, RENDERER, root[RENDERER]);
      privateSetNodes(this, nodes);
      (0, _Utils.privateSet)(this, OPTIONS, root[OPTIONS]);
      (0, _Utils.privateSet)(this, ROOT_NODES, root[NODES]);
    }
  }

  /**
   * Returns the root wrapper
   *
   * @return {ShallowWrapper}
   */


  _createClass(ShallowWrapper, [{
    key: 'root',
    value: function () {
      function root() {
        return this[ROOT];
      }

      return root;
    }()

    /**
     * Returns the wrapped component.
     *
     * @return {ReactComponent}
     */

  }, {
    key: 'getNodeInternal',
    value: function () {
      function getNodeInternal() {
        if (this.length !== 1) {
          throw new Error('ShallowWrapper::getNode() can only be called when wrapping one node');
        }
        if (this[ROOT] === this) {
          this.update();
        }
        return this[NODE];
      }

      return getNodeInternal;
    }()

    /**
     * Returns the the wrapped components.
     *
     * @return {Array<ReactComponent>}
     */

  }, {
    key: 'getNodesInternal',
    value: function () {
      function getNodesInternal() {
        if (this[ROOT] === this && this.length === 1) {
          this.update();
        }
        return this[NODES];
      }

      return getNodesInternal;
    }()

    /**
     * Returns the wrapped ReactElement.
     *
     * @return {ReactElement}
     */

  }, {
    key: 'getElement',
    value: function () {
      function getElement() {
        var _this2 = this;

        return this.single('getElement', function (n) {
          return (0, _getAdapter2['default'])(_this2[OPTIONS]).nodeToElement(n);
        });
      }

      return getElement;
    }()

    /**
     * Returns the wrapped ReactElements.
     *
     * @return {Array<ReactElement>}
     */

  }, {
    key: 'getElements',
    value: function () {
      function getElements() {
        return this.getNodesInternal().map((0, _getAdapter2['default'])(this[OPTIONS]).nodeToElement);
      }

      return getElements;
    }()

    // eslint-disable-next-line class-methods-use-this

  }, {
    key: 'getNode',
    value: function () {
      function getNode() {
        throw new Error('ShallowWrapper::getNode() is no longer supported. Use ShallowWrapper::getElement() instead');
      }

      return getNode;
    }()

    // eslint-disable-next-line class-methods-use-this

  }, {
    key: 'getNodes',
    value: function () {
      function getNodes() {
        throw new Error('ShallowWrapper::getNodes() is no longer supported. Use ShallowWrapper::getElements() instead');
      }

      return getNodes;
    }()

    /**
     * Gets the instance of the component being rendered as the root node passed into `shallow()`.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * Example:
     * ```
     * const wrapper = shallow(<MyComponent />);
     * const inst = wrapper.instance();
     * expect(inst).to.be.instanceOf(MyComponent);
     * ```
     * @returns {ReactComponent}
     */

  }, {
    key: 'instance',
    value: function () {
      function instance() {
        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::instance() can only be called on the root');
        }
        return this[RENDERER].getNode().instance;
      }

      return instance;
    }()

    /**
     * Forces a re-render. Useful to run before checking the render output if something external
     * may be updating the state of the component somewhere.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'update',
    value: function () {
      function update() {
        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::update() can only be called on the root');
        }
        if (this.length !== 1) {
          throw new Error('ShallowWrapper::update() can only be called when wrapping one node');
        }
        privateSetNodes(this, getRootNode(this[RENDERER].getNode()));
        return this;
      }

      return update;
    }()

    /**
     * A method that unmounts the component. This can be used to simulate a component going through
     * and unmount/mount lifecycle.
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'unmount',
    value: function () {
      function unmount() {
        this[RENDERER].unmount();
        return this;
      }

      return unmount;
    }()

    /**
     * A method is for re-render with new props and context.
     * This calls componentDidUpdate method if disableLifecycleMethods is not enabled.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} props
     * @param {Object} context
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'rerender',
    value: function () {
      function rerender(props, context) {
        var _this3 = this;

        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        this.single('rerender', function () {
          (0, _Utils.withSetStateAllowed)(function () {
            // NOTE(lmr): In react 16, instances will be null for SFCs, but
            // rerendering with props/context is still a valid thing to do. In
            // this case, state will be undefined, but props/context will exist.
            var node = _this3[RENDERER].getNode();
            var instance = node.instance || {};
            var state = instance.state;

            var prevProps = instance.props || _this3[UNRENDERED].props;
            var prevContext = instance.context || _this3[OPTIONS].context;
            var nextContext = context || prevContext;
            if (context) {
              _this3[OPTIONS] = (0, _object2['default'])({}, _this3[OPTIONS], { context: nextContext });
            }
            _this3[RENDERER].batchedUpdates(function () {
              // When shouldComponentUpdate returns false we shouldn't call componentDidUpdate.
              // so we spy shouldComponentUpdate to get the result.
              var lifecycles = getAdapterLifecycles(adapter);
              var shouldRender = true;
              var shouldComponentUpdateSpy = void 0;
              var getChildContextSpy = void 0;
              if (!_this3[OPTIONS].disableLifecycleMethods && instance) {
                if (typeof instance.shouldComponentUpdate === 'function') {
                  shouldComponentUpdateSpy = (0, _Utils.spyMethod)(instance, 'shouldComponentUpdate');
                }
                if (lifecycles.getChildContext.calledByRenderer && typeof instance.getChildContext === 'function') {
                  getChildContextSpy = (0, _Utils.spyMethod)(instance, 'getChildContext');
                }
              }
              if (!shouldComponentUpdateSpy && isPureComponent(instance)) {
                shouldRender = pureComponentShouldComponentUpdate(prevProps, props, state, instance.state);
              }
              if (props) _this3[UNRENDERED] = (0, _Utils.cloneElement)(adapter, _this3[UNRENDERED], props);
              _this3[RENDERER].render(_this3[UNRENDERED], nextContext);
              if (shouldComponentUpdateSpy) {
                shouldRender = shouldComponentUpdateSpy.getLastReturnValue();
                shouldComponentUpdateSpy.restore();
              }
              if (shouldRender && !_this3[OPTIONS].disableLifecycleMethods && instance) {
                privateSetChildContext(adapter, _this3, instance, node, getChildContextSpy);
                if (lifecycles.getSnapshotBeforeUpdate) {
                  var snapshot = void 0;
                  if (typeof instance.getSnapshotBeforeUpdate === 'function') {
                    snapshot = instance.getSnapshotBeforeUpdate(prevProps, state);
                  }
                  if (lifecycles.componentDidUpdate && typeof instance.componentDidUpdate === 'function' && (!state || (0, _Utils.shallowEqual)(state, _this3.instance().state))) {
                    instance.componentDidUpdate(prevProps, state, snapshot);
                  }
                } else if (lifecycles.componentDidUpdate && typeof instance.componentDidUpdate === 'function') {
                  if (lifecycles.componentDidUpdate.prevContext) {
                    instance.componentDidUpdate(prevProps, state, prevContext);
                  } else if (!state || (0, _Utils.shallowEqual)(_this3.instance().state, state)) {
                    instance.componentDidUpdate(prevProps, state);
                  }
                }
                // If it doesn't need to rerender, update only its props.
              } else if (!(0, _Utils.shallowEqual)(props, instance.props)) {
                instance.props = (Object.freeze || Object)((0, _object2['default'])({}, instance.props, props));
              }
              _this3.update();
            });
          });
        });
        return this;
      }

      return rerender;
    }()

    /**
     * A method that sets the props of the root component, and re-renders. Useful for when you are
     * wanting to test how the component behaves over time with changing props. Calling this, for
     * instance, will call the `componentWillReceiveProps` lifecycle method.
     *
     * Similar to `setState`, this method accepts a props object and will merge it in with the already
     * existing props.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} props object
     * @param {Function} cb - callback function
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'setProps',
    value: function () {
      function setProps(props) {
        var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::setProps() can only be called on the root');
        }
        if (arguments.length > 1 && typeof callback !== 'function') {
          throw new TypeError('ReactWrapper::setProps() expects a function as its second argument');
        }
        this.rerender(props);
        if (callback) {
          callback();
        }
        return this;
      }

      return setProps;
    }()

    /**
     * A method to invoke `setState` on the root component instance similar to how you might in the
     * definition of the component, and re-renders.  This method is useful for testing your component
     * in hard to achieve states, however should be used sparingly. If possible, you should utilize
     * your component's external API in order to get it into whatever state you want to test, in order
     * to be as accurate of a test as possible. This is not always practical, however.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} state to merge
     * @param {Function} cb - callback function
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'setState',
    value: function () {
      function setState(state) {
        var _this4 = this;

        var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::setState() can only be called on the root');
        }
        if (this.instance() === null || this[RENDERER].getNode().nodeType !== 'class') {
          throw new Error('ShallowWrapper::setState() can only be called on class components');
        }
        if (arguments.length > 1 && typeof callback !== 'function') {
          throw new TypeError('ReactWrapper::setState() expects a function as its second argument');
        }

        this.single('setState', function () {
          (0, _Utils.withSetStateAllowed)(function () {
            var adapter = (0, _getAdapter2['default'])(_this4[OPTIONS]);

            var lifecycles = getAdapterLifecycles(adapter);

            var node = _this4[RENDERER].getNode();
            var instance = node.instance;

            var prevProps = instance.props;
            var prevState = instance.state;
            var prevContext = instance.context;

            var statePayload = typeof state === 'function' ? state.call(instance, prevState, prevProps) : state;

            // returning null or undefined prevents the update in React 16+
            // https://github.com/facebook/react/pull/12756
            var maybeHasUpdate = !lifecycles.setState.skipsComponentDidUpdateOnNullish || statePayload != null;

            // When shouldComponentUpdate returns false we shouldn't call componentDidUpdate.
            // so we spy shouldComponentUpdate to get the result.
            var shouldComponentUpdateSpy = void 0;
            var getChildContextSpy = void 0;
            var shouldRender = true;
            if (!_this4[OPTIONS].disableLifecycleMethods && instance) {
              if (lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState && typeof instance.shouldComponentUpdate === 'function') {
                shouldComponentUpdateSpy = (0, _Utils.spyMethod)(instance, 'shouldComponentUpdate');
              }
              if (lifecycles.getChildContext.calledByRenderer && typeof instance.getChildContext === 'function') {
                getChildContextSpy = (0, _Utils.spyMethod)(instance, 'getChildContext');
              }
            }
            if (!shouldComponentUpdateSpy && isPureComponent(instance)) {
              shouldRender = pureComponentShouldComponentUpdate(prevProps, instance.props, prevState, statePayload);
            }

            // We don't pass the setState callback here
            // to guarantee to call the callback after finishing the render
            if (instance[SET_STATE]) {
              instance[SET_STATE](statePayload);
            } else {
              instance.setState(statePayload);
            }
            if (shouldComponentUpdateSpy) {
              shouldRender = shouldComponentUpdateSpy.getLastReturnValue();
              shouldComponentUpdateSpy.restore();
            }
            if (maybeHasUpdate && shouldRender && !_this4[OPTIONS].disableLifecycleMethods) {
              privateSetChildContext(adapter, _this4, instance, node, getChildContextSpy);
              if (lifecycles.componentDidUpdate && lifecycles.componentDidUpdate.onSetState) {
                if (lifecycles.getSnapshotBeforeUpdate && typeof instance.getSnapshotBeforeUpdate === 'function') {
                  var snapshot = instance.getSnapshotBeforeUpdate(prevProps, prevState);
                  if (typeof instance.componentDidUpdate === 'function') {
                    instance.componentDidUpdate(prevProps, prevState, snapshot);
                  }
                } else if (typeof instance.componentDidUpdate === 'function') {
                  if (lifecycles.componentDidUpdate.prevContext) {
                    instance.componentDidUpdate(prevProps, prevState, prevContext);
                  } else {
                    instance.componentDidUpdate(prevProps, prevState);
                  }
                }
              }
            }
            _this4.update();
            // call the setState callback
            if (callback) {
              if (adapter.invokeSetStateCallback) {
                adapter.invokeSetStateCallback(instance, callback);
              } else {
                callback.call(instance);
              }
            }
          });
        });
        return this;
      }

      return setState;
    }()

    /**
     * A method that sets the context of the root component, and re-renders. Useful for when you are
     * wanting to test how the component behaves over time with changing contexts.
     *
     * NOTE: can only be called on a wrapper instance that is also the root instance.
     *
     * @param {Object} context object
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'setContext',
    value: function () {
      function setContext(context) {
        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::setContext() can only be called on the root');
        }
        if (!this[OPTIONS].context) {
          throw new Error('ShallowWrapper::setContext() can only be called on a wrapper that was originally passed a context option');
        }
        return this.rerender(null, context);
      }

      return setContext;
    }()

    /**
     * Whether or not a given react element exists in the shallow render tree.
     *
     * Example:
     * ```
     * const wrapper = shallow(<MyComponent />);
     * expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
     * ```
     *
     * @param {ReactElement|Array<ReactElement>} nodeOrNodes
     * @returns {Boolean}
     */

  }, {
    key: 'contains',
    value: function () {
      function contains(nodeOrNodes) {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        if (!(0, _Utils.isReactElementAlike)(nodeOrNodes, adapter)) {
          throw new Error('ShallowWrapper::contains() can only be called with ReactElement (or array of them), string or number as argument.');
        }
        var predicate = Array.isArray(nodeOrNodes) ? function (other) {
          return (0, _Utils.containsChildrenSubArray)(_Utils.nodeEqual, other, nodeOrNodes.map(function (node) {
            return adapter.elementToNode(node);
          }));
        } : function (other) {
          return (0, _Utils.nodeEqual)(adapter.elementToNode(nodeOrNodes), other);
        };

        return findWhereUnwrapped(this, predicate).length > 0;
      }

      return contains;
    }()

    /**
     * Whether or not a given react element exists in the shallow render tree.
     * Match is based on the expected element and not on wrappers element.
     * It will determine if one of the wrappers element "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrappers element and equals to each other.
     *
     * Example:
     * ```
     * // MyComponent outputs <div><div class="foo">Hello</div></div>
     * const wrapper = shallow(<MyComponent />);
     * expect(wrapper.containsMatchingElement(<div>Hello</div>)).to.equal(true);
     * ```
     *
     * @param {ReactElement} node
     * @returns {Boolean}
     */

  }, {
    key: 'containsMatchingElement',
    value: function () {
      function containsMatchingElement(node) {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        var rstNode = adapter.elementToNode(node);
        var predicate = function () {
          function predicate(other) {
            return (0, _Utils.nodeMatches)(rstNode, other, function (a, b) {
              return a <= b;
            });
          }

          return predicate;
        }();
        return findWhereUnwrapped(this, predicate).length > 0;
      }

      return containsMatchingElement;
    }()

    /**
     * Whether or not all the given react elements exists in the shallow render tree.
     * Match is based on the expected element and not on wrappers element.
     * It will determine if one of the wrappers element "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrappers element and equals to each other.
     *
     * Example:
     * ```
     * const wrapper = shallow(<MyComponent />);
     * expect(wrapper.containsAllMatchingElements([
     *   <div>Hello</div>,
     *   <div>Goodbye</div>,
     * ])).to.equal(true);
     * ```
     *
     * @param {Array<ReactElement>} nodes
     * @returns {Boolean}
     */

  }, {
    key: 'containsAllMatchingElements',
    value: function () {
      function containsAllMatchingElements(nodes) {
        var _this5 = this;

        if (!Array.isArray(nodes)) {
          throw new TypeError('nodes should be an Array');
        }

        return nodes.every(function (node) {
          return _this5.containsMatchingElement(node);
        });
      }

      return containsAllMatchingElements;
    }()

    /**
     * Whether or not one of the given react elements exists in the shallow render tree.
     * Match is based on the expected element and not on wrappers element.
     * It will determine if one of the wrappers element "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrappers element and equals to each other.
     *
     * Example:
     * ```
     * const wrapper = shallow(<MyComponent />);
     * expect(wrapper.containsAnyMatchingElements([
     *   <div>Hello</div>,
     *   <div>Goodbye</div>,
     * ])).to.equal(true);
     * ```
     *
     * @param {Array<ReactElement>} nodes
     * @returns {Boolean}
     */

  }, {
    key: 'containsAnyMatchingElements',
    value: function () {
      function containsAnyMatchingElements(nodes) {
        var _this6 = this;

        return Array.isArray(nodes) && nodes.some(function (node) {
          return _this6.containsMatchingElement(node);
        });
      }

      return containsAnyMatchingElements;
    }()

    /**
     * Whether or not a given react element exists in the render tree.
     *
     * Example:
     * ```
     * const wrapper = shallow(<MyComponent />);
     * expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
     * ```
     *
     * @param {ReactElement} node
     * @returns {Boolean}
     */

  }, {
    key: 'equals',
    value: function () {
      function equals(node) {
        var _this7 = this;

        return this.single('equals', function () {
          return (0, _Utils.nodeEqual)(_this7.getNodeInternal(), node);
        });
      }

      return equals;
    }()

    /**
     * Whether or not a given react element matches the render tree.
     * Match is based on the expected element and not on wrapper root node.
     * It will determine if the wrapper root node "looks like" the expected
     * element by checking if all props of the expected element are present
     * on the wrapper root node and equals to each other.
     *
     * Example:
     * ```
     * // MyComponent outputs <div class="foo">Hello</div>
     * const wrapper = shallow(<MyComponent />);
     * expect(wrapper.matchesElement(<div>Hello</div>)).to.equal(true);
     * ```
     *
     * @param {ReactElement} node
     * @returns {Boolean}
     */

  }, {
    key: 'matchesElement',
    value: function () {
      function matchesElement(node) {
        var _this8 = this;

        return this.single('matchesElement', function () {
          var adapter = (0, _getAdapter2['default'])(_this8[OPTIONS]);
          var rstNode = adapter.elementToNode(node);
          return (0, _Utils.nodeMatches)(rstNode, _this8.getNodeInternal(), function (a, b) {
            return a <= b;
          });
        });
      }

      return matchesElement;
    }()

    /**
     * Finds every node in the render tree of the current wrapper that matches the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'find',
    value: function () {
      function find(selector) {
        return this.wrap((0, _selectors.reduceTreesBySelector)(selector, this.getNodesInternal()));
      }

      return find;
    }()

    /**
     * Returns whether or not current node matches a provided selector.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {EnzymeSelector} selector
     * @returns {boolean}
     */

  }, {
    key: 'is',
    value: function () {
      function is(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return this.single('is', function (n) {
          return predicate(n);
        });
      }

      return is;
    }()

    /**
     * Returns true if the component rendered nothing, i.e., null or false.
     *
     * @returns {boolean}
     */

  }, {
    key: 'isEmptyRender',
    value: function () {
      function isEmptyRender() {
        var nodes = this.getNodesInternal();

        return nodes.every(function (n) {
          return (0, _Utils.isEmptyValue)(n);
        });
      }

      return isEmptyRender;
    }()

    /**
     * Returns a new wrapper instance with only the nodes of the current wrapper instance that match
     * the provided predicate function. The predicate should receive a wrapped node as its first
     * argument.
     *
     * @param {Function} predicate
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'filterWhere',
    value: function () {
      function filterWhere(predicate) {
        var _this9 = this;

        return filterWhereUnwrapped(this, function (n) {
          return predicate(_this9.wrap(n));
        });
      }

      return filterWhere;
    }()

    /**
     * Returns a new wrapper instance with only the nodes of the current wrapper instance that match
     * the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'filter',
    value: function () {
      function filter(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return filterWhereUnwrapped(this, predicate);
      }

      return filter;
    }()

    /**
     * Returns a new wrapper instance with only the nodes of the current wrapper that did not match
     * the provided selector. Essentially the inverse of `filter`.
     *
     * @param {EnzymeSelector} selector
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'not',
    value: function () {
      function not(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return filterWhereUnwrapped(this, function (n) {
          return !predicate(n);
        });
      }

      return not;
    }()

    /**
     * Returns a string of the rendered text of the current render tree.  This function should be
     * looked at with skepticism if being used to test what the actual HTML output of the component
     * will be. If that is what you would like to test, use enzyme's `render` function instead.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {String}
     */

  }, {
    key: 'text',
    value: function () {
      function text() {
        return this.single('text', _RSTTraversal.getTextFromNode);
      }

      return text;
    }()

    /**
     * Returns the HTML of the node.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {String}
     */

  }, {
    key: 'html',
    value: function () {
      function html() {
        var _this10 = this;

        return this.single('html', function (n) {
          if (_this10.type() === null) return null;
          var adapter = (0, _getAdapter2['default'])(_this10[OPTIONS]);
          var renderer = adapter.createRenderer((0, _object2['default'])({}, _this10[OPTIONS], { mode: 'string' }));
          return renderer.render(adapter.nodeToElement(n));
        });
      }

      return html;
    }()

    /**
     * Returns the current node rendered to HTML and wrapped in a CheerioWrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {CheerioWrapper}
     */

  }, {
    key: 'render',
    value: function () {
      function render() {
        return this.type() === null ? (0, _cheerio2['default'])() : _cheerio2['default'].load('')(this.html());
      }

      return render;
    }()

    /**
     * Used to simulate events. Pass an eventname and (optionally) event arguments. This method of
     * testing events should be met with some skepticism.
     *
     * @param {String} event
     * @param {Array} args
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'simulate',
    value: function () {
      function simulate(event) {
        var _this11 = this;

        for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          args[_key - 1] = arguments[_key];
        }

        return this.single('simulate', function (n) {
          var _RENDERER;

          (_RENDERER = _this11[RENDERER]).simulateEvent.apply(_RENDERER, [n, event].concat(args));
          _this11[ROOT].update();
          return _this11;
        });
      }

      return simulate;
    }()

    /**
     * Used to simulate throwing a rendering error. Pass an error to throw.
     *
     * @param {String} error
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'simulateError',
    value: function () {
      function simulateError(error) {
        var _this12 = this;

        // in shallow, the "root" is the "rendered" thing.

        return this.single('simulateError', function (thisNode) {
          if (thisNode.nodeType === 'host') {
            throw new TypeError('ShallowWrapper::simulateError() can only be called on custom components');
          }

          var renderer = _this12[RENDERER];
          if (typeof renderer.simulateError !== 'function') {
            throw new TypeError('your adapter does not support `simulateError`. Try upgrading it!');
          }

          var rootNode = getRootNodeInternal(_this12);
          var nodeHierarchy = [thisNode].concat(nodeParents(_this12, thisNode));
          renderer.simulateError(nodeHierarchy, rootNode, error);

          return _this12;
        });
      }

      return simulateError;
    }()

    /**
     * Returns the props hash for the current node of the wrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @returns {Object}
     */

  }, {
    key: 'props',
    value: function () {
      function props() {
        return this.single('props', _RSTTraversal.propsOfNode);
      }

      return props;
    }()

    /**
     * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it
     * will return just that value.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {String} name (optional)
     * @returns {*}
     */

  }, {
    key: 'state',
    value: function () {
      function state(name) {
        var _this13 = this;

        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::state() can only be called on the root');
        }
        if (this.instance() === null || this[RENDERER].getNode().nodeType !== 'class') {
          throw new Error('ShallowWrapper::state() can only be called on class components');
        }
        var _state = this.single('state', function () {
          return _this13.instance().state;
        });
        if (typeof name !== 'undefined') {
          if (_state == null) {
            throw new TypeError('ShallowWrapper::state("' + String(name) + '") requires that `state` not be `null` or `undefined`');
          }
          return _state[name];
        }
        return _state;
      }

      return state;
    }()

    /**
     * Returns the context hash for the root node of the wrapper.
     * Optionally pass in a prop name and it will return just that value.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {String} name (optional)
     * @returns {*}
     */

  }, {
    key: 'context',
    value: function () {
      function context(name) {
        var _this14 = this;

        if (this[ROOT] !== this) {
          throw new Error('ShallowWrapper::context() can only be called on the root');
        }
        if (!this[OPTIONS].context) {
          throw new Error('ShallowWrapper::context() can only be called on a wrapper that was originally passed a context option');
        }
        if (this.instance() === null) {
          throw new Error('ShallowWrapper::context() can only be called on wrapped nodes that have a non-null instance');
        }
        var _context = this.single('context', function () {
          return _this14.instance().context;
        });
        if (name) {
          return _context[name];
        }
        return _context;
      }

      return context;
    }()

    /**
     * Returns a new wrapper with all of the children of the current wrapper.
     *
     * @param {EnzymeSelector} [selector]
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'children',
    value: function () {
      function children(selector) {
        var allChildren = this.flatMap(function (n) {
          return (0, _RSTTraversal.childrenOfNode)(n.getNodeInternal());
        });
        return selector ? allChildren.filter(selector) : allChildren;
      }

      return children;
    }()

    /**
     * Returns a new wrapper with a specific child
     *
     * @param {Number} [index]
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'childAt',
    value: function () {
      function childAt(index) {
        var _this15 = this;

        return this.single('childAt', function () {
          return _this15.children().at(index);
        });
      }

      return childAt;
    }()

    /**
     * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node
     * in the current wrapper.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param {EnzymeSelector} [selector]
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'parents',
    value: function () {
      function parents(selector) {
        var _this16 = this;

        return this.single('parents', function (n) {
          var allParents = _this16.wrap(nodeParents(_this16, n));
          return selector ? allParents.filter(selector) : allParents;
        });
      }

      return parents;
    }()

    /**
     * Returns a wrapper around the immediate parent of the current node.
     *
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'parent',
    value: function () {
      function parent() {
        return this.flatMap(function (n) {
          return [n.parents().get(0)];
        });
      }

      return parent;
    }()

    /**
     *
     * @param {EnzymeSelector} selector
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'closest',
    value: function () {
      function closest(selector) {
        if (this.is(selector)) {
          return this;
        }
        var matchingAncestors = this.parents().filter(selector);
        return matchingAncestors.length > 0 ? matchingAncestors.first() : this.findWhere(function () {
          return false;
        });
      }

      return closest;
    }()

    /**
     * Shallow renders the current node and returns a shallow wrapper around it.
     *
     * NOTE: can only be called on wrapper of a single node.
     *
     * @param {Object} options
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'shallow',
    value: function () {
      function shallow(options) {
        var _this17 = this;

        return this.single('shallow', function (n) {
          return _this17.wrap((0, _getAdapter2['default'])(_this17[OPTIONS]).nodeToElement(n), null, options);
        });
      }

      return shallow;
    }()

    /**
     * Returns the value of prop with the given name of the current node.
     *
     * @param propName
     * @returns {*}
     */

  }, {
    key: 'prop',
    value: function () {
      function prop(propName) {
        return this.props()[propName];
      }

      return prop;
    }()

    /**
     * Returns a wrapper of the node rendered by the provided render prop.
     *
     * @param {String} propName
     * @returns {Function}
     */

  }, {
    key: 'renderProp',
    value: function () {
      function renderProp(propName) {
        var _this18 = this;

        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        if (typeof adapter.wrap !== 'function') {
          throw new RangeError('your adapter does not support `wrap`. Try upgrading it!');
        }

        return this.single('renderProp', function (n) {
          if (n.nodeType === 'host') {
            throw new TypeError('ShallowWrapper::renderProp() can only be called on custom components');
          }
          if (typeof propName !== 'string') {
            throw new TypeError('`propName` must be a string');
          }
          var props = _this18.props();
          if (!(0, _has2['default'])(props, propName)) {
            throw new Error('no prop called \u201C' + String(propName) + '\u201C found');
          }
          var propValue = props[propName];
          if (typeof propValue !== 'function') {
            throw new TypeError('expected prop \u201C' + String(propName) + '\u201C to contain a function, but it holds \u201C' + (typeof prop === 'undefined' ? 'undefined' : _typeof(prop)) + '\u201C');
          }

          return function () {
            var element = propValue.apply(undefined, arguments);
            var wrapped = adapter.wrap(element);
            return _this18.wrap(wrapped, null, _this18[OPTIONS]);
          };
        });
      }

      return renderProp;
    }()

    /**
     * Returns the key assigned to the current node.
     *
     * @returns {String}
     */

  }, {
    key: 'key',
    value: function () {
      function key() {
        return this.single('key', function (n) {
          return n.key === undefined ? null : n.key;
        });
      }

      return key;
    }()

    /**
     * Returns the type of the current node of this wrapper. If it's a composite component, this will
     * be the component constructor. If it's a native DOM node, it will be a string of the tag name.
     * If it's null, it will be null.
     *
     * @returns {String|Function|null}
     */

  }, {
    key: 'type',
    value: function () {
      function type() {
        return this.single('type', function (n) {
          return (0, _Utils.typeOfNode)(n);
        });
      }

      return type;
    }()

    /**
     * Returns the name of the current node of this wrapper.
     *
     * In order of precedence => type.displayName -> type.name -> type.
     *
     * @returns {String}
     */

  }, {
    key: 'name',
    value: function () {
      function name() {
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        return this.single('name', function (n) {
          return adapter.displayNameOfNode ? adapter.displayNameOfNode(n) : (0, _Utils.displayNameOfNode)(n);
        });
      }

      return name;
    }()

    /**
     * Returns whether or not the current node has the given class name or not.
     *
     * NOTE: can only be called on a wrapper of a single node.
     *
     * @param className
     * @returns {Boolean}
     */

  }, {
    key: 'hasClass',
    value: function () {
      function hasClass(className) {
        if (className && className.indexOf('.') !== -1) {
          // eslint-disable-next-line no-console
          console.warn('It looks like you\'re calling `ShallowWrapper::hasClass()` with a CSS selector. hasClass() expects a class name, not a CSS selector.');
        }
        return this.single('hasClass', function (n) {
          return (0, _RSTTraversal.hasClassName)(n, className);
        });
      }

      return hasClass;
    }()

    /**
     * Iterates through each node of the current wrapper and executes the provided function with a
     * wrapper around the corresponding node passed in as the first argument.
     *
     * @param {Function} fn
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'forEach',
    value: function () {
      function forEach(fn) {
        var _this19 = this;

        this.getNodesInternal().forEach(function (n, i) {
          return fn.call(_this19, _this19.wrap(n), i);
        });
        return this;
      }

      return forEach;
    }()

    /**
     * Maps the current array of nodes to another array. Each node is passed in as a `ShallowWrapper`
     * to the map function.
     *
     * @param {Function} fn
     * @returns {Array}
     */

  }, {
    key: 'map',
    value: function () {
      function map(fn) {
        var _this20 = this;

        return this.getNodesInternal().map(function (n, i) {
          return fn.call(_this20, _this20.wrap(n), i);
        });
      }

      return map;
    }()

    /**
     * Reduces the current array of nodes to a value. Each node is passed in as a `ShallowWrapper`
     * to the reducer function.
     *
     * @param {Function} fn - the reducer function
     * @param {*} initialValue - the initial value
     * @returns {*}
     */

  }, {
    key: 'reduce',
    value: function () {
      function reduce(fn) {
        var _this21 = this;

        var initialValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (arguments.length > 1) {
          return this.getNodesInternal().reduce(function (accum, n, i) {
            return fn.call(_this21, accum, _this21.wrap(n), i);
          }, initialValue);
        }
        return this.getNodesInternal().reduce(function (accum, n, i) {
          return fn.call(_this21, i === 1 ? _this21.wrap(accum) : accum, _this21.wrap(n), i);
        });
      }

      return reduce;
    }()

    /**
     * Reduces the current array of nodes to another array, from right to left. Each node is passed
     * in as a `ShallowWrapper` to the reducer function.
     *
     * @param {Function} fn - the reducer function
     * @param {*} initialValue - the initial value
     * @returns {*}
     */

  }, {
    key: 'reduceRight',
    value: function () {
      function reduceRight(fn) {
        var _this22 = this;

        var initialValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;

        if (arguments.length > 1) {
          return this.getNodesInternal().reduceRight(function (accum, n, i) {
            return fn.call(_this22, accum, _this22.wrap(n), i);
          }, initialValue);
        }
        return this.getNodesInternal().reduceRight(function (accum, n, i) {
          return fn.call(_this22, i === 1 ? _this22.wrap(accum) : accum, _this22.wrap(n), i);
        });
      }

      return reduceRight;
    }()

    /**
     * Returns a new wrapper with a subset of the nodes of the original wrapper, according to the
     * rules of `Array#slice`.
     *
     * @param {Number} begin
     * @param {Number} end
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'slice',
    value: function () {
      function slice(begin, end) {
        return this.wrap(this.getNodesInternal().slice(begin, end));
      }

      return slice;
    }()

    /**
     * Returns whether or not any of the nodes in the wrapper match the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {Boolean}
     */

  }, {
    key: 'some',
    value: function () {
      function some(selector) {
        if (this[ROOT] === this) {
          throw new Error('ShallowWrapper::some() can not be called on the root');
        }
        var predicate = (0, _selectors.buildPredicate)(selector);
        return this.getNodesInternal().some(predicate);
      }

      return some;
    }()

    /**
     * Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
     *
     * @param {Function} predicate
     * @returns {Boolean}
     */

  }, {
    key: 'someWhere',
    value: function () {
      function someWhere(predicate) {
        var _this23 = this;

        return this.getNodesInternal().some(function (n, i) {
          return predicate.call(_this23, _this23.wrap(n), i);
        });
      }

      return someWhere;
    }()

    /**
     * Returns whether or not all of the nodes in the wrapper match the provided selector.
     *
     * @param {EnzymeSelector} selector
     * @returns {Boolean}
     */

  }, {
    key: 'every',
    value: function () {
      function every(selector) {
        var predicate = (0, _selectors.buildPredicate)(selector);
        return this.getNodesInternal().every(predicate);
      }

      return every;
    }()

    /**
     * Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
     *
     * @param {Function} predicate
     * @returns {Boolean}
     */

  }, {
    key: 'everyWhere',
    value: function () {
      function everyWhere(predicate) {
        var _this24 = this;

        return this.getNodesInternal().every(function (n, i) {
          return predicate.call(_this24, _this24.wrap(n), i);
        });
      }

      return everyWhere;
    }()

    /**
     * Utility method used to create new wrappers with a mapping function that returns an array of
     * nodes in response to a single node wrapper. The returned wrapper is a single wrapper around
     * all of the mapped nodes flattened (and de-duplicated).
     *
     * @param {Function} fn
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'flatMap',
    value: function () {
      function flatMap(fn) {
        var _this25 = this;

        var nodes = this.getNodesInternal().map(function (n, i) {
          return fn.call(_this25, _this25.wrap(n), i);
        });
        var flattened = (0, _arrayPrototype2['default'])(nodes, 1);
        return this.wrap(flattened.filter(Boolean));
      }

      return flatMap;
    }()

    /**
     * Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
     * function. The predicate function will receive the nodes inside a ShallowWrapper as its
     * first argument.
     *
     * @param {Function} predicate
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'findWhere',
    value: function () {
      function findWhere(predicate) {
        var _this26 = this;

        return findWhereUnwrapped(this, function (n) {
          var node = _this26.wrap(n);
          return node.length > 0 && predicate(node);
        });
      }

      return findWhere;
    }()

    /**
     * Returns the node at a given index of the current wrapper.
     *
     * @param index
     * @returns {ReactElement}
     */

  }, {
    key: 'get',
    value: function () {
      function get(index) {
        return this.getElements()[index];
      }

      return get;
    }()

    /**
     * Returns a wrapper around the node at a given index of the current wrapper.
     *
     * @param index
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'at',
    value: function () {
      function at(index) {
        var nodes = this.getNodesInternal();
        if (index < nodes.length) {
          return this.wrap(nodes[index]);
        }
        return this.wrap([]);
      }

      return at;
    }()

    /**
     * Returns a wrapper around the first node of the current wrapper.
     *
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'first',
    value: function () {
      function first() {
        return this.at(0);
      }

      return first;
    }()

    /**
     * Returns a wrapper around the last node of the current wrapper.
     *
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'last',
    value: function () {
      function last() {
        return this.at(this.length - 1);
      }

      return last;
    }()

    /**
     * Delegates to exists()
     *
     * @returns {boolean}
     */

  }, {
    key: 'isEmpty',
    value: function () {
      function isEmpty() {
        // eslint-disable-next-line no-console
        console.warn('Enzyme::Deprecated method isEmpty() called, use exists() instead.');
        return !this.exists();
      }

      return isEmpty;
    }()

    /**
     * Returns true if the current wrapper has nodes. False otherwise.
     * If called with a selector it returns `.find(selector).exists()` instead.
     *
     * @param {EnzymeSelector} selector (optional)
     * @returns {boolean}
     */

  }, {
    key: 'exists',
    value: function () {
      function exists() {
        var selector = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;

        return arguments.length > 0 ? this.find(selector).exists() : this.length > 0;
      }

      return exists;
    }()

    /**
     * Utility method that throws an error if the current instance has a length other than one.
     * This is primarily used to enforce that certain methods are only run on a wrapper when it is
     * wrapping a single node.
     *
     * @param fn
     * @returns {*}
     */

  }, {
    key: 'single',
    value: function () {
      function single(name, fn) {
        var fnName = typeof name === 'string' ? name : 'unknown';
        var callback = typeof fn === 'function' ? fn : name;
        if (this.length !== 1) {
          throw new Error('Method \u201C' + fnName + '\u201D is meant to be run on 1 node. ' + String(this.length) + ' found instead.');
        }
        return callback.call(this, this.getNodeInternal());
      }

      return single;
    }()

    /**
     * Helpful utility method to create a new wrapper with the same root as the current wrapper, with
     * any nodes passed in as the first parameter automatically wrapped.
     *
     * @param node
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'wrap',
    value: function () {
      function wrap(node) {
        var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this[ROOT];

        if (node instanceof ShallowWrapper) {
          return node;
        }

        for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
          args[_key2 - 2] = arguments[_key2];
        }

        return new (Function.prototype.bind.apply(ShallowWrapper, [null].concat([node, root], args)))();
      }

      return wrap;
    }()

    /**
     * Returns an HTML-like string of the shallow render for debugging purposes.
     *
     * @param {Object} [options] - Property bag of additional options.
     * @param {boolean} [options.ignoreProps] - if true, props are omitted from the string.
     * @param {boolean} [options.verbose] - if true, arrays and objects to be verbosely printed.
     * @returns {String}
     */

  }, {
    key: 'debug',
    value: function () {
      function debug() {
        var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        return (0, _Debug.debugNodes)(this.getNodesInternal(), options);
      }

      return debug;
    }()

    /**
     * Invokes intercepter and returns itself. intercepter is called with itself.
     * This is helpful when debugging nodes in method chains.
     * @param fn
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'tap',
    value: function () {
      function tap(intercepter) {
        intercepter(this);
        return this;
      }

      return tap;
    }()

    /**
     * Primarily useful for HOCs (higher-order components), this method may only be
     * run on a single, non-DOM node, and will return the node, shallow-rendered.
     *
     * @param {Object} options
     * @returns {ShallowWrapper}
     */

  }, {
    key: 'dive',
    value: function () {
      function dive() {
        var _this27 = this;

        var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        var name = 'dive';
        return this.single(name, function (n) {
          if (n && n.nodeType === 'host') {
            throw new TypeError('ShallowWrapper::' + name + '() can not be called on Host Components');
          }
          var el = (0, _getAdapter2['default'])(_this27[OPTIONS]).nodeToElement(n);
          if (!(0, _Utils.isCustomComponentElement)(el, adapter)) {
            throw new TypeError('ShallowWrapper::' + name + '() can only be called on components');
          }
          return _this27.wrap(el, null, (0, _object2['default'])({}, _this27[OPTIONS], options, {
            context: options.context || (0, _object2['default'])({}, _this27[OPTIONS].context, _this27[ROOT][CHILD_CONTEXT])
          }));
        });
      }

      return dive;
    }()

    /**
     * Strips out all the not host-nodes from the list of nodes
     *
     * This method is useful if you want to check for the presence of host nodes
     * (actually rendered HTML elements) ignoring the React nodes.
     */

  }, {
    key: 'hostNodes',
    value: function () {
      function hostNodes() {
        return this.filterWhere(function (n) {
          return typeof n.type() === 'string';
        });
      }

      return hostNodes;
    }()
  }]);

  return ShallowWrapper;
}();

if (_Utils.ITERATOR_SYMBOL) {
  Object.defineProperty(ShallowWrapper.prototype, _Utils.ITERATOR_SYMBOL, {
    configurable: true,
    value: function () {
      function iterator() {
        var _ref2;

        var iter = this.getNodesInternal()[_Utils.ITERATOR_SYMBOL]();
        var adapter = (0, _getAdapter2['default'])(this[OPTIONS]);
        return _ref2 = {}, _defineProperty(_ref2, _Utils.ITERATOR_SYMBOL, function () {
          return this;
        }), _defineProperty(_ref2, 'next', function () {
          function next() {
            var next = iter.next();
            if (next.done) {
              return { done: true };
            }
            return {
              done: false,
              value: adapter.nodeToElement(next.value)
            };
          }

          return next;
        }()), _ref2;
      }

      return iterator;
    }()
  });
}

function privateWarning(prop, extraMessage) {
  Object.defineProperty(ShallowWrapper.prototype, prop, {
    get: function () {
      function get() {
        throw new Error('\n        Attempted to access ShallowWrapper::' + String(prop) + ', which was previously a private property on\n        Enzyme ShallowWrapper instances, but is no longer and should not be relied upon.\n        ' + String(extraMessage) + '\n      ');
      }

      return get;
    }(),

    enumerable: false,
    configurable: false
  });
}

privateWarning('node', 'Consider using the getElement() method instead.');
privateWarning('nodes', 'Consider using the getElements() method instead.');
privateWarning('renderer', '');
privateWarning('options', '');
privateWarning('complexSelector', '');

exports['default'] = ShallowWrapper;

/***/ }),
/* 518 */
/***/ (function(module, exports, __nested_webpack_require_2691131__) {

module.exports = { "default": __nested_webpack_require_2691131__(519), __esModule: true };

/***/ }),
/* 519 */
/***/ (function(module, exports, __nested_webpack_require_2691285__) {

__nested_webpack_require_2691285__(76);
__nested_webpack_require_2691285__(61);
module.exports = __nested_webpack_require_2691285__(520);


/***/ }),
/* 520 */
/***/ (function(module, exports, __nested_webpack_require_2691457__) {

var classof = __nested_webpack_require_2691457__(111);
var ITERATOR = __nested_webpack_require_2691457__(21)('iterator');
var Iterators = __nested_webpack_require_2691457__(51);
module.exports = __nested_webpack_require_2691457__(12).isIterable = function (it) {
  var O = Object(it);
  return O[ITERATOR] !== undefined
    || '@@iterator' in O
    // eslint-disable-next-line no-prototype-builtins
    || Iterators.hasOwnProperty(classof(O));
};


/***/ }),
/* 521 */
/***/ (function(module, exports, __nested_webpack_require_2691923__) {

"use strict";


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

var _promise = __nested_webpack_require_2691923__(62);

var _promise2 = _interopRequireDefault(_promise);

var _d3Dsv = __nested_webpack_require_2691923__(104);

var _utils = __nested_webpack_require_2691923__(10);

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

var cache = {};

var getFromCache = function getFromCache(url, fallback) {
  return cache[url] ? _promise2['default'].resolve(cache[url]) : fallback(url);
};

var parseChromInfo = function parseChromInfo(text) {
  if (text.length === 0) return null;

  var tsv = (0, _d3Dsv.tsvParseRows)(text);
  return (0, _utils.parseChromsizesRows)(tsv);
};

var getFromRemote = function getFromRemote(url) {
  return fetch(url, { credentials: 'same-origin' }).then(function (response) {
    return response.text();
  }).then(function (text) {
    return parseChromInfo(text);
  })['catch'](function (error) {
    console.error('Could not retrieve or parse chrom info.', error);
  });
};

var cacheResults = function cacheResults(key, getter, fallback) {
  return getter(key, fallback).then(function (results) {
    cache[key] = results;
    return cache[key];
  });
};

var get = function get(url) {
  return cacheResults(url, getFromCache, getFromRemote);
};

var api = { get: get };

exports['default'] = api;

/***/ }),
/* 522 */
/***/ (function(module, exports, __nested_webpack_require_2693353__) {

__nested_webpack_require_2693353__(164);
__nested_webpack_require_2693353__(61);
__nested_webpack_require_2693353__(76);
__nested_webpack_require_2693353__(523);
__nested_webpack_require_2693353__(527);
__nested_webpack_require_2693353__(528);
module.exports = __nested_webpack_require_2693353__(12).Promise;


/***/ }),
/* 523 */
/***/ (function(module, exports, __nested_webpack_require_2693636__) {

"use strict";

var LIBRARY = __nested_webpack_require_2693636__(75);
var global = __nested_webpack_require_2693636__(23);
var ctx = __nested_webpack_require_2693636__(49);
var classof = __nested_webpack_require_2693636__(111);
var $export = __nested_webpack_require_2693636__(16);
var isObject = __nested_webpack_require_2693636__(33);
var aFunction = __nested_webpack_require_2693636__(92);
var anInstance = __nested_webpack_require_2693636__(218);
var forOf = __nested_webpack_require_2693636__(129);
var speciesConstructor = __nested_webpack_require_2693636__(318);
var task = __nested_webpack_require_2693636__(319).set;
var microtask = __nested_webpack_require_2693636__(525)();
var newPromiseCapabilityModule = __nested_webpack_require_2693636__(219);
var perform = __nested_webpack_require_2693636__(320);
var userAgent = __nested_webpack_require_2693636__(526);
var promiseResolve = __nested_webpack_require_2693636__(321);
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;

var USE_NATIVE = !!function () {
  try {
    // correct subclassing with @@species support
    var promise = $Promise.resolve(1);
    var FakePromise = (promise.constructor = {})[__nested_webpack_require_2693636__(21)('species')] = function (exec) {
      exec(empty, empty);
    };
    // unhandled rejections tracking support, NodeJS Promise without it fails @@species test
    return (isNode || typeof PromiseRejectionEvent == 'function')
      && promise.then(empty) instanceof FakePromise
      // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
      // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
      // we can't detect it synchronously, so just check versions
      && v8.indexOf('6.6') !== 0
      && userAgent.indexOf('Chrome/66') === -1;
  } catch (e) { /* empty */ }
}();

// helpers
var isThenable = function (it) {
  var then;
  return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
  if (promise._n) return;
  promise._n = true;
  var chain = promise._c;
  microtask(function () {
    var value = promise._v;
    var ok = promise._s == 1;
    var i = 0;
    var run = function (reaction) {
      var handler = ok ? reaction.ok : reaction.fail;
      var resolve = reaction.resolve;
      var reject = reaction.reject;
      var domain = reaction.domain;
      var result, then, exited;
      try {
        if (handler) {
          if (!ok) {
            if (promise._h == 2) onHandleUnhandled(promise);
            promise._h = 1;
          }
          if (handler === true) result = value;
          else {
            if (domain) domain.enter();
            result = handler(value); // may throw
            if (domain) {
              domain.exit();
              exited = true;
            }
          }
          if (result === reaction.promise) {
            reject(TypeError('Promise-chain cycle'));
          } else if (then = isThenable(result)) {
            then.call(result, resolve, reject);
          } else resolve(result);
        } else reject(value);
      } catch (e) {
        if (domain && !exited) domain.exit();
        reject(e);
      }
    };
    while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
    promise._c = [];
    promise._n = false;
    if (isReject && !promise._h) onUnhandled(promise);
  });
};
var onUnhandled = function (promise) {
  task.call(global, function () {
    var value = promise._v;
    var unhandled = isUnhandled(promise);
    var result, handler, console;
    if (unhandled) {
      result = perform(function () {
        if (isNode) {
          process.emit('unhandledRejection', value, promise);
        } else if (handler = global.onunhandledrejection) {
          handler({ promise: promise, reason: value });
        } else if ((console = global.console) && console.error) {
          console.error('Unhandled promise rejection', value);
        }
      });
      // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
      promise._h = isNode || isUnhandled(promise) ? 2 : 1;
    } promise._a = undefined;
    if (unhandled && result.e) throw result.v;
  });
};
var isUnhandled = function (promise) {
  return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
  task.call(global, function () {
    var handler;
    if (isNode) {
      process.emit('rejectionHandled', promise);
    } else if (handler = global.onrejectionhandled) {
      handler({ promise: promise, reason: promise._v });
    }
  });
};
var $reject = function (value) {
  var promise = this;
  if (promise._d) return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  promise._v = value;
  promise._s = 2;
  if (!promise._a) promise._a = promise._c.slice();
  notify(promise, true);
};
var $resolve = function (value) {
  var promise = this;
  var then;
  if (promise._d) return;
  promise._d = true;
  promise = promise._w || promise; // unwrap
  try {
    if (promise === value) throw TypeError("Promise can't be resolved itself");
    if (then = isThenable(value)) {
      microtask(function () {
        var wrapper = { _w: promise, _d: false }; // wrap
        try {
          then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
        } catch (e) {
          $reject.call(wrapper, e);
        }
      });
    } else {
      promise._v = value;
      promise._s = 1;
      notify(promise, false);
    }
  } catch (e) {
    $reject.call({ _w: promise, _d: false }, e); // wrap
  }
};

// constructor polyfill
if (!USE_NATIVE) {
  // 25.4.3.1 Promise(executor)
  $Promise = function Promise(executor) {
    anInstance(this, $Promise, PROMISE, '_h');
    aFunction(executor);
    Internal.call(this);
    try {
      executor(ctx($resolve, this, 1), ctx($reject, this, 1));
    } catch (err) {
      $reject.call(this, err);
    }
  };
  // eslint-disable-next-line no-unused-vars
  Internal = function Promise(executor) {
    this._c = [];             // <- awaiting reactions
    this._a = undefined;      // <- checked in isUnhandled reactions
    this._s = 0;              // <- state
    this._d = false;          // <- done
    this._v = undefined;      // <- value
    this._h = 0;              // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
    this._n = false;          // <- notify
  };
  Internal.prototype = __nested_webpack_require_2693636__(220)($Promise.prototype, {
    // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
    then: function then(onFulfilled, onRejected) {
      var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
      reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
      reaction.fail = typeof onRejected == 'function' && onRejected;
      reaction.domain = isNode ? process.domain : undefined;
      this._c.push(reaction);
      if (this._a) this._a.push(reaction);
      if (this._s) notify(this, false);
      return reaction.promise;
    },
    // 25.4.5.1 Promise.prototype.catch(onRejected)
    'catch': function (onRejected) {
      return this.then(undefined, onRejected);
    }
  });
  OwnPromiseCapability = function () {
    var promise = new Internal();
    this.promise = promise;
    this.resolve = ctx($resolve, promise, 1);
    this.reject = ctx($reject, promise, 1);
  };
  newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
    return C === $Promise || C === Wrapper
      ? new OwnPromiseCapability(C)
      : newGenericPromiseCapability(C);
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__nested_webpack_require_2693636__(77)($Promise, PROMISE);
__nested_webpack_require_2693636__(322)(PROMISE);
Wrapper = __nested_webpack_require_2693636__(12)[PROMISE];

// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
  // 25.4.4.5 Promise.reject(r)
  reject: function reject(r) {
    var capability = newPromiseCapability(this);
    var $$reject = capability.reject;
    $$reject(r);
    return capability.promise;
  }
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
  // 25.4.4.6 Promise.resolve(x)
  resolve: function resolve(x) {
    return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
  }
});
$export($export.S + $export.F * !(USE_NATIVE && __nested_webpack_require_2693636__(167)(function (iter) {
  $Promise.all(iter)['catch'](empty);
})), PROMISE, {
  // 25.4.4.1 Promise.all(iterable)
  all: function all(iterable) {
    var C = this;
    var capability = newPromiseCapability(C);
    var resolve = capability.resolve;
    var reject = capability.reject;
    var result = perform(function () {
      var values = [];
      var index = 0;
      var remaining = 1;
      forOf(iterable, false, function (promise) {
        var $index = index++;
        var alreadyCalled = false;
        values.push(undefined);
        remaining++;
        C.resolve(promise).then(function (value) {
          if (alreadyCalled) return;
          alreadyCalled = true;
          values[$index] = value;
          --remaining || resolve(values);
        }, reject);
      });
      --remaining || resolve(values);
    });
    if (result.e) reject(result.v);
    return capability.promise;
  },
  // 25.4.4.4 Promise.race(iterable)
  race: function race(iterable) {
    var C = this;
    var capability = newPromiseCapability(C);
    var reject = capability.reject;
    var result = perform(function () {
      forOf(iterable, false, function (promise) {
        C.resolve(promise).then(capability.resolve, reject);
      });
    });
    if (result.e) reject(result.v);
    return capability.promise;
  }
});


/***/ }),
/* 524 */
/***/ (function(module, exports) {

// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
  var un = that === undefined;
  switch (args.length) {
    case 0: return un ? fn()
                      : fn.call(that);
    case 1: return un ? fn(args[0])
                      : fn.call(that, args[0]);
    case 2: return un ? fn(args[0], args[1])
                      : fn.call(that, args[0], args[1]);
    case 3: return un ? fn(args[0], args[1], args[2])
                      : fn.call(that, args[0], args[1], args[2]);
    case 4: return un ? fn(args[0], args[1], args[2], args[3])
                      : fn.call(that, args[0], args[1], args[2], args[3]);
  } return fn.apply(that, args);
};


/***/ }),
/* 525 */
/***/ (function(module, exports, __nested_webpack_require_2704289__) {

var global = __nested_webpack_require_2704289__(23);
var macrotask = __nested_webpack_require_2704289__(319).set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __nested_webpack_require_2704289__(74)(process) == 'process';

module.exports = function () {
  var head, last, notify;

  var flush = function () {
    var parent, fn;
    if (isNode && (parent = process.domain)) parent.exit();
    while (head) {
      fn = head.fn;
      head = head.next;
      try {
        fn();
      } catch (e) {
        if (head) notify();
        else last = undefined;
        throw e;
      }
    } last = undefined;
    if (parent) parent.enter();
  };

  // Node.js
  if (isNode) {
    notify = function () {
      process.nextTick(flush);
    };
  // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
  } else if (Observer && !(global.navigator && global.navigator.standalone)) {
    var toggle = true;
    var node = document.createTextNode('');
    new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
    notify = function () {
      node.data = toggle = !toggle;
    };
  // environments with maybe non-completely correct, but existent Promise
  } else if (Promise && Promise.resolve) {
    // Promise.resolve without an argument throws an error in LG WebOS 2
    var promise = Promise.resolve(undefined);
    notify = function () {
      promise.then(flush);
    };
  // for other environments - macrotask based on:
  // - setImmediate
  // - MessageChannel
  // - window.postMessag
  // - onreadystatechange
  // - setTimeout
  } else {
    notify = function () {
      // strange IE + webpack dev server bug - use .call(global)
      macrotask.call(global, flush);
    };
  }

  return function (fn) {
    var task = { fn: fn, next: undefined };
    if (last) last.next = task;
    if (!head) {
      head = task;
      notify();
    } last = task;
  };
};


/***/ }),
/* 526 */
/***/ (function(module, exports, __nested_webpack_require_2706365__) {

var global = __nested_webpack_require_2706365__(23);
var navigator = global.navigator;

module.exports = navigator && navigator.userAgent || '';


/***/ }),
/* 527 */
/***/ (function(module, exports, __nested_webpack_require_2706574__) {

"use strict";
// https://github.com/tc39/proposal-promise-finally

var $export = __nested_webpack_require_2706574__(16);
var core = __nested_webpack_require_2706574__(12);
var global = __nested_webpack_require_2706574__(23);
var speciesConstructor = __nested_webpack_require_2706574__(318);
var promiseResolve = __nested_webpack_require_2706574__(321);

$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
  var C = speciesConstructor(this, core.Promise || global.Promise);
  var isFunction = typeof onFinally == 'function';
  return this.then(
    isFunction ? function (x) {
      return promiseResolve(C, onFinally()).then(function () { return x; });
    } : onFinally,
    isFunction ? function (e) {
      return promiseResolve(C, onFinally()).then(function () { throw e; });
    } : onFinally
  );
} });


/***/ }),
/* 528 */
/***/ (function(module, exports, __nested_webpack_require_2707414__) {

"use strict";

// https://github.com/tc39/proposal-promise-try
var $export = __nested_webpack_require_2707414__(16);
var newPromiseCapability = __nested_webpack_require_2707414__(219);
var perform = __nested_webpack_require_2707414__(320);

$export($export.S, 'Promise', { 'try': function (callbackfn) {
  var promiseCapability = newPromiseCapability.f(this);
  var result = perform(callbackfn);
  (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
  return promiseCapability.promise;
} });


/***/ }),
/* 529 */
/***/ (function(module, exports, __nested_webpack_require_2707965__) {

"use strict";


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

var _ = __nested_webpack_require_2707965__(10);

var absToChr = function absToChr(absPosition, chromInfo) {
  if (!chromInfo || !chromInfo.cumPositions || !chromInfo.cumPositions.length) {
    return null;
  }

  var insertPoint = (0, _.chromInfoBisector)(chromInfo.cumPositions, absPosition);
  var lastChr = chromInfo.cumPositions[chromInfo.cumPositions.length - 1].chr;
  var lastLength = chromInfo.chromLengths[lastChr];

  insertPoint -= insertPoint > 0 && 1;

  var chrPosition = Math.floor(absPosition - chromInfo.cumPositions[insertPoint].pos);
  var offset = 0;

  if (chrPosition < 0) {
    // before the start of the genome
    offset = chrPosition - 1;
    chrPosition = 1;
  }

  if (insertPoint === chromInfo.cumPositions.length - 1 && chrPosition > lastLength) {
    // beyond the last chromosome
    offset = chrPosition - lastLength;
    chrPosition = lastLength;
  }

  return [chromInfo.cumPositions[insertPoint].chr, chrPosition, offset, insertPoint];
};

exports['default'] = absToChr;

/***/ }),
/* 530 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Factory function for a transposition accessor for a 2D matrix in form of a 1D
 * array.
 *
 * @description
 * i^T = column * i + row
 * where column: `Math.floor(i / x)` and row: `Math.floor(i / x)`
 *
 * @param  {Integer}  x  X dimension of the 2D matrix
 * @param  {Integer}  y  Y dimension of the 2D matrix
 * @return  {Function}   Acessor function converting the orignal 1D index into
 *   the transposed index
 */
var accessorTransposition = function accessorTransposition(x, y) {
  return function (i) {
    return i % x * y + Math.floor(i / x);
  };
};

exports["default"] = accessorTransposition;

/***/ }),
/* 531 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var STD_ACC = function STD_ACC(i) {
  return i;
};

/**
 * Add two 1D arrays
 *
 * @description
 * `a2` is added onto `a1`, hence `a2` needs to be at least as long as `a1`.
 *
 * @example
 * ```
 * addArrays([1,2,3], [2,3,4,5]) === [3,5,7]
 * ```
 *
 * @param  {Array}  a1  First array of numbers
 * @param  {Array}  a2  Second array of numbers
 * @param  {Function}  accessor  Allows to use custom accessors. This can be
 *   useful when a2 represents a transformed (e.g., transposed matrix).
 * @return  {Array}  Combination of both arrays.
 */
var addArrays = function addArrays(a1, a2) {
  var accessor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : STD_ACC;
  return a1.map(function (val, i) {
    return val + a2[accessor(i)];
  });
};

exports["default"] = addArrays;

/***/ }),
/* 532 */
/***/ (function(module, exports, __nested_webpack_require_2710845__) {

"use strict";


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

var _hasClass = __nested_webpack_require_2710845__(221);

var _hasClass2 = _interopRequireDefault(_hasClass);

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

var XMLNS = 'http://www.w3.org/2000/svg';

/**
 * Method to add a class name to an HTML or SVG element.
 * @param  {object}  el  HTML or SVG element to add a class to.
 * @param  {string}  className  The class name to be added.
 */
var addClass = function addClass(el, className) {
  if (el.namespaceURI === XMLNS) {
    if (!(0, _hasClass2['default'])(el, className)) {
      var _class = el.getAttribute('class') || '';
      el.setAttribute('class', String(_class) + ' ' + String(className));
    }
  } else if (el.classList) {
    el.classList.add(className);
  } else if (!(0, _hasClass2['default'])(el, className)) {
    el.className += ' ' + String(className);
  }
};

exports['default'] = addClass;

/***/ }),
/* 533 */
/***/ (function(module, exports, __nested_webpack_require_2711907__) {

"use strict";


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

var _promise = __nested_webpack_require_2711907__(62);

var _promise2 = _interopRequireDefault(_promise);

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

/**
 * Convert a base64 encoded image into a canvas object.
 * @param   {string}  base64  Base64 string encoding the image.
 * @param   {number}  width  Custom width for the canvas object.
 * @param   {number}  height  Custom height for the canvas object.
 * @return  {object}  The converted canvas object
 */
var base64ToCanvas = function base64ToCanvas(base64, width, height) {
  var canvas = document.createElement('canvas');

  return new _promise2['default'](function (resolve, reject) {
    var img = new window.Image();
    img.onload = function () {
      canvas.width = width || img.width;
      canvas.height = height || img.height;
      canvas.getContext('2d').drawImage(img, 0, 0);
      resolve(canvas);
    };

    img.onerror = function () {
      reject(new Error('Could not convert base64 to canvas'));
    };

    img.src = 'data:image/png;base64,' + String(base64);
  });
};

exports['default'] = base64ToCanvas;

/***/ }),
/* 534 */
/***/ (function(module, exports, __nested_webpack_require_2713191__) {

"use strict";


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

var _d3Array = __nested_webpack_require_2713191__(8);

var chromInfoBisector = (0, _d3Array.bisector)(function (d) {
  return d.pos;
}).left;

exports['default'] = chromInfoBisector;

/***/ }),
/* 535 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var chrToAbs = function chrToAbs(chrom, chromPos, chromInfo) {
  return chromInfo.chrPositions[chrom].pos + chromPos;
};

exports["default"] = chrToAbs;

/***/ }),
/* 536 */
/***/ (function(module, exports, __nested_webpack_require_2713831__) {

"use strict";


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

var _d3Scale = __nested_webpack_require_2713831__(28);

var _d3Array = __nested_webpack_require_2713831__(8);

var _d3Color = __nested_webpack_require_2713831__(9);

/**
 * Convert a color domain to a 255 element array of [r,g,b,a]
 * values (all from 0 to 255). The last color (255) will always be
 * transparent
 */
var colorDomainToRgbaArray = function colorDomainToRgbaArray(colorRange) {
  var noTansparent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

  // we should always have at least two values in the color range
  var domain = colorRange.map(function (x, i) {
    return i * (255 / (colorRange.length - 1));
  });

  var d3Scale = (0, _d3Scale.scaleLinear)().domain(domain).range(colorRange);

  var fromX = noTansparent ? 255 : 254;

  var rgbaArray = (0, _d3Array.range)(fromX, -1, -1).map(d3Scale).map(function (x) {
    var r = (0, _d3Color.rgb)(x);
    return [r.r, r.g, r.b, r.opacity * 255];
  });

  // add a transparent color at the end for missing values and, more
  // importantly, non-existing values such as the empty upper right or lower
  // left triangle of tiles on the diagonal.
  if (rgbaArray.length < 256) rgbaArray.push([255, 255, 255, 0]);

  return rgbaArray;
};

exports['default'] = colorDomainToRgbaArray;

/***/ }),
/* 537 */
/***/ (function(module, exports, __nested_webpack_require_2715223__) {

"use strict";


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

var _d3Color = __nested_webpack_require_2715223__(9);

var _globals = __nested_webpack_require_2715223__(324);

var _globals2 = _interopRequireDefault(_globals);

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

/**
 * Convert a regular color value (e.g. 'red', '#FF0000', 'rgb(255,0,0)') to a
 * hex value which is legible by PIXI
 */
var colorToHex = function colorToHex(colorValue) {
  var c = (0, _d3Color.color)(colorValue);
  var hex = _globals2['default'].PIXI.utils.rgb2hex([c.r / 255.0, c.g / 255.0, c.b / 255.0]);

  return hex;
};

// Configs
exports['default'] = colorToHex;

/***/ }),
/* 538 */
/***/ (function(module, exports, __nested_webpack_require_2715990__) {

"use strict";


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

var _d3Color = __nested_webpack_require_2715990__(9);

/**
 * Convert a regular color value (e.g. 'red', '#FF0000', 'rgb(255,0,0)') to a
 * RGBA array, with support for the value "transparent".
 */
var colorToRgba = function colorToRgba(colorValue) {
  if (colorValue === 'transparent') {
    return [255, 255, 255, 0];
  }
  var c = (0, _d3Color.color)(colorValue);
  return [c.r, c.g, c.b, 255];
};

exports['default'] = colorToRgba;

/***/ }),
/* 539 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Debounce a function call
 *
 * @description
 * Function calls are delayed by `wait` milliseconds and only one out of
 * multiple function calls is executed.
 *
 * @note
 * Once webpack 2 with tree-shaking is supported I'd advocate to use lodash's
 * debounce method.
 *
 * @method  debounce
 * @author  Fritz Lekschas
 * @date    2017-01-14
 * @param   {Function}   func       Function to be debounced
 * @param   {Number}     wait       Number of milliseconds to debounce the
 *   function call.
 * @param   {Boolean}    immediate  If `true` function is not debounced.
 * @return  {Functiomn}             Debounced function.
 */
var debounce = exports.debounce = function debounce(func, wait, immediate) {
  var timeout = void 0;

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

    var later = function later() {
      timeout = null;
      if (!immediate) {
        func.apply(undefined, args);
      }
    };

    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);

    if (callNow) {
      func.apply(undefined, args);
    }
  };

  debounce.cancel = function () {
    clearTimeout(timeout);
    timeout = null;
  };

  return debounced;
};

exports["default"] = debounce;

/***/ }),
/* 540 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var decToHexStr = function decToHexStr(dec) {
  return (dec + Math.pow(16, 6)).toString(16).substr(-6);
};

exports["default"] = decToHexStr;

/***/ }),
/* 541 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Create a dictionary from a list of [key,value] pairs.
 * @param tuples: A list of [key,value] pairs
 * @return: A dictionary
 */
var dictFromTuples = function dictFromTuples(tuples) {
  var dict = {};

  tuples.forEach(function (x) {
    dict[x[0]] = x[1];
  });

  return dict;
};

exports["default"] = dictFromTuples;

/***/ }),
/* 542 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Return an array of (key,value) pairs that are present in this
 * dictionary
 */
var dictItems = function dictItems(dictionary) {
  var keyValues = [];

  for (var key in dictionary) {
    if (dictionary.hasOwnProperty(key)) {
      // eslint-disable-line no-prototype-builtins
      keyValues.push([key, dictionary[key]]);
    }
  }

  return keyValues;
};

exports["default"] = dictItems;

/***/ }),
/* 543 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = dictKeys;
/**
 * Return an array of values that are present in this dictionary
 */
function dictKeys(dictionary) {
  var keys = [];

  for (var key in dictionary) {
    if (dictionary.hasOwnProperty(key)) {
      // eslint-disable-line no-prototype-builtins
      keys.push(key);
    }
  }

  return keys;
}

/***/ }),
/* 544 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = dictValues;
/**
 * Return an array of values that are present in this dictionary
 */
function dictValues(dictionary) {
  var values = [];

  for (var key in dictionary) {
    if (dictionary.hasOwnProperty(key)) {
      // eslint-disable-line no-prototype-builtins
      values.push(dictionary[key]);
    }
  }

  return values;
}

/***/ }),
/* 545 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.download = download;
function download(filename, stringOrBlob) {
  // yanked from here
  // https://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server

  var blob = typeof stringOrBlob === 'string' ? new Blob([stringOrBlob], { type: 'application/octet-stream' }) : stringOrBlob;
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveBlob(blob, filename);
  } else {
    var elem = window.document.createElement('a');
    elem.href = window.URL.createObjectURL(blob);
    elem.download = filename;
    document.body.appendChild(elem);
    elem.click();
    document.body.removeChild(elem);
    URL.revokeObjectURL(elem.href);
  }
}

exports['default'] = download;

/***/ }),
/* 546 */
/***/ (function(module, exports, __nested_webpack_require_2721330__) {

"use strict";


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

var _extends2 = __nested_webpack_require_2721330__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _configs = __nested_webpack_require_2721330__(11);

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

/**
 * If tracks don't have specified dimensions, add in the known
 * minimums
 *
 * Operates on the tracks stored for this TiledPlot.
 */
var fillInMinWidths = function fillInMinWidths(tracks) {
  var horizontalLocations = ['top', 'bottom', 'gallery'];
  var verticalLocations = ['left', 'right', 'gallery'];

  // first make sure all track types are specified
  // this will make the code later on simpler
  tracks.center = tracks.center || [];
  tracks.left = tracks.left || [];
  tracks.right = tracks.right || [];
  tracks.top = tracks.top || [];
  tracks.bottom = tracks.bottom || [];
  tracks.whole = tracks.whole || [];
  tracks.gallery = tracks.gallery || [];

  horizontalLocations.map(function (horizontalLocation) {
    return tracks[horizontalLocation];
  }).forEach(function (horizontalTracks) {
    return horizontalTracks.forEach(function (track) {
      var trackInfo = _configs.TRACKS_INFO_BY_TYPE[track.type];
      var defaultOptions = trackInfo && trackInfo.defaultOptions || {};
      var options = track.options ? (0, _extends3['default'])({}, defaultOptions, track.options) // values in track.options take precedence
      : defaultOptions;

      if (options.minHeight !== undefined && track.height === undefined) {
        track.height = options.minHeight;
      }

      if (track.height === undefined) {
        track.height = trackInfo && trackInfo.defaultHeight || _configs.MIN_HORIZONTAL_HEIGHT;
      }
    });
  });

  verticalLocations.map(function (verticalLocation) {
    return tracks[verticalLocation];
  }).forEach(function (verticalTracks) {
    return verticalTracks.forEach(function (track) {
      var trackInfo = _configs.TRACKS_INFO_BY_TYPE[track.type];
      var defaultOptions = trackInfo && trackInfo.defaultOptions || {};

      var options = track.options ? (0, _extends3['default'])({}, defaultOptions, track.options) // values in track.options take precedence
      : defaultOptions;

      if (options.minWidth !== undefined && track.width === undefined) {
        track.width = options.minWidth;
      }

      if (track.width === undefined) {
        track.width = trackInfo && trackInfo.defaultWidth || _configs.MIN_VERTICAL_WIDTH;
      }
    });
  });

  return tracks;
}; // Configs
exports['default'] = fillInMinWidths;

/***/ }),
/* 547 */
/***/ (function(module, exports, __nested_webpack_require_2724004__) {

__nested_webpack_require_2724004__(548);
__nested_webpack_require_2724004__(164);
__nested_webpack_require_2724004__(551);
__nested_webpack_require_2724004__(552);
module.exports = __nested_webpack_require_2724004__(12).Symbol;


/***/ }),
/* 548 */
/***/ (function(module, exports, __nested_webpack_require_2724236__) {

"use strict";

// ECMAScript 6 symbols shim
var global = __nested_webpack_require_2724236__(23);
var has = __nested_webpack_require_2724236__(47);
var DESCRIPTORS = __nested_webpack_require_2724236__(36);
var $export = __nested_webpack_require_2724236__(16);
var redefine = __nested_webpack_require_2724236__(161);
var META = __nested_webpack_require_2724236__(226).KEY;
var $fails = __nested_webpack_require_2724236__(50);
var shared = __nested_webpack_require_2724236__(106);
var setToStringTag = __nested_webpack_require_2724236__(77);
var uid = __nested_webpack_require_2724236__(91);
var wks = __nested_webpack_require_2724236__(21);
var wksExt = __nested_webpack_require_2724236__(168);
var wksDefine = __nested_webpack_require_2724236__(227);
var enumKeys = __nested_webpack_require_2724236__(549);
var isArray = __nested_webpack_require_2724236__(328);
var anObject = __nested_webpack_require_2724236__(39);
var isObject = __nested_webpack_require_2724236__(33);
var toIObject = __nested_webpack_require_2724236__(48);
var toPrimitive = __nested_webpack_require_2724236__(127);
var createDesc = __nested_webpack_require_2724236__(66);
var _create = __nested_webpack_require_2724236__(110);
var gOPNExt = __nested_webpack_require_2724236__(550);
var $GOPD = __nested_webpack_require_2724236__(228);
var $DP = __nested_webpack_require_2724236__(32);
var $keys = __nested_webpack_require_2724236__(60);
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function';
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;

// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
  return _create(dP({}, 'a', {
    get: function () { return dP(this, 'a', { value: 7 }).a; }
  })).a != 7;
}) ? function (it, key, D) {
  var protoDesc = gOPD(ObjectProto, key);
  if (protoDesc) delete ObjectProto[key];
  dP(it, key, D);
  if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;

var wrap = function (tag) {
  var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
  sym._k = tag;
  return sym;
};

var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
  return typeof it == 'symbol';
} : function (it) {
  return it instanceof $Symbol;
};

var $defineProperty = function defineProperty(it, key, D) {
  if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
  anObject(it);
  key = toPrimitive(key, true);
  anObject(D);
  if (has(AllSymbols, key)) {
    if (!D.enumerable) {
      if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
      it[HIDDEN][key] = true;
    } else {
      if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
      D = _create(D, { enumerable: createDesc(0, false) });
    } return setSymbolDesc(it, key, D);
  } return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
  anObject(it);
  var keys = enumKeys(P = toIObject(P));
  var i = 0;
  var l = keys.length;
  var key;
  while (l > i) $defineProperty(it, key = keys[i++], P[key]);
  return it;
};
var $create = function create(it, P) {
  return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
  var E = isEnum.call(this, key = toPrimitive(key, true));
  if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
  return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
  it = toIObject(it);
  key = toPrimitive(key, true);
  if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
  var D = gOPD(it, key);
  if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
  return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
  var names = gOPN(toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
  } return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
  var IS_OP = it === ObjectProto;
  var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
  var result = [];
  var i = 0;
  var key;
  while (names.length > i) {
    if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
  } return result;
};

// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
  $Symbol = function Symbol() {
    if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
    var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
    var $set = function (value) {
      if (this === ObjectProto) $set.call(OPSymbols, value);
      if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
      setSymbolDesc(this, tag, createDesc(1, value));
    };
    if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
    return wrap(tag);
  };
  redefine($Symbol[PROTOTYPE], 'toString', function toString() {
    return this._k;
  });

  $GOPD.f = $getOwnPropertyDescriptor;
  $DP.f = $defineProperty;
  __nested_webpack_require_2724236__(329).f = gOPNExt.f = $getOwnPropertyNames;
  __nested_webpack_require_2724236__(93).f = $propertyIsEnumerable;
  __nested_webpack_require_2724236__(130).f = $getOwnPropertySymbols;

  if (DESCRIPTORS && !__nested_webpack_require_2724236__(75)) {
    redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
  }

  wksExt.f = function (name) {
    return wrap(wks(name));
  };
}

$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });

for (var es6Symbols = (
  // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
  'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);

for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);

$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
  // 19.4.2.1 Symbol.for(key)
  'for': function (key) {
    return has(SymbolRegistry, key += '')
      ? SymbolRegistry[key]
      : SymbolRegistry[key] = $Symbol(key);
  },
  // 19.4.2.5 Symbol.keyFor(sym)
  keyFor: function keyFor(sym) {
    if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
    for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
  },
  useSetter: function () { setter = true; },
  useSimple: function () { setter = false; }
});

$export($export.S + $export.F * !USE_NATIVE, 'Object', {
  // 19.1.2.2 Object.create(O [, Properties])
  create: $create,
  // 19.1.2.4 Object.defineProperty(O, P, Attributes)
  defineProperty: $defineProperty,
  // 19.1.2.3 Object.defineProperties(O, Properties)
  defineProperties: $defineProperties,
  // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
  getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
  // 19.1.2.7 Object.getOwnPropertyNames(O)
  getOwnPropertyNames: $getOwnPropertyNames,
  // 19.1.2.8 Object.getOwnPropertySymbols(O)
  getOwnPropertySymbols: $getOwnPropertySymbols
});

// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
  var S = $Symbol();
  // MS Edge converts symbol values to JSON as {}
  // WebKit converts symbol values to JSON as null
  // V8 throws on boxed symbols
  return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
  stringify: function stringify(it) {
    var args = [it];
    var i = 1;
    var replacer, $replacer;
    while (arguments.length > i) args.push(arguments[i++]);
    $replacer = replacer = args[1];
    if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
    if (!isArray(replacer)) replacer = function (key, value) {
      if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
      if (!isSymbol(value)) return value;
    };
    args[1] = replacer;
    return _stringify.apply($JSON, args);
  }
});

// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __nested_webpack_require_2724236__(43)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);


/***/ }),
/* 549 */
/***/ (function(module, exports, __nested_webpack_require_2733189__) {

// all enumerable object keys, includes symbols
var getKeys = __nested_webpack_require_2733189__(60);
var gOPS = __nested_webpack_require_2733189__(130);
var pIE = __nested_webpack_require_2733189__(93);
module.exports = function (it) {
  var result = getKeys(it);
  var getSymbols = gOPS.f;
  if (getSymbols) {
    var symbols = getSymbols(it);
    var isEnum = pIE.f;
    var i = 0;
    var key;
    while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
  } return result;
};


/***/ }),
/* 550 */
/***/ (function(module, exports, __nested_webpack_require_2733733__) {

// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __nested_webpack_require_2733733__(48);
var gOPN = __nested_webpack_require_2733733__(329).f;
var toString = {}.toString;

var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
  ? Object.getOwnPropertyNames(window) : [];

var getWindowNames = function (it) {
  try {
    return gOPN(it);
  } catch (e) {
    return windowNames.slice();
  }
};

module.exports.f = function getOwnPropertyNames(it) {
  return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};


/***/ }),
/* 551 */
/***/ (function(module, exports, __nested_webpack_require_2734414__) {

__nested_webpack_require_2734414__(227)('asyncIterator');


/***/ }),
/* 552 */
/***/ (function(module, exports, __nested_webpack_require_2734536__) {

__nested_webpack_require_2734536__(227)('observable');


/***/ }),
/* 553 */
/***/ (function(module, exports, __nested_webpack_require_2734655__) {

"use strict";


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

var _ = __nested_webpack_require_2734655__(11);

var DATATYPE_TO_TRACK_TYPE = exports.DATATYPE_TO_TRACK_TYPE = function DATATYPE_TO_TRACK_TYPE(orientation) {
  var localDatatypeToTrackType = {};

  // can a track be placed in a given orientation
  var orientationMatches = function orientationMatches(trackInfo) {
    // if the track's orientation matches the given orientation, then yes
    if (trackInfo.orientation === orientation) {
      return true;
    }

    if (orientation === '1d-vertical' && trackInfo.orientation === '1d-horizontal' && trackInfo.rotatable) {
      // we can place 1d-horizontal tracks in a vertical position if they are rotatable
      return true;
    }

    return false;
  };

  _.TRACKS_INFO.filter(orientationMatches).forEach(function (ti) {
    var datatypes = ti.datatype;

    if (!Array.isArray(ti.datatype)) {
      datatypes = [datatypes];
    }

    datatypes.forEach(function (datatype) {
      if (!(datatype in localDatatypeToTrackType)) {
        localDatatypeToTrackType[datatype] = [];
      }

      localDatatypeToTrackType[datatype].push(ti);
    });
  });

  localDatatypeToTrackType.none = [];

  return localDatatypeToTrackType;
};

exports['default'] = DATATYPE_TO_TRACK_TYPE;

/***/ }),
/* 554 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var HEATED_OBJECT_MAP = exports.HEATED_OBJECT_MAP = [[0, 0, 0, 255], [35, 0, 0, 255], [52, 0, 0, 255], [60, 0, 0, 255], [63, 1, 0, 255], [64, 2, 0, 255], [68, 5, 0, 255], [69, 6, 0, 255], [72, 8, 0, 255], [74, 10, 0, 255], [77, 12, 0, 255], [78, 14, 0, 255], [81, 16, 0, 255], [83, 17, 0, 255], [85, 19, 0, 255], [86, 20, 0, 255], [89, 22, 0, 255], [91, 24, 0, 255], [92, 25, 0, 255], [94, 26, 0, 255], [95, 28, 0, 255], [98, 30, 0, 255], [100, 31, 0, 255], [102, 33, 0, 255], [103, 34, 0, 255], [105, 35, 0, 255], [106, 36, 0, 255], [108, 38, 0, 255], [109, 39, 0, 255], [111, 40, 0, 255], [112, 42, 0, 255], [114, 43, 0, 255], [115, 44, 0, 255], [117, 45, 0, 255], [119, 47, 0, 255], [119, 47, 0, 255], [120, 48, 0, 255], [122, 49, 0, 255], [123, 51, 0, 255], [125, 52, 0, 255], [125, 52, 0, 255], [126, 53, 0, 255], [128, 54, 0, 255], [129, 56, 0, 255], [129, 56, 0, 255], [131, 57, 0, 255], [132, 58, 0, 255], [134, 59, 0, 255], [134, 59, 0, 255], [136, 61, 0, 255], [137, 62, 0, 255], [137, 62, 0, 255], [139, 63, 0, 255], [139, 63, 0, 255], [140, 65, 0, 255], [142, 66, 0, 255], [142, 66, 0, 255], [143, 67, 0, 255], [143, 67, 0, 255], [145, 68, 0, 255], [145, 68, 0, 255], [146, 70, 0, 255], [146, 70, 0, 255], [148, 71, 0, 255], [148, 71, 0, 255], [149, 72, 0, 255], [149, 72, 0, 255], [151, 73, 0, 255], [151, 73, 0, 255], [153, 75, 0, 255], [153, 75, 0, 255], [154, 76, 0, 255], [154, 76, 0, 255], [154, 76, 0, 255], [156, 77, 0, 255], [156, 77, 0, 255], [157, 79, 0, 255], [157, 79, 0, 255], [159, 80, 0, 255], [159, 80, 0, 255], [159, 80, 0, 255], [160, 81, 0, 255], [160, 81, 0, 255], [162, 82, 0, 255], [162, 82, 0, 255], [163, 84, 0, 255], [163, 84, 0, 255], [165, 85, 0, 255], [165, 85, 0, 255], [166, 86, 0, 255], [166, 86, 0, 255], [166, 86, 0, 255], [168, 87, 0, 255], [168, 87, 0, 255], [170, 89, 0, 255], [170, 89, 0, 255], [171, 90, 0, 255], [171, 90, 0, 255], [173, 91, 0, 255], [173, 91, 0, 255], [174, 93, 0, 255], [174, 93, 0, 255], [176, 94, 0, 255], [176, 94, 0, 255], [177, 95, 0, 255], [177, 95, 0, 255], [179, 96, 0, 255], [179, 96, 0, 255], [180, 98, 0, 255], [182, 99, 0, 255], [182, 99, 0, 255], [183, 100, 0, 255], [183, 100, 0, 255], [185, 102, 0, 255], [185, 102, 0, 255], [187, 103, 0, 255], [187, 103, 0, 255], [188, 104, 0, 255], [188, 104, 0, 255], [190, 105, 0, 255], [191, 107, 0, 255], [191, 107, 0, 255], [193, 108, 0, 255], [193, 108, 0, 255], [194, 109, 0, 255], [196, 110, 0, 255], [196, 110, 0, 255], [197, 112, 0, 255], [197, 112, 0, 255], [199, 113, 0, 255], [200, 114, 0, 255], [200, 114, 0, 255], [202, 116, 0, 255], [202, 116, 0, 255], [204, 117, 0, 255], [205, 118, 0, 255], [205, 118, 0, 255], [207, 119, 0, 255], [208, 121, 0, 255], [208, 121, 0, 255], [210, 122, 0, 255], [211, 123, 0, 255], [211, 123, 0, 255], [213, 124, 0, 255], [214, 126, 0, 255], [214, 126, 0, 255], [216, 127, 0, 255], [217, 128, 0, 255], [217, 128, 0, 255], [219, 130, 0, 255], [221, 131, 0, 255], [221, 131, 0, 255], [222, 132, 0, 255], [224, 133, 0, 255], [224, 133, 0, 255], [225, 135, 0, 255], [227, 136, 0, 255], [227, 136, 0, 255], [228, 137, 0, 255], [230, 138, 0, 255], [230, 138, 0, 255], [231, 140, 0, 255], [233, 141, 0, 255], [233, 141, 0, 255], [234, 142, 0, 255], [236, 144, 0, 255], [236, 144, 0, 255], [238, 145, 0, 255], [239, 146, 0, 255], [241, 147, 0, 255], [241, 147, 0, 255], [242, 149, 0, 255], [244, 150, 0, 255], [244, 150, 0, 255], [245, 151, 0, 255], [247, 153, 0, 255], [247, 153, 0, 255], [248, 154, 0, 255], [250, 155, 0, 255], [251, 156, 0, 255], [251, 156, 0, 255], [253, 158, 0, 255], [255, 159, 0, 255], [255, 159, 0, 255], [255, 160, 0, 255], [255, 161, 0, 255], [255, 163, 0, 255], [255, 163, 0, 255], [255, 164, 0, 255], [255, 165, 0, 255], [255, 167, 0, 255], [255, 167, 0, 255], [255, 168, 0, 255], [255, 169, 0, 255], [255, 169, 0, 255], [255, 170, 0, 255], [255, 172, 0, 255], [255, 173, 0, 255], [255, 173, 0, 255], [255, 174, 0, 255], [255, 175, 0, 255], [255, 177, 0, 255], [255, 178, 0, 255], [255, 179, 0, 255], [255, 181, 0, 255], [255, 181, 0, 255], [255, 182, 0, 255], [255, 183, 0, 255], [255, 184, 0, 255], [255, 187, 7, 255], [255, 188, 10, 255], [255, 189, 14, 255], [255, 191, 18, 255], [255, 192, 21, 255], [255, 193, 25, 255], [255, 195, 29, 255], [255, 197, 36, 255], [255, 198, 40, 255], [255, 200, 43, 255], [255, 202, 51, 255], [255, 204, 54, 255], [255, 206, 61, 255], [255, 207, 65, 255], [255, 210, 72, 255], [255, 211, 76, 255], [255, 214, 83, 255], [255, 216, 91, 255], [255, 219, 98, 255], [255, 221, 105, 255], [255, 223, 109, 255], [255, 225, 116, 255], [255, 228, 123, 255], [255, 232, 134, 255], [255, 234, 142, 255], [255, 237, 149, 255], [255, 239, 156, 255], [255, 240, 160, 255], [255, 243, 167, 255], [255, 246, 174, 255], [255, 248, 182, 255], [255, 249, 185, 255], [255, 252, 193, 255], [255, 253, 196, 255], [255, 255, 204, 255], [255, 255, 207, 255], [255, 255, 211, 255], [255, 255, 218, 255], [255, 255, 222, 255], [255, 255, 225, 255], [255, 255, 229, 255], [255, 255, 233, 255], [255, 255, 236, 255], [255, 255, 240, 255], [255, 255, 244, 255], [255, 255, 247, 255], [255, 255, 255, 0]];

exports["default"] = HEATED_OBJECT_MAP;

/***/ }),
/* 555 */
/***/ (function(module, exports, __nested_webpack_require_2741379__) {

"use strict";


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

var _utils = __nested_webpack_require_2741379__(10);

var IS_TRACK_RANGE_SELECTABLE = exports.IS_TRACK_RANGE_SELECTABLE = function IS_TRACK_RANGE_SELECTABLE(track) {
  switch (track.type) {
    case 'heatmap':
    case 'horizontal-1d-heatmap':
    case 'horizontal-bar':
    case 'horizontal-line':
    case 'horizontal-point':
    case 'vertical-1d-heatmap':
    case 'vertical-bar':
    case 'vertical-line':
    case 'vertical-point':
    case 'horizontal-1d-tiles':
    case 'vertical-1d-tiles':
    case '2d-tiles':
    case 'horizontal-gene-annotations':
    case 'vertical-gene-annotations':
    case 'horizontal-heatmap':
    case 'vertical-heatmap':
    case 'osm-tiles':
    case 'mapbox-tiles':
    case 'horizontal-multivec':
      return true;

    case 'combined':
      {
        return track.contents.map(function (t) {
          return IS_TRACK_RANGE_SELECTABLE(t);
        }).reduce(_utils.or, false);
      }

    default:
      return false;
  }
};

exports['default'] = IS_TRACK_RANGE_SELECTABLE;

/***/ }),
/* 556 */
/***/ (function(module, exports, __nested_webpack_require_2742589__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_2742589__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _values = __nested_webpack_require_2742589__(37);

var _values2 = _interopRequireDefault(_values);

var _getIterator2 = __nested_webpack_require_2742589__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _extends2 = __nested_webpack_require_2742589__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _assign = __nested_webpack_require_2742589__(44);

var _assign2 = _interopRequireDefault(_assign);

var _d3Format = __nested_webpack_require_2742589__(20);

var _HeatmapOptions = __nested_webpack_require_2742589__(559);

var _HeatmapOptions2 = _interopRequireDefault(_HeatmapOptions);

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

var valueColumnOptions = function valueColumnOptions(track) {
  if (!track.header) return [];

  var headerParts = track.header.split('\t');
  var options = [];

  for (var i = 0; i < headerParts.length; i++) {
    options.push({
      name: headerParts[i],
      value: i + 1
    });
  }

  return options;
};

var sizesInPx = function sizesInPx(sizes) {
  var unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var multiplier = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  return sizes.reduce(function (sizeOption, size) {
    sizeOption[size] = { name: '' + size * multiplier + String(unit), value: size };
    return sizeOption;
  }, {});
};

var YES_NO = {
  yes: { name: 'Yes', value: true },
  no: { name: 'No', value: false }
};

var AVAILABLE_COLORS = {
  black: { name: 'Black', value: 'black' },
  blue: { name: 'Blue', value: 'blue' },
  brown: { name: 'Brown', value: 'brown' },
  cyan: { name: 'Cyan', value: 'cyan' },
  green: { name: 'Green', value: 'green' },
  grey: { name: 'Grey', value: 'grey' },
  orange: { name: 'Orange', value: 'orange' },
  purple: { name: 'Purple', value: 'purple' },
  turquoise: { name: 'Turquoise', value: 'turquoise' },
  red: { name: 'Red', value: 'red' },
  white: { name: 'White', value: 'white' }
};

var SPECIAL_COLORS = {
  use_stroke: { name: 'Glyph color', value: '[glyph-color]' }
};

var AVAILABLE_WIDTHS = sizesInPx([1, 2, 3, 5, 8, 13, 21]);
var AVAILABLE_WIDTHS_AND_NONE = (0, _assign2['default'])(AVAILABLE_WIDTHS, {
  none: { name: 'none', value: 'none' }
});

var AVAILABLE_MARGIN = sizesInPx([0, 2, 4, 8, 16, 32, 64, 128, 256]);

var OPACITY_OPTIONS = sizesInPx([0.0, 0.2, 0.4, 0.6, 0.8, 1.0], '%', 100);
var OPACITY_OPTIONS_NO_ZERO = sizesInPx([0.2, 0.4, 0.6, 0.8, 1.0], '%', 100);

// these values define the options that are visible in the track config
// menu
var OPTIONS_INFO = exports.OPTIONS_INFO = {
  axisLabelFormatting: {
    name: 'Axis Label Formatting',
    inlineOptions: {
      normal: {
        name: 'normal',
        value: 'normal'
      },
      scientific: {
        name: 'scientific',
        value: 'scientific'
      }
    }
  },
  flipDiagonal: {
    name: 'Flip Across Diagonal',
    inlineOptions: {
      none: { name: 'No', value: 'none' },
      yes: { name: 'Yes', value: 'yes' },
      copy: { name: 'Copy', value: 'copy' }
    }
  },
  heatmapValueScaling: {
    name: 'Value Scaling',
    inlineOptions: {
      linear: { name: 'Linear', value: 'linear' },
      log: { name: 'Log', value: 'log' }
    }
  },
  valueScaling: {
    name: 'Value Scaling',
    inlineOptions: {
      linear: { name: 'Linear', value: 'linear' },
      log: { name: 'Log', value: 'log' }
    }
  },
  extent: {
    name: 'Extent',
    inlineOptions: {
      full: { name: 'Full', value: 'full' },
      upperRight: { name: 'Upper Right', value: 'upper-right' },
      lowerLeft: { name: 'Lower Left', value: 'lower-left' }
    }
  },
  labelLeftMargin: {
    name: 'Label Left Margin',
    inlineOptions: AVAILABLE_MARGIN
  },
  labelRightMargin: {
    name: 'Label Right Margin',
    inlineOptions: AVAILABLE_MARGIN
  },
  labelTopMargin: {
    name: 'Label Top Margin',
    inlineOptions: AVAILABLE_MARGIN
  },
  labelBottomMargin: {
    name: 'Label Bottom Margin',
    inlineOptions: AVAILABLE_MARGIN
  },
  labelShowResolution: {
    name: 'Label Show Resolution',
    inlineOptions: YES_NO
  },
  labelShowAssembly: {
    name: 'Label Show Assembly',
    inlineOptions: YES_NO
  },
  lineStrokeWidth: {
    name: 'Stroke Width',
    inlineOptions: AVAILABLE_WIDTHS
  },
  strokeWidth: {
    name: 'Stroke Width',
    inlineOptions: AVAILABLE_WIDTHS
  },
  trackBorderWidth: {
    name: 'Track Border Width',
    inlineOptions: AVAILABLE_WIDTHS
  },
  separatePlusMinusStrands: {
    name: 'Separate +/- strands',
    inlineOptions: YES_NO
  },
  sortLargestOnTop: {
    name: 'Sort Largest On Top',
    inlineOptions: YES_NO
  },
  showTexts: {
    name: 'Show texts',
    inlineOptions: YES_NO
  },
  staggered: {
    name: 'Staggered',
    inlineOptions: YES_NO
  },
  minSquareSize: {
    name: 'Minimum size',
    inlineOptions: AVAILABLE_WIDTHS_AND_NONE
  },
  pointSize: {
    name: 'Point Size',
    inlineOptions: AVAILABLE_WIDTHS
  },
  pointColor: {
    name: 'Point Color',
    inlineOptions: AVAILABLE_COLORS
  },
  trackBorderColor: {
    name: 'Track Border Color',
    inlineOptions: AVAILABLE_COLORS
  },
  backgroundColor: {
    name: 'Background Color',
    inlineOptions: {
      white: { name: 'White', value: 'white' },
      lightGrey: { name: 'Light Grey', value: '#eeeeee' },
      grey: { name: 'Grey', value: '#cccccc' },
      black: { name: 'Black', value: 'black' },
      transparent: { name: 'Transparent', value: 'transparent' }
    }
  },
  colorScale: {
    name: 'Color Scale',
    inlineOptions: {
      epilogos: {
        name: 'Epilogos',
        values: ['#FF0000', '#FF4500', '#32CD32', '#008000', '#006400', '#C2E105', '#FFFF00', '#66CDAA', '#8A91D0', '#CD5C5C', '#E9967A', '#BDB76B', '#808080', '#C0C0C0', '#FFFFFF']
      },
      category10: {
        name: 'D3 Category10',
        values: ['#1F77B4', '#FF7F0E', '#2CA02C', '#D62728', '#9467BD', '#8C564B', '#E377C2', '#7F7F7F', '#BCBD22', '#17BECF']
      }
    }
  },
  minusStrandColor: {
    name: '- Strand Color',
    inlineOptions: AVAILABLE_COLORS
  },
  plusStrandColor: {
    name: '+ Strand Color',
    inlineOptions: AVAILABLE_COLORS
  },
  lineStrokeColor: {
    name: 'Stroke color',
    inlineOptions: AVAILABLE_COLORS
  },
  projectionStrokeColor: {
    name: 'Stroke color',
    inlineOptions: AVAILABLE_COLORS
  },
  projectionFillColor: {
    name: 'Fill color',
    inlineOptions: AVAILABLE_COLORS
  },
  stroke: {
    name: 'Stroke Color',
    inlineOptions: AVAILABLE_COLORS
  },
  strokeColor: {
    name: 'Stroke color',
    inlineOptions: AVAILABLE_COLORS
  },
  fill: {
    name: 'Fill Color',
    inlineOptions: AVAILABLE_COLORS
  },
  color: {
    name: 'Color',
    inlineOptions: AVAILABLE_COLORS
  },
  fontColor: {
    name: 'Font color',
    inlineOptions: AVAILABLE_COLORS
  },
  fillColor: {
    name: 'Fill color',
    inlineOptions: AVAILABLE_COLORS
  },
  barFillColor: {
    name: 'Fill color',
    inlineOptions: AVAILABLE_COLORS
  },
  barFillColorTop: {
    name: 'Top Fill color',
    inlineOptions: AVAILABLE_COLORS
  },
  barFillColorBottom: {
    name: 'Bottom Fill color',
    inlineOptions: AVAILABLE_COLORS
  },
  barOpacity: {
    name: 'Bar opacity',
    inlineOptions: OPACITY_OPTIONS
  },
  zeroLineVisible: {
    name: 'Zero line visible',
    inlineOptions: YES_NO
  },
  zeroLineColor: {
    name: 'Zero line color',
    inlineOptions: AVAILABLE_COLORS
  },
  zeroLineOpacity: {
    name: 'Zero line opacity',
    inlineOptions: OPACITY_OPTIONS_NO_ZERO
  },
  fillOpacity: {
    name: 'Fill Opacity',
    inlineOptions: OPACITY_OPTIONS
  },
  strokeOpacity: {
    name: 'Stroke Opacity',
    inlineOptions: OPACITY_OPTIONS
  },
  strokePos: {
    name: 'Stroke Position',
    inlineOptions: {
      aroundInner: { name: 'Around Inner', value: 'around' },
      aroundCenter: { name: 'Around Center', value: null },
      hidden: { name: 'Hidden', value: 'hidden' },
      top: { name: 'Top', value: 'top' },
      right: { name: 'Right', value: 'right' },
      bottom: { name: 'Bottom', value: 'bottom' },
      left: { name: 'Left', value: 'left' }
    }
  },
  barBorder: {
    name: 'Bar border',
    inlineOptions: YES_NO
  },
  scaledHeight: {
    name: 'Scaled height',
    inlineOptions: YES_NO
  },
  rectangleDomainStrokeColor: {
    name: 'Stroke color',
    inlineOptions: AVAILABLE_COLORS
  },
  rectangleDomainFillColor: {
    name: 'Fill color',
    inlineOptions: AVAILABLE_COLORS
  },
  rectangleDomainFillOpacity: {
    name: 'Fill opacity',
    inlineOptions: OPACITY_OPTIONS
  },
  rectangleDomainOpacity: {
    name: 'Opacity',
    inlineOptions: OPACITY_OPTIONS
  },
  mapboxStyle: {
    name: 'Map style',
    inlineOptions: {
      streets: {
        name: 'streets',
        value: 'mapbox.streets'
      },
      light: {
        name: 'light',
        value: 'mapbox.light'
      },
      dark: {
        name: 'dark',
        value: 'mapbox.dark'
      },
      satellite: {
        name: 'satellite',
        value: 'mapbox.satellite'
      },
      'streets-satellite': {
        name: 'streets-satellite',
        value: 'mapbox.streets-satellite'
      },
      wheatpaste: {
        name: 'wheatpaste',
        value: 'mapbox.wheatpaste'
      },
      'streets-basic': {
        name: 'streets-basic',
        value: 'mapbox.streets-basic'
      },
      comic: {
        name: 'comic',
        value: 'mapbox.comic'
      },
      outdoors: {
        name: 'outdoors',
        value: 'mapbox.outdoors'
      },
      'run-bike-hike': {
        name: 'run-bike-hike',
        value: 'mapbox.run-bike-hike'
      },
      pencil: {
        name: 'pencil',
        value: 'mapbox.pencil'
      },
      pirates: {
        name: 'pirates',
        value: 'mapbox.pirates'
      },
      emerald: {
        name: 'emerald',
        value: 'mapbox.emerald'
      },
      'high-contrast': {
        name: 'high-contrast',
        value: 'mapbox.high-contrast'
      }
    }
  },
  oneDHeatmapFlipped: {
    name: 'Flip Heatmap',
    inlineOptions: {
      yes: { name: 'Yes', value: 'yes' },
      no: { name: 'No', value: null }
    }
  },
  showMousePosition: {
    name: 'Show Mouse Position',
    inlineOptions: YES_NO
  },
  showTooltip: {
    name: 'Show Tooltip',
    inlineOptions: YES_NO
  },

  fontSize: {
    name: 'Font Size',
    inlineOptions: sizesInPx([8, 9, 10, 11, 12, 14, 16, 18, 24], 'px')
  },

  tickPositions: {
    name: 'Tick Positions',
    inlineOptions: {
      even: {
        name: 'Even',
        value: 'even'
      },
      ends: {
        name: 'Ends',
        value: 'ends'
      }
    }
  },

  tickFormat: {
    name: 'Tick Format',
    inlineOptions: {
      plain: {
        name: 'Plain',
        value: 'plain'
      },
      si: {
        name: 'SI',
        value: 'si'
      }
    }
  },

  colorEncoding: {
    name: 'Color Encode Annotations',
    inlineOptions: {
      none: { name: 'None', value: null },
      itemRgb: { name: 'itemRgb', value: 'itemRgb' }
    },
    generateOptions: valueColumnOptions
  },

  fontIsAligned: {
    name: 'Left-Align Font',
    inlineOptions: YES_NO
  },

  axisPositionHorizontal: {
    name: 'Axis Position',
    inlineOptions: {
      left: { name: 'Left', value: 'left' },
      outsideLeft: { name: 'Outside left', value: 'outsideLeft' },
      right: { name: 'Right', value: 'right' },
      outsideRight: { name: 'Outside right', value: 'outsideRight' },
      hidden: { name: 'Hidden', value: null }
    }
  },

  axisPositionVertical: {
    name: 'Axis Position',
    inlineOptions: {
      top: { name: 'Top', value: 'top' },
      outsideTop: { name: 'Outside top', value: 'outsideTop' },
      bottom: { name: 'Bottom', value: 'bottom' },
      outsideBottom: { name: 'Outside bottom', value: 'outsideBottom' },
      hidden: { name: 'Hidden', value: null }
    }
  },

  axisMargin: {
    name: 'Axis Margin',
    inlineOptions: sizesInPx([0, 10, 20, 30, 40, 50, 100, 200, 400], 'px')
  },

  colorbarPosition: {
    name: 'Colorbar Position',
    inlineOptions: {
      topLeft: { name: 'Top Left', value: 'topLeft' },
      topRight: { name: 'Top Right', value: 'topRight' },
      bottomLeft: { name: 'Bottom Left', value: 'bottomLeft' },
      bottomRight: { name: 'Bottom Right', value: 'bottomRight' },
      hidden: { name: 'Hidden', value: null }
    }
  },

  colorbarBackgroundColor: {
    name: 'Colorbar Background Color',
    inlineOptions: AVAILABLE_COLORS
  },

  colorbarBackgroundOpacity: {
    name: 'Colorbar Background Opacity',
    inlineOptions: OPACITY_OPTIONS
  },

  /*
  colorbarOrientation: {
    name: 'Colorbar Orientation',
    inlineOptions: {
      'horizontal': { name: 'Horizontal', value: 'horizontal' },
      'vertical': { name: 'Vertical', value: 'vertical' },
    }
  },
  */

  // This will default to 'inside' if it's not set when colorbarPosition
  // is set
  colorbarLabelsPosition: {
    name: 'Colorbar Labels Position',
    inlineOptions: {
      inside: { name: 'Inside', value: 'inside' },
      outside: { name: 'Outside', value: 'outside' }
    }
  },

  labelColor: {
    name: 'Label Color',
    inlineOptions: (0, _extends3['default'])({}, AVAILABLE_COLORS, SPECIAL_COLORS)
  },

  labelPosition: {
    name: 'Label Position',
    inlineOptions: {
      ol: { name: 'Outer left', value: 'outerLeft' },
      or: { name: 'Outer right', value: 'outerRight' },
      ot: { name: 'Outer top', value: 'outerTop' },
      ob: { name: 'Outer bottom', value: 'outerBottom' },
      tl: { name: 'Top left', value: 'topLeft' },
      tr: { name: 'Top right', value: 'topRight' },
      bl: { name: 'Bottom left', value: 'bottomLeft' },
      br: { name: 'Bottom right', value: 'bottomRight' },
      hidden: { name: 'Hidden', value: 'hidden' }
    }
  },

  labelTextOpacity: {
    name: 'Label Text Opacity',
    inlineOptions: OPACITY_OPTIONS
  },

  geneAnnotationHeight: {
    name: 'Gene Annotation Height',
    inlineOptions: {
      8: { name: '8px', value: 8 },
      10: { name: '10px', value: 10 },
      12: { name: '12px', value: 12 },
      16: { name: '16px', value: 16 }
    }
  },

  annotationHeight: {
    name: 'Annotation Height',
    inlineOptions: {
      5: { name: '5px', value: 5 },
      8: { name: '8px', value: 8 },
      10: { name: '10px', value: 10 },
      12: { name: '12px', value: 12 },
      16: { name: '16px', value: 16 },
      20: { name: '20px', value: 20 },
      scaled: { name: 'scaled', value: 'scaled' }
    }
  },

  maxAnnotationHeight: {
    name: 'Max Annotation Height',
    inlineOptions: {
      5: { name: '5px', value: 5 },
      8: { name: '8px', value: 8 },
      10: { name: '10px', value: 10 },
      12: { name: '12px', value: 12 },
      16: { name: '16px', value: 16 },
      20: { name: '20px', value: 20 },
      none: { name: 'none', value: null }
    }
  },

  annotationStyle: {
    name: 'Annotation Style',
    inlineOptions: {
      box: { name: 'Box', value: 'box' },
      segment: { name: 'Segment', value: 'segment' }
    }
  },

  geneLabelPosition: {
    name: 'Gene Label Position',
    inlineOptions: {
      inside: { name: 'Inside', value: 'inside' },
      outside: { name: 'Outside', value: 'outside' }
    }
  },

  geneStrandSpacing: {
    name: 'Gene Strand Spacing',
    inlineOptions: {
      2: { name: '2px', value: 2 },
      4: { name: '4px', value: 4 },
      8: { name: '8px', value: 8 }
    }
  },

  labelBackgroundColor: {
    name: 'Label Background Color',
    inlineOptions: AVAILABLE_COLORS
  },

  labelBackgroundOpacity: {
    name: 'Label Background Opacity',
    inlineOptions: OPACITY_OPTIONS
  },

  viewResolution: {
    name: 'View Resolution',
    inlineOptions: {
      high: { name: 'High', value: 384 },
      medium: { name: 'Medium', value: 1024 },
      low: { name: 'Low', value: 2048 }
    }
  },

  // colormaps are mostly taken from here:
  // http://matplotlib.org/api/pyplot_summary.html?highlight=colormaps#matplotlib.pyplot.colormaps
  colorRange: {
    name: 'Color map',
    inlineOptions: {
      afmhot: {
        name: 'afmhot',
        value: ['rgba(0,0,0,1.0)', 'rgba(128,0,0,1.0)', 'rgba(256,129,1,1.0)', 'rgba(256,256,129,1.0)', 'rgba(256,256,256,1.0)']
      },
      fall: {
        name: 'fall',
        value: ['white', 'rgba(245,166,35,1.0)', 'rgba(208,2,27,1.0)', 'black']
      },
      hot: {
        name: 'hot',
        value: ['rgba(10,0,0,1.0)', 'rgba(179,0,0,1.0)', 'rgba(256,91,0,1.0)', 'rgba(256,256,6,1.0)', 'rgba(256,256,256,1.0)']
      },
      jet: {
        name: 'jet',
        value: ['rgba(0,0,128,1.0)', 'rgba(0,129,256,1.0)', 'rgba(125,256,122,1.0)', 'rgba(256,148,0,1.0)', 'rgba(128,0,0,1.0)']
      },

      bwr: {
        name: 'bwr',
        value: ['rgba(0,0,256,1.0)', 'rgba(128,128,256,1.0)', 'rgba(256,254,254,1.0)', 'rgba(256,126,126,1.0)', 'rgba(256,0,0,1.0)']
      },
      cubehelix: {
        name: 'cubehelix',
        value: ['rgba(0,0,0,1.0)', 'rgba(21,83,76,1.0)', 'rgba(162,121,74,1.0)', 'rgba(199,180,238,1.0)', 'rgba(256,256,256,1.0)']
      },
      rainbow: {
        name: 'rainbow',
        value: ['rgba(128,0,256,1.0)', 'rgba(0,181,236,1.0)', 'rgba(129,255,180,1.0)', 'rgba(256,179,96,1.0)', 'rgba(256,0,0,1.0)']
      },

      gray: {
        name: 'greys',
        value: ['rgba(255,255,255,1)', 'rgba(0,0,0,1)']
      },
      red: {
        name: 'White to red',
        value: ['rgba(255,255,255,1)', 'rgba(255,0,0,1)']
      },
      green: {
        name: 'White to green',
        value: ['rgba(255,255,255,1)', 'rgba(0,255,0,1)']
      },
      blue: {
        name: 'White to blue',
        value: ['rgba(255,255,255,1)', 'rgba(0,0,255,1)']
      },
      custard: {
        name: 'custard',
        value: ['#FFFFFF', '#F8E71C', 'rgba(245,166,35,1)', 'rgba(0,0,0,1)']
      },
      magma: {
        name: 'magma',
        value: ['rgba(0,0,3,1)', 'rgba(0,0,4,1)', 'rgba(0,0,6,1)', 'rgba(1,0,7,1)', 'rgba(1,1,9,1)', 'rgba(1,1,11,1)', 'rgba(2,2,13,1)', 'rgba(2,2,15,1)', 'rgba(3,3,17,1)', 'rgba(4,3,19,1)', 'rgba(4,4,21,1)', 'rgba(5,4,23,1)', 'rgba(6,5,25,1)', 'rgba(7,5,27,1)', 'rgba(8,6,29,1)', 'rgba(9,7,32,1)', 'rgba(10,7,34,1)', 'rgba(11,8,36,1)', 'rgba(12,9,38,1)', 'rgba(13,10,40,1)', 'rgba(14,10,42,1)', 'rgba(15,11,45,1)', 'rgba(16,12,47,1)', 'rgba(17,12,49,1)', 'rgba(19,13,51,1)', 'rgba(20,13,54,1)', 'rgba(21,14,56,1)', 'rgba(22,14,58,1)', 'rgba(23,15,61,1)', 'rgba(25,15,63,1)', 'rgba(26,16,66,1)', 'rgba(27,16,68,1)', 'rgba(28,16,70,1)', 'rgba(30,17,73,1)', 'rgba(31,17,75,1)', 'rgba(33,17,78,1)', 'rgba(34,17,80,1)', 'rgba(36,17,83,1)', 'rgba(37,17,85,1)', 'rgba(39,17,87,1)', 'rgba(40,17,90,1)', 'rgba(42,17,92,1)', 'rgba(43,17,94,1)', 'rgba(45,17,97,1)', 'rgba(47,16,99,1)', 'rgba(49,16,101,1)', 'rgba(50,16,103,1)', 'rgba(52,16,105,1)', 'rgba(54,15,107,1)', 'rgba(55,15,108,1)', 'rgba(57,15,110,1)', 'rgba(59,15,112,1)', 'rgba(61,15,113,1)', 'rgba(62,15,114,1)', 'rgba(64,15,116,1)', 'rgba(66,15,117,1)', 'rgba(67,15,118,1)', 'rgba(69,15,119,1)', 'rgba(71,15,120,1)', 'rgba(72,16,120,1)', 'rgba(74,16,121,1)', 'rgba(76,16,122,1)', 'rgba(77,17,123,1)', 'rgba(79,17,123,1)', 'rgba(81,18,124,1)', 'rgba(82,18,124,1)', 'rgba(84,19,125,1)', 'rgba(85,20,125,1)', 'rgba(87,20,126,1)', 'rgba(88,21,126,1)', 'rgba(90,21,126,1)', 'rgba(92,22,127,1)', 'rgba(93,23,127,1)', 'rgba(95,23,127,1)', 'rgba(96,24,128,1)', 'rgba(98,25,128,1)', 'rgba(99,25,128,1)', 'rgba(101,26,128,1)', 'rgba(103,26,128,1)', 'rgba(104,27,129,1)', 'rgba(106,28,129,1)', 'rgba(107,28,129,1)', 'rgba(109,29,129,1)', 'rgba(110,30,129,1)', 'rgba(112,30,129,1)', 'rgba(113,31,129,1)', 'rgba(115,32,129,1)', 'rgba(117,32,129,1)', 'rgba(118,33,129,1)', 'rgba(120,33,129,1)', 'rgba(121,34,130,1)', 'rgba(123,35,130,1)', 'rgba(124,35,130,1)', 'rgba(126,36,130,1)', 'rgba(128,36,130,1)', 'rgba(129,37,129,1)', 'rgba(131,37,129,1)', 'rgba(132,38,129,1)', 'rgba(134,39,129,1)', 'rgba(136,39,129,1)', 'rgba(137,40,129,1)', 'rgba(139,40,129,1)', 'rgba(140,41,129,1)', 'rgba(142,41,129,1)', 'rgba(144,42,129,1)', 'rgba(145,42,129,1)', 'rgba(147,43,128,1)', 'rgba(148,43,128,1)', 'rgba(150,44,128,1)', 'rgba(152,44,128,1)', 'rgba(153,45,128,1)', 'rgba(155,46,127,1)', 'rgba(157,46,127,1)', 'rgba(158,47,127,1)', 'rgba(160,47,127,1)', 'rgba(161,48,126,1)', 'rgba(163,48,126,1)', 'rgba(165,49,126,1)', 'rgba(166,49,125,1)', 'rgba(168,50,125,1)', 'rgba(170,50,125,1)', 'rgba(171,51,124,1)', 'rgba(173,51,124,1)', 'rgba(175,52,123,1)', 'rgba(176,52,123,1)', 'rgba(178,53,123,1)', 'rgba(180,53,122,1)', 'rgba(181,54,122,1)', 'rgba(183,55,121,1)', 'rgba(185,55,121,1)', 'rgba(186,56,120,1)', 'rgba(188,56,120,1)', 'rgba(189,57,119,1)', 'rgba(191,57,118,1)', 'rgba(193,58,118,1)', 'rgba(194,59,117,1)', 'rgba(196,59,117,1)', 'rgba(198,60,116,1)', 'rgba(199,61,115,1)', 'rgba(201,61,115,1)', 'rgba(202,62,114,1)', 'rgba(204,63,113,1)', 'rgba(206,63,113,1)', 'rgba(207,64,112,1)', 'rgba(209,65,111,1)', 'rgba(210,66,110,1)', 'rgba(212,67,110,1)', 'rgba(213,67,109,1)', 'rgba(215,68,108,1)', 'rgba(216,69,107,1)', 'rgba(218,70,107,1)', 'rgba(219,71,106,1)', 'rgba(221,72,105,1)', 'rgba(222,73,104,1)', 'rgba(223,74,103,1)', 'rgba(225,75,103,1)', 'rgba(226,76,102,1)', 'rgba(227,78,101,1)', 'rgba(229,79,100,1)', 'rgba(230,80,100,1)', 'rgba(231,81,99,1)', 'rgba(232,83,98,1)', 'rgba(233,84,97,1)', 'rgba(234,85,97,1)', 'rgba(236,87,96,1)', 'rgba(237,88,95,1)', 'rgba(238,90,95,1)', 'rgba(239,91,94,1)', 'rgba(239,93,94,1)', 'rgba(240,95,93,1)', 'rgba(241,96,93,1)', 'rgba(242,98,93,1)', 'rgba(243,100,92,1)', 'rgba(243,101,92,1)', 'rgba(244,103,92,1)', 'rgba(245,105,92,1)', 'rgba(246,107,92,1)', 'rgba(246,108,92,1)', 'rgba(247,110,92,1)', 'rgba(247,112,92,1)', 'rgba(248,114,92,1)', 'rgba(248,116,92,1)', 'rgba(249,118,92,1)', 'rgba(249,120,92,1)', 'rgba(250,121,93,1)', 'rgba(250,123,93,1)', 'rgba(250,125,94,1)', 'rgba(251,127,94,1)', 'rgba(251,129,95,1)', 'rgba(251,131,95,1)', 'rgba(252,133,96,1)', 'rgba(252,135,97,1)', 'rgba(252,137,97,1)', 'rgba(252,139,98,1)', 'rgba(253,140,99,1)', 'rgba(253,142,100,1)', 'rgba(253,144,101,1)', 'rgba(253,146,102,1)', 'rgba(253,148,103,1)', 'rgba(254,150,104,1)', 'rgba(254,152,105,1)', 'rgba(254,154,106,1)', 'rgba(254,156,107,1)', 'rgba(254,157,108,1)', 'rgba(254,159,109,1)', 'rgba(254,161,110,1)', 'rgba(254,163,111,1)', 'rgba(254,165,112,1)', 'rgba(255,167,114,1)', 'rgba(255,169,115,1)', 'rgba(255,171,116,1)', 'rgba(255,172,118,1)', 'rgba(255,174,119,1)', 'rgba(255,176,120,1)', 'rgba(255,178,122,1)', 'rgba(255,180,123,1)', 'rgba(255,182,124,1)', 'rgba(255,184,126,1)', 'rgba(255,185,127,1)', 'rgba(255,187,129,1)', 'rgba(255,189,130,1)', 'rgba(255,191,132,1)', 'rgba(255,193,133,1)', 'rgba(255,195,135,1)', 'rgba(255,197,136,1)', 'rgba(255,198,138,1)', 'rgba(255,200,140,1)', 'rgba(255,202,141,1)', 'rgba(255,204,143,1)', 'rgba(254,206,144,1)', 'rgba(254,208,146,1)', 'rgba(254,209,148,1)', 'rgba(254,211,149,1)', 'rgba(254,213,151,1)', 'rgba(254,215,153,1)', 'rgba(254,217,155,1)', 'rgba(254,219,156,1)', 'rgba(254,220,158,1)', 'rgba(254,222,160,1)', 'rgba(254,224,162,1)', 'rgba(254,226,163,1)', 'rgba(253,228,165,1)', 'rgba(253,230,167,1)', 'rgba(253,231,169,1)', 'rgba(253,233,171,1)', 'rgba(253,235,172,1)', 'rgba(253,237,174,1)', 'rgba(253,239,176,1)', 'rgba(253,241,178,1)', 'rgba(253,242,180,1)', 'rgba(253,244,182,1)', 'rgba(253,246,184,1)', 'rgba(252,248,186,1)', 'rgba(252,250,188,1)', 'rgba(252,251,189,1)', 'rgba(252,253,191,1)']
      },
      viridis: {
        name: 'viridis',
        value: ['rgba(68,1,84,1)', 'rgba(68,2,85,1)', 'rgba(69,3,87,1)', 'rgba(69,5,88,1)', 'rgba(69,6,90,1)', 'rgba(70,8,91,1)', 'rgba(70,9,93,1)', 'rgba(70,11,94,1)', 'rgba(70,12,96,1)', 'rgba(71,14,97,1)', 'rgba(71,15,98,1)', 'rgba(71,17,100,1)', 'rgba(71,18,101,1)', 'rgba(71,20,102,1)', 'rgba(72,21,104,1)', 'rgba(72,22,105,1)', 'rgba(72,24,106,1)', 'rgba(72,25,108,1)', 'rgba(72,26,109,1)', 'rgba(72,28,110,1)', 'rgba(72,29,111,1)', 'rgba(72,30,112,1)', 'rgba(72,32,113,1)', 'rgba(72,33,115,1)', 'rgba(72,34,116,1)', 'rgba(72,36,117,1)', 'rgba(72,37,118,1)', 'rgba(72,38,119,1)', 'rgba(72,39,120,1)', 'rgba(71,41,121,1)', 'rgba(71,42,121,1)', 'rgba(71,43,122,1)', 'rgba(71,44,123,1)', 'rgba(71,46,124,1)', 'rgba(70,47,125,1)', 'rgba(70,48,126,1)', 'rgba(70,49,126,1)', 'rgba(70,51,127,1)', 'rgba(69,52,128,1)', 'rgba(69,53,129,1)', 'rgba(69,54,129,1)', 'rgba(68,56,130,1)', 'rgba(68,57,131,1)', 'rgba(68,58,131,1)', 'rgba(67,59,132,1)', 'rgba(67,60,132,1)', 'rgba(67,62,133,1)', 'rgba(66,63,133,1)', 'rgba(66,64,134,1)', 'rgba(65,65,134,1)', 'rgba(65,66,135,1)', 'rgba(65,67,135,1)', 'rgba(64,69,136,1)', 'rgba(64,70,136,1)', 'rgba(63,71,136,1)', 'rgba(63,72,137,1)', 'rgba(62,73,137,1)', 'rgba(62,74,137,1)', 'rgba(61,75,138,1)', 'rgba(61,77,138,1)', 'rgba(60,78,138,1)', 'rgba(60,79,138,1)', 'rgba(59,80,139,1)', 'rgba(59,81,139,1)', 'rgba(58,82,139,1)', 'rgba(58,83,139,1)', 'rgba(57,84,140,1)', 'rgba(57,85,140,1)', 'rgba(56,86,140,1)', 'rgba(56,87,140,1)', 'rgba(55,88,140,1)', 'rgba(55,89,140,1)', 'rgba(54,91,141,1)', 'rgba(54,92,141,1)', 'rgba(53,93,141,1)', 'rgba(53,94,141,1)', 'rgba(52,95,141,1)', 'rgba(52,96,141,1)', 'rgba(51,97,141,1)', 'rgba(51,98,141,1)', 'rgba(51,99,141,1)', 'rgba(50,100,142,1)', 'rgba(50,101,142,1)', 'rgba(49,102,142,1)', 'rgba(49,103,142,1)', 'rgba(48,104,142,1)', 'rgba(48,105,142,1)', 'rgba(47,106,142,1)', 'rgba(47,107,142,1)', 'rgba(47,108,142,1)', 'rgba(46,109,142,1)', 'rgba(46,110,142,1)', 'rgba(45,111,142,1)', 'rgba(45,112,142,1)', 'rgba(45,112,142,1)', 'rgba(44,113,142,1)', 'rgba(44,114,142,1)', 'rgba(43,115,142,1)', 'rgba(43,116,142,1)', 'rgba(43,117,142,1)', 'rgba(42,118,142,1)', 'rgba(42,119,142,1)', 'rgba(41,120,142,1)', 'rgba(41,121,142,1)', 'rgba(41,122,142,1)', 'rgba(40,123,142,1)', 'rgba(40,124,142,1)', 'rgba(40,125,142,1)', 'rgba(39,126,142,1)', 'rgba(39,127,142,1)', 'rgba(38,128,142,1)', 'rgba(38,129,142,1)', 'rgba(38,130,142,1)', 'rgba(37,131,142,1)', 'rgba(37,131,142,1)', 'rgba(37,132,142,1)', 'rgba(36,133,142,1)', 'rgba(36,134,142,1)', 'rgba(35,135,142,1)', 'rgba(35,136,142,1)', 'rgba(35,137,142,1)', 'rgba(34,138,141,1)', 'rgba(34,139,141,1)', 'rgba(34,140,141,1)', 'rgba(33,141,141,1)', 'rgba(33,142,141,1)', 'rgba(33,143,141,1)', 'rgba(32,144,141,1)', 'rgba(32,145,140,1)', 'rgba(32,146,140,1)', 'rgba(32,147,140,1)', 'rgba(31,147,140,1)', 'rgba(31,148,140,1)', 'rgba(31,149,139,1)', 'rgba(31,150,139,1)', 'rgba(31,151,139,1)', 'rgba(30,152,139,1)', 'rgba(30,153,138,1)', 'rgba(30,154,138,1)', 'rgba(30,155,138,1)', 'rgba(30,156,137,1)', 'rgba(30,157,137,1)', 'rgba(30,158,137,1)', 'rgba(30,159,136,1)', 'rgba(30,160,136,1)', 'rgba(31,161,136,1)', 'rgba(31,162,135,1)', 'rgba(31,163,135,1)', 'rgba(31,163,134,1)', 'rgba(32,164,134,1)', 'rgba(32,165,134,1)', 'rgba(33,166,133,1)', 'rgba(33,167,133,1)', 'rgba(34,168,132,1)', 'rgba(35,169,131,1)', 'rgba(35,170,131,1)', 'rgba(36,171,130,1)', 'rgba(37,172,130,1)', 'rgba(38,173,129,1)', 'rgba(39,174,129,1)', 'rgba(40,175,128,1)', 'rgba(41,175,127,1)', 'rgba(42,176,127,1)', 'rgba(43,177,126,1)', 'rgba(44,178,125,1)', 'rgba(46,179,124,1)', 'rgba(47,180,124,1)', 'rgba(48,181,123,1)', 'rgba(50,182,122,1)', 'rgba(51,183,121,1)', 'rgba(53,183,121,1)', 'rgba(54,184,120,1)', 'rgba(56,185,119,1)', 'rgba(57,186,118,1)', 'rgba(59,187,117,1)', 'rgba(61,188,116,1)', 'rgba(62,189,115,1)', 'rgba(64,190,114,1)', 'rgba(66,190,113,1)', 'rgba(68,191,112,1)', 'rgba(70,192,111,1)', 'rgba(72,193,110,1)', 'rgba(73,194,109,1)', 'rgba(75,194,108,1)', 'rgba(77,195,107,1)', 'rgba(79,196,106,1)', 'rgba(81,197,105,1)', 'rgba(83,198,104,1)', 'rgba(85,198,102,1)', 'rgba(88,199,101,1)', 'rgba(90,200,100,1)', 'rgba(92,201,99,1)', 'rgba(94,201,98,1)', 'rgba(96,202,96,1)', 'rgba(98,203,95,1)', 'rgba(101,204,94,1)', 'rgba(103,204,92,1)', 'rgba(105,205,91,1)', 'rgba(108,206,90,1)', 'rgba(110,206,88,1)', 'rgba(112,207,87,1)', 'rgba(115,208,85,1)', 'rgba(117,208,84,1)', 'rgba(119,209,82,1)', 'rgba(122,210,81,1)', 'rgba(124,210,79,1)', 'rgba(127,211,78,1)', 'rgba(129,212,76,1)', 'rgba(132,212,75,1)', 'rgba(134,213,73,1)', 'rgba(137,213,72,1)', 'rgba(139,214,70,1)', 'rgba(142,215,68,1)', 'rgba(144,215,67,1)', 'rgba(147,216,65,1)', 'rgba(149,216,63,1)', 'rgba(152,217,62,1)', 'rgba(155,217,60,1)', 'rgba(157,218,58,1)', 'rgba(160,218,57,1)', 'rgba(163,219,55,1)', 'rgba(165,219,53,1)', 'rgba(168,220,51,1)', 'rgba(171,220,50,1)', 'rgba(173,221,48,1)', 'rgba(176,221,46,1)', 'rgba(179,221,45,1)', 'rgba(181,222,43,1)', 'rgba(184,222,41,1)', 'rgba(187,223,39,1)', 'rgba(189,223,38,1)', 'rgba(192,223,36,1)', 'rgba(195,224,35,1)', 'rgba(197,224,33,1)', 'rgba(200,225,32,1)', 'rgba(203,225,30,1)', 'rgba(205,225,29,1)', 'rgba(208,226,28,1)', 'rgba(211,226,27,1)', 'rgba(213,226,26,1)', 'rgba(216,227,25,1)', 'rgba(219,227,24,1)', 'rgba(221,227,24,1)', 'rgba(224,228,24,1)', 'rgba(226,228,24,1)', 'rgba(229,228,24,1)', 'rgba(232,229,25,1)', 'rgba(234,229,25,1)', 'rgba(237,229,26,1)', 'rgba(239,230,27,1)', 'rgba(242,230,28,1)', 'rgba(244,230,30,1)', 'rgba(247,230,31,1)', 'rgba(249,231,33,1)', 'rgba(251,231,35,1)', 'rgba(254,231,36,1)']
      },
      custom: {
        name: 'Custom...',
        componentPickers: {
          heatmap: _HeatmapOptions2['default'],
          'horizontal-heatmap': _HeatmapOptions2['default']
        }
      }
    }
  },

  align: {
    name: 'Align',
    inlineOptions: {
      white: { name: 'Top', value: 'top' },
      lightGrey: { name: 'Bottom', value: 'bottom' }
    }
  },

  colorRangeGradient: {
    name: 'Color Gradient',
    inlineOptions: YES_NO
  },

  dataTransform: {
    name: 'Transforms',
    inlineOptions: {
      'default': { name: 'Default', value: 'default' },
      None: { name: 'None', value: 'None' }
    },
    generateOptions: function () {
      function generateOptions(track) {
        var inlineOptions = [];

        if (track.transforms) {
          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = undefined;

          try {
            for (var _iterator = (0, _getIterator3['default'])(track.transforms), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              var transform = _step.value;

              inlineOptions.push({
                name: transform.name,
                value: transform.value
              });
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator['return']) {
                _iterator['return']();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }
        }

        return inlineOptions;
      }

      return generateOptions;
    }()
  },

  aggregationMode: {
    name: 'Aggregation Mode',
    inlineOptions: {},
    generateOptions: function () {
      function generateOptions(track) {
        var inlineOptions = [];

        if (track.aggregationModes) {
          (0, _values2['default'])(track.aggregationModes).forEach(function (_ref) {
            var name = _ref.name,
                value = _ref.value;

            inlineOptions.push({ name: name, value: value });
          });
        } else {
          inlineOptions.push({ name: 'Default', value: 'default' });
        }

        return inlineOptions;
      }

      return generateOptions;
    }()
  },

  maxZoom: {
    name: 'Zoom limit',
    inlineOptions: {
      none: { name: 'None', value: null }
    },
    generateOptions: function () {
      function generateOptions(track) {
        if (track.maxZoom) {
          var inlineOptions = [];

          for (var i = 0; i <= track.maxZoom; i++) {
            var maxWidth = track.maxWidth,
                binsPerDimension = track.binsPerDimension,
                maxZoom = track.maxZoom;


            var maxResolutionSize = 1;
            var resolution = 1;

            if (track.resolutions) {
              var sortedResolutions = track.resolutions.map(function (x) {
                return +x;
              }).sort(function (a, b) {
                return b - a;
              });

              var _sortedResolutions = (0, _slicedToArray3['default'])(sortedResolutions, 1);

              maxResolutionSize = _sortedResolutions[0];

              resolution = sortedResolutions[i];
            } else {
              resolution = track.maxWidth / (Math.pow(2, i) * track.binsPerDimension);
              maxResolutionSize = maxWidth / (Math.pow(2, maxZoom) * binsPerDimension);
            }

            var pp = (0, _d3Format.precisionPrefix)(maxResolutionSize, resolution);
            var f = (0, _d3Format.formatPrefix)('.' + String(pp), resolution);
            var formattedResolution = f(resolution);

            inlineOptions.push({
              name: formattedResolution,
              value: i.toString()
            });
            //
          }

          return inlineOptions;
        }
        return [];
      }

      return generateOptions;
    }()
  },

  valueColumn: {
    name: 'Value column',
    inlineOptions: {
      none: { name: 'None', value: null }
    },
    generateOptions: valueColumnOptions
  },
  zeroValueColor: {
    name: 'Zero Value Color',
    inlineOptions: AVAILABLE_COLORS
  }
};

exports['default'] = OPTIONS_INFO;

/***/ }),
/* 557 */
/***/ (function(module, exports, __nested_webpack_require_2776197__) {

__nested_webpack_require_2776197__(558);
module.exports = __nested_webpack_require_2776197__(12).Object.values;


/***/ }),
/* 558 */
/***/ (function(module, exports, __nested_webpack_require_2776358__) {

// https://github.com/tc39/proposal-object-values-entries
var $export = __nested_webpack_require_2776358__(16);
var $values = __nested_webpack_require_2776358__(330)(false);

$export($export.S, 'Object', {
  values: function values(it) {
    return $values(it);
  }
});


/***/ }),
/* 559 */
/***/ (function(module, exports, __nested_webpack_require_2776677__) {

"use strict";


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

var _assign = __nested_webpack_require_2776677__(44);

var _assign2 = _interopRequireDefault(_assign);

var _stringify = __nested_webpack_require_2776677__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getPrototypeOf = __nested_webpack_require_2776677__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2776677__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2776677__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2776677__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2776677__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_2776677__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_2776677__(1);

var _react2 = _interopRequireDefault(_react);

var _Dialog = __nested_webpack_require_2776677__(169);

var _Dialog2 = _interopRequireDefault(_Dialog);

var _HiGlassComponent = __nested_webpack_require_2776677__(232);

var _HiGlassComponent2 = _interopRequireDefault(_HiGlassComponent);

var _SketchInlinePicker = __nested_webpack_require_2776677__(732);

var _SketchInlinePicker2 = _interopRequireDefault(_SketchInlinePicker);

__nested_webpack_require_2776677__(881);

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

var HeatmapOptions = function (_React$Component) {
  (0, _inherits3['default'])(HeatmapOptions, _React$Component);

  function HeatmapOptions(props) {
    (0, _classCallCheck3['default'])(this, HeatmapOptions);

    // props should include the definition of the heatmap data series

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HeatmapOptions.__proto__ || (0, _getPrototypeOf2['default'])(HeatmapOptions)).call(this, props));

    _this.state = {
      colors: props.track.options.colorRange.slice()
    };
    return _this;
  }

  (0, _createClass3['default'])(HeatmapOptions, [{
    key: 'handleColorsChanged',
    value: function () {
      function handleColorsChanged(newColors) {
        /*
            this.props.onTrackOptionsChanged(Object.assign(this.props.track.options,
                                                           {colorRange: newColors}));
            */
        this.setState({
          colors: newColors
        });
      }

      return handleColorsChanged;
    }()
  }, {
    key: 'handleSubmit',
    value: function () {
      function handleSubmit() {
        var options = this.props.track.options;

        options.colorRange = this.state.colors;

        this.props.onSubmit(this.props.track.options);
      }

      return handleSubmit;
    }()

    /**
     * Add a color to the end
     */

  }, {
    key: 'handleAddColor',
    value: function () {
      function handleAddColor() {
        this.setState(function (prevState) {
          return {
            colors: prevState.colors.concat(prevState.colors[prevState.colors.length - 1])
          };
        });
      }

      return handleAddColor;
    }()

    /**
     * Remove one of the colors from the color map
     */

  }, {
    key: 'handleRemoveColor',
    value: function () {
      function handleRemoveColor(i) {
        this.setState(function (prevState) {
          return {
            colors: prevState.colors.slice(0, i).concat(prevState.colors.slice(i + 1))
          };
        });
      }

      return handleRemoveColor;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var track = JSON.parse((0, _stringify2['default'])(this.props.track));

        var centerTrack = (0, _assign2['default'])(track, {
          options: {
            colorRange: this.state.colors
          }
        });

        var mvConfig = {
          editable: false,
          zoomFixed: true,
          views: [{
            uid: 'hmo-' + String(this.props.track.uid),
            initialXDomain: this.props.xScale ? this.props.xScale.domain() : [0, 1],
            initialYDomain: this.props.yScale ? this.props.yScale.domain() : [0, 1],
            tracks: { center: [centerTrack] },
            layout: {
              x: 0,
              y: 0,
              h: 12,
              w: 12,
              i: 'hmo-' + String(this.props.track.id)
            }
          }]
        };

        var colorFields = this.state.colors.map(function (x, i) {
          // only let colors be removed if there's more than two present
          var removeButton = _this2.state.colors.length > 2 && i === _this2.state.colors.length - 1 ? _react2['default'].createElement(
            'div',
            {
              onClick: function () {
                function onClick() {
                  return _this2.handleRemoveColor(i);
                }

                return onClick;
              }(),
              style: {
                background: 'white',
                position: 'absolute',
                top: 0,
                right: 0,
                opacity: 1,
                width: 14,
                height: 14,
                borderRadius: 2,
                cursor: 'pointer'
              }
            },
            _react2['default'].createElement(
              'svg',
              {
                height: '10px',
                style: {
                  position: 'absolute',
                  top: 2,
                  right: 2,
                  opacity: 0.5,
                  width: 10,
                  height: 10
                }
              },
              _react2['default'].createElement('use', { xlinkHref: '#cross' })
            )
          ) : null; // removeButton

          return (
            /* eslint-disable react/no-array-index-key */
            // Colors may be repeated, so the array index is the best choice here.
            _react2['default'].createElement(
              'div',
              {
                key: 'l' + String(i),
                style: {
                  borderRadius: '1px',
                  boxShadow: '0 0 0 1px #E5E5E5',
                  position: 'relative',
                  outline: 'none'
                }
              },
              removeButton,
              _react2['default'].createElement(_SketchInlinePicker2['default'], {
                key: i,
                color: _this2.state.colors[i],
                onChange: function () {
                  function onChange(c) {
                    _this2.setState(function (prevState) {
                      var colors = prevState.colors.slice();
                      colors[i] = c;
                      return { colors: colors };
                    }, function () {
                      _this2.handleColorsChanged(_this2.state.colors);
                    });
                  }

                  return onChange;
                }()
              })
            )
            /* eslint-enable react/no-array-index-key */

          );
        }).reverse();

        var addButton = this.state.colors.length < 10 ? _react2['default'].createElement(
          'div',
          {
            onClick: this.handleAddColor.bind(this),
            style: {
              position: 'relative',
              outline: 'none',
              height: '25px',
              padding: '5px',
              background: '#fff',
              borderRadius: '1px',
              boxShadow: '0 0 0 1px #E5E5E5',
              cursor: 'pointer'
            }
          },
          _react2['default'].createElement(
            'div',
            {
              style: {
                textAlign: 'center',
                width: '32px',
                height: '14px'
              }
            },
            _react2['default'].createElement(
              'svg',
              {
                height: '100%',
                style: {
                  opacity: 0.5,
                  margin: 'auto',
                  display: 'block'
                },
                width: '10px'
              },
              _react2['default'].createElement('use', { xlinkHref: '#plus' })
            )
          )
        ) : null; // addButton

        return _react2['default'].createElement(
          _Dialog2['default'],
          {
            okayTitle: 'Submit',
            onCancel: this.props.onCancel,
            onOkay: this.handleSubmit.bind(this),
            title: 'Custom Color Map'
          },
          _react2['default'].createElement(
            'table',
            { className: 'table-track-options' },
            _react2['default'].createElement('thead', null),
            _react2['default'].createElement(
              'tbody',
              { style: { verticalAlign: 'top' } },
              _react2['default'].createElement(
                'tr',
                null,
                _react2['default'].createElement(
                  'td',
                  { className: 'td-track-options' },
                  _react2['default'].createElement(
                    'table',
                    null,
                    _react2['default'].createElement(
                      'tbody',
                      null,
                      _react2['default'].createElement(
                        'tr',
                        null,
                        _react2['default'].createElement(
                          'td',
                          { className: 'td-track-options' },
                          'Preview'
                        )
                      ),
                      _react2['default'].createElement(
                        'tr',
                        null,
                        _react2['default'].createElement(
                          'td',
                          { className: 'td-track-options' },
                          _react2['default'].createElement(
                            'div',
                            { style: { width: 200 } },
                            _react2['default'].createElement(_HiGlassComponent2['default'], {
                              options: { bounded: false },
                              viewConfig: mvConfig
                            })
                          )
                        )
                      )
                    )
                  )
                ),
                _react2['default'].createElement(
                  'td',
                  { className: 'td-track-options' },
                  _react2['default'].createElement(
                    'table',
                    null,
                    _react2['default'].createElement(
                      'tbody',
                      null,
                      _react2['default'].createElement(
                        'tr',
                        null,
                        _react2['default'].createElement(
                          'td',
                          { className: 'td-track-options' },
                          'Colors'
                        )
                      ),
                      _react2['default'].createElement(
                        'tr',
                        null,
                        _react2['default'].createElement(
                          'td',
                          { className: 'td-track-options' },
                          addButton,
                          _react2['default'].createElement(
                            'div',
                            { style: { position: 'relative' } },
                            colorFields
                          )
                        )
                      )
                    )
                  )
                )
              )
            )
          )
        );
      }

      return render;
    }()
  }]);
  return HeatmapOptions;
}(_react2['default'].Component);

HeatmapOptions.propTypes = {
  handleCancel: _propTypes2['default'].func,
  onCancel: _propTypes2['default'].func,
  onSubmit: _propTypes2['default'].func,
  track: _propTypes2['default'].object,
  xScale: _propTypes2['default'].object,
  yScale: _propTypes2['default'].object
};

exports['default'] = HeatmapOptions;

/***/ }),
/* 560 */
/***/ (function(module, exports, __nested_webpack_require_2788973__) {

__nested_webpack_require_2788973__(561);
module.exports = __nested_webpack_require_2788973__(12).Object.getPrototypeOf;


/***/ }),
/* 561 */
/***/ (function(module, exports, __nested_webpack_require_2789142__) {

// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __nested_webpack_require_2789142__(54);
var $getPrototypeOf = __nested_webpack_require_2789142__(128);

__nested_webpack_require_2789142__(126)('getPrototypeOf', function () {
  return function getPrototypeOf(it) {
    return $getPrototypeOf(toObject(it));
  };
});


/***/ }),
/* 562 */
/***/ (function(module, exports, __nested_webpack_require_2789494__) {

module.exports = { "default": __nested_webpack_require_2789494__(563), __esModule: true };

/***/ }),
/* 563 */
/***/ (function(module, exports, __nested_webpack_require_2789648__) {

__nested_webpack_require_2789648__(61);
__nested_webpack_require_2789648__(76);
module.exports = __nested_webpack_require_2789648__(168).f('iterator');


/***/ }),
/* 564 */
/***/ (function(module, exports, __nested_webpack_require_2789834__) {

__nested_webpack_require_2789834__(565);
module.exports = __nested_webpack_require_2789834__(12).Object.setPrototypeOf;


/***/ }),
/* 565 */
/***/ (function(module, exports, __nested_webpack_require_2790003__) {

// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __nested_webpack_require_2790003__(16);
$export($export.S, 'Object', { setPrototypeOf: __nested_webpack_require_2790003__(566).set });


/***/ }),
/* 566 */
/***/ (function(module, exports, __nested_webpack_require_2790246__) {

// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __nested_webpack_require_2790246__(33);
var anObject = __nested_webpack_require_2790246__(39);
var check = function (O, proto) {
  anObject(O);
  if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
  set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
    function (test, buggy, set) {
      try {
        set = __nested_webpack_require_2790246__(49)(Function.call, __nested_webpack_require_2790246__(228).f(Object.prototype, '__proto__').set, 2);
        set(test, []);
        buggy = !(test instanceof Array);
      } catch (e) { buggy = true; }
      return function setPrototypeOf(O, proto) {
        check(O, proto);
        if (buggy) O.__proto__ = proto;
        else set(O, proto);
        return O;
      };
    }({}, false) : undefined),
  check: check
};


/***/ }),
/* 567 */
/***/ (function(module, exports, __nested_webpack_require_2791236__) {

module.exports = { "default": __nested_webpack_require_2791236__(568), __esModule: true };

/***/ }),
/* 568 */
/***/ (function(module, exports, __nested_webpack_require_2791390__) {

__nested_webpack_require_2791390__(569);
var $Object = __nested_webpack_require_2791390__(12).Object;
module.exports = function create(P, D) {
  return $Object.create(P, D);
};


/***/ }),
/* 569 */
/***/ (function(module, exports, __nested_webpack_require_2791616__) {

var $export = __nested_webpack_require_2791616__(16);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __nested_webpack_require_2791616__(110) });


/***/ }),
/* 570 */
/***/ (function(module, exports, __nested_webpack_require_2791857__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



var ReactPropTypesSecret = __nested_webpack_require_2791857__(571);

function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;

module.exports = function() {
  function shim(props, propName, componentName, location, propFullName, secret) {
    if (secret === ReactPropTypesSecret) {
      // It is still safe when called from React.
      return;
    }
    var err = new Error(
      'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
      'Use PropTypes.checkPropTypes() to call them. ' +
      'Read more at http://fb.me/use-check-prop-types'
    );
    err.name = 'Invariant Violation';
    throw err;
  };
  shim.isRequired = shim;
  function getShim() {
    return shim;
  };
  // Important!
  // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
  var ReactPropTypes = {
    array: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,

    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,

    checkPropTypes: emptyFunctionWithReset,
    resetWarningCache: emptyFunction
  };

  ReactPropTypes.PropTypes = ReactPropTypes;

  return ReactPropTypes;
};


/***/ }),
/* 571 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */



var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';

module.exports = ReactPropTypesSecret;


/***/ }),
/* 572 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"button":"Button-module_button-3YXsQ","button-shortcut":"Button-module_button-shortcut-1zMAn"};

/***/ }),
/* 573 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"cross":"Cross-module_cross-3WYME"};

/***/ }),
/* 574 */
/***/ (function(module, exports, __nested_webpack_require_2794344__) {

"use strict";


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

var _getClassName2 = __nested_webpack_require_2794344__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_2794344__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_2794344__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Button = __nested_webpack_require_2794344__(170);

var _Button2 = _interopRequireDefault(_Button);

var _Cross = __nested_webpack_require_2794344__(332);

var _Cross2 = _interopRequireDefault(_Cross);

var _withModal = __nested_webpack_require_2794344__(132);

var _withModal2 = _interopRequireDefault(_withModal);

__nested_webpack_require_2794344__(575);

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

var _styleModuleImportMap = {
  '../styles/Modal.module.scss': {
    'modal-background': 'Modal-module_modal-background-3vDy1',
    'fade-in': 'Modal-module_fade-in-3Nm-O',
    'modal-hide': 'Modal-module_modal-hide-3huBg',
    'modal-wrap': 'Modal-module_modal-wrap-1HWNn',
    'modal-window': 'Modal-module_modal-window-1XZAq',
    'fade-scale-in': 'Modal-module_fade-scale-in-11Dkx',
    'modal-window-max-height': 'Modal-module_modal-window-max-height-CZYCl',
    'modal-content': 'Modal-module_modal-content-2xb_x'
  }
};


var Modal = function Modal(props) {
  var handleClose = function handleClose() {
    props.modal.close();
    if (props.onClose) props.onClose();
  };

  return _react2['default'].createElement(
    'div',
    {
      className: (0, _getClassName3['default'])('modal-background ' + (props.hide ? 'modal-hide' : ''), _styleModuleImportMap)
    },
    _react2['default'].createElement(
      'div',
      { className: 'Modal-module_modal-wrap-1HWNn' },
      _react2['default'].createElement(
        'div',
        {
          className: (0, _getClassName3['default'])('modal-window ' + (props.maxHeight ? 'modal-window-max-height' : ''), _styleModuleImportMap)
        },
        props.closeButton && _react2['default'].createElement(
          _Button2['default'],
          { onClick: handleClose },
          _react2['default'].createElement(_Cross2['default'], null)
        ),
        _react2['default'].createElement(
          'div',
          { className: 'Modal-module_modal-content-2xb_x' },
          props.children
        )
      )
    )
  );
};

Modal.defaultProps = {
  closeButton: true,
  hide: false,
  maxHeight: false
};

Modal.propTypes = {
  children: _propTypes2['default'].element.isRequired,
  closeButton: _propTypes2['default'].bool,
  hide: _propTypes2['default'].bool,
  maxHeight: _propTypes2['default'].bool,
  modal: _propTypes2['default'].object.isRequired,
  onClose: _propTypes2['default'].func
};

exports['default'] = (0, _withModal2['default'])(Modal);

/***/ }),
/* 575 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"modal-background":"Modal-module_modal-background-3vDy1","fade-in":"Modal-module_fade-in-3Nm-O","modal-hide":"Modal-module_modal-hide-3huBg","modal-wrap":"Modal-module_modal-wrap-1HWNn","modal-window":"Modal-module_modal-window-1XZAq","fade-scale-in":"Modal-module_fade-scale-in-11Dkx","modal-window-max-height":"Modal-module_modal-window-max-height-CZYCl","modal-content":"Modal-module_modal-content-2xb_x"};

/***/ }),
/* 576 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"dialog-header":"Dialog-module_dialog-header-2mk2M","dialog-main-max-height":"Dialog-module_dialog-main-max-height-1EAb2","dialog-footer":"Dialog-module_dialog-footer-1BnEv","dialog-footer-max-height":"Dialog-module_dialog-footer-max-height-KjDek"};

/***/ }),
/* 577 */
/***/ (function(module, exports, __nested_webpack_require_2798149__) {

module.exports = { "default": __nested_webpack_require_2798149__(578), __esModule: true };

/***/ }),
/* 578 */
/***/ (function(module, exports, __nested_webpack_require_2798303__) {

__nested_webpack_require_2798303__(579);
module.exports = __nested_webpack_require_2798303__(12).Object.entries;


/***/ }),
/* 579 */
/***/ (function(module, exports, __nested_webpack_require_2798465__) {

// https://github.com/tc39/proposal-object-values-entries
var $export = __nested_webpack_require_2798465__(16);
var $entries = __nested_webpack_require_2798465__(330)(true);

$export($export.S, 'Object', {
  entries: function entries(it) {
    return $entries(it);
  }
});


/***/ }),
/* 580 */
/***/ (function(module, exports, __nested_webpack_require_2798787__) {

__nested_webpack_require_2798787__(164);
__nested_webpack_require_2798787__(61);
__nested_webpack_require_2798787__(76);
__nested_webpack_require_2798787__(581);
__nested_webpack_require_2798787__(585);
__nested_webpack_require_2798787__(587);
__nested_webpack_require_2798787__(588);
module.exports = __nested_webpack_require_2798787__(12).Set;


/***/ }),
/* 581 */
/***/ (function(module, exports, __nested_webpack_require_2799092__) {

"use strict";

var strong = __nested_webpack_require_2799092__(333);
var validate = __nested_webpack_require_2799092__(238);
var SET = 'Set';

// 23.2 Set Objects
module.exports = __nested_webpack_require_2799092__(334)(SET, function (get) {
  return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
  // 23.2.3.1 Set.prototype.add(value)
  add: function add(value) {
    return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
  }
}, strong);


/***/ }),
/* 582 */
/***/ (function(module, exports, __nested_webpack_require_2799637__) {

// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __nested_webpack_require_2799637__(49);
var IObject = __nested_webpack_require_2799637__(105);
var toObject = __nested_webpack_require_2799637__(54);
var toLength = __nested_webpack_require_2799637__(88);
var asc = __nested_webpack_require_2799637__(583);
module.exports = function (TYPE, $create) {
  var IS_MAP = TYPE == 1;
  var IS_FILTER = TYPE == 2;
  var IS_SOME = TYPE == 3;
  var IS_EVERY = TYPE == 4;
  var IS_FIND_INDEX = TYPE == 6;
  var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
  var create = $create || asc;
  return function ($this, callbackfn, that) {
    var O = toObject($this);
    var self = IObject(O);
    var f = ctx(callbackfn, that, 3);
    var length = toLength(self.length);
    var index = 0;
    var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
    var val, res;
    for (;length > index; index++) if (NO_HOLES || index in self) {
      val = self[index];
      res = f(val, index, O);
      if (TYPE) {
        if (IS_MAP) result[index] = res;   // map
        else if (res) switch (TYPE) {
          case 3: return true;             // some
          case 5: return val;              // find
          case 6: return index;            // findIndex
          case 2: result.push(val);        // filter
        } else if (IS_EVERY) return false; // every
      }
    }
    return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
  };
};


/***/ }),
/* 583 */
/***/ (function(module, exports, __nested_webpack_require_2801209__) {

// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __nested_webpack_require_2801209__(584);

module.exports = function (original, length) {
  return new (speciesConstructor(original))(length);
};


/***/ }),
/* 584 */
/***/ (function(module, exports, __nested_webpack_require_2801496__) {

var isObject = __nested_webpack_require_2801496__(33);
var isArray = __nested_webpack_require_2801496__(328);
var SPECIES = __nested_webpack_require_2801496__(21)('species');

module.exports = function (original) {
  var C;
  if (isArray(original)) {
    C = original.constructor;
    // cross-realm fallback
    if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
    if (isObject(C)) {
      C = C[SPECIES];
      if (C === null) C = undefined;
    }
  } return C === undefined ? Array : C;
};


/***/ }),
/* 585 */
/***/ (function(module, exports, __nested_webpack_require_2802058__) {

// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __nested_webpack_require_2802058__(16);

$export($export.P + $export.R, 'Set', { toJSON: __nested_webpack_require_2802058__(335)('Set') });


/***/ }),
/* 586 */
/***/ (function(module, exports, __nested_webpack_require_2802320__) {

var forOf = __nested_webpack_require_2802320__(129);

module.exports = function (iter, ITERATOR) {
  var result = [];
  forOf(iter, false, result.push, result, ITERATOR);
  return result;
};


/***/ }),
/* 587 */
/***/ (function(module, exports, __nested_webpack_require_2802575__) {

// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
__nested_webpack_require_2802575__(336)('Set');


/***/ }),
/* 588 */
/***/ (function(module, exports, __nested_webpack_require_2802748__) {

// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
__nested_webpack_require_2802748__(337)('Set');


/***/ }),
/* 589 */
/***/ (function(module, exports, __nested_webpack_require_2802923__) {

/* WEBPACK VAR INJECTION */(function(Buffer) {// The MIT License (MIT)
//
// Copyright (c) 2014 Jonas Finnemann Jensen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

var uuid = __nested_webpack_require_2802923__(592);

/**
 * Returns the given uuid as a 22 character slug. This can be a regular v4
 * slug or a "nice" slug.
 */
exports.encode = function(uuid_) {
  var bytes   = uuid.parse(uuid_);
  var base64  = (new Buffer(bytes)).toString('base64');
  var slug = base64
              .replace(/\+/g, '-')  // Replace + with - (see RFC 4648, sec. 5)
              .replace(/\//g, '_')  // Replace / with _ (see RFC 4648, sec. 5)
              .substring(0, 22);    // Drop '==' padding
  return slug;
};

/**
 * Returns the uuid represented by the given v4 or "nice" slug
 */
exports.decode = function(slug) {
  var base64 = slug
                  .replace(/-/g, '+')
                  .replace(/_/g, '/')
                  + '==';
  return uuid.unparse(new Buffer(base64, 'base64'));
};

/**
 * Returns a randomly generated uuid v4 compliant slug
 */
exports.v4 = function() {
  var bytes   = uuid.v4(null, new Buffer(16));
  var base64  = bytes.toString('base64');
  var slug = base64
              .replace(/\+/g, '-')  // Replace + with - (see RFC 4648, sec. 5)
              .replace(/\//g, '_')  // Replace / with _ (see RFC 4648, sec. 5)
              .substring(0, 22);    // Drop '==' padding
  return slug;
};

/** 
 * Returns a randomly generated uuid v4 compliant slug which conforms to a set
 * of "nice" properties, at the cost of some entropy. Currently this means one
 * extra fixed bit (the first bit of the uuid is set to 0) which guarantees the
 * slug will begin with [A-Za-f]. For example such slugs don't require special
 * handling when used as command line parameters (whereas non-nice slugs may
 * start with `-` which can confuse command line tools).
 *
 * Potentially other "nice" properties may be added in future to further
 * restrict the range of potential uuids that may be generated.
 */
exports.nice = function() {
  var bytes   = uuid.v4(null, new Buffer(16));
  bytes[0] = bytes[0] & 0x7f;  // unset first bit to ensure [A-Za-f] first char
  var base64  = bytes.toString('base64');
  var slug = base64
              .replace(/\+/g, '-')  // Replace + with - (see RFC 4648, sec. 5)
              .replace(/\//g, '_')  // Replace / with _ (see RFC 4648, sec. 5)
              .substring(0, 22);    // Drop '==' padding
  return slug;
};

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2802923__(113).Buffer))

/***/ }),
/* 590 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  for (var i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}


/***/ }),
/* 591 */
/***/ (function(module, exports) {

exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),
/* 592 */
/***/ (function(module, exports, __nested_webpack_require_2812707__) {

//     uuid.js
//
//     Copyright (c) 2010-2012 Robert Kieffer
//     MIT License - http://opensource.org/licenses/mit-license.php

// Unique ID creation requires a high quality random # generator.  We feature
// detect to determine the best RNG source, normalizing to a function that
// returns 128-bits of randomness, since that's what's usually required
var _rng = __nested_webpack_require_2812707__(593);

// Maps for number <-> hex string conversion
var _byteToHex = [];
var _hexToByte = {};
for (var i = 0; i < 256; i++) {
  _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  _hexToByte[_byteToHex[i]] = i;
}

// **`parse()` - Parse a UUID into it's component bytes**
function parse(s, buf, offset) {
  var i = (buf && offset) || 0, ii = 0;

  buf = buf || [];
  s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
    if (ii < 16) { // Don't overflow!
      buf[i + ii++] = _hexToByte[oct];
    }
  });

  // Zero out remaining bytes if string was short
  while (ii < 16) {
    buf[i + ii++] = 0;
  }

  return buf;
}

// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
function unparse(buf, offset) {
  var i = offset || 0, bth = _byteToHex;
  return  bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]];
}

// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html

// random #'s we need to init node and clockseq
var _seedBytes = _rng();

// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
var _nodeId = [
  _seedBytes[0] | 0x01,
  _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
];

// Per 4.2.2, randomize (14 bit) clockseq
var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;

// Previous uuid creation time
var _lastMSecs = 0, _lastNSecs = 0;

// See https://github.com/broofa/node-uuid for API details
function v1(options, buf, offset) {
  var i = buf && offset || 0;
  var b = buf || [];

  options = options || {};

  var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;

  // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
  // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();

  // Per 4.2.1.2, use count of uuid's generated during the current clock
  // cycle to simulate higher resolution clock
  var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;

  // Time since last uuid creation (in msecs)
  var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;

  // Per 4.2.1.2, Bump clockseq on clock regression
  if (dt < 0 && options.clockseq === undefined) {
    clockseq = clockseq + 1 & 0x3fff;
  }

  // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  // time interval
  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
    nsecs = 0;
  }

  // Per 4.2.1.2 Throw error if too many uuids are requested
  if (nsecs >= 10000) {
    throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  }

  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;

  // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  msecs += 12219292800000;

  // `time_low`
  var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  b[i++] = tl >>> 24 & 0xff;
  b[i++] = tl >>> 16 & 0xff;
  b[i++] = tl >>> 8 & 0xff;
  b[i++] = tl & 0xff;

  // `time_mid`
  var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  b[i++] = tmh >>> 8 & 0xff;
  b[i++] = tmh & 0xff;

  // `time_high_and_version`
  b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  b[i++] = tmh >>> 16 & 0xff;

  // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  b[i++] = clockseq >>> 8 | 0x80;

  // `clock_seq_low`
  b[i++] = clockseq & 0xff;

  // `node`
  var node = options.node || _nodeId;
  for (var n = 0; n < 6; n++) {
    b[i + n] = node[n];
  }

  return buf ? buf : unparse(b);
}

// **`v4()` - Generate random UUID**

// See https://github.com/broofa/node-uuid for API details
function v4(options, buf, offset) {
  // Deprecated - 'format' argument, as supported in v1.2
  var i = buf && offset || 0;

  if (typeof(options) == 'string') {
    buf = options == 'binary' ? new Array(16) : null;
    options = null;
  }
  options = options || {};

  var rnds = options.random || (options.rng || _rng)();

  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = (rnds[6] & 0x0f) | 0x40;
  rnds[8] = (rnds[8] & 0x3f) | 0x80;

  // Copy bytes to buffer, if provided
  if (buf) {
    for (var ii = 0; ii < 16; ii++) {
      buf[i + ii] = rnds[ii];
    }
  }

  return buf || unparse(rnds);
}

// Export public API
var uuid = v4;
uuid.v1 = v1;
uuid.v4 = v4;
uuid.parse = parse;
uuid.unparse = unparse;

module.exports = uuid;


/***/ }),
/* 593 */
/***/ (function(module, exports, __nested_webpack_require_2818079__) {

/* WEBPACK VAR INJECTION */(function(global) {
var rng;

var crypto = global.crypto || global.msCrypto; // for IE 11
if (crypto && crypto.getRandomValues) {
  // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  // Moderately fast, high quality
  var _rnds8 = new Uint8Array(16);
  rng = function whatwgRNG() {
    crypto.getRandomValues(_rnds8);
    return _rnds8;
  };
}

if (!rng) {
  // Math.random()-based (RNG)
  //
  // If all else fails, use Math.random().  It's fast, but is of unspecified
  // quality.
  var  _rnds = new Array(16);
  rng = function() {
    for (var i = 0, r; i < 16; i++) {
      if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
      _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
    }

    return _rnds;
  };
}

module.exports = rng;


/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2818079__(27)))

/***/ }),
/* 594 */
/***/ (function(module, exports, __nested_webpack_require_2819005__) {

module.exports = __nested_webpack_require_2819005__(339).default;
module.exports.utils = __nested_webpack_require_2819005__(133);
module.exports.Responsive = __nested_webpack_require_2819005__(599).default;
module.exports.Responsive.utils = __nested_webpack_require_2819005__(343);
module.exports.WidthProvider = __nested_webpack_require_2819005__(600).default;


/***/ }),
/* 595 */
/***/ (function(module, exports, __nested_webpack_require_2819371__) {

"use strict";


exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_2819371__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_2819371__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDraggable = __nested_webpack_require_2819371__(341);

var _reactResizable = __nested_webpack_require_2819371__(596);

var _utils = __nested_webpack_require_2819371__(133);

var _classnames = __nested_webpack_require_2819371__(340);

var _classnames2 = _interopRequireDefault(_classnames);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/**
 * An individual item within a ReactGridLayout.
 */
var GridItem = function (_React$Component) {
  _inherits(GridItem, _React$Component);

  function GridItem() {
    var _temp, _this, _ret;

    _classCallCheck(this, GridItem);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
      resizing: null,
      dragging: null,
      className: ""
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  // Helper for generating column width
  GridItem.prototype.calcColWidth = function calcColWidth() {
    var _props = this.props,
        margin = _props.margin,
        containerPadding = _props.containerPadding,
        containerWidth = _props.containerWidth,
        cols = _props.cols;

    return (containerWidth - margin[0] * (cols - 1) - containerPadding[0] * 2) / cols;
  };

  /**
   * Return position on the page given an x, y, w, h.
   * left, top, width, height are all in pixels.
   * @param  {Number}  x             X coordinate in grid units.
   * @param  {Number}  y             Y coordinate in grid units.
   * @param  {Number}  w             W coordinate in grid units.
   * @param  {Number}  h             H coordinate in grid units.
   * @return {Object}                Object containing coords.
   */


  GridItem.prototype.calcPosition = function calcPosition(x, y, w, h, state) {
    var _props2 = this.props,
        margin = _props2.margin,
        containerPadding = _props2.containerPadding,
        rowHeight = _props2.rowHeight;

    var colWidth = this.calcColWidth();

    var out = {
      left: Math.round((colWidth + margin[0]) * x + containerPadding[0]),
      top: Math.round((rowHeight + margin[1]) * y + containerPadding[1]),
      // 0 * Infinity === NaN, which causes problems with resize constraints;
      // Fix this if it occurs.
      // Note we do it here rather than later because Math.round(Infinity) causes deopt
      width: w === Infinity ? w : Math.round(colWidth * w + Math.max(0, w - 1) * margin[0]),
      height: h === Infinity ? h : Math.round(rowHeight * h + Math.max(0, h - 1) * margin[1])
    };

    if (state && state.resizing) {
      out.width = Math.round(state.resizing.width);
      out.height = Math.round(state.resizing.height);
    }

    if (state && state.dragging) {
      out.top = Math.round(state.dragging.top);
      out.left = Math.round(state.dragging.left);
    }

    return out;
  };

  /**
   * Translate x and y coordinates from pixels to grid units.
   * @param  {Number} top  Top position (relative to parent) in pixels.
   * @param  {Number} left Left position (relative to parent) in pixels.
   * @return {Object} x and y in grid units.
   */


  GridItem.prototype.calcXY = function calcXY(top, left) {
    var _props3 = this.props,
        margin = _props3.margin,
        cols = _props3.cols,
        rowHeight = _props3.rowHeight,
        w = _props3.w,
        h = _props3.h,
        maxRows = _props3.maxRows;

    var colWidth = this.calcColWidth();

    // left = colWidth * x + margin * (x + 1)
    // l = cx + m(x+1)
    // l = cx + mx + m
    // l - m = cx + mx
    // l - m = x(c + m)
    // (l - m) / (c + m) = x
    // x = (left - margin) / (coldWidth + margin)
    var x = Math.round((left - margin[0]) / (colWidth + margin[0]));
    var y = Math.round((top - margin[1]) / (rowHeight + margin[1]));

    // Capping
    x = Math.max(Math.min(x, cols - w), 0);
    y = Math.max(Math.min(y, maxRows - h), 0);

    return { x: x, y: y };
  };

  /**
   * Given a height and width in pixel values, calculate grid units.
   * @param  {Number} height Height in pixels.
   * @param  {Number} width  Width in pixels.
   * @return {Object} w, h as grid units.
   */


  GridItem.prototype.calcWH = function calcWH(_ref) {
    var height = _ref.height,
        width = _ref.width;
    var _props4 = this.props,
        margin = _props4.margin,
        maxRows = _props4.maxRows,
        cols = _props4.cols,
        rowHeight = _props4.rowHeight,
        x = _props4.x,
        y = _props4.y;

    var colWidth = this.calcColWidth();

    // width = colWidth * w - (margin * (w - 1))
    // ...
    // w = (width + margin) / (colWidth + margin)
    var w = Math.round((width + margin[0]) / (colWidth + margin[0]));
    var h = Math.round((height + margin[1]) / (rowHeight + margin[1]));

    // Capping
    w = Math.max(Math.min(w, cols - x), 0);
    h = Math.max(Math.min(h, maxRows - y), 0);
    return { w: w, h: h };
  };

  /**
   * This is where we set the grid item's absolute placement. It gets a little tricky because we want to do it
   * well when server rendering, and the only way to do that properly is to use percentage width/left because
   * we don't know exactly what the browser viewport is.
   * Unfortunately, CSS Transforms, which are great for performance, break in this instance because a percentage
   * left is relative to the item itself, not its container! So we cannot use them on the server rendering pass.
   *
   * @param  {Object} pos Position object with width, height, left, top.
   * @return {Object}     Style object.
   */


  GridItem.prototype.createStyle = function createStyle(pos) {
    var _props5 = this.props,
        usePercentages = _props5.usePercentages,
        containerWidth = _props5.containerWidth,
        useCSSTransforms = _props5.useCSSTransforms;


    var style = void 0;
    // CSS Transforms support (default)
    if (useCSSTransforms) {
      style = (0, _utils.setTransform)(pos);
    } else {
      // top,left (slow)
      style = (0, _utils.setTopLeft)(pos);

      // This is used for server rendering.
      if (usePercentages) {
        style.left = (0, _utils.perc)(pos.left / containerWidth);
        style.width = (0, _utils.perc)(pos.width / containerWidth);
      }
    }

    return style;
  };

  /**
   * Mix a Draggable instance into a child.
   * @param  {Element} child    Child element.
   * @return {Element}          Child wrapped in Draggable.
   */


  GridItem.prototype.mixinDraggable = function mixinDraggable(child) {
    return _react2.default.createElement(
      _reactDraggable.DraggableCore,
      {
        onStart: this.onDragHandler("onDragStart"),
        onDrag: this.onDragHandler("onDrag"),
        onStop: this.onDragHandler("onDragStop"),
        handle: this.props.handle,
        cancel: ".react-resizable-handle" + (this.props.cancel ? "," + this.props.cancel : "")
      },
      child
    );
  };

  /**
   * Mix a Resizable instance into a child.
   * @param  {Element} child    Child element.
   * @param  {Object} position  Position object (pixel values)
   * @return {Element}          Child wrapped in Resizable.
   */


  GridItem.prototype.mixinResizable = function mixinResizable(child, position) {
    var _props6 = this.props,
        cols = _props6.cols,
        x = _props6.x,
        minW = _props6.minW,
        minH = _props6.minH,
        maxW = _props6.maxW,
        maxH = _props6.maxH;

    // This is the max possible width - doesn't go to infinity because of the width of the window

    var maxWidth = this.calcPosition(0, 0, cols - x, 0).width;

    // Calculate min/max constraints using our min & maxes
    var mins = this.calcPosition(0, 0, minW, minH);
    var maxes = this.calcPosition(0, 0, maxW, maxH);
    var minConstraints = [mins.width, mins.height];
    var maxConstraints = [Math.min(maxes.width, maxWidth), Math.min(maxes.height, Infinity)];
    return _react2.default.createElement(
      _reactResizable.Resizable,
      {
        width: position.width,
        height: position.height,
        minConstraints: minConstraints,
        maxConstraints: maxConstraints,
        onResizeStop: this.onResizeHandler("onResizeStop"),
        onResizeStart: this.onResizeHandler("onResizeStart"),
        onResize: this.onResizeHandler("onResize")
      },
      child
    );
  };

  /**
   * Wrapper around drag events to provide more useful data.
   * All drag events call the function with the given handler name,
   * with the signature (index, x, y).
   *
   * @param  {String} handlerName Handler name to wrap.
   * @return {Function}           Handler function.
   */


  GridItem.prototype.onDragHandler = function onDragHandler(handlerName) {
    var _this2 = this;

    return function (e, _ref2) {
      var node = _ref2.node,
          deltaX = _ref2.deltaX,
          deltaY = _ref2.deltaY;

      var handler = _this2.props[handlerName];
      if (!handler) return;

      var newPosition = { top: 0, left: 0 };

      // Get new XY
      switch (handlerName) {
        case "onDragStart":
          {
            // TODO: this wont work on nested parents
            var offsetParent = node.offsetParent;

            if (!offsetParent) return;
            var parentRect = offsetParent.getBoundingClientRect();
            var clientRect = node.getBoundingClientRect();
            newPosition.left = clientRect.left - parentRect.left + offsetParent.scrollLeft;
            newPosition.top = clientRect.top - parentRect.top + offsetParent.scrollTop;
            _this2.setState({ dragging: newPosition });
            break;
          }
        case "onDrag":
          if (!_this2.state.dragging) throw new Error("onDrag called before onDragStart.");
          newPosition.left = _this2.state.dragging.left + deltaX;
          newPosition.top = _this2.state.dragging.top + deltaY;
          _this2.setState({ dragging: newPosition });
          break;
        case "onDragStop":
          if (!_this2.state.dragging) throw new Error("onDragEnd called before onDragStart.");
          newPosition.left = _this2.state.dragging.left;
          newPosition.top = _this2.state.dragging.top;
          _this2.setState({ dragging: null });
          break;
        default:
          throw new Error("onDragHandler called with unrecognized handlerName: " + handlerName);
      }

      var _calcXY = _this2.calcXY(newPosition.top, newPosition.left),
          x = _calcXY.x,
          y = _calcXY.y;

      return handler.call(_this2, _this2.props.i, x, y, { e: e, node: node, newPosition: newPosition });
    };
  };

  /**
   * Wrapper around drag events to provide more useful data.
   * All drag events call the function with the given handler name,
   * with the signature (index, x, y).
   *
   * @param  {String} handlerName Handler name to wrap.
   * @return {Function}           Handler function.
   */


  GridItem.prototype.onResizeHandler = function onResizeHandler(handlerName) {
    var _this3 = this;

    return function (e, _ref3) {
      var node = _ref3.node,
          size = _ref3.size;

      var handler = _this3.props[handlerName];
      if (!handler) return;
      var _props7 = _this3.props,
          cols = _props7.cols,
          x = _props7.x,
          i = _props7.i,
          maxW = _props7.maxW,
          minW = _props7.minW,
          maxH = _props7.maxH,
          minH = _props7.minH;

      // Get new XY

      var _calcWH = _this3.calcWH(size),
          w = _calcWH.w,
          h = _calcWH.h;

      // Cap w at numCols


      w = Math.min(w, cols - x);
      // Ensure w is at least 1
      w = Math.max(w, 1);

      // Min/max capping
      w = Math.max(Math.min(w, maxW), minW);
      h = Math.max(Math.min(h, maxH), minH);

      _this3.setState({ resizing: handlerName === "onResizeStop" ? null : size });

      handler.call(_this3, i, w, h, { e: e, node: node, size: size });
    };
  };

  GridItem.prototype.render = function render() {
    var _props8 = this.props,
        x = _props8.x,
        y = _props8.y,
        w = _props8.w,
        h = _props8.h,
        isDraggable = _props8.isDraggable,
        isResizable = _props8.isResizable,
        useCSSTransforms = _props8.useCSSTransforms;


    var pos = this.calcPosition(x, y, w, h, this.state);
    var child = _react2.default.Children.only(this.props.children);

    // Create the child element. We clone the existing element but modify its className and style.
    var newChild = _react2.default.cloneElement(child, {
      className: (0, _classnames2.default)("react-grid-item", child.props.className, this.props.className, {
        static: this.props.static,
        resizing: Boolean(this.state.resizing),
        "react-draggable": isDraggable,
        "react-draggable-dragging": Boolean(this.state.dragging),
        cssTransforms: useCSSTransforms
      }),
      // We can set the width and height on the child, but unfortunately we can't set the position.
      style: _extends({}, this.props.style, child.props.style, this.createStyle(pos))
    });

    // Resizable support. This is usually on but the user can toggle it off.
    if (isResizable) newChild = this.mixinResizable(newChild, pos);

    // Draggable support. This is always on, except for with placeholders.
    if (isDraggable) newChild = this.mixinDraggable(newChild);

    return newChild;
  };

  return GridItem;
}(_react2.default.Component);

GridItem.propTypes = {
  // Children must be only a single element
  children: _propTypes2.default.element,

  // General grid attributes
  cols: _propTypes2.default.number.isRequired,
  containerWidth: _propTypes2.default.number.isRequired,
  rowHeight: _propTypes2.default.number.isRequired,
  margin: _propTypes2.default.array.isRequired,
  maxRows: _propTypes2.default.number.isRequired,
  containerPadding: _propTypes2.default.array.isRequired,

  // These are all in grid units
  x: _propTypes2.default.number.isRequired,
  y: _propTypes2.default.number.isRequired,
  w: _propTypes2.default.number.isRequired,
  h: _propTypes2.default.number.isRequired,

  // All optional
  minW: function minW(props, propName) {
    var value = props[propName];
    if (typeof value !== "number") return new Error("minWidth not Number");
    if (value > props.w || value > props.maxW) return new Error("minWidth larger than item width/maxWidth");
  },

  maxW: function maxW(props, propName) {
    var value = props[propName];
    if (typeof value !== "number") return new Error("maxWidth not Number");
    if (value < props.w || value < props.minW) return new Error("maxWidth smaller than item width/minWidth");
  },

  minH: function minH(props, propName) {
    var value = props[propName];
    if (typeof value !== "number") return new Error("minHeight not Number");
    if (value > props.h || value > props.maxH) return new Error("minHeight larger than item height/maxHeight");
  },

  maxH: function maxH(props, propName) {
    var value = props[propName];
    if (typeof value !== "number") return new Error("maxHeight not Number");
    if (value < props.h || value < props.minH) return new Error("maxHeight smaller than item height/minHeight");
  },

  // ID is nice to have for callbacks
  i: _propTypes2.default.string.isRequired,

  // Functions
  onDragStop: _propTypes2.default.func,
  onDragStart: _propTypes2.default.func,
  onDrag: _propTypes2.default.func,
  onResizeStop: _propTypes2.default.func,
  onResizeStart: _propTypes2.default.func,
  onResize: _propTypes2.default.func,

  // Flags
  isDraggable: _propTypes2.default.bool.isRequired,
  isResizable: _propTypes2.default.bool.isRequired,
  static: _propTypes2.default.bool,

  // Use CSS transforms instead of top/left
  useCSSTransforms: _propTypes2.default.bool.isRequired,

  // Others
  className: _propTypes2.default.string,
  // Selector for draggable handle
  handle: _propTypes2.default.string,
  // Selector for draggable cancel (see react-draggable)
  cancel: _propTypes2.default.string
};
GridItem.defaultProps = {
  className: "",
  cancel: "",
  handle: "",
  minH: 1,
  minW: 1,
  maxH: Infinity,
  maxW: Infinity
};
exports.default = GridItem;

/***/ }),
/* 596 */
/***/ (function(module, exports, __nested_webpack_require_2837028__) {

"use strict";

module.exports = function() {
  throw new Error("Don't instantiate Resizable directly! Use require('react-resizable').Resizable");
};

module.exports.Resizable = __nested_webpack_require_2837028__(342).default;
module.exports.ResizableBox = __nested_webpack_require_2837028__(598).default;


/***/ }),
/* 597 */
/***/ (function(module, exports, __nested_webpack_require_2837382__) {

"use strict";


var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_2837382__(1);

var _react2 = _interopRequireDefault(_react);

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

// React.addons.cloneWithProps look-alike that merges style & className.
module.exports = function cloneElement(element, props) {
  if (props.style && element.props.style) {
    props.style = _extends({}, element.props.style, props.style);
  }
  if (props.className && element.props.className) {
    props.className = element.props.className + ' ' + props.className;
  }
  return _react2.default.cloneElement(element, props);
};

/***/ }),
/* 598 */
/***/ (function(module, exports, __nested_webpack_require_2838346__) {

"use strict";


exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_2838346__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_2838346__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Resizable = __nested_webpack_require_2838346__(342);

var _Resizable2 = _interopRequireDefault(_Resizable);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

// An example use of Resizable.
var ResizableBox = function (_React$Component) {
  _inherits(ResizableBox, _React$Component);

  function ResizableBox() {
    var _temp, _this, _ret;

    _classCallCheck(this, ResizableBox);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
      width: _this.props.width,
      height: _this.props.height
    }, _this.onResize = function (e, data) {
      var size = data.size;
      var width = size.width,
          height = size.height;


      if (_this.props.onResize) {
        e.persist && e.persist();
        _this.setState(size, function () {
          return _this.props.onResize && _this.props.onResize(e, data);
        });
      } else {
        _this.setState(size);
      }
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  ResizableBox.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    if (nextProps.width !== this.props.width || nextProps.height !== this.props.height) {
      this.setState({
        width: nextProps.width,
        height: nextProps.height
      });
    }
  };

  ResizableBox.prototype.render = function render() {
    // Basic wrapper around a Resizable instance.
    // If you use Resizable directly, you are responsible for updating the child component
    // with a new width and height.
    var _props = this.props,
        handle = _props.handle,
        handleSize = _props.handleSize,
        onResize = _props.onResize,
        onResizeStart = _props.onResizeStart,
        onResizeStop = _props.onResizeStop,
        draggableOpts = _props.draggableOpts,
        minConstraints = _props.minConstraints,
        maxConstraints = _props.maxConstraints,
        lockAspectRatio = _props.lockAspectRatio,
        axis = _props.axis,
        width = _props.width,
        height = _props.height,
        resizeHandles = _props.resizeHandles,
        props = _objectWithoutProperties(_props, ['handle', 'handleSize', 'onResize', 'onResizeStart', 'onResizeStop', 'draggableOpts', 'minConstraints', 'maxConstraints', 'lockAspectRatio', 'axis', 'width', 'height', 'resizeHandles']);

    return _react2.default.createElement(
      _Resizable2.default,
      {
        handle: handle,
        handleSize: handleSize,
        width: this.state.width,
        height: this.state.height,
        onResizeStart: onResizeStart,
        onResize: this.onResize,
        onResizeStop: onResizeStop,
        draggableOpts: draggableOpts,
        minConstraints: minConstraints,
        maxConstraints: maxConstraints,
        lockAspectRatio: lockAspectRatio,
        axis: axis,
        resizeHandles: resizeHandles
      },
      _react2.default.createElement('div', _extends({ style: { width: this.state.width + 'px', height: this.state.height + 'px' } }, props))
    );
  };

  return ResizableBox;
}(_react2.default.Component);

ResizableBox.propTypes = {
  height: _propTypes2.default.number,
  width: _propTypes2.default.number
};
ResizableBox.defaultProps = {
  handleSize: [20, 20]
};
exports.default = ResizableBox;

/***/ }),
/* 599 */
/***/ (function(module, exports, __nested_webpack_require_2843511__) {

"use strict";


exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_2843511__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_2843511__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _lodash = __nested_webpack_require_2843511__(172);

var _lodash2 = _interopRequireDefault(_lodash);

var _utils = __nested_webpack_require_2843511__(133);

var _responsiveUtils = __nested_webpack_require_2843511__(343);

var _ReactGridLayout = __nested_webpack_require_2843511__(339);

var _ReactGridLayout2 = _interopRequireDefault(_ReactGridLayout);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var type = function type(obj) {
  return Object.prototype.toString.call(obj);
};

var ResponsiveReactGridLayout = function (_React$Component) {
  _inherits(ResponsiveReactGridLayout, _React$Component);

  function ResponsiveReactGridLayout() {
    var _temp, _this, _ret;

    _classCallCheck(this, ResponsiveReactGridLayout);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = _this.generateInitialState(), _this.onLayoutChange = function (layout) {
      var _extends2;

      _this.props.onLayoutChange(layout, _extends({}, _this.props.layouts, (_extends2 = {}, _extends2[_this.state.breakpoint] = layout, _extends2)));
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }
  // This should only include propTypes needed in this code; RGL itself
  // will do validation of the rest props passed to it.


  ResponsiveReactGridLayout.prototype.generateInitialState = function generateInitialState() {
    var _props = this.props,
        width = _props.width,
        breakpoints = _props.breakpoints,
        layouts = _props.layouts,
        cols = _props.cols;

    var breakpoint = (0, _responsiveUtils.getBreakpointFromWidth)(breakpoints, width);
    var colNo = (0, _responsiveUtils.getColsFromBreakpoint)(breakpoint, cols);
    // verticalCompact compatibility, now deprecated
    var compactType = this.props.verticalCompact === false ? null : this.props.compactType;
    // Get the initial layout. This can tricky; we try to generate one however possible if one doesn't exist
    // for this layout.
    var initialLayout = (0, _responsiveUtils.findOrGenerateResponsiveLayout)(layouts, breakpoints, breakpoint, breakpoint, colNo, compactType);

    return {
      layout: initialLayout,
      breakpoint: breakpoint,
      cols: colNo
    };
  };

  ResponsiveReactGridLayout.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    // Allow parent to set width or breakpoint directly.
    if (nextProps.width != this.props.width || nextProps.breakpoint !== this.props.breakpoint || !(0, _lodash2.default)(nextProps.breakpoints, this.props.breakpoints) || !(0, _lodash2.default)(nextProps.cols, this.props.cols)) {
      this.onWidthChange(nextProps);
    } else if (!(0, _lodash2.default)(nextProps.layouts, this.props.layouts)) {
      // Allow parent to set layouts directly.
      var _state = this.state,
          _breakpoint = _state.breakpoint,
          _cols = _state.cols;

      // Since we're setting an entirely new layout object, we must generate a new responsive layout
      // if one does not exist.

      var newLayout = (0, _responsiveUtils.findOrGenerateResponsiveLayout)(nextProps.layouts, nextProps.breakpoints, _breakpoint, _breakpoint, _cols, nextProps.compactType);
      this.setState({ layout: newLayout });
    }
  };

  // wrap layouts so we do not need to pass layouts to child


  /**
   * When the width changes work through breakpoints and reset state with the new width & breakpoint.
   * Width changes are necessary to figure out the widget widths.
   */
  ResponsiveReactGridLayout.prototype.onWidthChange = function onWidthChange(nextProps) {
    var breakpoints = nextProps.breakpoints,
        cols = nextProps.cols,
        layouts = nextProps.layouts,
        compactType = nextProps.compactType;

    var newBreakpoint = nextProps.breakpoint || (0, _responsiveUtils.getBreakpointFromWidth)(nextProps.breakpoints, nextProps.width);

    var lastBreakpoint = this.state.breakpoint;

    // Breakpoint change
    if (lastBreakpoint !== newBreakpoint || this.props.breakpoints !== breakpoints || this.props.cols !== cols) {
      // Preserve the current layout if the current breakpoint is not present in the next layouts.
      if (!(lastBreakpoint in layouts)) layouts[lastBreakpoint] = (0, _utils.cloneLayout)(this.state.layout);

      // Find or generate a new layout.
      var newCols = (0, _responsiveUtils.getColsFromBreakpoint)(newBreakpoint, cols);
      var _layout = (0, _responsiveUtils.findOrGenerateResponsiveLayout)(layouts, breakpoints, newBreakpoint, lastBreakpoint, newCols, compactType);

      // This adds missing items.
      _layout = (0, _utils.synchronizeLayoutWithChildren)(_layout, nextProps.children, newCols, compactType);

      // Store the new layout.
      layouts[newBreakpoint] = _layout;

      // callbacks
      this.props.onLayoutChange(_layout, layouts);
      this.props.onBreakpointChange(newBreakpoint, newCols);
      this.props.onWidthChange(nextProps.width, nextProps.margin, newCols, nextProps.containerPadding);

      this.setState({
        breakpoint: newBreakpoint,
        layout: _layout,
        cols: newCols
      });
    }
  };

  ResponsiveReactGridLayout.prototype.render = function render() {
    /* eslint-disable no-unused-vars */
    var _props2 = this.props,
        breakpoint = _props2.breakpoint,
        breakpoints = _props2.breakpoints,
        cols = _props2.cols,
        layouts = _props2.layouts,
        onBreakpointChange = _props2.onBreakpointChange,
        onLayoutChange = _props2.onLayoutChange,
        onWidthChange = _props2.onWidthChange,
        other = _objectWithoutProperties(_props2, ["breakpoint", "breakpoints", "cols", "layouts", "onBreakpointChange", "onLayoutChange", "onWidthChange"]);
    /* eslint-enable no-unused-vars */

    return _react2.default.createElement(_ReactGridLayout2.default, _extends({}, other, {
      onLayoutChange: this.onLayoutChange,
      layout: this.state.layout,
      cols: this.state.cols
    }));
  };

  return ResponsiveReactGridLayout;
}(_react2.default.Component);

ResponsiveReactGridLayout.propTypes = {
  //
  // Basic props
  //

  // Optional, but if you are managing width yourself you may want to set the breakpoint
  // yourself as well.
  breakpoint: _propTypes2.default.string,

  // {name: pxVal}, e.g. {lg: 1200, md: 996, sm: 768, xs: 480}
  breakpoints: _propTypes2.default.object,

  // # of cols. This is a breakpoint -> cols map
  cols: _propTypes2.default.object,

  // layouts is an object mapping breakpoints to layouts.
  // e.g. {lg: Layout, md: Layout, ...}
  layouts: function layouts(props, propName) {
    if (type(props[propName]) !== "[object Object]") {
      throw new Error("Layout property must be an object. Received: " + type(props[propName]));
    }
    Object.keys(props[propName]).forEach(function (key) {
      if (!(key in props.breakpoints)) {
        throw new Error("Each key in layouts must align with a key in breakpoints.");
      }
      (0, _utils.validateLayout)(props.layouts[key], "layouts." + key);
    });
  },


  // The width of this component.
  // Required in this propTypes stanza because generateInitialState() will fail without it.
  width: _propTypes2.default.number.isRequired,

  //
  // Callbacks
  //

  // Calls back with breakpoint and new # cols
  onBreakpointChange: _propTypes2.default.func,

  // Callback so you can save the layout.
  // Calls back with (currentLayout, allLayouts). allLayouts are keyed by breakpoint.
  onLayoutChange: _propTypes2.default.func,

  // Calls back with (containerWidth, margin, cols, containerPadding)
  onWidthChange: _propTypes2.default.func
};
ResponsiveReactGridLayout.defaultProps = {
  breakpoints: { lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 },
  cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 },
  layouts: {},
  onBreakpointChange: _utils.noop,
  onLayoutChange: _utils.noop,
  onWidthChange: _utils.noop
};
exports.default = ResponsiveReactGridLayout;

/***/ }),
/* 600 */
/***/ (function(module, exports, __nested_webpack_require_2853315__) {

"use strict";


exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.default = WidthProvider;

var _react = __nested_webpack_require_2853315__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_2853315__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDom = __nested_webpack_require_2853315__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

/*
 * A simple HOC that provides facility for listening to container resizes.
 */
function WidthProvider(ComposedComponent) {
  var _class, _temp2;

  return _temp2 = _class = function (_React$Component) {
    _inherits(WidthProvider, _React$Component);

    function WidthProvider() {
      var _temp, _this, _ret;

      _classCallCheck(this, WidthProvider);

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

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
        width: 1280
      }, _this.mounted = false, _this.onWindowResize = function () {
        if (!_this.mounted) return;
        // eslint-disable-next-line
        var node = _reactDom2.default.findDOMNode(_this); // Flow casts this to Text | Element
        if (node instanceof HTMLElement) _this.setState({ width: node.offsetWidth });
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    WidthProvider.prototype.componentDidMount = function componentDidMount() {
      this.mounted = true;

      window.addEventListener("resize", this.onWindowResize);
      // Call to properly set the breakpoint and resize the elements.
      // Note that if you're doing a full-width element, this can get a little wonky if a scrollbar
      // appears because of the grid. In that case, fire your own resize event, or set `overflow: scroll` on your body.
      this.onWindowResize();
    };

    WidthProvider.prototype.componentWillUnmount = function componentWillUnmount() {
      this.mounted = false;
      window.removeEventListener("resize", this.onWindowResize);
    };

    WidthProvider.prototype.render = function render() {
      var _props = this.props,
          measureBeforeMount = _props.measureBeforeMount,
          rest = _objectWithoutProperties(_props, ["measureBeforeMount"]);

      if (measureBeforeMount && !this.mounted) {
        return _react2.default.createElement("div", { className: this.props.className, style: this.props.style });
      }

      return _react2.default.createElement(ComposedComponent, _extends({}, rest, this.state));
    };

    return WidthProvider;
  }(_react2.default.Component), _class.defaultProps = {
    measureBeforeMount: false
  }, _class.propTypes = {
    // If true, will not render children until mounted. Useful for getting the exact width before
    // rendering, to prevent any unsightly resizing.
    measureBeforeMount: _propTypes2.default.bool
  }, _temp2;
}

/***/ }),
/* 601 */
/***/ (function(module, exports, __nested_webpack_require_2857825__) {

"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;

/**
 * Copyright Marc J. Schmidt. See the LICENSE file at the top-level
 * directory of this distribution and at
 * https://github.com/marcj/css-element-queries/blob/master/LICENSE.
 */
(function (root, factory) {
    if (true) {
        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__nested_webpack_require_2857825__(345)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else {}
}(typeof window !== 'undefined' ? window : this, function (ResizeSensor) {

    /**
     *
     * @type {Function}
     * @constructor
     */
    var ElementQueries = function () {
        //<style> element with our dynamically created styles
        var cssStyleElement;

        //all rules found for element queries
        var allQueries = {};

        //association map to identify which selector belongs to a element from the animationstart event.
        var idToSelectorMapping = [];

        /**
         *
         * @param element
         * @returns {Number}
         */
        function getEmSize(element) {
            if (!element) {
                element = document.documentElement;
            }
            var fontSize = window.getComputedStyle(element, null).fontSize;
            return parseFloat(fontSize) || 16;
        }

        /**
         * Get element size
         * @param {HTMLElement} element
         * @returns {Object} {width, height}
         */
        function getElementSize(element) {
            if (!element.getBoundingClientRect) {
                return {
                    width: element.offsetWidth,
                    height: element.offsetHeight
                }
            }

            var rect = element.getBoundingClientRect();
            return {
                width: Math.round(rect.width),
                height: Math.round(rect.height)
            }
        }

        /**
         *
         * @copyright https://github.com/Mr0grog/element-query/blob/master/LICENSE
         *
         * @param {HTMLElement} element
         * @param {*} value
         * @returns {*}
         */
        function convertToPx(element, value) {
            var numbers = value.split(/\d/);
            var units = numbers[numbers.length - 1];
            value = parseFloat(value);
            switch (units) {
                case "px":
                    return value;
                case "em":
                    return value * getEmSize(element);
                case "rem":
                    return value * getEmSize();
                // Viewport units!
                // According to http://quirksmode.org/mobile/tableViewport.html
                // documentElement.clientWidth/Height gets us the most reliable info
                case "vw":
                    return value * document.documentElement.clientWidth / 100;
                case "vh":
                    return value * document.documentElement.clientHeight / 100;
                case "vmin":
                case "vmax":
                    var vw = document.documentElement.clientWidth / 100;
                    var vh = document.documentElement.clientHeight / 100;
                    var chooser = Math[units === "vmin" ? "min" : "max"];
                    return value * chooser(vw, vh);
                default:
                    return value;
                // for now, not supporting physical units (since they are just a set number of px)
                // or ex/ch (getting accurate measurements is hard)
            }
        }

        /**
         *
         * @param {HTMLElement} element
         * @param {String} id
         * @constructor
         */
        function SetupInformation(element, id) {
            this.element = element;
            var key, option, elementSize, value, actualValue, attrValues, attrValue, attrName;

            var attributes = ['min-width', 'min-height', 'max-width', 'max-height'];

            /**
             * Extracts the computed width/height and sets to min/max- attribute.
             */
            this.call = function () {
                // extract current dimensions
                elementSize = getElementSize(this.element);

                attrValues = {};

                for (key in allQueries[id]) {
                    if (!allQueries[id].hasOwnProperty(key)) {
                        continue;
                    }
                    option = allQueries[id][key];

                    value = convertToPx(this.element, option.value);

                    actualValue = option.property === 'width' ? elementSize.width : elementSize.height;
                    attrName = option.mode + '-' + option.property;
                    attrValue = '';

                    if (option.mode === 'min' && actualValue >= value) {
                        attrValue += option.value;
                    }

                    if (option.mode === 'max' && actualValue <= value) {
                        attrValue += option.value;
                    }

                    if (!attrValues[attrName]) attrValues[attrName] = '';
                    if (attrValue && -1 === (' ' + attrValues[attrName] + ' ').indexOf(' ' + attrValue + ' ')) {
                        attrValues[attrName] += ' ' + attrValue;
                    }
                }

                for (var k in attributes) {
                    if (!attributes.hasOwnProperty(k)) continue;

                    if (attrValues[attributes[k]]) {
                        this.element.setAttribute(attributes[k], attrValues[attributes[k]].substr(1));
                    } else {
                        this.element.removeAttribute(attributes[k]);
                    }
                }
            };
        }

        /**
         * @param {HTMLElement} element
         * @param {Object}      id
         */
        function setupElement(element, id) {
            if (!element.elementQueriesSetupInformation) {
                element.elementQueriesSetupInformation = new SetupInformation(element, id);
            }
            if (!element.elementQueriesSensor) {
                element.elementQueriesSensor = new ResizeSensor(element, function () {
                    element.elementQueriesSetupInformation.call();
                });
            }

            element.elementQueriesSetupInformation.call();
        }

        /**
         * Stores rules to the selector that should be applied once resized.
         *
         * @param {String} selector
         * @param {String} mode min|max
         * @param {String} property width|height
         * @param {String} value
         */
        function queueQuery(selector, mode, property, value) {
            if (typeof(allQueries[selector]) === 'undefined') {
                allQueries[selector] = [];
                // add animation to trigger animationstart event, so we know exactly when a element appears in the DOM

                var id = idToSelectorMapping.length;
                cssStyleElement.innerHTML += '\n' + selector + ' {animation: 0.1s element-queries;}';
                cssStyleElement.innerHTML += '\n' + selector + ' > .resize-sensor {min-width: '+id+'px;}';
                idToSelectorMapping.push(selector);
            }

            allQueries[selector].push({
                mode: mode,
                property: property,
                value: value
            });
        }

        function getQuery(container) {
            var query;
            if (document.querySelectorAll) query = (container) ? container.querySelectorAll.bind(container) : document.querySelectorAll.bind(document);
            if (!query && 'undefined' !== typeof $$) query = $$;
            if (!query && 'undefined' !== typeof jQuery) query = jQuery;

            if (!query) {
                throw 'No document.querySelectorAll, jQuery or Mootools\'s $$ found.';
            }

            return query;
        }

        /**
         * If animationStart didn't catch a new element in the DOM, we can manually search for it
         */
        function findElementQueriesElements(container) {
            var query = getQuery(container);

            for (var selector in allQueries) if (allQueries.hasOwnProperty(selector)) {
                // find all elements based on the extract query selector from the element query rule
                var elements = query(selector, container);

                for (var i = 0, j = elements.length; i < j; i++) {
                    setupElement(elements[i], selector);
                }
            }
        }

        /**
         *
         * @param {HTMLElement} element
         */
        function attachResponsiveImage(element) {
            var children = [];
            var rules = [];
            var sources = [];
            var defaultImageId = 0;
            var lastActiveImage = -1;
            var loadedImages = [];

            for (var i in element.children) {
                if (!element.children.hasOwnProperty(i)) continue;

                if (element.children[i].tagName && element.children[i].tagName.toLowerCase() === 'img') {
                    children.push(element.children[i]);

                    var minWidth = element.children[i].getAttribute('min-width') || element.children[i].getAttribute('data-min-width');
                    //var minHeight = element.children[i].getAttribute('min-height') || element.children[i].getAttribute('data-min-height');
                    var src = element.children[i].getAttribute('data-src') || element.children[i].getAttribute('url');

                    sources.push(src);

                    var rule = {
                        minWidth: minWidth
                    };

                    rules.push(rule);

                    if (!minWidth) {
                        defaultImageId = children.length - 1;
                        element.children[i].style.display = 'block';
                    } else {
                        element.children[i].style.display = 'none';
                    }
                }
            }

            lastActiveImage = defaultImageId;

            function check() {
                var imageToDisplay = false, i;

                for (i in children) {
                    if (!children.hasOwnProperty(i)) continue;

                    if (rules[i].minWidth) {
                        if (element.offsetWidth > rules[i].minWidth) {
                            imageToDisplay = i;
                        }
                    }
                }

                if (!imageToDisplay) {
                    //no rule matched, show default
                    imageToDisplay = defaultImageId;
                }

                if (lastActiveImage !== imageToDisplay) {
                    //image change

                    if (!loadedImages[imageToDisplay]) {
                        //image has not been loaded yet, we need to load the image first in memory to prevent flash of
                        //no content

                        var image = new Image();
                        image.onload = function () {
                            children[imageToDisplay].src = sources[imageToDisplay];

                            children[lastActiveImage].style.display = 'none';
                            children[imageToDisplay].style.display = 'block';

                            loadedImages[imageToDisplay] = true;

                            lastActiveImage = imageToDisplay;
                        };

                        image.src = sources[imageToDisplay];
                    } else {
                        children[lastActiveImage].style.display = 'none';
                        children[imageToDisplay].style.display = 'block';
                        lastActiveImage = imageToDisplay;
                    }
                } else {
                    //make sure for initial check call the .src is set correctly
                    children[imageToDisplay].src = sources[imageToDisplay];
                }
            }

            element.resizeSensorInstance = new ResizeSensor(element, check);
            check();
        }

        function findResponsiveImages() {
            var query = getQuery();

            var elements = query('[data-responsive-image],[responsive-image]');
            for (var i = 0, j = elements.length; i < j; i++) {
                attachResponsiveImage(elements[i]);
            }
        }

        var regex = /,?[\s\t]*([^,\n]*?)((?:\[[\s\t]*?(?:min|max)-(?:width|height)[\s\t]*?[~$\^]?=[\s\t]*?"[^"]*?"[\s\t]*?])+)([^,\n\s\{]*)/mgi;
        var attrRegex = /\[[\s\t]*?(min|max)-(width|height)[\s\t]*?[~$\^]?=[\s\t]*?"([^"]*?)"[\s\t]*?]/mgi;

        /**
         * @param {String} css
         */
        function extractQuery(css) {
            var match, smatch, attrs, attrMatch;

            css = css.replace(/'/g, '"');
            while (null !== (match = regex.exec(css))) {
                smatch = match[1] + match[3];
                attrs = match[2];

                while (null !== (attrMatch = attrRegex.exec(attrs))) {
                    queueQuery(smatch, attrMatch[1], attrMatch[2], attrMatch[3]);
                }
            }
        }

        /**
         * @param {CssRule[]|String} rules
         */
        function readRules(rules) {
            var selector = '';

            if (!rules) {
                return;
            }

            if ('string' === typeof rules) {
                rules = rules.toLowerCase();
                if (-1 !== rules.indexOf('min-width') || -1 !== rules.indexOf('max-width')) {
                    extractQuery(rules);
                }
            } else {
                for (var i = 0, j = rules.length; i < j; i++) {
                    if (1 === rules[i].type) {
                        selector = rules[i].selectorText || rules[i].cssText;
                        if (-1 !== selector.indexOf('min-height') || -1 !== selector.indexOf('max-height')) {
                            extractQuery(selector);
                        } else if (-1 !== selector.indexOf('min-width') || -1 !== selector.indexOf('max-width')) {
                            extractQuery(selector);
                        }
                    } else if (4 === rules[i].type) {
                        readRules(rules[i].cssRules || rules[i].rules);
                    } else if (3 === rules[i].type) {
                        if(rules[i].styleSheet.hasOwnProperty("cssRules")) {
                            readRules(rules[i].styleSheet.cssRules);
                        }
                    }
                }
            }
        }

        var defaultCssInjected = false;

        /**
         * Searches all css rules and setups the event listener to all elements with element query rules..
         */
        this.init = function () {
            var animationStart = 'animationstart';
            if (typeof document.documentElement.style['webkitAnimationName'] !== 'undefined') {
                animationStart = 'webkitAnimationStart';
            } else if (typeof document.documentElement.style['MozAnimationName'] !== 'undefined') {
                animationStart = 'mozanimationstart';
            } else if (typeof document.documentElement.style['OAnimationName'] !== 'undefined') {
                animationStart = 'oanimationstart';
            }

            document.body.addEventListener(animationStart, function (e) {
                var element = e.target;
                var styles = element && window.getComputedStyle(element, null);
                var animationName = styles && styles.getPropertyValue('animation-name');
                var requiresSetup = animationName && (-1 !== animationName.indexOf('element-queries'));

                if (requiresSetup) {
                    element.elementQueriesSensor = new ResizeSensor(element, function () {
                        if (element.elementQueriesSetupInformation) {
                            element.elementQueriesSetupInformation.call();
                        }
                    });

                    var sensorStyles = window.getComputedStyle(element.resizeSensor, null);
                    var id = sensorStyles.getPropertyValue('min-width');
                    id = parseInt(id.replace('px', ''));
                    setupElement(e.target, idToSelectorMapping[id]);
                }
            });

            if (!defaultCssInjected) {
                cssStyleElement = document.createElement('style');
                cssStyleElement.type = 'text/css';
                cssStyleElement.innerHTML = '[responsive-image] > img, [data-responsive-image] {overflow: hidden; padding: 0; } [responsive-image] > img, [data-responsive-image] > img {width: 100%;}';

                //safari wants at least one rule in keyframes to start working
                cssStyleElement.innerHTML += '\n@keyframes element-queries { 0% { visibility: inherit; } }';
                document.getElementsByTagName('head')[0].appendChild(cssStyleElement);
                defaultCssInjected = true;
            }

            for (var i = 0, j = document.styleSheets.length; i < j; i++) {
                try {
                    if (document.styleSheets[i].href && 0 === document.styleSheets[i].href.indexOf('file://')) {
                        console.log("CssElementQueries: unable to parse local css files, " + document.styleSheets[i].href);
                    }

                    readRules(document.styleSheets[i].cssRules || document.styleSheets[i].rules || document.styleSheets[i].cssText);
                } catch (e) {
                }
            }

            findResponsiveImages();
        };

        /**
         * Go through all collected rules (readRules()) and attach the resize-listener.
         * Not necessary to call it manually, since we detect automatically when new elements
         * are available in the DOM. However, sometimes handy for dirty DOM modifications.
         *
         * @param {HTMLElement} container only elements of the container are considered (document.body if not set)
         */
        this.findElementQueriesElements = function (container) {
            findElementQueriesElements(container);
        };

        this.update = function () {
            this.init();
        };
    };

    ElementQueries.update = function () {
        ElementQueries.instance.update();
    };

    /**
     * Removes all sensor and elementquery information from the element.
     *
     * @param {HTMLElement} element
     */
    ElementQueries.detach = function (element) {
        if (element.elementQueriesSetupInformation) {
            //element queries
            element.elementQueriesSensor.detach();
            delete element.elementQueriesSetupInformation;
            delete element.elementQueriesSensor;

        } else if (element.resizeSensorInstance) {
            //responsive image

            element.resizeSensorInstance.detach();
            delete element.resizeSensorInstance;
        }
    };

    ElementQueries.init = function () {
        if (!ElementQueries.instance) {
            ElementQueries.instance = new ElementQueries();
        }

        ElementQueries.instance.init();
    };

    var domLoaded = function (callback) {
        /* Mozilla, Chrome, Opera */
        if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', callback, false);
        }
        /* Safari, iCab, Konqueror */
        else if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
            var DOMLoadTimer = setInterval(function () {
                if (/loaded|complete/i.test(document.readyState)) {
                    callback();
                    clearInterval(DOMLoadTimer);
                }
            }, 10);
        }
        /* Other web browsers */
        else window.onload = callback;
    };

    ElementQueries.findElementQueriesElements = function (container) {
        ElementQueries.instance.findElementQueriesElements(container);
    };

    ElementQueries.listen = function () {
        domLoaded(ElementQueries.init);
    };

    return ElementQueries;

}));


/***/ }),
/* 602 */
/***/ (function(module, exports) {

/**
* vkBeautify - javascript plugin to pretty-print or minify text in XML, JSON, CSS and SQL formats.
*
* Copyright (c) 2012 Vadim Kiryukhin
* vkiryukhin @ gmail.com
* http://www.eslinstructor.net/vkbeautify/
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*   Pretty print
*
*        vkbeautify.xml(text [,indent_pattern]);
*        vkbeautify.json(text [,indent_pattern]);
*        vkbeautify.css(text [,indent_pattern]);
*        vkbeautify.sql(text [,indent_pattern]);
*
*        @text - String; text to beatufy;
*        @indent_pattern - Integer | String;
*                Integer:  number of white spaces;
*                String:   character string to visualize indentation ( can also be a set of white spaces )
*   Minify
*
*        vkbeautify.xmlmin(text [,preserve_comments]);
*        vkbeautify.jsonmin(text);
*        vkbeautify.cssmin(text [,preserve_comments]);
*        vkbeautify.sqlmin(text);
*
*        @text - String; text to minify;
*        @preserve_comments - Bool; [optional];
*                Set this flag to true to prevent removing comments from @text ( minxml and mincss functions only. )
*
*   Examples:
*        vkbeautify.xml(text); // pretty print XML
*        vkbeautify.json(text, 4 ); // pretty print JSON
*        vkbeautify.css(text, '. . . .'); // pretty print CSS
*        vkbeautify.sql(text, '----'); // pretty print SQL
*
*        vkbeautify.xmlmin(text, true);// minify XML, preserve comments
*        vkbeautify.jsonmin(text);// minify JSON
*        vkbeautify.cssmin(text);// minify CSS, remove comments ( default )
*        vkbeautify.sqlmin(text);// minify SQL
*
*/
function createShiftArr(step) {

	var space = '    ';

	if ( isNaN(parseInt(step)) ) {  // argument is string
		space = step;
	} else { // argument is integer
		switch(step) {
			case 1: space = ' '; break;
			case 2: space = '  '; break;
			case 3: space = '   '; break;
			case 4: space = '    '; break;
			case 5: space = '     '; break;
			case 6: space = '      '; break;
			case 7: space = '       '; break;
			case 8: space = '        '; break;
			case 9: space = '         '; break;
			case 10: space = '          '; break;
			case 11: space = '           '; break;
			case 12: space = '            '; break;
		}
	}

	var shift = ['\n']; // array of shifts
	for(var ix=0;ix<100;ix++) {
		shift.push(shift[ix]+space);
	}
	return shift;
}

function vkbeautify(){
	this.step = '    '; // 4 spaces
	this.shift = createShiftArr(this.step);
};

vkbeautify.prototype.xml = function(text,step) {

	var ar = text.replace(/>\s{0,}</g,"><")
				 .replace(/</g,"~::~<")
				 .replace(/\s*xmlns\:/g,"~::~xmlns:")
				 .replace(/\s*xmlns\=/g,"~::~xmlns=")
				 .split('~::~'),
		len = ar.length,
		inComment = false,
		deep = 0,
		str = '',
		ix = 0,
		shift = step ? createShiftArr(step) : this.shift;

		for(ix=0;ix<len;ix++) {
			// start comment or <![CDATA[...]]> or <!DOCTYPE //
			if(ar[ix].search(/<!/) > -1) {
				str += shift[deep]+ar[ix];
				inComment = true;
				// end comment  or <![CDATA[...]]> //
				if(ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1 || ar[ix].search(/!DOCTYPE/) > -1 ) {
					inComment = false;
				}
			} else
			// end comment  or <![CDATA[...]]> //
			if(ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1) {
				str += ar[ix];
				inComment = false;
			} else
			// <elm></elm> //
			if( /^<\w/.exec(ar[ix-1]) && /^<\/\w/.exec(ar[ix]) &&
				/^<[\w:\-\.\,]+/.exec(ar[ix-1]) == /^<\/[\w:\-\.\,]+/.exec(ar[ix])[0].replace('/','')) {
				str += ar[ix];
				if(!inComment) deep--;
			} else
			 // <elm> //
			if(ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) == -1 && ar[ix].search(/\/>/) == -1 ) {
				str = !inComment ? str += shift[deep++]+ar[ix] : str += ar[ix];
			} else
			 // <elm>...</elm> //
			if(ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) > -1) {
				str = !inComment ? str += shift[deep]+ar[ix] : str += ar[ix];
			} else
			// </elm> //
			if(ar[ix].search(/<\//) > -1) {
				str = !inComment ? str += shift[--deep]+ar[ix] : str += ar[ix];
			} else
			// <elm/> //
			if(ar[ix].search(/\/>/) > -1 ) {
				str = !inComment ? str += shift[deep]+ar[ix] : str += ar[ix];
			} else
			// <? xml ... ?> //
			if(ar[ix].search(/<\?/) > -1) {
				str += shift[deep]+ar[ix];
			} else
			// xmlns //
			if( ar[ix].search(/xmlns\:/) > -1  || ar[ix].search(/xmlns\=/) > -1) {
				str += shift[deep]+ar[ix];
			}

			else {
				str += ar[ix];
			}
		}

	return  (str[0] == '\n') ? str.slice(1) : str;
}

vkbeautify.prototype.json = function(text,step) {

	var step = step ? step : this.step;

	if (typeof JSON === 'undefined' ) return text;

	if ( typeof text === "string" ) return JSON.stringify(JSON.parse(text), null, step);
	if ( typeof text === "object" ) return JSON.stringify(text, null, step);

	return text; // text is not string nor object
}

vkbeautify.prototype.css = function(text, step) {

	var ar = text.replace(/\s{1,}/g,' ')
				.replace(/\{/g,"{~::~")
				.replace(/\}/g,"~::~}~::~")
				.replace(/\;/g,";~::~")
				.replace(/\/\*/g,"~::~/*")
				.replace(/\*\//g,"*/~::~")
				.replace(/~::~\s{0,}~::~/g,"~::~")
				.split('~::~'),
		len = ar.length,
		deep = 0,
		str = '',
		ix = 0,
		shift = step ? createShiftArr(step) : this.shift;

		for(ix=0;ix<len;ix++) {

			if( /\{/.exec(ar[ix]))  {
				str += shift[deep++]+ar[ix];
			} else
			if( /\}/.exec(ar[ix]))  {
				str += shift[--deep]+ar[ix];
			} else
			if( /\*\\/.exec(ar[ix]))  {
				str += shift[deep]+ar[ix];
			}
			else {
				str += shift[deep]+ar[ix];
			}
		}
		return str.replace(/^\n{1,}/,'');
}

//----------------------------------------------------------------------------

function isSubquery(str, parenthesisLevel) {
	return  parenthesisLevel - (str.replace(/\(/g,'').length - str.replace(/\)/g,'').length )
}

function split_sql(str, tab) {

	return str.replace(/\s{1,}/g," ")

				.replace(/ AND /ig,"~::~"+tab+tab+"AND ")
				.replace(/ BETWEEN /ig,"~::~"+tab+"BETWEEN ")
				.replace(/ CASE /ig,"~::~"+tab+"CASE ")
				.replace(/ ELSE /ig,"~::~"+tab+"ELSE ")
				.replace(/ END /ig,"~::~"+tab+"END ")
				.replace(/ FROM /ig,"~::~FROM ")
				.replace(/ GROUP\s{1,}BY/ig,"~::~GROUP BY ")
				.replace(/ HAVING /ig,"~::~HAVING ")
				//.replace(/ SET /ig," SET~::~")
				.replace(/ IN /ig," IN ")

				.replace(/ JOIN /ig,"~::~JOIN ")
				.replace(/ CROSS~::~{1,}JOIN /ig,"~::~CROSS JOIN ")
				.replace(/ INNER~::~{1,}JOIN /ig,"~::~INNER JOIN ")
				.replace(/ LEFT~::~{1,}JOIN /ig,"~::~LEFT JOIN ")
				.replace(/ RIGHT~::~{1,}JOIN /ig,"~::~RIGHT JOIN ")

				.replace(/ ON /ig,"~::~"+tab+"ON ")
				.replace(/ OR /ig,"~::~"+tab+tab+"OR ")
				.replace(/ ORDER\s{1,}BY/ig,"~::~ORDER BY ")
				.replace(/ OVER /ig,"~::~"+tab+"OVER ")

				.replace(/\(\s{0,}SELECT /ig,"~::~(SELECT ")
				.replace(/\)\s{0,}SELECT /ig,")~::~SELECT ")

				.replace(/ THEN /ig," THEN~::~"+tab+"")
				.replace(/ UNION /ig,"~::~UNION~::~")
				.replace(/ USING /ig,"~::~USING ")
				.replace(/ WHEN /ig,"~::~"+tab+"WHEN ")
				.replace(/ WHERE /ig,"~::~WHERE ")
				.replace(/ WITH /ig,"~::~WITH ")

				//.replace(/\,\s{0,}\(/ig,",~::~( ")
				//.replace(/\,/ig,",~::~"+tab+tab+"")

				.replace(/ ALL /ig," ALL ")
				.replace(/ AS /ig," AS ")
				.replace(/ ASC /ig," ASC ")
				.replace(/ DESC /ig," DESC ")
				.replace(/ DISTINCT /ig," DISTINCT ")
				.replace(/ EXISTS /ig," EXISTS ")
				.replace(/ NOT /ig," NOT ")
				.replace(/ NULL /ig," NULL ")
				.replace(/ LIKE /ig," LIKE ")
				.replace(/\s{0,}SELECT /ig,"SELECT ")
				.replace(/\s{0,}UPDATE /ig,"UPDATE ")
				.replace(/ SET /ig," SET ")

				.replace(/~::~{1,}/g,"~::~")
				.split('~::~');
}

vkbeautify.prototype.sql = function(text,step) {

	var ar_by_quote = text.replace(/\s{1,}/g," ")
							.replace(/\'/ig,"~::~\'")
							.split('~::~'),
		len = ar_by_quote.length,
		ar = [],
		deep = 0,
		tab = this.step,//+this.step,
		inComment = true,
		inQuote = false,
		parenthesisLevel = 0,
		str = '',
		ix = 0,
		shift = step ? createShiftArr(step) : this.shift;;

		for(ix=0;ix<len;ix++) {
			if(ix%2) {
				ar = ar.concat(ar_by_quote[ix]);
			} else {
				ar = ar.concat(split_sql(ar_by_quote[ix], tab) );
			}
		}

		len = ar.length;
		for(ix=0;ix<len;ix++) {

			parenthesisLevel = isSubquery(ar[ix], parenthesisLevel);

			if( /\s{0,}\s{0,}SELECT\s{0,}/.exec(ar[ix]))  {
				ar[ix] = ar[ix].replace(/\,/g,",\n"+tab+tab+"")
			}

			if( /\s{0,}\s{0,}SET\s{0,}/.exec(ar[ix]))  {
				ar[ix] = ar[ix].replace(/\,/g,",\n"+tab+tab+"")
			}

			if( /\s{0,}\(\s{0,}SELECT\s{0,}/.exec(ar[ix]))  {
				deep++;
				str += shift[deep]+ar[ix];
			} else
			if( /\'/.exec(ar[ix]) )  {
				if(parenthesisLevel<1 && deep) {
					deep--;
				}
				str += ar[ix];
			}
			else  {
				str += shift[deep]+ar[ix];
				if(parenthesisLevel<1 && deep) {
					deep--;
				}
			}
			var junk = 0;
		}

		str = str.replace(/^\n{1,}/,'').replace(/\n{1,}/g,"\n");
		return str;
}


vkbeautify.prototype.xmlmin = function(text, preserveComments) {

	var str = preserveComments ? text
							   : text.replace(/\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>/g,"")
									 .replace(/[ \r\n\t]{1,}xmlns/g, ' xmlns');
	return  str.replace(/>\s{0,}</g,"><");
}

vkbeautify.prototype.jsonmin = function(text) {

	if (typeof JSON === 'undefined' ) return text;

	return JSON.stringify(JSON.parse(text), null, 0);

}

vkbeautify.prototype.cssmin = function(text, preserveComments) {

	var str = preserveComments ? text
							   : text.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//g,"") ;

	return str.replace(/\s{1,}/g,' ')
			  .replace(/\{\s{1,}/g,"{")
			  .replace(/\}\s{1,}/g,"}")
			  .replace(/\;\s{1,}/g,";")
			  .replace(/\/\*\s{1,}/g,"/*")
			  .replace(/\*\/\s{1,}/g,"*/");
}

vkbeautify.prototype.sqlmin = function(text) {
	return text.replace(/\s{1,}/g," ").replace(/\s{1,}\(/,"(").replace(/\s{1,}\)/,")");
}

module.exports = new vkbeautify();


/***/ }),
/* 603 */
/***/ (function(module, exports, __nested_webpack_require_2888756__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var required = __nested_webpack_require_2888756__(604)
  , qs = __nested_webpack_require_2888756__(605)
  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
  , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]'
  , left = new RegExp('^'+ whitespace +'+');

/**
 * Trim a given string.
 *
 * @param {String} str String to trim.
 * @public
 */
function trimLeft(str) {
  return (str ? str : '').toString().replace(left, '');
}

/**
 * These are the parse rules for the URL parser, it informs the parser
 * about:
 *
 * 0. The char it Needs to parse, if it's a string it should be done using
 *    indexOf, RegExp using exec and NaN means set as current value.
 * 1. The property we should set when parsing this value.
 * 2. Indication if it's backwards or forward parsing, when set as number it's
 *    the value of extra chars that should be split off.
 * 3. Inherit from location if non existing in the parser.
 * 4. `toLowerCase` the resulting value.
 */
var rules = [
  ['#', 'hash'],                        // Extract from the back.
  ['?', 'query'],                       // Extract from the back.
  function sanitize(address) {          // Sanitize what is left of the address
    return address.replace('\\', '/');
  },
  ['/', 'pathname'],                    // Extract from the back.
  ['@', 'auth', 1],                     // Extract from the front.
  [NaN, 'host', undefined, 1, 1],       // Set left over value.
  [/:(\d+)$/, 'port', undefined, 1],    // RegExp the back.
  [NaN, 'hostname', undefined, 1, 1]    // Set left over.
];

/**
 * These properties should not be copied or inherited from. This is only needed
 * for all non blob URL's as a blob URL does not include a hash, only the
 * origin.
 *
 * @type {Object}
 * @private
 */
var ignore = { hash: 1, query: 1 };

/**
 * The location object differs when your code is loaded through a normal page,
 * Worker or through a worker using a blob. And with the blobble begins the
 * trouble as the location object will contain the URL of the blob, not the
 * location of the page where our code is loaded in. The actual origin is
 * encoded in the `pathname` so we can thankfully generate a good "default"
 * location from it so we can generate proper relative URL's again.
 *
 * @param {Object|String} loc Optional default location object.
 * @returns {Object} lolcation object.
 * @public
 */
function lolcation(loc) {
  var globalVar;

  if (typeof window !== 'undefined') globalVar = window;
  else if (typeof global !== 'undefined') globalVar = global;
  else if (typeof self !== 'undefined') globalVar = self;
  else globalVar = {};

  var location = globalVar.location || {};
  loc = loc || location;

  var finaldestination = {}
    , type = typeof loc
    , key;

  if ('blob:' === loc.protocol) {
    finaldestination = new Url(unescape(loc.pathname), {});
  } else if ('string' === type) {
    finaldestination = new Url(loc, {});
    for (key in ignore) delete finaldestination[key];
  } else if ('object' === type) {
    for (key in loc) {
      if (key in ignore) continue;
      finaldestination[key] = loc[key];
    }

    if (finaldestination.slashes === undefined) {
      finaldestination.slashes = slashes.test(loc.href);
    }
  }

  return finaldestination;
}

/**
 * @typedef ProtocolExtract
 * @type Object
 * @property {String} protocol Protocol matched in the URL, in lowercase.
 * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
 * @property {String} rest Rest of the URL that is not part of the protocol.
 */

/**
 * Extract protocol information from a URL with/without double slash ("//").
 *
 * @param {String} address URL we want to extract from.
 * @return {ProtocolExtract} Extracted information.
 * @private
 */
function extractProtocol(address) {
  address = trimLeft(address);
  var match = protocolre.exec(address);

  return {
    protocol: match[1] ? match[1].toLowerCase() : '',
    slashes: !!match[2],
    rest: match[3]
  };
}

/**
 * Resolve a relative URL pathname against a base URL pathname.
 *
 * @param {String} relative Pathname of the relative URL.
 * @param {String} base Pathname of the base URL.
 * @return {String} Resolved pathname.
 * @private
 */
function resolve(relative, base) {
  if (relative === '') return base;

  var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
    , i = path.length
    , last = path[i - 1]
    , unshift = false
    , up = 0;

  while (i--) {
    if (path[i] === '.') {
      path.splice(i, 1);
    } else if (path[i] === '..') {
      path.splice(i, 1);
      up++;
    } else if (up) {
      if (i === 0) unshift = true;
      path.splice(i, 1);
      up--;
    }
  }

  if (unshift) path.unshift('');
  if (last === '.' || last === '..') path.push('');

  return path.join('/');
}

/**
 * The actual URL instance. Instead of returning an object we've opted-in to
 * create an actual constructor as it's much more memory efficient and
 * faster and it pleases my OCD.
 *
 * It is worth noting that we should not use `URL` as class name to prevent
 * clashes with the global URL instance that got introduced in browsers.
 *
 * @constructor
 * @param {String} address URL we want to parse.
 * @param {Object|String} [location] Location defaults for relative paths.
 * @param {Boolean|Function} [parser] Parser for the query string.
 * @private
 */
function Url(address, location, parser) {
  address = trimLeft(address);

  if (!(this instanceof Url)) {
    return new Url(address, location, parser);
  }

  var relative, extracted, parse, instruction, index, key
    , instructions = rules.slice()
    , type = typeof location
    , url = this
    , i = 0;

  //
  // The following if statements allows this module two have compatibility with
  // 2 different API:
  //
  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  //    where the boolean indicates that the query string should also be parsed.
  //
  // 2. The `URL` interface of the browser which accepts a URL, object as
  //    arguments. The supplied object will be used as default values / fall-back
  //    for relative paths.
  //
  if ('object' !== type && 'string' !== type) {
    parser = location;
    location = null;
  }

  if (parser && 'function' !== typeof parser) parser = qs.parse;

  location = lolcation(location);

  //
  // Extract protocol information before running the instructions.
  //
  extracted = extractProtocol(address || '');
  relative = !extracted.protocol && !extracted.slashes;
  url.slashes = extracted.slashes || relative && location.slashes;
  url.protocol = extracted.protocol || location.protocol || '';
  address = extracted.rest;

  //
  // When the authority component is absent the URL starts with a path
  // component.
  //
  if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];

  for (; i < instructions.length; i++) {
    instruction = instructions[i];

    if (typeof instruction === 'function') {
      address = instruction(address);
      continue;
    }

    parse = instruction[0];
    key = instruction[1];

    if (parse !== parse) {
      url[key] = address;
    } else if ('string' === typeof parse) {
      if (~(index = address.indexOf(parse))) {
        if ('number' === typeof instruction[2]) {
          url[key] = address.slice(0, index);
          address = address.slice(index + instruction[2]);
        } else {
          url[key] = address.slice(index);
          address = address.slice(0, index);
        }
      }
    } else if ((index = parse.exec(address))) {
      url[key] = index[1];
      address = address.slice(0, index.index);
    }

    url[key] = url[key] || (
      relative && instruction[3] ? location[key] || '' : ''
    );

    //
    // Hostname, host and protocol should be lowercased so they can be used to
    // create a proper `origin`.
    //
    if (instruction[4]) url[key] = url[key].toLowerCase();
  }

  //
  // Also parse the supplied query string in to an object. If we're supplied
  // with a custom parser as function use that instead of the default build-in
  // parser.
  //
  if (parser) url.query = parser(url.query);

  //
  // If the URL is relative, resolve the pathname against the base URL.
  //
  if (
      relative
    && location.slashes
    && url.pathname.charAt(0) !== '/'
    && (url.pathname !== '' || location.pathname !== '')
  ) {
    url.pathname = resolve(url.pathname, location.pathname);
  }

  //
  // We should not add port numbers if they are already the default port number
  // for a given protocol. As the host also contains the port number we're going
  // override it with the hostname which contains no port number.
  //
  if (!required(url.port, url.protocol)) {
    url.host = url.hostname;
    url.port = '';
  }

  //
  // Parse down the `auth` for the username and password.
  //
  url.username = url.password = '';
  if (url.auth) {
    instruction = url.auth.split(':');
    url.username = instruction[0] || '';
    url.password = instruction[1] || '';
  }

  url.origin = url.protocol && url.host && url.protocol !== 'file:'
    ? url.protocol +'//'+ url.host
    : 'null';

  //
  // The href is just the compiled result.
  //
  url.href = url.toString();
}

/**
 * This is convenience method for changing properties in the URL instance to
 * insure that they all propagate correctly.
 *
 * @param {String} part          Property we need to adjust.
 * @param {Mixed} value          The newly assigned value.
 * @param {Boolean|Function} fn  When setting the query, it will be the function
 *                               used to parse the query.
 *                               When setting the protocol, double slash will be
 *                               removed from the final url if it is true.
 * @returns {URL} URL instance for chaining.
 * @public
 */
function set(part, value, fn) {
  var url = this;

  switch (part) {
    case 'query':
      if ('string' === typeof value && value.length) {
        value = (fn || qs.parse)(value);
      }

      url[part] = value;
      break;

    case 'port':
      url[part] = value;

      if (!required(value, url.protocol)) {
        url.host = url.hostname;
        url[part] = '';
      } else if (value) {
        url.host = url.hostname +':'+ value;
      }

      break;

    case 'hostname':
      url[part] = value;

      if (url.port) value += ':'+ url.port;
      url.host = value;
      break;

    case 'host':
      url[part] = value;

      if (/:\d+$/.test(value)) {
        value = value.split(':');
        url.port = value.pop();
        url.hostname = value.join(':');
      } else {
        url.hostname = value;
        url.port = '';
      }

      break;

    case 'protocol':
      url.protocol = value.toLowerCase();
      url.slashes = !fn;
      break;

    case 'pathname':
    case 'hash':
      if (value) {
        var char = part === 'pathname' ? '/' : '#';
        url[part] = value.charAt(0) !== char ? char + value : value;
      } else {
        url[part] = value;
      }
      break;

    default:
      url[part] = value;
  }

  for (var i = 0; i < rules.length; i++) {
    var ins = rules[i];

    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  }

  url.origin = url.protocol && url.host && url.protocol !== 'file:'
    ? url.protocol +'//'+ url.host
    : 'null';

  url.href = url.toString();

  return url;
}

/**
 * Transform the properties back in to a valid and full URL string.
 *
 * @param {Function} stringify Optional query stringify function.
 * @returns {String} Compiled version of the URL.
 * @public
 */
function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result = protocol + (url.slashes ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}

Url.prototype = { set: set, toString: toString };

//
// Expose the URL parser and some additional properties that might be useful for
// others or testing.
//
Url.extractProtocol = extractProtocol;
Url.location = lolcation;
Url.trimLeft = trimLeft;
Url.qs = qs;

module.exports = Url;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_2888756__(27)))

/***/ }),
/* 604 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Check if we're required to add a port number.
 *
 * @see https://url.spec.whatwg.org/#default-port
 * @param {Number|String} port Port number we need to check
 * @param {String} protocol Protocol we need to check against.
 * @returns {Boolean} Is it a default port for the given protocol
 * @api private
 */
module.exports = function required(port, protocol) {
  protocol = protocol.split(':')[0];
  port = +port;

  if (!port) return false;

  switch (protocol) {
    case 'http':
    case 'ws':
    return port !== 80;

    case 'https':
    case 'wss':
    return port !== 443;

    case 'ftp':
    return port !== 21;

    case 'gopher':
    return port !== 70;

    case 'file':
    return false;
  }

  return port !== 0;
};


/***/ }),
/* 605 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var has = Object.prototype.hasOwnProperty
  , undef;

/**
 * Decode a URI encoded string.
 *
 * @param {String} input The URI encoded string.
 * @returns {String|Null} The decoded string.
 * @api private
 */
function decode(input) {
  try {
    return decodeURIComponent(input.replace(/\+/g, ' '));
  } catch (e) {
    return null;
  }
}

/**
 * Attempts to encode a given input.
 *
 * @param {String} input The string that needs to be encoded.
 * @returns {String|Null} The encoded string.
 * @api private
 */
function encode(input) {
  try {
    return encodeURIComponent(input);
  } catch (e) {
    return null;
  }
}

/**
 * Simple query string parser.
 *
 * @param {String} query The query string that needs to be parsed.
 * @returns {Object}
 * @api public
 */
function querystring(query) {
  var parser = /([^=?&]+)=?([^&]*)/g
    , result = {}
    , part;

  while (part = parser.exec(query)) {
    var key = decode(part[1])
      , value = decode(part[2]);

    //
    // Prevent overriding of existing properties. This ensures that build-in
    // methods like `toString` or __proto__ are not overriden by malicious
    // querystrings.
    //
    // In the case if failed decoding, we want to omit the key/value pairs
    // from the result.
    //
    if (key === null || value === null || key in result) continue;
    result[key] = value;
  }

  return result;
}

/**
 * Transform a query string to an object.
 *
 * @param {Object} obj Object that should be transformed.
 * @param {String} prefix Optional prefix.
 * @returns {String}
 * @api public
 */
function querystringify(obj, prefix) {
  prefix = prefix || '';

  var pairs = []
    , value
    , key;

  //
  // Optionally prefix with a '?' if needed
  //
  if ('string' !== typeof prefix) prefix = '?';

  for (key in obj) {
    if (has.call(obj, key)) {
      value = obj[key];

      //
      // Edge cases where we actually want to encode the value to an empty
      // string instead of the stringified value.
      //
      if (!value && (value === null || value === undef || isNaN(value))) {
        value = '';
      }

      key = encodeURIComponent(key);
      value = encodeURIComponent(value);

      //
      // If we failed to encode the strings, we should bail out as we don't
      // want to add invalid strings to the query.
      //
      if (key === null || value === null) continue;
      pairs.push(key +'='+ value);
    }
  }

  return pairs.length ? prefix + pairs.join('&') : '';
}

//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;


/***/ }),
/* 606 */
/***/ (function(module, exports, __nested_webpack_require_2905161__) {

"use strict";


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

var _set = __nested_webpack_require_2905161__(38);

var _set2 = _interopRequireDefault(_set);

var _getIterator2 = __nested_webpack_require_2905161__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _minSafeInteger = __nested_webpack_require_2905161__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

var _maxSafeInteger = __nested_webpack_require_2905161__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _assign = __nested_webpack_require_2905161__(44);

var _assign2 = _interopRequireDefault(_assign);

var _values = __nested_webpack_require_2905161__(37);

var _values2 = _interopRequireDefault(_values);

var _stringify = __nested_webpack_require_2905161__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _keys = __nested_webpack_require_2905161__(18);

var _keys2 = _interopRequireDefault(_keys);

var _toConsumableArray2 = __nested_webpack_require_2905161__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _getPrototypeOf = __nested_webpack_require_2905161__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_2905161__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_2905161__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_2905161__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_2905161__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _d3Selection = __nested_webpack_require_2905161__(0);

var _slugid = __nested_webpack_require_2905161__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _react = __nested_webpack_require_2905161__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_2905161__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _propTypes = __nested_webpack_require_2905161__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _cssElementQueries = __nested_webpack_require_2905161__(344);

var _ContextMenuItem = __nested_webpack_require_2905161__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _CenterTrack = __nested_webpack_require_2905161__(607);

var _CenterTrack2 = _interopRequireDefault(_CenterTrack);

var _DragListeningDiv = __nested_webpack_require_2905161__(609);

var _DragListeningDiv2 = _interopRequireDefault(_DragListeningDiv);

var _GalleryTracks = __nested_webpack_require_2905161__(611);

var _GalleryTracks2 = _interopRequireDefault(_GalleryTracks);

var _TrackRenderer = __nested_webpack_require_2905161__(613);

var _TrackRenderer2 = _interopRequireDefault(_TrackRenderer);

var _AddTrackDialog = __nested_webpack_require_2905161__(657);

var _AddTrackDialog2 = _interopRequireDefault(_AddTrackDialog);

var _ConfigTrackMenu = __nested_webpack_require_2905161__(664);

var _ConfigTrackMenu2 = _interopRequireDefault(_ConfigTrackMenu);

var _CloseTrackMenu = __nested_webpack_require_2905161__(666);

var _CloseTrackMenu2 = _interopRequireDefault(_CloseTrackMenu);

var _PopupMenu = __nested_webpack_require_2905161__(264);

var _PopupMenu2 = _interopRequireDefault(_PopupMenu);

var _ContextMenuContainer = __nested_webpack_require_2905161__(96);

var _ContextMenuContainer2 = _interopRequireDefault(_ContextMenuContainer);

var _HorizontalTiledPlot = __nested_webpack_require_2905161__(392);

var _HorizontalTiledPlot2 = _interopRequireDefault(_HorizontalTiledPlot);

var _VerticalTiledPlot = __nested_webpack_require_2905161__(672);

var _VerticalTiledPlot2 = _interopRequireDefault(_VerticalTiledPlot);

var _ViewContextMenu = __nested_webpack_require_2905161__(675);

var _ViewContextMenu2 = _interopRequireDefault(_ViewContextMenu);

var _withPubSub = __nested_webpack_require_2905161__(69);

var _withPubSub2 = _interopRequireDefault(_withPubSub);

var _withModal = __nested_webpack_require_2905161__(132);

var _withModal2 = _interopRequireDefault(_withModal);

var _withTheme = __nested_webpack_require_2905161__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _utils = __nested_webpack_require_2905161__(10);

var _configs = __nested_webpack_require_2905161__(11);

var _TiledPlotModule = __nested_webpack_require_2905161__(176);

var _TiledPlotModule2 = _interopRequireDefault(_TiledPlotModule);

var _CenterTrackModule = __nested_webpack_require_2905161__(346);

var _CenterTrackModule2 = _interopRequireDefault(_CenterTrackModule);

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

// eslint-disable-line no-unused-vars

// Styles


// Utils


// Components
var TiledPlot = function (_React$Component) {
  (0, _inherits3['default'])(TiledPlot, _React$Component);

  function TiledPlot(props) {
    (0, _classCallCheck3['default'])(this, TiledPlot);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (TiledPlot.__proto__ || (0, _getPrototypeOf2['default'])(TiledPlot)).call(this, props));

    _this.closing = false;
    // that the tracks will be drawn on

    var tracks = _this.props.tracks;

    _this.canvasElement = null;

    _this.tracksByUidInit = {};
    [].concat((0, _toConsumableArray3['default'])(_this.props.tracks.top || []), (0, _toConsumableArray3['default'])(_this.props.tracks.right || []), (0, _toConsumableArray3['default'])(_this.props.tracks.bottom || []), (0, _toConsumableArray3['default'])(_this.props.tracks.left || []), (0, _toConsumableArray3['default'])(_this.props.tracks.gallery || []), (0, _toConsumableArray3['default'])(_this.props.tracks.center || [])).forEach(function (track) {
      if (track.type === 'combined') {
        // Damn this combined track...
        track.contents.forEach(function (track2) {
          _this.tracksByUidInit[track2.uid] = false;
        });
      } else {
        _this.tracksByUidInit[track.uid] = false;
      }
    });

    _this.xScale = null;
    _this.yScale = null;

    _this.addUidsToTracks(tracks);

    // Add names to all the tracks
    _this.trackToReplace = null;
    _this.trackRenderer = null;

    _this.configTrackMenu = null;

    /*
    let trackOptions = this.props.editable ?
        {'track': this.props.tracks.center[0].contents[0],
        'configComponent': HeatmapOptions}
        : null;
    */

    // these values should be changed in componentDidMount
    _this.state = {
      sizeMeasured: false,
      height: 10,
      width: 10,

      tracks: tracks,
      init: false,
      addTrackPosition: null,
      mouseOverOverlayUid: null,
      // trackOptions: null
      // trackOptions: trackOptions
      forceUpdate: 0, // a random value that will be assigned by
      // crucial functions to force an update

      rangeSelection: [null, null],
      rangeSelectionEnd: false,

      chromInfo: null,
      defaultChromSizes: null,
      contextMenuCustomItems: null,
      contextMenuPosition: null,
      addDivisorDialog: null
    };

    // This should be `true` until one tracks was added and initialized.
    // The main difference to `this.state.init` is that `reset` should be reset
    // to `true` when the user removes all tracks and starts with a blank view!
    _this.reset = true;

    if (window.higlassTracksByType) {
      // Extend `TRACKS_INFO_BY_TYPE` with the configs of plugin tracks.
      (0, _keys2['default'])(window.higlassTracksByType).forEach(function (pluginTrackType) {
        _configs.TRACKS_INFO_BY_TYPE[pluginTrackType] = window.higlassTracksByType[pluginTrackType].config;
      });
    }

    // these dimensions are computed in the render() function and depend
    // on the sizes of the tracks in each section
    _this.topHeight = 0;
    _this.bottomHeight = 0;

    _this.leftWidth = 0;
    _this.rightWidth = 0;

    _this.centerHeight = 0;
    _this.centerWidth = 0;

    _this.dragTimeout = null;
    _this.previousPropsStr = '';

    _this.contextMenuHandlerBound = _this.contextMenuHandler.bind(_this);
    _this.handleNoTrackAddedBound = _this.handleNoTrackAdded.bind(_this);
    _this.handleTracksAddedBound = _this.handleTracksAdded.bind(_this);
    _this.closeMenusBound = _this.closeMenus.bind(_this);
    _this.handleAddDivisorBound = _this.handleAddDivisor.bind(_this);
    _this.handleAddSeriesBound = _this.handleAddSeries.bind(_this);
    _this.handleChangeTrackDataBound = _this.handleChangeTrackData.bind(_this);
    _this.handleChangeTrackTypeBound = _this.handleChangeTrackType.bind(_this);
    _this.handleCloseTrackBound = _this.handleCloseTrack.bind(_this);
    _this.handleConfigureTrackBound = _this.handleConfigureTrack.bind(_this);
    _this.handleExportTrackDataBound = _this.handleExportTrackData.bind(_this);
    _this.handleLockValueScaleBound = _this.handleLockValueScale.bind(_this);
    _this.handleReplaceTrackBound = _this.handleReplaceTrack.bind(_this);
    _this.handleTrackOptionsChangedBound = _this.handleTrackOptionsChanged.bind(_this);
    _this.handleUnlockValueScaleBound = _this.handleUnlockValueScale.bind(_this);
    _this.onAddTrack = _this.handleAddTrack.bind(_this);
    return _this;
  }

  (0, _createClass3['default'])(TiledPlot, [{
    key: 'waitForDOMAttachment',
    value: function () {
      function waitForDOMAttachment(callback) {
        var _this2 = this;

        if (!this.mounted) return;

        var thisElement = _reactDom2['default'].findDOMNode(this);

        if (document.body.contains(thisElement)) {
          callback();
        } else {
          requestAnimationFrame(function () {
            return _this2.waitForDOMAttachment(callback);
          });
        }
      }

      return waitForDOMAttachment;
    }()
  }, {
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        var _this3 = this;

        this.mounted = true;
        this.element = _reactDom2['default'].findDOMNode(this);
        this.canvasElement = _reactDom2['default'].findDOMNode(this.props.canvasElement);

        // new ResizeSensor(this.element, this.measureSize.bind(this));
        this.waitForDOMAttachment(function () {
          _cssElementQueries.ElementQueries.listen();
          _this3.resizeSensor = new _cssElementQueries.ResizeSensor(_this3.element.parentNode, _this3.measureSize.bind(_this3));

          _this3.measureSize();
        });

        // add event listeners for drag and drop events
        this.addEventListeners();
        // this.getDefaultChromSizes();

        this.pubSubs = [];
        this.pubSubs.push(this.props.pubSub.subscribe('contextmenu', this.contextMenuHandlerBound));
      }

      return componentDidMount;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(newProps) {
        this.addUidsToTracks(newProps.tracks);

        this.setState({
          tracks: newProps.tracks
        });
      }

      return UNSAFE_componentWillReceiveProps;
    }()
  }, {
    key: 'shouldComponentUpdate',
    value: function () {
      function shouldComponentUpdate(nextProps, nextState) {
        var _this4 = this;

        var thisPropsStr = this.previousPropsStr;
        var nextPropsStr = this.updatablePropsToString(nextProps);

        var thisStateStr = (0, _stringify2['default'])(this.state);
        var nextStateStr = (0, _stringify2['default'])(nextState);

        var toUpdate = thisPropsStr !== nextPropsStr || thisStateStr !== nextStateStr || this.props.chooseTrackHandler !== nextProps.chooseTrackHandler;

        if (toUpdate) this.previousPropsStr = nextPropsStr;

        var numPrevTracks = this.numTracks;

        this.numTracks = 0;
        // Note that there is no point in running the code below with
        // `this.props.tracks` and `nextProps.tracks` because the object is mutable
        // and so the props of `this.props.tracks` and `nextProps.tracks` are always
        // identical. To work around this we store the number of tracks in
        // `this.numTracks`
        (0, _utils.visitPositionedTracks)(this.props.tracks, function () {
          return _this4.numTracks++;
        });

        // With `this.reset ||` we ensure that subsequent updates do not unset the
        // `this.reset = true`. Only `this.checkAllTilesetInfoReceived()` should set
        // `this.reset` to `false`.
        this.reset = this.reset || numPrevTracks === 0 && this.numTracks > 0;

        if (!this.numTracks) this.tracksByUidInit = {};

        return toUpdate;
      }

      return shouldComponentUpdate;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillUpdate',
    value: function () {
      function UNSAFE_componentWillUpdate() {
        /**
         * Need to determine the offset of this element relative to the canvas on which stuff
         * will be drawn
         */
      }

      return UNSAFE_componentWillUpdate;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate(prevProps, prevState) {
        var _this5 = this;

        if (prevState.rangeSelection !== this.state.rangeSelection) {
          var genomicRange = [null, null]; // Default range

          if (this.state.defaultChromSizes && this.state.rangeSelection.every(function (range) {
            return range && range.length;
          })) {
            // Convert data into genomic loci
            genomicRange = this.state.rangeSelection.map(function (range) {
              return _utils.dataToGenomicLoci.apply(undefined, (0, _toConsumableArray3['default'])(range).concat([_this5.state.defaultChromSizes]));
            });
          }

          this.props.onRangeSelection({
            dataRange: this.state.rangeSelection,
            genomicRange: genomicRange
          });
        }

        if (prevProps.tracks.center !== this.props.tracks.center) {
          // this.getDefaultChromSizes();
        }

        if (this.state.addTrackPosition || this.props.addTrackPosition) {
          this.props.modal.open(_react2['default'].createElement(_AddTrackDialog2['default'], {
            host: this.state.addTrackHost,
            onCancel: this.handleNoTrackAddedBound,
            onTracksChosen: this.handleTracksAddedBound,
            position: this.state.addTrackPosition || this.props.addTrackPosition,
            trackSourceServers: this.props.trackSourceServers
          }));
        }

        if (this.state.addDivisorDialog) {
          var series = this.state.addDivisorDialog;

          this.props.modal.open(_react2['default'].createElement(_AddTrackDialog2['default'], {
            datatype: _configs.TRACKS_INFO_BY_TYPE[series.type].datatype[0],
            host: this.state.addTrackHost,
            onCancel: function () {
              function onCancel() {
                _this5.setState({ addDivisorDialog: null });
              }

              return onCancel;
            }(),
            onTracksChosen: function () {
              function onTracksChosen(newTrack) {
                _this5.handleDivisorChosen(series, newTrack);
              }

              return onTracksChosen;
            }(),
            trackSourceServers: this.props.trackSourceServers
          }));
        }
      }

      return componentDidUpdate;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        var _this6 = this;

        this.closing = true;

        this.removeEventListeners();
        this.pubSubs.forEach(function (subscription) {
          return _this6.props.pubSub.unsubscribe(subscription);
        });
      }

      return componentWillUnmount;
    }()
  }, {
    key: 'addUidsToTracks',
    value: function () {
      function addUidsToTracks(positionedTracks) {
        (0, _keys2['default'])(positionedTracks).forEach(function (position) {
          positionedTracks[position].forEach(function (track) {
            track.uid = track.uid || _slugid2['default'].nice();
          });
        });
      }

      return addUidsToTracks;
    }()

    /*
    getDefaultChromSizes() {
      try {
        const centralHeatmap = this.findCentralHeatmapTrack(
          this.props.tracks.center
        );
        this.getChromInfo = chromInfo
          .get(`${centralHeatmap.server}/chrom-sizes/?id=${centralHeatmap.tilesetUid}`)
          .then(defaultChromSizes => this.setState({ defaultChromSizes }));
      } catch (err) {  }
    }
    */

  }, {
    key: 'contextMenuHandler',
    value: function () {
      function contextMenuHandler(e) {
        if (!this.divTiledPlot) return;

        var bBox = this.divTiledPlot.getBoundingClientRect();
        var isClickWithin = (0, _utils.isWithin)(e.clientX, e.clientY, bBox.left, bBox.left + bBox.width, bBox.top, bBox.top + bBox.height);

        if (!isClickWithin) return;

        var mousePos = [e.clientX, e.clientY];
        // Relative mouse position
        var canvasMousePos = (0, _d3Selection.clientPoint)(this.divTiledPlot, e);

        // the x and y values of the rendered plots
        // will be used if someone decides to draw a horizontal or vertical
        // rule
        var xVal = this.trackRenderer.zoomedXScale.invert(canvasMousePos[0]);
        var yVal = this.trackRenderer.zoomedYScale.invert(canvasMousePos[1]);

        var contextMenuCustomItems = null;
        if (e.hgCustomItems) {
          contextMenuCustomItems = e.hgCustomItems.map(function (item) {
            return _react2['default'].createElement(
              _ContextMenuItem2['default'],
              { key: item.key, onClick: item.onClick },
              item.text
            );
          });
        }

        this.setState({
          contextMenuCustomItems: contextMenuCustomItems,
          contextMenuPosition: {
            left: mousePos[0],
            top: mousePos[1],
            canvasLeft: canvasMousePos[0] + this.trackRenderer.xPositionOffset,
            canvasTop: canvasMousePos[1] + this.trackRenderer.yPositionOffset
          },
          contextMenuDataX: xVal,
          contextMenuDataY: yVal
        });
      }

      return contextMenuHandler;
    }()
  }, {
    key: 'measureSize',
    value: function () {
      function measureSize() {
        if (this.element.clientWidth > 0 && this.element.clientHeight > 0) {
          this.setState({
            sizeMeasured: true,
            width: this.element.clientWidth,
            height: this.element.clientHeight
          });
        }
      }

      return measureSize;
    }()
  }, {
    key: 'handleTrackOptionsChanged',
    value: function () {
      function handleTrackOptionsChanged(trackUid, newOptions) {
        /**
         * The drawing options for a track have changed.
         */
        return this.props.onTrackOptionsChanged(trackUid, newOptions);
      }

      return handleTrackOptionsChanged;
    }()
  }, {
    key: 'handleScalesChanged',
    value: function () {
      function handleScalesChanged(x, y) {
        this.xScale = x;
        this.yScale = y;

        this.props.onScalesChanged(x, y);
      }

      return handleScalesChanged;
    }()

    /**
     * We've received information about a tileset from the server. Register it
     * with the track definition.
     * @param trackUid (string): The identifier for the track
     * @param tilesetInfo (object): Information about the track (hopefully including
     *                              its name.
     */

  }, {
    key: 'handleTilesetInfoReceived',
    value: function () {
      function handleTilesetInfoReceived(trackUid, tilesetInfo) {
        var track = (0, _utils.getTrackByUid)(this.props.tracks, trackUid);

        if (!track) {
          console.warn('Strange, track not found:', trackUid);
          return;
        }

        this.tracksByUidInit[track.uid] = true;
        this.checkAllTilesetInfoReceived();

        if (!track.options) {
          track.options = {};
        }

        // track.options.name = tilesetInfo.name;
        track.name = tilesetInfo.name;
        track.maxWidth = tilesetInfo.max_width;
        track.transforms = tilesetInfo.transforms;
        track.aggregationModes = tilesetInfo.aggregation_modes;
        track.header = tilesetInfo.header;
        track.binsPerDimension = tilesetInfo.bins_per_dimension;
        if (tilesetInfo.resolutions) {
          track.maxZoom = tilesetInfo.resolutions.length - 1;
          track.resolutions = tilesetInfo.resolutions;
        } else {
          track.maxZoom = tilesetInfo.max_zoom;
        }
        track.coordSystem = tilesetInfo.coordSystem;
        track.datatype = tilesetInfo.datatype;
      }

      return handleTilesetInfoReceived;
    }()

    /**
     * Check if all track which are expecting a tileset info have been loaded.
     */

  }, {
    key: 'checkAllTilesetInfoReceived',
    value: function () {
      function checkAllTilesetInfoReceived() {
        var _this7 = this;

        // Do nothing if HiGlass initialized already
        if (this.state.init && !this.reset || !this.trackRenderer || !this.props.zoomToDataExtentOnInit()) {
          return;
        }

        // Get the total number of track that are expecting a tilesetInfo
        var allTracksWithTilesetInfos = (0, _keys2['default'])(this.trackRenderer.trackDefObjects)
        // Map track to a list of tileset infos
        .map(function (trackUuid) {
          var track = _this7.trackRenderer.trackDefObjects[trackUuid].trackObject;
          if (track.childTracks) return track.childTracks;
          return track;
        })
        // Needed because of combined tracks
        .reduce(function (a, b) {
          return a.concat(b);
        }, [])
        // We distinguish between tracks that need a tileset info and those whoch
        // don't by comparing `undefined` vs something else, i.e., tracks that
        // need a tileset info will be initialized with `this.tilesetInfo = null;`.
        .filter(function (_ref) {
          var tilesetInfo = _ref.tilesetInfo;
          return typeof tilesetInfo !== 'undefined' && tilesetInfo !== true;
        });

        // Only count tracks that are suppose to get a tileset
        var loadedTilesetInfos = (0, _values2['default'])(this.tracksByUidInit).filter(function (x) {
          return x;
        }).length;

        if (allTracksWithTilesetInfos.length === loadedTilesetInfos) {
          this.setState({ init: true });
          this.reset = false;
          this.handleZoomToData();
        }
      }

      return checkAllTilesetInfoReceived;
    }()
  }, {
    key: 'handleOverlayMouseEnter',
    value: function () {
      function handleOverlayMouseEnter(uid) {
        this.setState({
          mouseOverOverlayUid: uid
        });
      }

      return handleOverlayMouseEnter;
    }()
  }, {
    key: 'handleOverlayMouseLeave',
    value: function () {
      function handleOverlayMouseLeave(uid) {
        if (uid === this.state.mouseOverOverlayUid) {
          this.setState({
            mouseOverOverlayUid: null
          });
        }
      }

      return handleOverlayMouseLeave;
    }()
  }, {
    key: 'handleTrackPositionChosen',
    value: function () {
      function handleTrackPositionChosen(pTrack) {
        this.setState({ mouseOverOverlayUid: null });
        this.props.chooseTrackHandler(pTrack.track.uid);
      }

      return handleTrackPositionChosen;
    }()
  }, {
    key: 'handleNoTrackAdded',
    value: function () {
      function handleNoTrackAdded() {
        /*
         * User hit cancel on the AddTrack dialog so we need to
         * just close it and do nothin
         */
        this.trackToReplace = null;

        this.props.onNoTrackAdded();

        this.setState({
          addTrackPosition: null,
          addTrackHost: null
        });
      }

      return handleNoTrackAdded;
    }()
  }, {
    key: 'handleAddDivisor',
    value: function () {
      function handleAddDivisor(series) {
        this.setState({
          addDivisorDialog: series
        });
      }

      return handleAddDivisor;
    }()

    /**
     * The user has selected a track that they wish to use to normalize another
     * track.
     */

  }, {
    key: 'handleDivisorChosen',
    value: function () {
      function handleDivisorChosen(series, newTrack) {
        this.setState({
          addDivisorDialog: null
        });

        var numerator = series.data ? {
          server: series.data.server,
          tilesetUid: series.data.tilesetUid
        } : {
          server: series.server,
          tilesetUid: series.tilesetUid
        };

        var denominator = {
          server: newTrack[0].server,
          tilesetUid: newTrack[0].uuid
        };

        this.handleChangeTrackData(series.uid, {
          type: 'divided',
          children: [numerator, denominator]
        });
      }

      return handleDivisorChosen;
    }()
  }, {
    key: 'handleDivideSeries',
    value: function () {
      function handleDivideSeries(seriesUid) {
        /*
         * We want to create a new series that consists of this series
         * being divided by another. Useful for comparing two tracks
         * by division.
         *
         * Will start working with just heatmaps and then progress to
         * other track types.
         */
      }

      return handleDivideSeries;
    }()
  }, {
    key: 'handleAddSeries',
    value: function () {
      function handleAddSeries(trackUid) {
        var trackPosition = (0, _utils.getTrackPositionByUid)(this.props.tracks, trackUid);
        var track = (0, _utils.getTrackByUid)(this.props.tracks, trackUid);

        this.setState({
          addTrackPosition: trackPosition,
          addTrackHost: track
        });
      }

      return handleAddSeries;
    }()
  }, {
    key: 'handleReplaceTrack',
    value: function () {
      function handleReplaceTrack(uid, orientation) {
        /**
         * @param uid (string): The uid of the track to replace
         * @param orientation (string): The place where to put the new track
         */
        this.trackToReplace = uid;
        this.handleAddTrack(orientation);
      }

      return handleReplaceTrack;
    }()
  }, {
    key: 'handleAddTrack',
    value: function () {
      function handleAddTrack(position) {
        this.setState({
          addTrackPosition: position,
          addTrackHost: null
        });
      }

      return handleAddTrack;
    }()
  }, {
    key: 'handleResizeTrack',
    value: function () {
      function handleResizeTrack(uid, width, height) {
        var tracks = this.state.tracks;


        for (var trackType in tracks) {
          var theseTracks = tracks[trackType];

          var filteredTracks = theseTracks.filter(function (d) {
            return d.uid === uid;
          });

          if (filteredTracks.length > 0) {
            filteredTracks[0].width = width;
            filteredTracks[0].height = height;
          }
        }

        this.setState({
          tracks: tracks,
          forceUpdate: Math.random()
        });

        this.props.onResizeTrack();
      }

      return handleResizeTrack;
    }()
  }, {
    key: 'closeMenus',
    value: function () {
      function closeMenus() {
        this.setState({
          closeTrackMenuId: null,
          configTrackMenuId: null,
          contextMenuPosition: null,
          contextMenuCustomItems: null
        });
      }

      return closeMenus;
    }()
  }, {
    key: 'handleLockValueScale',
    value: function () {
      function handleLockValueScale(uid) {
        this.closeMenus();

        this.props.onLockValueScale(uid);
      }

      return handleLockValueScale;
    }()
  }, {
    key: 'handleUnlockValueScale',
    value: function () {
      function handleUnlockValueScale(uid) {
        this.closeMenus();

        this.props.onUnlockValueScale(uid);
      }

      return handleUnlockValueScale;
    }()
  }, {
    key: 'handleCloseTrack',
    value: function () {
      function handleCloseTrack(uid) {
        this.closeMenus();

        this.props.onCloseTrack(uid);
      }

      return handleCloseTrack;
    }()
  }, {
    key: 'handleChangeTrackType',
    value: function () {
      function handleChangeTrackType(uid, newType) {
        // close the config track menu
        this.closeMenus();

        // change the track type
        this.props.onChangeTrackType(uid, newType);
      }

      return handleChangeTrackType;
    }()

    /**
     * Change this tracks data section so that it
     * is either of type "divided" or the "divided"
     * type is removed
     */

  }, {
    key: 'handleChangeTrackData',
    value: function () {
      function handleChangeTrackData(uid, newData) {
        this.closeMenus();

        this.props.onChangeTrackData(uid, newData);
      }

      return handleChangeTrackData;
    }()
  }, {
    key: 'handleTracksAdded',
    value: function () {
      function handleTracksAdded(newTracks, position, host) {
        /**
         * Arguments
         * ---------
         *  newTracks: {object}
         *      The description of the track, including its type
         *      and data source.
         *  position: string
         *      Where to place this track
         *  host: track
         *    The existing track that we're adding the new one to
         *
         * Returns
         * -------
         *
         *  { uid: "", width: }:
         *      The trackConfig object describing this track. Essentially
         *      the newTrack object passed in with some extra information
         *      (such as the uid) added.
         */

        if (this.trackToReplace) {
          this.handleCloseTrack(this.trackToReplace);
          this.trackToReplace = null;
        }

        // if host is defined, then we're adding a new series
        // further down the chain a combined track will be created
        this.props.onTracksAdded(newTracks, position, host);

        this.setState({
          addTrackPosition: null,
          addTrackHost: null
        });

        return newTracks;
      }

      return handleTracksAdded;
    }()
  }, {
    key: 'handleCloseTrackMenuOpened',
    value: function () {
      function handleCloseTrackMenuOpened(uid, clickPosition) {
        this.setState({
          closeTrackMenuId: uid,
          closeTrackMenuLocation: clickPosition
        });
      }

      return handleCloseTrackMenuOpened;
    }()
  }, {
    key: 'handleCloseContextMenu',
    value: function () {
      function handleCloseContextMenu() {
        this.setState({
          contextMenuCustomItems: null,
          contextMenuPosition: null,
          contextMenuDataX: null,
          contextMenuDataY: null
        });
      }

      return handleCloseContextMenu;
    }()
  }, {
    key: 'handleCloseTrackMenuClosed',
    value: function () {
      function handleCloseTrackMenuClosed() {
        this.setState({
          closeTrackMenuId: null
        });
      }

      return handleCloseTrackMenuClosed;
    }()
  }, {
    key: 'handleConfigTrackMenuOpened',
    value: function () {
      function handleConfigTrackMenuOpened(uid, clickPosition) {
        // let orientation = getTrackPositionByUid(uid);
        this.closeMenus();

        this.setState({
          configTrackMenuId: uid,
          configTrackMenuLocation: clickPosition
        });
      }

      return handleConfigTrackMenuOpened;
    }()
  }, {
    key: 'handleConfigureTrack',
    value: function () {
      function handleConfigureTrack(track, configComponent) {
        this.setState({
          configTrackMenuId: null,
          trackOptions: { track: track, configComponent: configComponent }
        });

        this.closeMenus();
      }

      return handleConfigureTrack;
    }()
  }, {
    key: 'handleSortEnd',
    value: function () {
      function handleSortEnd(sortedTracks) {
        this.setState(function (prevState) {
          // some tracks were reordered in the list so we need to reorder them in the original
          // dataset
          var tracks = prevState.tracks;

          // calculate the positions of the sortedTracks
          var positions = {};
          for (var i = 0; i < sortedTracks.length; i++) {
            positions[sortedTracks[i].uid] = i;
          }

          for (var trackType in tracks) {
            var theseTracks = tracks[trackType];
            if (!theseTracks.length) {
              continue;
            }

            if (theseTracks[0].uid in positions) {
              var newTracks = new Array(theseTracks.length);
              // this is the right track position
              for (var _i = 0; _i < theseTracks.length; _i++) {
                newTracks[positions[theseTracks[_i].uid]] = theseTracks[_i];
              }

              tracks[trackType] = newTracks;
            }
          }
          return {
            tracks: tracks,
            forceUpdate: Math.random()
          };
        });
      }

      return handleSortEnd;
    }()
  }, {
    key: 'createTracksAndLocations',
    value: function () {
      function createTracksAndLocations() {
        var tracksAndLocations = [];
        var tracks = this.state.tracks;


        _configs.TRACK_LOCATIONS.forEach(function (location) {
          if (tracks[location]) {
            tracks[location].forEach(function (track) {
              if (track.contents) {
                track.contents.forEach(function (content) {
                  content.position = location;
                });
              }
              // track.position is used in TrackRenderer to determine
              // whether to use LeftTrackModifier
              track.position = location;
              tracksAndLocations.push({ track: track, location: location });
            });
          }
        });

        return tracksAndLocations;
      }

      return createTracksAndLocations;
    }()

    /**
     * Calculate where a track is absoluately positioned within the drawing area
     *
     * @param track: The track object (with members, e.g. track.uid, track.width,
     *   track.height)
     * @param location: Where it's being plotted (e.g. 'top', 'bottom')
     * @return: The position of the track and it's height and width
     *          (e.g. {left: 10, top: 20, width: 30, height: 40}
     */

  }, {
    key: 'calculateTrackPosition',
    value: function () {
      function calculateTrackPosition(track, location) {
        var top = this.props.paddingTop;
        var bottom = this.props.paddingBottom;
        var left = this.props.paddingLeft;
        var right = this.props.paddingRight;
        var width = this.centerWidth;
        var height = track.height;
        var offsetX = 0;
        var offsetY = 0;

        switch (location) {
          case 'top':
            left += this.leftWidth;

            for (var i = 0; i < this.state.tracks.top.length; i++) {
              if (this.state.tracks.top[i].uid === track.uid) {
                break;
              } else {
                top += this.state.tracks.top[i].height;
              }
            }

            break;

          case 'bottom':
            left += this.leftWidth;
            top += this.topHeight + this.centerHeight + this.galleryDim;

            for (var _i2 = 0; _i2 < this.state.tracks.bottom.length; _i2++) {
              if (this.state.tracks.bottom[_i2].uid === track.uid) {
                break;
              } else {
                top += this.state.tracks.bottom[_i2].height;
              }
            }

            break;

          case 'left':
            top += this.topHeight;
            width = track.width;
            height = this.centerHeight;

            for (var _i3 = 0; _i3 < this.state.tracks.left.length; _i3++) {
              if (this.state.tracks.left[_i3].uid === track.uid) {
                break;
              } else {
                left += this.state.tracks.left[_i3].width;
              }
            }

            break;

          case 'right':
            left += this.leftWidth + this.centerWidth + this.galleryDim;
            top += this.topHeight;
            width = track.width;
            height = this.centerHeight;

            for (var _i4 = 0; _i4 < this.state.tracks.right.length; _i4++) {
              if (this.state.tracks.right[_i4].uid === track.uid) {
                break;
              } else {
                left += this.state.tracks.right[_i4].width;
              }
            }

            break;

          case 'center':
            left += this.leftWidth;
            top += this.topHeight;
            height = this.centerHeight;

            break;

          case 'gallery':
            left += this.leftWidthNoGallery;
            top += this.topHeightNoGallery;
            width = this.state.width - this.leftWidthNoGallery - this.rightWidthNoGallery - this.props.paddingLeft;
            height = this.state.height - this.topHeightNoGallery - this.bottomHeightNoGallery - this.props.paddingTop;
            offsetX = this.galleryDim;
            offsetY = this.galleryDim;

            for (var _i5 = 0; _i5 < this.state.tracks.gallery.length; _i5++) {
              if (this.state.tracks.gallery[_i5].uid === track.uid) {
                break;
              } else {
                width -= 2 * this.state.tracks.gallery[_i5].height;
                height -= 2 * this.state.tracks.gallery[_i5].height;
                left += this.state.tracks.gallery[_i5].height;
                top += this.state.tracks.gallery[_i5].height;
                offsetX -= this.state.tracks.gallery[_i5].height;
                offsetY -= this.state.tracks.gallery[_i5].height;
              }
            }

            for (var _i6 = 0; _i6 < this.state.tracks.right.length; _i6++) {
              right += this.state.tracks.right[_i6].width;
            }
            for (var _i7 = 0; _i7 < this.state.tracks.bottom.length; _i7++) {
              bottom += this.state.tracks.bottom[_i7].height;
            }

            track.offsetX = offsetX;
            track.offsetY = offsetY;
            track.offsetTop = top;
            track.offsetRight = right;
            track.offsetBottom = bottom;
            track.offsetLeft = left;

            break;

          case 'whole':
          default:
            width = this.leftWidth + this.centerWidth + this.rightWidth;
            height = this.topHeight + this.centerHeight + this.bottomHeight;
        }

        if (_configs.TRACK_LOCATIONS.indexOf(location) === -1) {
          console.warn('Track with unknown position present:', location, track);
        }

        return {
          left: left,
          top: top,
          width: width,
          height: height,
          track: track
        };
      }

      return calculateTrackPosition;
    }()

    /**
     * Find a central heatmap track among all displayed tracks
     *
     * @param  {Array}  tracks  Tracks to be searched.
     * @return  {Object}  The first central heatmap track or `undefined`.
     */

  }, {
    key: 'findCentralHeatmapTrack',
    value: function () {
      function findCentralHeatmapTrack(tracks) {
        for (var i = 0; i < tracks.length; i++) {
          if (tracks[i].type === 'combined') {
            return this.findCentralHeatmapTrack(tracks[i].contents);
          }
          if (tracks[i].type === 'heatmap') return tracks[i];
        }
        return undefined;
      }

      return findCentralHeatmapTrack;
    }()
  }, {
    key: 'trackUuidToOrientation',
    value: function () {
      function trackUuidToOrientation(trackUuid) {
        /**
         * Obtain the orientation of the track defined
         * by the Uuid and return it.
         *
         * Parameters
         * ----------
         *  trackUuid: 'xsdfsd'
         *
         * Returns
         * -------
         *  orientation: '1d-horizontal'
         */
      }

      return trackUuidToOrientation;
    }()
  }, {
    key: 'overlayTracks',
    value: function () {
      function overlayTracks(positionedTracks) {
        var _this8 = this;

        /**
         * Return the current set of overlay tracks.
         *
         * These have no positions of their own because
         * they depend on other tracks to be drawn first.
         *
         * Parameters
         * ----------
         *  positionedTracks: The tracks along with their positions
         *
         * Returns
         * -------
         *  overlaysWithOrientationsAndPositions: []
         *
         */
        if (this.props.overlays) {
          var overlayDefs = this.props.overlays.filter(function (overlayTrack) {
            return overlayTrack.includes && overlayTrack.includes.length;
          }).map(function (overlayTrack) {
            var type = overlayTrack.type ? 'overlay-' + String(overlayTrack.type) + '-track' : 'overlay-track';

            var overlayDef = (0, _assign2['default'])({}, overlayTrack, {
              uid: overlayTrack.uid || _slugid2['default'].nice(),
              includes: overlayTrack.includes,
              type: type,
              options: (0, _assign2['default'])(overlayTrack.options, {
                orientationsAndPositions: overlayTrack.includes.map(function (trackUuid) {
                  // translate a trackUuid into that track's orientation
                  var includedTrack = (0, _utils.getTrackByUid)(_this8.props.tracks, trackUuid);

                  if (!includedTrack) {
                    console.warn('OverlayTrack included uid (' + String(trackUuid) + ') not found in the track list');
                    return null;
                  }

                  var trackPos = (0, _utils.getTrackPositionByUid)(_this8.props.tracks, includedTrack.uid);

                  var orientation = void 0;
                  if (trackPos === 'top' || trackPos === 'bottom') {
                    orientation = '1d-horizontal';
                  }

                  if (trackPos === 'left' || trackPos === 'right') {
                    orientation = '1d-vertical';
                  }

                  if (trackPos === 'center') {
                    orientation = '2d';
                  }

                  if (!orientation) {
                    console.warn('Only top, bottom, left, right, or center tracks can be overlaid at the moment');
                    return null;
                  }

                  var positionedTrack = positionedTracks.filter(function (track) {
                    return track.track.uid === trackUuid;
                  });

                  if (!positionedTrack.length) {
                    // couldn't find a matching track, somebody must have included
                    // an invalid uuid
                    return null;
                  }

                  var position = {
                    left: positionedTrack[0].left - _this8.props.paddingLeft,
                    top: positionedTrack[0].top - _this8.props.paddingTop,
                    width: positionedTrack[0].width,
                    height: positionedTrack[0].height
                  };

                  return {
                    orientation: orientation,
                    position: position
                  };
                }).filter(function (x) {
                  return x;
                }) // filter out null entries
              })
            });

            // the 2 * verticalMargin is to make up for the space taken away
            // in render(): this.centerHeight = this.state.height...
            return {
              top: _this8.props.paddingTop,
              left: _this8.props.paddingLeft,
              width: _this8.leftWidth + _this8.centerWidth + _this8.rightWidth,
              height: _this8.topHeight + _this8.centerHeight + _this8.bottomHeight + _this8.props.marginTop + _this8.props.marginBottom,
              track: overlayDef
            };
          });

          return overlayDefs;
        }

        return [];
      }

      return overlayTracks;
    }()
  }, {
    key: 'positionedTracks',
    value: function () {
      function positionedTracks() {
        var _this9 = this;

        /**
         * Return the current set of tracks along with their positions
         * and dimensions
         */
        var tracksAndLocations = this.createTracksAndLocations().map(function (_ref2) {
          var track = _ref2.track,
              location = _ref2.location;
          return _this9.calculateTrackPosition(track, location);
        });

        return tracksAndLocations;
      }

      return positionedTracks;
    }()
  }, {
    key: 'createTrackPositionTexts',
    value: function () {
      function createTrackPositionTexts() {
        /**
         * Create little text fields that show the position and width of
         * each track, just to show that we can calculate that and pass
         * it to the rendering context.
         */
        var positionedTracks = this.positionedTracks();
        this.createTracksAndLocations();

        var trackElements = positionedTracks.map(function (trackPosition) {
          var track = trackPosition.track;


          return _react2['default'].createElement(
            'div',
            {
              key: track.uid,
              style: {
                left: trackPosition.left,
                top: trackPosition.top,
                width: trackPosition.width,
                height: trackPosition.height,
                position: 'absolute'
              }
            },
            track.uid.slice(0, 2)
          );
        });

        return trackElements;
      }

      return createTrackPositionTexts;
    }()
  }, {
    key: 'handleExportTrackData',
    value: function () {
      function handleExportTrackData(hostTrackUid, trackUid) {
        /*
         * Export the data present in a track. Whether a track can export data is defined
         * in the track type definition in config.js
         */
        var track = (0, _utils.getTrackByUid)(this.props.tracks, trackUid);
        var trackObject = null;

        if (hostTrackUid !== trackUid) {
          // the track whose data we're trying to export is part of a combined track
          trackObject = this.trackRenderer.trackDefObjects[hostTrackUid].trackObject.createdTracks[track.uid];
        } else {
          trackObject = this.trackRenderer.trackDefObjects[hostTrackUid].trackObject;
        }

        trackObject.exportData();

        this.closeMenus();
      }

      return handleExportTrackData;
    }()

    /**
     * List all the tracks that are under this mouse position
     */

  }, {
    key: 'listTracksAtPosition',
    value: function () {
      function listTracksAtPosition(x, y) {
        var isReturnTrackObj = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

        var trackObjectsAtPosition = [];

        if (!this.trackRenderer) return [];

        for (var uid in this.trackRenderer.trackDefObjects) {
          var trackObj = this.trackRenderer.trackDefObjects[uid].trackObject;

          if (trackObj.respondsToPosition(x, y)) {
            // check if this track wishes to respond to events at position x,y
            // by default, this is true
            // it is false in tracks like the horizontal and vertical rule which only
            // wish to be identified if the mouse is directly over them

            if (isReturnTrackObj) {
              if (this.props.tracks.center) {
                if (this.props.tracks.center.contents) {
                  for (var i = 0; i < this.props.tracks.center.contents.length; i++) {
                    if (this.props.tracks.center.contents[i].uid === uid) {
                      trackObj.is2d = true;
                    }
                  }
                } else if (this.props.tracks.center && this.props.tracks.center.length && this.props.tracks.center[0].uid === uid) {
                  trackObj.is2d = true;
                }
              }

              trackObjectsAtPosition.push(trackObj);
            } else {
              trackObjectsAtPosition.push(this.trackRenderer.trackDefObjects[uid].trackDef.track);
            }
          }
        }

        return trackObjectsAtPosition;
      }

      return listTracksAtPosition;
    }()
  }, {
    key: 'listAllTrackObjects',
    value: function () {
      function listAllTrackObjects() {
        /**
         * Get a list of all the track objects in this
         * view.
         *
         * These are the objects that do the drawing, not the track
         * definitions in the viewconf.
         *
         * Returns
         * -------
         *  trackObjects: []
         *    A list of the track objects in this view
         */
        var trackObjectsToCheck = [];

        for (var uid in this.trackRenderer.trackDefObjects) {
          var tdo = this.trackRenderer.trackDefObjects[uid];

          // if this is a combined track then we need to recurse into its
          // subtracks
          if (tdo.trackObject.createdTracks) {
            for (var uid1 in tdo.trackObject.createdTracks) {
              var trackObject = tdo.trackObject.createdTracks[uid1];
              trackObjectsToCheck.push(trackObject);
            }
          } else {
            trackObjectsToCheck.push(tdo.trackObject);
          }
        }

        return trackObjectsToCheck;
      }

      return listAllTrackObjects;
    }()
  }, {
    key: 'handleZoomToData',
    value: function () {
      function handleZoomToData() {
        /**
         * Try to zoom in or out so that the bounds of the view correspond to the
         * extent of the data.
         */
        var maxSafeInt = _maxSafeInteger2['default'];
        var minSafeInt = _minSafeInteger2['default'];
        var minPos = [maxSafeInt, maxSafeInt];
        var maxPos = [minSafeInt, minSafeInt];

        var trackObjectsToCheck = this.listAllTrackObjects();

        // go through every track definition
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(trackObjectsToCheck), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var trackObject = _step.value;

            // get the minimum and maximum positions of all the subtracks
            if (trackObject.tilesetInfo) {
              if (trackObject.tilesetInfo.min_pos) {
                for (var j = 0; j < trackObject.tilesetInfo.min_pos.length; j++) {
                  if (trackObject.tilesetInfo.min_pos[j] < minPos[j]) {
                    minPos[j] = trackObject.tilesetInfo.min_pos[j];
                  }

                  if (trackObject.tilesetInfo.max_pos[j] > maxPos[j]) {
                    maxPos[j] = trackObject.tilesetInfo.max_pos[j];
                  }
                }
              }
            }
          }

          // set the initial domain
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var left = this.trackRenderer.currentProps.paddingLeft + this.trackRenderer.currentProps.leftWidth;
        var newXDomain = [left, left + this.trackRenderer.currentProps.centerWidth].map(this.trackRenderer.zoomTransform.rescaleX(this.trackRenderer.xScale).invert);

        var top = this.trackRenderer.currentProps.paddingTop + this.trackRenderer.currentProps.topHeight;
        var newYDomain = [top, top + this.trackRenderer.currentProps.centerHeight].map(this.trackRenderer.zoomTransform.rescaleY(this.trackRenderer.yScale).invert);

        // reset the zoom transform
        this.trackRenderer.zoomTransform.k = 1;

        this.trackRenderer.zoomTransform.x = 0;
        this.trackRenderer.zoomTransform.y = 0;
        this.trackRenderer.applyZoomTransform();

        if (minPos[0] < _maxSafeInteger2['default'] && maxPos[0] > _minSafeInteger2['default']) {
          newXDomain = [minPos[0], maxPos[0]];
        }

        if (minPos[1] < _maxSafeInteger2['default'] && maxPos[1] > _minSafeInteger2['default']) {
          newYDomain = [minPos[1], maxPos[1]];
        }

        this.props.onDataDomainChanged(newXDomain, newYDomain);
      }

      return handleZoomToData;
    }()
  }, {
    key: 'resetViewport',
    value: function () {
      function resetViewport() {
        // Reset the zoom transform
        this.trackRenderer.zoomTransform.k = 1;
        this.trackRenderer.zoomTransform.x = 0;
        this.trackRenderer.zoomTransform.y = 0;
        this.trackRenderer.applyZoomTransform();

        this.props.onDataDomainChanged(this.props.initialXDomain, this.props.initialYDomain);
      }

      return resetViewport;
    }()
  }, {
    key: 'updatablePropsToString',
    value: function () {
      function updatablePropsToString(props) {
        return (0, _stringify2['default'])({
          tracks: props.tracks,
          overlays: props.overlays,
          viewOptions: props.viewOptions,
          uid: props.uid,
          addTrackPosition: props.addTrackPosition,
          editable: props.editable,
          marginTop: props.marginTop,
          marginBottom: props.marginBottom,
          marginLeft: props.marginLeft,
          marginRight: props.marginRight,
          paddingTop: props.paddingTop,
          paddingBottom: props.paddingBottom,
          paddingLeft: props.paddingLeft,
          paddingRight: props.paddingRight,
          mouseTool: props.mouseTool,
          initialXDomain: props.initialXDomain,
          initialYDomain: props.initialYDomain,
          trackSourceServers: props.trackSourceServers,
          zoomable: props.zoomable,
          draggingHappending: props.draggingHappening
        });
      }

      return updatablePropsToString;
    }()
  }, {
    key: 'getXYScales',
    value: function () {
      function getXYScales() {
        if (this.trackRenderer) {
          this.xScale = this.trackRenderer.currentXScale;
          this.yScale = this.trackRenderer.currentYScale;
        }
      }

      return getXYScales;
    }()

    /**
     * Translate view to data location.
     *
     * @description
     * The view location is in pixels relative to the browser window. The data
     * location is given by the scaling relative to the initial x and y domains.
     * And the genomic location depends on the chrom sizes.
     *
     * @method  rangeViewToDataLoci
     * @author  Fritz Lekschas
     * @date    2018-01-14
     * @param  {Array}  range  Selected view range
     * @param  {Function}  scale  View to data scaling
     * @return  {Array}  2D array of data locations
     */

  }, {
    key: 'rangeViewToDataLoci',
    value: function () {
      function rangeViewToDataLoci(range, scale) {
        if (!scale) return [null, null];

        return [parseInt(scale.invert(range[0]), 10), parseInt(scale.invert(range[1]), 10)];
      }

      return rangeViewToDataLoci;
    }()
  }, {
    key: 'rangeSelectionResetHandler',
    value: function () {
      function rangeSelectionResetHandler() {
        if (this.state.rangeSelectionMaster) {
          this.setState({
            is1dRangeSelection: null,
            rangeSelection: [null, null],
            rangeSelectionMaster: null,
            rangeSelectionEnd: false
          });
        }
      }

      return rangeSelectionResetHandler;
    }()
  }, {
    key: 'rangeSelection1dEndHandler',
    value: function () {
      function rangeSelection1dEndHandler(axis) {
        var _this10 = this;

        if (!this.xScale || !this.yScale) {
          this.getXYScales();
        }

        var scale = axis === 'x' ? this.xScale : this.yScale;

        return function (range) {
          _this10.setState(function (prevState) {
            var newRangeSelection = prevState.is1dRangeSelection ? [null, null] : prevState.rangeSelection.slice();

            var accessor = !_this10.state.is1dRangeSelection && axis === 'y' ? 1 : 0;

            var dataPos = _this10.rangeViewToDataLoci(range, scale);

            // Enforce range selection size constraints
            var size = dataPos[1] - dataPos[0];
            if (_this10.props.rangeSelection1dSize[0] > size) {
              // Blow selection up
              var center = dataPos[0] + size / 2;
              dataPos = [center - _this10.props.rangeSelection1dSize[0] / 2, center + _this10.props.rangeSelection1dSize[0] / 2];
            } else if (_this10.props.rangeSelection1dSize[1] < size) {
              // Shrink selection
              var _center = dataPos[0] + size / 2;
              dataPos = [_center - _this10.props.rangeSelection1dSize[1] / 2, _center + _this10.props.rangeSelection1dSize[1] / 2];
            }

            newRangeSelection[accessor] = dataPos;

            if (_this10.props.rangeSelectionToInt) {
              newRangeSelection[accessor] = newRangeSelection[accessor].map(function (x) {
                return Math.round(x);
              });
            }

            return {
              rangeSelection: newRangeSelection,
              rangeSelectionEnd: true
            };
          });
        };
      }

      return rangeSelection1dEndHandler;
    }()
  }, {
    key: 'rangeSelection1dHandler',
    value: function () {
      function rangeSelection1dHandler(axis) {
        var _this11 = this;

        if (!this.xScale || !this.yScale) this.getXYScales();

        var scale = axis === 'x' ? this.xScale : this.yScale;

        return function (range) {
          _this11.setState(function (prevState) {
            var newRangeSelection = prevState.is1dRangeSelection ? [null, null] : prevState.rangeSelection.slice();

            var accessor = !prevState.is1dRangeSelection && axis === 'y' ? 1 : 0;

            newRangeSelection[accessor] = _this11.rangeViewToDataLoci(range, scale);

            return {
              rangeSelection: newRangeSelection,
              rangeSelectionEnd: false
            };
          });
        };
      }

      return rangeSelection1dHandler;
    }()
  }, {
    key: 'rangeSelection1dStartHandler',
    value: function () {
      function rangeSelection1dStartHandler() {
        if (!this.state.rangeSelectionMaster) {
          this.setState({
            is1dRangeSelection: true,
            rangeSelectionMaster: true,
            rangeSelectionEnd: false
          });
        }
      }

      return rangeSelection1dStartHandler;
    }()
  }, {
    key: 'rangeSelection2dHandler',
    value: function () {
      function rangeSelection2dHandler(range) {
        if (!this.xScale || !this.yScale) this.getXYScales();

        this.setState({
          rangeSelection: [this.rangeViewToDataLoci(range[0], this.xScale), this.rangeViewToDataLoci(range[1], this.yScale)],
          rangeSelectionEnd: false
        });
      }

      return rangeSelection2dHandler;
    }()
  }, {
    key: 'rangeSelection2dStartHandler',
    value: function () {
      function rangeSelection2dStartHandler() {
        if (!this.state.rangeSelectionMaster) {
          this.setState({
            is1dRangeSelection: false,
            rangeSelectionMaster: true,
            rangeSelectionEnd: false
          });
        }
      }

      return rangeSelection2dStartHandler;
    }()
  }, {
    key: 'rangeSelection2dEndHandler',
    value: function () {
      function rangeSelection2dEndHandler(range) {
        var _this12 = this;

        if (!this.xScale || !this.yScale) this.getXYScales();

        var dataPosX = this.rangeViewToDataLoci(range[0], this.xScale);
        var dataPosY = this.rangeViewToDataLoci(range[1], this.yScale);
        var dataPos = [dataPosX, dataPosY];

        // Enforce range selection size constraints
        var sizeX = dataPosX[1] - dataPosX[0];
        var sizeY = dataPosY[1] - dataPosY[0];
        var size = [sizeX, sizeY];

        dataPos.forEach(function (pos, i) {
          if (_this12.props.rangeSelection1dSize[0] > size[i]) {
            // Blow selection up
            var center = pos[0] + Math.round(size[i] / 2);
            pos[0] = center - _this12.props.rangeSelection1dSize[0] / 2;
            pos[1] = center + _this12.props.rangeSelection1dSize[0] / 2;
          } else if (_this12.props.rangeSelection1dSize[1] < size[i]) {
            // Shrink selection
            var _center2 = pos[0] + Math.round(size[i] / 2);
            pos[0] = _center2 - _this12.props.rangeSelection1dSize[1] / 2;
            pos[1] = _center2 + _this12.props.rangeSelection1dSize[1] / 2;
          }
        });

        if (this.props.rangeSelectionToInt) {
          dataPos = dataPos.map(function (x) {
            return x.map(function (y) {
              return Math.round(y);
            });
          });
        }

        this.setState({
          rangeSelection: dataPos,
          rangeSelectionEnd: true
        });
      }

      return rangeSelection2dEndHandler;
    }()
  }, {
    key: 'getContextMenu',
    value: function () {
      function getContextMenu() {
        var _this13 = this;

        if (this.state.contextMenuPosition) {
          var relevantTracks = this.listTracksAtPosition(this.state.contextMenuPosition.canvasLeft, this.state.contextMenuPosition.canvasTop);

          return _react2['default'].createElement(
            _PopupMenu2['default'],
            { onMenuClosed: this.closeMenusBound },
            _react2['default'].createElement(_ViewContextMenu2['default'], {
              closeMenu: this.closeMenusBound,
              coords: [this.state.contextMenuDataX, this.state.contextMenuDataY],
              customItems: this.state.contextMenuCustomItems,
              onAddDivisor: this.handleAddDivisorBound,
              onAddSeries: this.handleAddSeriesBound
              // Can only add one new track at a time
              // because "whole" tracks are always drawn on top of each other,
              // the notion of Series is unnecessary and so 'host' is null
              , onAddTrack: function () {
                function onAddTrack(newTrack) {
                  _this13.props.onTracksAdded([newTrack], newTrack.position, null);
                  _this13.handleCloseContextMenu();
                }

                return onAddTrack;
              }(),
              onChangeTrackData: this.handleChangeTrackDataBound,
              onChangeTrackType: this.handleChangeTrackTypeBound,
              onCloseTrack: this.handleCloseTrackBound,
              onConfigureTrack: this.handleConfigureTrackBound,
              onExportData: this.handleExportTrackDataBound,
              onLockValueScale: this.handleLockValueScaleBound,
              onReplaceTrack: this.handleReplaceTrackBound,
              onTrackOptionsChanged: this.handleTrackOptionsChangedBound,
              onUnlockValueScale: this.handleUnlockValueScaleBound,
              orientation: 'right',
              position: this.state.contextMenuPosition,
              theme: this.props.theme,
              tracks: relevantTracks,
              trackSourceServers: this.props.trackSourceServers
            })
          );
        }

        return null;
      }

      return getContextMenu;
    }()

    /**
     * Draw an overlay that shows the positions of all the different
     * track areas
     */

  }, {
    key: 'getIdealizedTrackPositionsOverlay',
    value: function () {
      function getIdealizedTrackPositionsOverlay() {
        var _this14 = this;

        var evtJson = this.props.draggingHappening;
        var datatype = evtJson.datatype;

        if (!(datatype in _configs.DEFAULT_TRACKS_FOR_DATATYPE) && !evtJson.defaultTracks) {
          console.warn('unknown data type:', evtJson.higlassTrack);
          return undefined;
        }

        var orientationToPositions = {
          '1d-horizontal': ['top', 'bottom', 'left', 'right'],
          '2d': ['center'],
          '1d-vertical': ['left', 'right']
        };

        var defaultTracks = _configs.DEFAULT_TRACKS_FOR_DATATYPE[datatype] || {};

        if (evtJson.defaultTracks) {
          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = undefined;

          try {
            for (var _iterator2 = (0, _getIterator3['default'])(evtJson.defaultTracks), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              var trackType = _step2.value;

              if (!_configs.TRACKS_INFO_BY_TYPE[trackType]) {
                console.warn('unknown track type', trackType);
              } else {
                var _iteratorNormalCompletion3 = true;
                var _didIteratorError3 = false;
                var _iteratorError3 = undefined;

                try {
                  for (var _iterator3 = (0, _getIterator3['default'])(orientationToPositions[_configs.TRACKS_INFO_BY_TYPE[trackType].orientation]), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                    var position = _step3.value;

                    defaultTracks[position] = trackType;
                  }
                } catch (err) {
                  _didIteratorError3 = true;
                  _iteratorError3 = err;
                } finally {
                  try {
                    if (!_iteratorNormalCompletion3 && _iterator3['return']) {
                      _iterator3['return']();
                    }
                  } finally {
                    if (_didIteratorError3) {
                      throw _iteratorError3;
                    }
                  }
                }
              }
            }
          } catch (err) {
            _didIteratorError2 = true;
            _iteratorError2 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2['return']) {
                _iterator2['return']();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }
        }

        var presentTracks = new _set2['default'](['top', 'left', 'right', 'center', 'bottom'].filter(function (x) {
          return x in _this14.state.tracks && _this14.state.tracks[x].length;
        }));

        var topAllowed = 'top' in defaultTracks;
        var leftAllowed = 'left' in defaultTracks;
        var rightAllowed = 'right' in defaultTracks;
        var bottomAllowed = 'bottom' in defaultTracks;
        var centerAllowed = 'center' in defaultTracks;

        var hasVerticalComponent = 'center' in defaultTracks || presentTracks.has('left') || presentTracks.has('right') || presentTracks.has('center');

        var topDisplayed = 'top' in defaultTracks;
        var bottomDisplayed = 'bottom' in defaultTracks && hasVerticalComponent;
        var leftDisplayed = 'left' in defaultTracks && hasVerticalComponent;
        var rightDisplayed = 'right' in defaultTracks && hasVerticalComponent;
        var centerDisplayed = (0, _keys2['default'])(defaultTracks).length && ('center' in defaultTracks || hasVerticalComponent);

        var topLeftDiv = _react2['default'].createElement('div', {
          style: {
            flexGrow: 1
          }
        });
        var topRightDiv = _react2['default'].cloneElement(topLeftDiv);

        var topDiv = _react2['default'].createElement(
          'div',
          {
            style: {
              display: 'flex',
              flexGrow: 1
            }
          },
          topDisplayed && (centerDisplayed || leftDisplayed) ? topLeftDiv : null,
          _react2['default'].createElement(_DragListeningDiv2['default'], {
            defaultTrackType: defaultTracks.top,
            draggingHappening: this.props.draggingHappening,
            enabled: topAllowed,
            onTrackDropped: function () {
              function onTrackDropped(track) {
                return _this14.handleTracksAdded([track], 'top');
              }

              return onTrackDropped;
            }(),
            style: {
              border: '1px solid black',
              flexGrow: 1
            }
          }),
          topDisplayed && (centerDisplayed || leftDisplayed) ? topRightDiv : null
        );

        var bottomDiv = _react2['default'].createElement(
          'div',
          {
            style: {
              display: 'flex',
              flexGrow: 1
            }
          },
          topDisplayed && (centerDisplayed || leftDisplayed) ? topLeftDiv : null,
          _react2['default'].createElement(_DragListeningDiv2['default'], {
            defaultTrackType: defaultTracks.bottom,
            draggingHappening: this.props.draggingHappening,
            enabled: bottomAllowed,
            onTrackDropped: function () {
              function onTrackDropped(track) {
                return _this14.handleTracksAdded([track], 'bottom');
              }

              return onTrackDropped;
            }(),
            style: {
              border: '1px solid black',
              flexGrow: 1
            }
          }),
          topDisplayed && (centerDisplayed || leftDisplayed) ? topRightDiv : null
        );

        var leftDiv = _react2['default'].createElement(_DragListeningDiv2['default'], {
          defaultTrackType: defaultTracks.left,
          draggingHappening: this.props.draggingHappening,
          enabled: leftAllowed,
          onTrackDropped: function () {
            function onTrackDropped(track) {
              return _this14.handleTracksAdded([track], 'left');
            }

            return onTrackDropped;
          }(),
          style: {
            border: '1px solid black',
            flexGrow: 1
          }
        });

        var centerDiv = _react2['default'].createElement(_DragListeningDiv2['default'], {
          defaultTrackType: defaultTracks.center,
          draggingHappening: this.props.draggingHappening,
          enabled: centerAllowed,
          onTrackDropped: function () {
            function onTrackDropped(track) {
              return _this14.handleTracksAdded([track], 'center');
            }

            return onTrackDropped;
          }(),
          position: 'center',
          style: {
            border: '1px solid black',
            flexGrow: 1
          }
        });

        var rightDiv = _react2['default'].cloneElement(leftDiv, {
          defaultTrackType: defaultTracks.right,
          enabled: rightAllowed,
          onTrackDropped: function () {
            function onTrackDropped(track) {
              return _this14.handleTracksAdded([track], 'right');
            }

            return onTrackDropped;
          }()
        });

        return _react2['default'].createElement(
          'div',
          {
            style: {
              position: 'absolute',
              left: '0px',
              top: '0px',
              width: this.state.width,
              height: this.state.height
            }
          },
          _react2['default'].createElement('div', {
            style: {
              position: 'absolute',
              width: this.state.width,
              height: this.state.height,
              background: 'white',
              opacity: 0.4
            }
          }),
          _react2['default'].createElement(
            'div',
            {
              style: {
                width: this.state.width,
                height: this.state.height,
                position: 'absolute',
                display: 'flex',
                flexDirection: 'column'
              }
            },
            topDisplayed ? topDiv : null,
            hasVerticalComponent && _react2['default'].createElement(
              'div',
              {
                style: {
                  display: 'flex',
                  height: topDisplayed || bottomDisplayed ? '40%' : '100%',
                  width: '100%'
                }
              },
              leftDisplayed ? leftDiv : null,
              centerDisplayed ? centerDiv : null,
              rightDisplayed ? rightDiv : null
            ),
            bottomDisplayed ? bottomDiv : null
          )
        );
      }

      return getIdealizedTrackPositionsOverlay;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this15 = this;

        // A gallery track consumes equal width and height. Note that since the
        // gallery goes around the central view it's dimension takes up twice the
        // space!
        this.galleryDim = this.props.tracks.gallery ? this.props.tracks.gallery.map(function (x) {
          return x.height;
        }).reduce(_utils.sum, 0) : 0;

        // left, top, right, and bottom have fixed heights / widths
        // the center will vary to accomodate their dimensions
        this.topHeightNoGallery = this.props.tracks.top.map(function (x) {
          return x.height;
        }).reduce(_utils.sum, 0);
        this.topHeight = this.topHeightNoGallery + this.galleryDim;

        this.bottomHeightNoGallery = this.props.tracks.bottom.map(function (x) {
          return x.height;
        }).reduce(_utils.sum, 0);
        this.bottomHeight = this.bottomHeightNoGallery + this.galleryDim;

        this.leftWidthNoGallery = this.props.tracks.left.map(function (x) {
          return x.width;
        }).reduce(_utils.sum, 0);
        this.leftWidth = this.leftWidthNoGallery + this.galleryDim;

        this.rightWidthNoGallery = this.props.tracks.right.map(function (x) {
          return x.width;
        }).reduce(_utils.sum, 0);
        this.rightWidth = this.rightWidthNoGallery + this.galleryDim;

        var verticalPadding = this.props.paddingTop + this.props.paddingBottom;
        var horizontalPadding = this.props.paddingLeft + this.props.paddingRight;

        this.centerHeight = Math.max(0, this.state.height - this.topHeight - this.bottomHeight - verticalPadding);
        this.centerWidth = Math.max(0, this.state.width - this.leftWidth - this.rightWidth - horizontalPadding);

        var trackOutline = 'none';

        var topTracks = _react2['default'].createElement(
          'div',
          {
            className: 'top-track-container',
            style: {
              left: this.leftWidth + this.props.paddingLeft,
              top: this.props.paddingTop,
              width: this.centerWidth,
              height: this.topHeightNoGallery,
              outline: trackOutline,
              position: 'absolute'
            }
          },
          _react2['default'].createElement(_HorizontalTiledPlot2['default'], {
            configTrackMenuId: this.state.configTrackMenuId,
            editable: this.props.editable,
            handleConfigTrack: this.handleConfigTrackMenuOpened.bind(this),
            handleResizeTrack: this.handleResizeTrack.bind(this),
            handleSortEnd: this.handleSortEnd.bind(this),
            is1dRangeSelection: this.state.is1dRangeSelection,
            isRangeSelectionActive: this.props.mouseTool === _configs.MOUSE_TOOL_SELECT,
            onAddSeries: this.handleAddSeries.bind(this),
            onCloseTrack: this.handleCloseTrack.bind(this),
            onCloseTrackMenuOpened: this.handleCloseTrackMenuOpened.bind(this),
            onConfigTrackMenuOpened: this.handleConfigTrackMenuOpened.bind(this),
            onRangeSelection: this.rangeSelection1dHandler('x').bind(this),
            onRangeSelectionEnd: this.rangeSelection1dEndHandler('x').bind(this),
            onRangeSelectionReset: this.rangeSelectionResetHandler.bind(this),
            onRangeSelectionStart: this.rangeSelection1dStartHandler.bind(this),
            rangeSelection: this.state.rangeSelection,
            rangeSelectionEnd: this.state.rangeSelectionEnd,
            resizeHandles: new _set2['default'](['bottom']),
            scale: this.xScale,
            tracks: this.props.tracks.top,
            width: this.centerWidth
          })
        );

        var leftTracks = _react2['default'].createElement(
          'div',
          {
            className: 'left-track-container',
            style: {
              left: this.props.paddingLeft,
              top: this.topHeight + this.props.paddingTop,
              width: this.leftWidthNoGallery,
              height: this.centerHeight,
              outline: trackOutline,
              position: 'absolute'
            }
          },
          _react2['default'].createElement(_VerticalTiledPlot2['default'], {
            configTrackMenuId: this.state.configTrackMenuId,
            editable: this.props.editable,
            handleConfigTrack: this.handleConfigTrackMenuOpened.bind(this),
            handleResizeTrack: this.handleResizeTrack.bind(this),
            handleSortEnd: this.handleSortEnd.bind(this),
            height: this.centerHeight,
            is1dRangeSelection: this.state.is1dRangeSelection,
            isRangeSelectionActive: this.props.mouseTool === _configs.MOUSE_TOOL_SELECT,
            onAddSeries: this.handleAddSeries.bind(this),
            onCloseTrack: this.handleCloseTrack.bind(this),
            onCloseTrackMenuOpened: this.handleCloseTrackMenuOpened.bind(this),
            onConfigTrackMenuOpened: this.handleConfigTrackMenuOpened.bind(this),
            onRangeSelection: this.rangeSelection1dHandler('y').bind(this),
            onRangeSelectionEnd: this.rangeSelection1dEndHandler('y').bind(this),
            onRangeSelectionReset: this.rangeSelectionResetHandler.bind(this),
            onRangeSelectionStart: this.rangeSelection1dStartHandler.bind(this),
            rangeSelection: this.state.rangeSelection,
            rangeSelectionEnd: this.state.rangeSelectionEnd,
            resizeHandles: new _set2['default'](['right']),
            scale: this.yScale,
            tracks: this.props.tracks.left
          })
        );

        var rightTracks = _react2['default'].createElement(
          'div',
          {
            className: 'right-track-container',
            style: {
              right: this.props.paddingRight,
              top: this.topHeight + this.props.paddingTop,
              width: this.rightWidthNoGallery,
              height: this.centerHeight,
              outline: trackOutline,
              position: 'absolute'
            }
          },
          _react2['default'].createElement(_VerticalTiledPlot2['default'], {
            configTrackMenuId: this.state.configTrackMenuId,
            editable: this.props.editable,
            handleConfigTrack: this.handleConfigTrackMenuOpened.bind(this),
            handleResizeTrack: this.handleResizeTrack.bind(this),
            handleSortEnd: this.handleSortEnd.bind(this),
            height: this.centerHeight,
            is1dRangeSelection: this.state.is1dRangeSelection,
            isRangeSelectionActive: this.props.mouseTool === _configs.MOUSE_TOOL_SELECT,
            onAddSeries: this.handleAddSeries.bind(this),
            onCloseTrack: this.handleCloseTrack.bind(this),
            onCloseTrackMenuOpened: this.handleCloseTrackMenuOpened.bind(this),
            onConfigTrackMenuOpened: this.handleConfigTrackMenuOpened.bind(this),
            onRangeSelection: this.rangeSelection1dHandler('y').bind(this),
            onRangeSelectionEnd: this.rangeSelection1dEndHandler('y').bind(this),
            onRangeSelectionReset: this.rangeSelectionResetHandler.bind(this),
            onRangeSelectionStart: this.rangeSelection1dStartHandler.bind(this),
            rangeSelection: this.state.rangeSelection,
            rangeSelectionEnd: this.state.rangeSelectionEnd,
            resizeHandles: new _set2['default'](['left']),
            scale: this.yScale,
            tracks: this.props.tracks.right,
            tracksControlAlignLeft: true
          })
        );

        var bottomTracks = _react2['default'].createElement(
          'div',
          {
            className: 'bottom-track-container',
            style: {
              left: this.leftWidth + this.props.paddingLeft,
              bottom: this.props.paddingBottom,
              width: this.centerWidth,
              height: this.bottomHeightNoGallery,
              outline: trackOutline,
              position: 'absolute'
            }
          },
          _react2['default'].createElement(_HorizontalTiledPlot2['default'], {
            configTrackMenuId: this.state.configTrackMenuId,
            editable: this.props.editable,
            handleConfigTrack: this.handleConfigTrackMenuOpened.bind(this),
            handleResizeTrack: this.handleResizeTrack.bind(this),
            handleSortEnd: this.handleSortEnd.bind(this),
            is1dRangeSelection: this.state.is1dRangeSelection,
            isRangeSelectionActive: this.props.mouseTool === _configs.MOUSE_TOOL_SELECT,
            onAddSeries: this.handleAddSeries.bind(this),
            onCloseTrack: this.handleCloseTrack.bind(this),
            onCloseTrackMenuOpened: this.handleCloseTrackMenuOpened.bind(this),
            onConfigTrackMenuOpened: this.handleConfigTrackMenuOpened.bind(this),
            onRangeSelection: this.rangeSelection1dHandler('x').bind(this),
            onRangeSelectionEnd: this.rangeSelection1dEndHandler('x').bind(this),
            onRangeSelectionReset: this.rangeSelectionResetHandler.bind(this),
            onRangeSelectionStart: this.rangeSelection1dStartHandler.bind(this),
            rangeSelection: this.state.rangeSelection,
            rangeSelectionEnd: this.state.rangeSelectionEnd,
            resizeHandles: new _set2['default'](['top']),
            scale: this.xScale,
            tracks: this.props.tracks.bottom,
            width: this.centerWidth
          })
        );

        var galleryTracks = _react2['default'].createElement(
          'div',
          {
            key: 'galleryTracksDiv',
            className: 'gallery-track-container',
            style: {
              left: this.leftWidthNoGallery + this.props.paddingLeft,
              top: this.topHeightNoGallery + this.props.paddingTop,
              width: this.centerWidth + 2 * this.galleryDim,
              height: this.centerHeight + 2 * this.galleryDim,
              outline: trackOutline,
              position: 'absolute'
            }
          },
          _react2['default'].createElement(_GalleryTracks2['default'], {
            configTrackMenuId: this.state.configTrackMenuId,
            editable: this.props.editable,
            height: this.centerHeight + 2 * this.galleryDim,
            onAddSeries: this.handleAddSeries.bind(this),
            onCloseTrack: this.handleCloseTrack.bind(this),
            onCloseTrackMenuOpened: this.handleCloseTrackMenuOpened.bind(this),
            onConfigTrackMenuOpened: this.handleConfigTrackMenuOpened.bind(this),
            tracks: this.props.tracks.gallery,
            width: this.centerWidth + 2 * this.galleryDim
          })
        );

        var centerTrack = _react2['default'].createElement('div', {
          className: 'center-track-container CenterTrack-module_center-track-container-2ELhp',
          style: {
            left: this.leftWidth + this.props.paddingLeft,
            top: this.topHeight + this.props.paddingTop,
            width: this.centerWidth,
            height: this.bottomHeight,
            outline: trackOutline
          }
        });

        if (this.props.tracks.center.length) {
          centerTrack = _react2['default'].createElement(
            'div',
            {
              className: 'center-track-container CenterTrack-module_center-track-container-2ELhp',
              style: {
                left: this.leftWidth + this.props.paddingLeft,
                top: this.topHeight + this.props.paddingTop,
                width: this.centerWidth,
                height: this.centerHeight,
                outline: trackOutline
              }
            },
            _react2['default'].createElement(_CenterTrack2['default'], {
              configTrackMenuId: this.state.configTrackMenuId,
              editable: this.props.editable,
              height: this.centerHeight,
              is1dRangeSelection: this.state.is1dRangeSelection,
              isRangeSelectionActive: this.props.mouseTool === _configs.MOUSE_TOOL_SELECT,
              onAddSeries: this.handleAddSeries.bind(this),
              onCloseTrackMenuOpened: this.handleCloseTrackMenuOpened.bind(this),
              onConfigTrackMenuOpened: this.handleConfigTrackMenuOpened.bind(this),
              onRangeSelectionReset: this.rangeSelectionResetHandler.bind(this),
              onRangeSelectionStart: this.rangeSelection2dStartHandler.bind(this),
              onRangeSelectionX: this.rangeSelection1dHandler('x').bind(this),
              onRangeSelectionXEnd: this.rangeSelection1dEndHandler('x').bind(this),
              onRangeSelectionXY: this.rangeSelection2dHandler.bind(this),
              onRangeSelectionXYEnd: this.rangeSelection2dEndHandler.bind(this),
              onRangeSelectionY: this.rangeSelection1dHandler('y').bind(this),
              onRangeSelectionYEnd: this.rangeSelection1dEndHandler('y').bind(this),
              rangeSelection: this.state.rangeSelection,
              rangeSelectionEnd: this.state.rangeSelectionEnd,
              scaleX: this.xScale,
              scaleY: this.yScale,
              tracks: this.props.tracks.center,
              uid: this.props.tracks.center[0].uid,
              width: this.centerWidth
            })
          );
        }

        this.createTrackPositionTexts();

        var positionedTracks = this.positionedTracks();
        positionedTracks = positionedTracks.concat(this.overlayTracks(positionedTracks));

        var trackRenderer = null;
        if (this.state.sizeMeasured) {
          trackRenderer = _react2['default'].createElement(
            _TrackRenderer2['default']
            // Reserved props
            ,
            { ref: function () {
                function ref(c) {
                  _this15.trackRenderer = c;

                  // if tracks use "local-tiles" as a data source then
                  // we may have received a tileset info synchronously
                  // and need to check for it.
                  _this15.checkAllTilesetInfoReceived();
                }

                return ref;
              }()
              // Custom props
              , canvasElement: this.canvasElement,
              centerHeight: this.centerHeight,
              centerWidth: this.centerWidth,
              disableTrackMenu: this.props.disableTrackMenu,
              dragging: this.props.dragging,
              galleryDim: this.galleryDim,
              getLockGroupExtrema: this.props.getLockGroupExtrema,
              height: this.state.height,
              initialXDomain: this.props.initialXDomain,
              initialYDomain: this.props.initialYDomain,
              isRangeSelection: this.props.mouseTool === _configs.MOUSE_TOOL_SELECT,
              isShowGlobalMousePosition: this.props.isShowGlobalMousePosition,
              isValueScaleLocked: this.props.isValueScaleLocked,
              leftWidth: this.leftWidth,
              leftWidthNoGallery: this.leftWidthNoGallery,
              metaTracks: this.props.metaTracks,
              onMouseMoveZoom: this.props.onMouseMoveZoom,
              onNewTilesLoaded: this.props.onNewTilesLoaded,
              onScalesChanged: this.handleScalesChanged.bind(this),
              onTilesetInfoReceived: this.handleTilesetInfoReceived.bind(this),
              onTrackOptionsChanged: this.handleTrackOptionsChanged.bind(this),
              onValueScaleChanged: this.props.onValueScaleChanged,
              paddingLeft: this.props.paddingLeft,
              paddingTop: this.props.paddingTop,
              pixiRenderer: this.props.pixiRenderer,
              pixiStage: this.props.pixiStage,
              pluginDataFetchers: this.props.pluginDataFetchers,
              pluginTracks: this.props.pluginTracks,
              positionedTracks: positionedTracks,
              registerDraggingChangedListener: this.props.registerDraggingChangedListener,
              removeDraggingChangedListener: this.props.removeDraggingChangedListener,
              setCentersFunction: this.props.setCentersFunction,
              svgElement: this.props.svgElement,
              topHeight: this.topHeight,
              topHeightNoGallery: this.topHeightNoGallery,
              uid: this.props.uid,
              viewOptions: this.props.viewOptions,
              width: this.state.width,
              xDomainLimits: this.props.xDomainLimits,
              yDomainLimits: this.props.yDomainLimits,
              zoomable: this.props.zoomable,
              zoomLimits: this.props.zoomLimits
            },
            topTracks,
            leftTracks,
            rightTracks,
            bottomTracks,
            galleryTracks,
            centerTrack
          );
        }

        var configTrackMenu = null;
        var closeTrackMenu = null;

        if (this.state.configTrackMenuId) {
          configTrackMenu = _react2['default'].createElement(
            _PopupMenu2['default'],
            { onMenuClosed: this.closeMenusBound },
            _react2['default'].createElement(_ConfigTrackMenu2['default'], {
              ref: function () {
                function ref(c) {
                  _this15.configTrackMenu = c;
                }

                return ref;
              }(),
              closeMenu: this.closeMenusBound,
              onAddDivisor: this.handleAddDivisorBound,
              onAddSeries: this.handleAddSeriesBound,
              onAddTrack: this.handleAddTrackBound,
              onChangeTrackType: this.handleChangeTrackTypeBound,
              onCloseTrack: this.handleCloseTrackBound,
              onConfigureTrack: this.handleConfigureTrackBound,
              onExportData: this.handleExportTrackDataBound,
              onLockValueScale: this.handleLockValueScaleBound,
              onReplaceTrack: this.handleReplaceTrackBound,
              onTrackOptionsChanged: this.handleTrackOptionsChangedBound,
              onUnlockValueScale: this.handleUnlockValueScaleBound,
              position: this.state.configTrackMenuLocation,
              theme: this.props.theme,
              trackOrientation: (0, _utils.getTrackPositionByUid)(this.props.tracks, this.state.configTrackMenuId),
              tracks: [(0, _utils.getTrackByUid)(this.props.tracks, this.state.configTrackMenuId)]
            })
          );
        }

        if (this.state.closeTrackMenuId) {
          closeTrackMenu = _react2['default'].createElement(
            _PopupMenu2['default'],
            { onMenuClosed: this.handleCloseTrackMenuClosed.bind(this) },
            _react2['default'].createElement(
              _ContextMenuContainer2['default'],
              {
                position: this.state.closeTrackMenuLocation,
                theme: this.props.theme
              },
              _react2['default'].createElement(_CloseTrackMenu2['default'], {
                onCloseTrack: this.handleCloseTrack.bind(this),
                tracks: [(0, _utils.getTrackByUid)(this.props.tracks, this.state.closeTrackMenuId)]
              })
            )
          );
        }

        var overlays = null;
        if (this.props.chooseTrackHandler) {
          // We want to choose a track and call a function. To choose the track, we display
          // an overlay on top of each track
          overlays = positionedTracks.filter(function (pTrack) {
            return pTrack.track.position !== 'whole';
          }).map(function (pTrack) {
            var background = 'transparent';
            var border = 'none';

            if (_this15.state.mouseOverOverlayUid === pTrack.track.uid) {
              background = 'yellow';
              border = '1px solid black';
            }

            return _react2['default'].createElement('div', {
              key: pTrack.track.uid,
              className: 'tiled-plot-track-overlay'
              // we want to remove the mouseOverOverlayUid so that next time we try
              // to choose an overlay track, the previously selected one isn't
              // automatically highlighted

              , onClick: function () {
                function onClick() {
                  return _this15.handleTrackPositionChosen(pTrack);
                }

                return onClick;
              }(),
              onDragEnter: function () {
                function onDragEnter(evt) {
                  _this15.handleOverlayMouseEnter(pTrack.track.uid);
                  evt.preventDefault();
                }

                return onDragEnter;
              }(),
              onDragLeave: function () {
                function onDragLeave() {
                  return _this15.handleOverlayMouseLeave(pTrack.track.uid);
                }

                return onDragLeave;
              }(),
              onDragOver: function () {
                function onDragOver(evt) {
                  return evt.preventDefault();
                }

                return onDragOver;
              }(),
              onDrop: function () {
                function onDrop() {
                  return _this15.handleTrackPositionChosen(pTrack);
                }

                return onDrop;
              }(),
              onMouseEnter: function () {
                function onMouseEnter() {
                  return _this15.handleOverlayMouseEnter(pTrack.track.uid);
                }

                return onMouseEnter;
              }(),
              onMouseLeave: function () {
                function onMouseLeave() {
                  return _this15.handleOverlayMouseLeave(pTrack.track.uid);
                }

                return onMouseLeave;
              }(),
              style: {
                position: 'absolute',
                left: pTrack.left,
                top: pTrack.top,
                width: pTrack.width,
                height: pTrack.height,
                background: background,
                opacity: 0.4,
                border: border,
                zIndex: 1
              }
            });
          });
        }

        var trackOptionsElement = null;

        if (this.xScale && this.yScale && this.props.editable && this.state.trackOptions) {
          var configComponent = this.state.trackOptions.configComponent;
          var track = this.state.trackOptions.track;

          trackOptionsElement = _react2['default'].createElement(configComponent, {
            track: track,
            xScale: this.xScale,
            yScale: this.yScale,
            onCancel: function () {
              function onCancel() {
                _this15.setState({
                  trackOptions: null
                });
              }

              return onCancel;
            }(),
            onTrackOptionsChanged: function () {
              function onTrackOptionsChanged(newOptions) {
                return newOptions;
              }

              return onTrackOptionsChanged;
            }(),
            onSubmit: function () {
              function onSubmit(newOptions) {
                _this15.handleTrackOptionsChanged(_this15.state.trackOptions.track.uid, newOptions);
                _this15.setState({
                  trackOptions: null
                });
              }

              return onSubmit;
            }()
          });
        }

        // track renderer needs to enclose all the other divs so that it
        // can catch the zoom events
        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this15.divTiledPlot = c;
              }

              return ref;
            }(),
            className: 'tiled-plot-div TiledPlot-module_tiled-plot-uFHiB',
            style: {
              marginBottom: this.props.marginBottom,
              marginLeft: this.props.marginLeft,
              marginRight: this.props.marginRight,
              marginTop: this.props.marginTop
            }
          },
          trackRenderer,
          overlays,
          configTrackMenu,
          closeTrackMenu,
          trackOptionsElement,
          this.getContextMenu(),
          this.props.draggingHappening && this.getIdealizedTrackPositionsOverlay()
        );
      }

      return render;
    }()

    /* -------------------- Custom Methods -----------------------*/

  }, {
    key: 'addEventListeners',
    value: function () {
      function addEventListeners() {
        this.eventListeners = [];

        this.eventListeners.forEach(function (event) {
          return document.addEventListener(event.name, event.callback, false);
        });
      }

      return addEventListeners;
    }()
  }, {
    key: 'removeEventListeners',
    value: function () {
      function removeEventListeners() {
        this.eventListeners.forEach(function (event) {
          return document.removeEventListener(event.name, event.callback);
        });
      }

      return removeEventListeners;
    }()
  }]);
  return TiledPlot;
}(_react2['default'].Component); // eslint-disable-line no-unused-vars


// Configs

// import {HeatmapOptions} from './HeatmapOptions';

// Higher-order components


TiledPlot.defaultProps = {
  isShowGlobalMousePosition: false,
  pluginDataFetchers: {},
  pluginTracks: {},
  metaTracks: [],
  zoomable: true
};

TiledPlot.propTypes = {
  addTrackPosition: _propTypes2['default'].string,
  canvasElement: _propTypes2['default'].object,
  chooseTrackHandler: _propTypes2['default'].func,
  chromInfoPath: _propTypes2['default'].string,
  disableTrackMenu: _propTypes2['default'].bool,
  dragging: _propTypes2['default'].bool,
  draggingHappening: _propTypes2['default'].bool,
  editable: _propTypes2['default'].bool,
  getLockGroupExtrema: _propTypes2['default'].func,
  initialXDomain: _propTypes2['default'].array,
  initialYDomain: _propTypes2['default'].array,
  isShowGlobalMousePosition: _propTypes2['default'].bool,
  isValueScaleLocked: _propTypes2['default'].func,
  marginBottom: _propTypes2['default'].number.isRequired,
  marginLeft: _propTypes2['default'].number.isRequired,
  marginRight: _propTypes2['default'].number.isRequired,
  marginTop: _propTypes2['default'].number.isRequired,
  paddingBottom: _propTypes2['default'].number.isRequired,
  paddingLeft: _propTypes2['default'].number.isRequired,
  paddingRight: _propTypes2['default'].number.isRequired,
  paddingTop: _propTypes2['default'].number.isRequired,
  metaTracks: _propTypes2['default'].array,
  modal: _propTypes2['default'].object,
  mouseTool: _propTypes2['default'].string,
  onCloseTrack: _propTypes2['default'].func,
  onChangeTrackData: _propTypes2['default'].func,
  onChangeTrackType: _propTypes2['default'].func,
  onDataDomainChanged: _propTypes2['default'].func,
  onLockValueScale: _propTypes2['default'].func,
  onMouseMoveZoom: _propTypes2['default'].func,
  onNewTilesLoaded: _propTypes2['default'].func,
  onNoTrackAdded: _propTypes2['default'].func,
  onRangeSelection: _propTypes2['default'].func.isRequired,
  onScalesChanged: _propTypes2['default'].func,
  onTrackOptionsChanged: _propTypes2['default'].func,
  onTrackPositionChosen: _propTypes2['default'].func,
  onTracksAdded: _propTypes2['default'].func,
  onUnlockValueScale: _propTypes2['default'].func,
  onValueScaleChanged: _propTypes2['default'].func,
  onResizeTrack: _propTypes2['default'].func,
  overlays: _propTypes2['default'].array,
  openModal: _propTypes2['default'].func,
  pixiRenderer: _propTypes2['default'].object,
  pixiStage: _propTypes2['default'].object,
  pluginDataFetchers: _propTypes2['default'].object,
  pluginTracks: _propTypes2['default'].object,
  pubSub: _propTypes2['default'].object.isRequired,
  rangeSelection1dSize: _propTypes2['default'].array,
  rangeSelectionToInt: _propTypes2['default'].bool,
  registerDraggingChangedListener: _propTypes2['default'].func,
  removeDraggingChangedListener: _propTypes2['default'].func,
  setCentersFunction: _propTypes2['default'].func,
  svgElement: _propTypes2['default'].object,
  theme: _propTypes2['default'].symbol.isRequired,
  tracks: _propTypes2['default'].object,
  trackSourceServers: _propTypes2['default'].array,
  uid: _propTypes2['default'].string,
  viewOptions: _propTypes2['default'].object,
  xDomainLimits: _propTypes2['default'].array,
  yDomainLimits: _propTypes2['default'].array,
  zoomable: _propTypes2['default'].bool,
  zoomLimits: _propTypes2['default'].array,
  zoomToDataExtentOnInit: _propTypes2['default'].func
};

exports['default'] = (0, _withPubSub2['default'])((0, _withModal2['default'])((0, _withTheme2['default'])(TiledPlot)));

/***/ }),
/* 607 */
/***/ (function(module, exports, __nested_webpack_require_3005983__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3005983__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3005983__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3005983__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3005983__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3005983__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3005983__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_3005983__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3005983__(1);

var _react2 = _interopRequireDefault(_react);

var _d3Brush = __nested_webpack_require_3005983__(83);

var _d3Selection = __nested_webpack_require_3005983__(0);

var _TrackControl = __nested_webpack_require_3005983__(174);

var _TrackControl2 = _interopRequireDefault(_TrackControl);

var _utils = __nested_webpack_require_3005983__(10);

var _configs = __nested_webpack_require_3005983__(11);

var _CenterTrackModule = __nested_webpack_require_3005983__(346);

var _CenterTrackModule2 = _interopRequireDefault(_CenterTrackModule);

var _TrackModule = __nested_webpack_require_3005983__(175);

var _TrackModule2 = _interopRequireDefault(_TrackModule);

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

// eslint-disable-line no-unused-vars

// Styles


// Utils
var _styleModuleImportMap = {
  'styles': {
    'center-track': 'CenterTrack-module_center-track-3ptRW',
    'center-track-container': 'CenterTrack-module_center-track-container-2ELhp'
  },
  'stylesTrack': {
    'track-range-selection': 'Track-module_track-range-selection-1yrDf',
    'track-range-selection-active': 'Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-active-primary': 'Track-module_track-range-selection-active-primary-29M73 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-active-secondary': 'Track-module_track-range-selection-active-secondary-1s0t5 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-group-inactive': 'Track-module_track-range-selection-group-inactive-YNRM4',
    'track-range-selection-group-brush-selection': 'Track-module_track-range-selection-group-brush-selection-2VYDl'
  }
}; // eslint-disable-line no-unused-vars


// Configs

var STYLES = {
  pointerEvents: 'all'
};

var CenterTrack = function (_React$Component) {
  (0, _inherits3['default'])(CenterTrack, _React$Component);

  function CenterTrack(props) {
    (0, _classCallCheck3['default'])(this, CenterTrack);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (CenterTrack.__proto__ || (0, _getPrototypeOf2['default'])(CenterTrack)).call(this, props));

    _this.state = {
      isVisible: false
    };

    _this.brushBehaviorX = (0, _d3Brush.brushX)(true, true).on('brush', _this.brushedX.bind(_this)).on('end', _this.brushedXEnded.bind(_this));

    _this.brushBehaviorY = (0, _d3Brush.brushY)(true, true, true).on('brush', _this.brushedY.bind(_this)).on('end', _this.brushedYEnded.bind(_this));

    _this.brushBehaviorXY = (0, _d3Brush.brush)(true).on('start', _this.brushStarted.bind(_this)).on('brush', _this.brushedXY.bind(_this)).on('end', _this.brushedXYEnded.bind(_this));
    return _this;
  }

  /* -------------------------- Life Cycle Methods -------------------------- */

  (0, _createClass3['default'])(CenterTrack, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        if (this.props.isRangeSelectionActive) {
          this.addBrush2d();
        }
      }

      return componentDidMount;
    }()
  }, {
    key: 'shouldComponentUpdate',
    value: function () {
      function shouldComponentUpdate(nextProps, nextState) {
        if (this.rangeSelectionTriggeredXY) {
          this.rangeSelectionTriggeredXY = false;
          if (this.rangeSelectionTriggeredXYEnd) {
            var dim1 = nextProps.rangeSelection[0] || null;
            this.moveBrushXY([dim1, nextProps.rangeSelection[1]], true);
            this.rangeSelectionTriggeredXYEnd = false;
          }
          return this.state !== nextState;
        }
        if (this.props.rangeSelection !== nextProps.rangeSelection) {
          var _dim = nextProps.rangeSelection[0] || null;

          if (this.props.is1dRangeSelection) {
            if (!this.rangeSelectionTriggeredX) {
              this.moveBrushX(_dim, nextProps.rangeSelectionEnd);
            }
            if (this.rangeSelectionTriggeredXEnd) {
              this.moveBrushX(_dim, nextProps.rangeSelectionEnd, true);
            }
            if (!this.rangeSelectionTriggeredY) {
              this.moveBrushY(_dim, nextProps.rangeSelectionEnd);
            }
            if (this.rangeSelectionTriggeredYEnd) {
              this.moveBrushY(_dim, nextProps.rangeSelectionEnd, true);
            }
            this.rangeSelectionTriggeredX = false;
            this.rangeSelectionTriggeredXEnd = false;
            this.rangeSelectionTriggeredY = false;
            this.rangeSelectionTriggeredYEnd = false;
          } else {
            this.moveBrushXY([_dim, nextProps.rangeSelection[1]], nextProps.rangeSelectionEnd);
          }

          var isUnset = this.props.is1dRangeSelection && !nextProps.is1dRangeSelection && _dim === null;

          return this.state !== nextState || isUnset;
        }
        return true;
      }

      return shouldComponentUpdate;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate() {
        if (this.props.isRangeSelectionActive) {
          this.addBrush2d();
        } else {
          this.removeBrush1d();
          this.removeBrush2d();
        }
      }

      return componentDidUpdate;
    }()

    /* --------------------------- Getter / Setter ---------------------------- */

  }, {
    key: 'addBrush1d',


    /* ---------------------------- Custom Methods ---------------------------- */

    value: function () {
      function addBrush1d() {
        if (!this.brushElX || !this.brushElY || this.brushElXOld === this.brushElX && this.brushElYOld === this.brushElY) {
          return;
        }

        if (this.brushElXOld) {
          // Remove event listener on old element to avoid memory leaks
          this.brushElXOld.on('.brush', null);
        }

        if (this.brushElYOld) {
          // Remove event listener on old element to avoid memory leaks
          this.brushElYOld.on('.brush', null);
        }

        this.brushElX.call(this.brushBehaviorX);
        this.brushElY.call(this.brushBehaviorY);

        (0, _utils.resetD3BrushStyle)(this.brushElX, _TrackModule2['default']['track-range-selection-group-brush-selection']);
        (0, _utils.resetD3BrushStyle)(this.brushElY, _TrackModule2['default']['track-range-selection-group-brush-selection']);

        this.brushElXOld = this.brushElX;
        this.brushElYOld = this.brushElY;

        this.brushIs1dBound = true;
      }

      return addBrush1d;
    }()
  }, {
    key: 'addBrush2d',
    value: function () {
      function addBrush2d() {
        if (!this.brushElXY || this.brushElXYOld === this.brushElXY) {
          return;
        }

        if (this.brushElXYOld) {
          // Remove event listener on old element to avoid memory leaks
          this.brushElXYOld.on('.brush', null);
        }

        this.brushElXY.call(this.brushBehaviorXY);
        this.brushElXYOld = this.brushElXY;
        this.brushIs2dBound = true;

        (0, _utils.resetD3BrushStyle)(this.brushElXY, _TrackModule2['default']['track-range-selection-group-brush-selection']);
      }

      return addBrush2d;
    }()
  }, {
    key: 'brushedX',
    value: function () {
      function brushedX() {
        // Need to reassign variable to check after reset
        var rangeSelectionMoved = this.rangeSelectionMoved;
        this.rangeSelectionMoved = false;

        if (!this.sourceEvent || !this.props.onRangeSelectionX || !this.props.is1dRangeSelection || rangeSelectionMoved) return;

        this.rangeSelectionTriggeredX = true;
        this.props.onRangeSelectionX(_d3Selection.event.selection);
      }

      return brushedX;
    }()
  }, {
    key: 'brushedXEnded',
    value: function () {
      function brushedXEnded() {
        var rangeSelectionMovedEnd = this.rangeSelectionMovedEnd;
        this.rangeSelectionMovedEnd = false;

        if (!this.sourceEvent || !this.props.onRangeSelectionX || !this.props.is1dRangeSelection || rangeSelectionMovedEnd) return;

        this.rangeSelectionTriggeredX = true;
        this.rangeSelectionTriggeredXEnd = true;
        this.props.onRangeSelectionXEnd(_d3Selection.event.selection);
      }

      return brushedXEnded;
    }()
  }, {
    key: 'brushedY',
    value: function () {
      function brushedY() {
        // Need to reassign variable to check after reset
        var rangeSelectionMoved = this.rangeSelectionMoved;
        this.rangeSelectionMoved = false;

        if (!this.sourceEvent || !this.props.onRangeSelectionY || !this.props.is1dRangeSelection || rangeSelectionMoved) return;

        this.rangeSelectionTriggeredY = true;
        this.props.onRangeSelectionY(_d3Selection.event.selection);
      }

      return brushedY;
    }()
  }, {
    key: 'brushedYEnded',
    value: function () {
      function brushedYEnded() {
        var rangeSelectionMovedEnd = this.rangeSelectionMovedEnd;
        this.rangeSelectionMovedEnd = false;

        if (!this.sourceEvent || !this.props.onRangeSelectionY || !this.props.is1dRangeSelection || rangeSelectionMovedEnd) return;

        this.rangeSelectionTriggeredY = true;
        this.rangeSelectionTriggeredYEnd = true;
        this.props.onRangeSelectionYEnd(_d3Selection.event.selection);
      }

      return brushedYEnded;
    }()
  }, {
    key: 'brushedXY',
    value: function () {
      function brushedXY() {
        // Need to reassign variable to check after reset
        var rangeSelectionMoved = this.rangeSelectionMoved;
        this.rangeSelectionMoved = false;

        if (!this.sourceEvent || !this.props.onRangeSelectionXY || rangeSelectionMoved || this.props.is1dRangeSelection) return;

        this.rangeSelectionTriggeredXY = true;
        this.props.onRangeSelectionXY([[_d3Selection.event.selection[0][0], _d3Selection.event.selection[1][0]], [_d3Selection.event.selection[0][1], _d3Selection.event.selection[1][1]]]);
      }

      return brushedXY;
    }()
  }, {
    key: 'brushedXYEnded',
    value: function () {
      function brushedXYEnded() {
        if (this.props.is1dRangeSelection) return;

        var rangeSelectionMovedEnd = this.rangeSelectionMovedEnd;
        this.rangeSelectionMovedEnd = false;

        // Brush end event with a selection
        if (_d3Selection.event.selection && _d3Selection.event.sourceEvent && this.props.onRangeSelectionXY && !rangeSelectionMovedEnd) {
          this.rangeSelectionTriggeredXY = true;
          this.rangeSelectionTriggeredXYEnd = true;
          this.props.onRangeSelectionXYEnd([[_d3Selection.event.selection[0][0], _d3Selection.event.selection[1][0]], [_d3Selection.event.selection[0][1], _d3Selection.event.selection[1][1]]]);
        }

        if (!_d3Selection.event.selection) {
          this.rangeSelectionTriggeredXY = true;
          this.props.onRangeSelectionReset();
        }
      }

      return brushedXYEnded;
    }()
  }, {
    key: 'brushStarted',
    value: function () {
      function brushStarted() {
        if (!this.sourceEvent) return;

        this.props.onRangeSelectionStart();
      }

      return brushStarted;
    }()
  }, {
    key: 'moveBrushX',
    value: function () {
      function moveBrushX(rangeSelection) {
        var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        if (!this.brushEl && !this.sourceEvent) {
          return;
        }

        if (this.brushIs2dBound) {
          this.removeBrush2d();
          this.addBrush1d();
        }

        var relRangeX = rangeSelection ? [this.props.scaleX(rangeSelection[0]), this.props.scaleX(rangeSelection[1])] : null;

        this.rangeSelectionMoved = true;
        this.rangeSelectionMovedEnd = true;

        if (animate) {
          this.brushElX.transition().call(this.brushBehaviorX.move, relRangeX);
        } else {
          this.brushElX.call(this.brushBehaviorX.move, relRangeX);
        }
      }

      return moveBrushX;
    }()
  }, {
    key: 'moveBrushY',
    value: function () {
      function moveBrushY(rangeSelection) {
        var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        if (!this.brushEl && !this.sourceEvent) {
          return;
        }

        if (this.brushIs2dBound) {
          this.removeBrush2d();
          this.addBrush1d();
        }

        var relRangeY = rangeSelection ? [this.props.scaleY(rangeSelection[0]), this.props.scaleY(rangeSelection[1])] : null;

        this.rangeSelectionMoved = true;
        this.rangeSelectionMovedEnd = true;

        if (animate) {
          this.brushElY.transition().call(this.brushBehaviorY.move, relRangeY);
        } else {
          this.brushElY.call(this.brushBehaviorY.move, relRangeY);
        }
      }

      return moveBrushY;
    }()
  }, {
    key: 'moveBrushXY',
    value: function () {
      function moveBrushXY(rangeSelection) {
        var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        if (!this.brushEl && !this.sourceEvent) {
          return;
        }

        var relRange = [[this.props.scaleX(rangeSelection[0][0]), this.props.scaleY(rangeSelection[1][0])], [this.props.scaleX(rangeSelection[0][1]), this.props.scaleY(rangeSelection[1][1])]];

        this.rangeSelectionMoved = true;
        this.rangeSelectionMovedEnd = true;

        if (animate) {
          this.brushElXY.transition().call(this.brushBehaviorXY.move, relRange);
        } else {
          this.brushElXY.call(this.brushBehaviorXY.move, relRange);
        }
      }

      return moveBrushXY;
    }()
  }, {
    key: 'mouseEnterHandler',
    value: function () {
      function mouseEnterHandler() {
        if (this.props.isRangeSelectionActive) return;

        this.setState({
          isVisible: true
        });
      }

      return mouseEnterHandler;
    }()
  }, {
    key: 'mouseLeaveHandler',
    value: function () {
      function mouseLeaveHandler() {
        this.setState({
          isVisible: false
        });
      }

      return mouseLeaveHandler;
    }()
  }, {
    key: 'removeBrush1d',
    value: function () {
      function removeBrush1d() {
        if (!this.brushIs1dBound) {
          return;
        }

        if (this.brushElX) {
          // Reset brush selection
          this.brushElX.call(this.brushBehaviorX.move, null);

          // Remove brush behavior
          this.brushElX.on('.brush', null);
        }

        if (this.brushElY) {
          // Reset brush selection
          this.brushElY.call(this.brushBehaviorY.move, null);

          // Remove brush behavior
          this.brushElY.on('.brush', null);
        }

        this.brushIs1dBound = false;
      }

      return removeBrush1d;
    }()
  }, {
    key: 'removeBrush2d',
    value: function () {
      function removeBrush2d() {
        if (!this.brushIs2dBound) {
          return;
        }

        if (this.brushElXY) {
          // Reset brush selection
          this.brushElXY.call(this.brushBehaviorXY.move, null);

          // Remove brush behavior
          this.brushElXY.on('.brush', null);
          this.brushElXYOld = undefined;

          this.brushIs2dBound = false;

          if (!this.props.is1dRangeSelection) this.props.onRangeSelectionReset();
        }
      }

      return removeBrush2d;
    }()

    /* ------------------------------ Rendering ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var isBrushable = this.props.tracks.map(function (track) {
          return (0, _configs.IS_TRACK_RANGE_SELECTABLE)(track);
        }).reduce(_utils.or, false);

        // Althought the tracks property is an array and could contain more than one
        // track, in practice there is only one combined track.
        var menuClash = this.props.tracks.some(function (track) {
          if (track.contents) {
            // if this is a combined track, iterate over children
            return track.contents.some(function (subTrack) {
              if (subTrack.type === 'heatmap') {
                return subTrack.options.colorbarPosition === 'topRight';
              }
              return false;
            });
          }
          // if this isn't a combined track, just check if this a heatmap
          // with a topright colorbar
          if (track.type === 'heatmap') {
            return track.options.colorbarPosition === 'topRight';
          }
          return false;
        });

        var rangeSelectorClass = 'stylesTrack.track-range-selection';
        if (this.props.isRangeSelectionActive) {
          rangeSelectorClass += this.props.is1dRangeSelection ? '-active-secondary' : '-active-primary';
        }

        var rangeSelectorGroup1dClass = !this.props.is1dRangeSelection ? 'stylesTrack.track-range-selection-group-inactive' : '';

        var rangeSelectorGroup2dClass = this.props.is1dRangeSelection ? 'stylesTrack.track-range-selection-group-inactive' : '';

        return _react2['default'].createElement(
          'div',
          {
            className: (this.props.className ? this.props.className + ' ' : '') + 'CenterTrack-module_center-track-3ptRW',
            onMouseEnter: this.mouseEnterHandler.bind(this),
            onMouseLeave: this.mouseLeaveHandler.bind(this),
            style: {
              height: this.props.height,
              width: this.props.width
            }
          },
          isBrushable && _react2['default'].createElement(
            'svg',
            {
              style: {
                height: this.props.height,
                width: this.props.width
              },

              xmlns: 'http://www.w3.org/2000/svg',
              className: (0, _getClassName3['default'])(rangeSelectorClass, _styleModuleImportMap)
            },
            _react2['default'].createElement('g', {
              ref: function () {
                function ref(el) {
                  _this2.brushElX = (0, _d3Selection.select)(el);
                }

                return ref;
              }(),
              className: (0, _getClassName3['default'])(rangeSelectorGroup1dClass, _styleModuleImportMap)
            }),
            _react2['default'].createElement('g', {
              ref: function () {
                function ref(el) {
                  _this2.brushElY = (0, _d3Selection.select)(el);
                }

                return ref;
              }(),
              className: (0, _getClassName3['default'])(rangeSelectorGroup1dClass, _styleModuleImportMap)
            }),
            _react2['default'].createElement('g', {
              ref: function () {
                function ref(el) {
                  _this2.brushElXY = (0, _d3Selection.select)(el);
                }

                return ref;
              }(),
              className: (0, _getClassName3['default'])(rangeSelectorGroup2dClass, _styleModuleImportMap)
            })
          ),
          this.props.editable &&
          // show track controls if config menu is visible or
          // mouse is within the bounds of the track
          _react2['default'].createElement(_TrackControl2['default'], {
            imgStyleAdd: STYLES,
            imgStyleClose: STYLES,
            imgStyleMove: STYLES,
            imgStyleSettings: STYLES,
            isMoveable: false,
            isVisible: this.state.isVisible || this.props.uid === this.props.configTrackMenuId,
            onAddSeries: this.props.onAddSeries,
            onCloseTrackMenuOpened: this.props.onCloseTrackMenuOpened,
            onConfigTrackMenuOpened: this.props.onConfigTrackMenuOpened,
            paddingRight: menuClash,
            uid: this.props.uid
          })
        );
      }

      return render;
    }()
  }, {
    key: 'sourceEvent',
    get: function () {
      function get() {
        return _d3Selection.event && _d3Selection.event.sourceEvent;
      }

      return get;
    }()
  }]);
  return CenterTrack;
}(_react2['default'].Component);

CenterTrack.defaultProps = {
  className: 'center-track',
  configTrackMenuId: null,
  is1dRangeSelection: false,
  rangeSelectionEnd: _propTypes2['default'].bool,
  isRangeSelectionActive: false,
  scaleX: function () {
    function scaleX(x) {
      return x;
    }

    return scaleX;
  }(),
  scaleY: function () {
    function scaleY(x) {
      return x;
    }

    return scaleY;
  }()
};

CenterTrack.propTypes = {
  className: _propTypes2['default'].string,
  configTrackMenuId: _propTypes2['default'].string,
  editable: _propTypes2['default'].bool.isRequired,
  height: _propTypes2['default'].number.isRequired,
  is1dRangeSelection: _propTypes2['default'].bool,
  isRangeSelectionActive: _propTypes2['default'].bool,
  onAddSeries: _propTypes2['default'].func.isRequired,
  onCloseTrackMenuOpened: _propTypes2['default'].func.isRequired,
  onConfigTrackMenuOpened: _propTypes2['default'].func.isRequired,
  onRangeSelectionX: _propTypes2['default'].func.isRequired,
  onRangeSelectionXEnd: _propTypes2['default'].func.isRequired,
  onRangeSelectionY: _propTypes2['default'].func.isRequired,
  onRangeSelectionYEnd: _propTypes2['default'].func.isRequired,
  onRangeSelectionXY: _propTypes2['default'].func.isRequired,
  onRangeSelectionXYEnd: _propTypes2['default'].func.isRequired,
  onRangeSelectionReset: _propTypes2['default'].func.isRequired,
  onRangeSelectionStart: _propTypes2['default'].func.isRequired,
  rangeSelection: _propTypes2['default'].array.isRequired,
  rangeSelectionEnd: _propTypes2['default'].bool,
  scaleX: _propTypes2['default'].func,
  scaleY: _propTypes2['default'].func,
  tracks: _propTypes2['default'].array.isRequired,
  uid: _propTypes2['default'].string.isRequired,
  width: _propTypes2['default'].number.isRequired
};

exports['default'] = CenterTrack;

/***/ }),
/* 608 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"track-control":"TrackControl-module_track-control-2zDf3","track-control-vertical":"TrackControl-module_track-control-vertical-2McB_","track-control-dark":"TrackControl-module_track-control-dark-fP2uZ","track-control-active":"TrackControl-module_track-control-active-2JD9i TrackControl-module_track-control-2zDf3","track-control-left":"TrackControl-module_track-control-left-zHd9W","track-control-vertical-active":"TrackControl-module_track-control-vertical-active-1QCKn","track-control-padding-right":"TrackControl-module_track-control-padding-right-2p6Lp","track-control-button":"TrackControl-module_track-control-button-2fdIb","track-control-button-vertical":"TrackControl-module_track-control-button-vertical-1s22z"};

/***/ }),
/* 609 */
/***/ (function(module, exports, __nested_webpack_require_3029630__) {

"use strict";


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

var _assign = __nested_webpack_require_3029630__(44);

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = __nested_webpack_require_3029630__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3029630__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3029630__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3029630__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3029630__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3029630__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_3029630__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3029630__(1);

var _react2 = _interopRequireDefault(_react);

var _slugid = __nested_webpack_require_3029630__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _withPubSub = __nested_webpack_require_3029630__(69);

var _withPubSub2 = _interopRequireDefault(_withPubSub);

__nested_webpack_require_3029630__(610);

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

var _styleModuleImportMap = {
  '../styles/DragListeningDiv.module.scss': {
    'drag-listening-div-active': 'DragListeningDiv-module_drag-listening-div-active-3wpRk'
  }
};

// Styles

var DragListeningDiv = function (_React$Component) {
  (0, _inherits3['default'])(DragListeningDiv, _React$Component);

  function DragListeningDiv(props) {
    (0, _classCallCheck3['default'])(this, DragListeningDiv);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (DragListeningDiv.__proto__ || (0, _getPrototypeOf2['default'])(DragListeningDiv)).call(this, props));

    _this.state = {
      dragOnTop: false
    };
    return _this;
  }

  (0, _createClass3['default'])(DragListeningDiv, [{
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        // color red if not enabled, green if a track is not top and blue otherwise
        var background = 'red';

        if (this.props.enabled && this.state.dragOnTop) {
          background = 'green';
        } else if (this.props.enabled) {
          background = 'blue';
        }

        var styleNames = this.props.enabled ? 'drag-listening-div-active' : '';

        return _react2['default'].createElement('div', {
          onDragEnter: function () {
            function onDragEnter() {
              _this2.setState({ dragOnTop: true });
            }

            return onDragEnter;
          }(),
          onDragLeave: function () {
            function onDragLeave() {
              _this2.setState({ dragOnTop: false });
            }

            return onDragLeave;
          }(),
          onDragOver: function () {
            function onDragOver(evt) {
              evt.preventDefault();
            }

            return onDragOver;
          }(),
          onDrop: function () {
            function onDrop() {
              if (!_this2.props.enabled) return;

              var evtJson = _this2.props.draggingHappening;

              var newTrack = {
                type: _this2.props.defaultTrackType,
                uid: _slugid2['default'].nice(),
                tilesetUid: evtJson.tilesetUid,
                server: evtJson.server
              };

              _this2.props.onTrackDropped(newTrack);
              _this2.props.pubSub.publish('trackDropped', newTrack);
            }

            return onDrop;
          }(),
          style: (0, _assign2['default'])({
            background: background,
            opacity: 0.6
          }, this.props.style),
          className: 'DragListeningDiv ' + (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
        });
      }

      return render;
    }()
  }]);
  return DragListeningDiv;
}(_react2['default'].Component);

DragListeningDiv.defaultProps = {
  enabled: false,
  style: {},
  draggingHappening: {},
  onTrackDropped: function () {
    function onTrackDropped() {}

    return onTrackDropped;
  }()
};

DragListeningDiv.propTypes = {
  enabled: _propTypes2['default'].bool,
  style: _propTypes2['default'].object,
  defaultTrackType: _propTypes2['default'].object,
  draggingHappening: _propTypes2['default'].object,
  onTrackDropped: _propTypes2['default'].func,
  position: _propTypes2['default'].string.isRequired,
  pubSub: _propTypes2['default'].object.isRequired
};

exports['default'] = (0, _withPubSub2['default'])(DragListeningDiv);

/***/ }),
/* 610 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"drag-listening-div-active":"DragListeningDiv-module_drag-listening-div-active-3wpRk"};

/***/ }),
/* 611 */
/***/ (function(module, exports, __nested_webpack_require_3034649__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3034649__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3034649__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3034649__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3034649__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3034649__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_3034649__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3034649__(1);

var _react2 = _interopRequireDefault(_react);

var _TrackControl = __nested_webpack_require_3034649__(174);

var _TrackControl2 = _interopRequireDefault(_TrackControl);

var _GalleryTracksModule = __nested_webpack_require_3034649__(612);

var _GalleryTracksModule2 = _interopRequireDefault(_GalleryTracksModule);

var _TiledPlotModule = __nested_webpack_require_3034649__(176);

var _TiledPlotModule2 = _interopRequireDefault(_TiledPlotModule);

var _TrackModule = __nested_webpack_require_3034649__(175);

var _TrackModule2 = _interopRequireDefault(_TrackModule);

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

// eslint-disable-line no-unused-vars

// eslint-disable-line no-unused-vars
var STYLES = {
  pointerEvents: 'all'
}; // eslint-disable-line no-unused-vars


// Styles

var GalleryTracks = function (_React$Component) {
  (0, _inherits3['default'])(GalleryTracks, _React$Component);

  function GalleryTracks(props) {
    (0, _classCallCheck3['default'])(this, GalleryTracks);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (GalleryTracks.__proto__ || (0, _getPrototypeOf2['default'])(GalleryTracks)).call(this, props));

    _this.state = { hovering: false };
    return _this;
  }

  (0, _createClass3['default'])(GalleryTracks, [{
    key: 'mouseEnterHandler',
    value: function () {
      function mouseEnterHandler() {
        this.setState({ hovering: true });
      }

      return mouseEnterHandler;
    }()
  }, {
    key: 'mouseLeaveHandler',
    value: function () {
      function mouseLeaveHandler() {
        this.setState({ hovering: false });
      }

      return mouseLeaveHandler;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        return _react2['default'].createElement(
          'div',
          { className: 'gallery-tracks GalleryTracks-module_gallery-tracks-3tsUO' },
          this.props.tracks && this.props.tracks.map(function (track, index) {
            return _react2['default'].createElement(
              'div',
              {
                key: track.uid || index,
                onMouseLeave: _this2.mouseLeaveHandler.bind(_this2),
                style: {
                  top: track.height * index,
                  right: track.height * index,
                  bottom: track.height * index,
                  left: track.height * index
                },
                className: 'GalleryTracks-module_gallery-track-eGKoq'
              },
              _react2['default'].createElement('div', {
                onMouseEnter: _this2.mouseEnterHandler.bind(_this2),
                style: {
                  top: 0,
                  right: 0,
                  left: 0,
                  height: track.height
                },
                className: 'GalleryTracks-module_gallery-sub-track-z1HEh'
              }),
              _react2['default'].createElement('div', {
                onMouseEnter: _this2.mouseEnterHandler.bind(_this2),
                style: {
                  top: 0,
                  right: 0,
                  bottom: 0,
                  width: track.height
                },
                className: 'GalleryTracks-module_gallery-sub-track-z1HEh'
              }),
              _react2['default'].createElement('div', {
                onMouseEnter: _this2.mouseEnterHandler.bind(_this2),
                style: {
                  right: 0,
                  bottom: 0,
                  left: 0,
                  height: track.height
                },
                className: 'GalleryTracks-module_gallery-sub-track-z1HEh'
              }),
              _react2['default'].createElement('div', {
                onMouseEnter: _this2.mouseEnterHandler.bind(_this2),
                style: {
                  top: 0,
                  bottom: 0,
                  left: 0,
                  width: track.height
                },
                className: 'GalleryTracks-module_gallery-sub-track-z1HEh'
              }),
              _react2['default'].createElement('div', {
                onMouseLeave: _this2.mouseLeaveHandler.bind(_this2),
                style: {
                  top: track.height,
                  right: track.height,
                  bottom: track.height,
                  left: track.height
                },
                className: 'GalleryTracks-module_gallery-invisible-track-1hMJp'
              }),
              _this2.props.editable && _react2['default'].createElement(_TrackControl2['default'], {
                configMenuVisible: true,
                imgStyleAdd: STYLES,
                imgStyleClose: STYLES,
                imgStyleMove: STYLES,
                imgStyleSettings: STYLES,
                isMoveable: false,
                isVisible: _this2.state.hovering,
                onCloseTrackMenuOpened: _this2.props.onCloseTrackMenuOpened,
                onConfigTrackMenuOpened: _this2.props.onConfigTrackMenuOpened,
                uid: track.uid || index
              })
            );
          })
        );
      }

      return render;
    }()
  }]);
  return GalleryTracks;
}(_react2['default'].Component);

GalleryTracks.propTypes = {
  editable: _propTypes2['default'].bool.isRequired,
  onCloseTrackMenuOpened: _propTypes2['default'].func.isRequired,
  onConfigTrackMenuOpened: _propTypes2['default'].func.isRequired,
  tracks: _propTypes2['default'].array.isRequired
};

exports['default'] = GalleryTracks;

/***/ }),
/* 612 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"gallery-tracks":"GalleryTracks-module_gallery-tracks-3tsUO","gallery-track":"GalleryTracks-module_gallery-track-eGKoq","gallery-sub-track":"GalleryTracks-module_gallery-sub-track-z1HEh","gallery-invisible-track":"GalleryTracks-module_gallery-invisible-track-1hMJp"};

/***/ }),
/* 613 */
/***/ (function(module, exports, __nested_webpack_require_3041396__) {

"use strict";


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

var _set = __nested_webpack_require_3041396__(38);

var _set2 = _interopRequireDefault(_set);

var _slicedToArray2 = __nested_webpack_require_3041396__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _stringify = __nested_webpack_require_3041396__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _toConsumableArray2 = __nested_webpack_require_3041396__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _getIterator2 = __nested_webpack_require_3041396__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _keys = __nested_webpack_require_3041396__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getPrototypeOf = __nested_webpack_require_3041396__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3041396__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3041396__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3041396__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3041396__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_3041396__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3041396__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _d3Zoom = __nested_webpack_require_3041396__(157);

var _d3Selection = __nested_webpack_require_3041396__(0);

var _d3Scale = __nested_webpack_require_3041396__(28);

var _slugid = __nested_webpack_require_3041396__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _PixiTrack = __nested_webpack_require_3041396__(40);

var _PixiTrack2 = _interopRequireDefault(_PixiTrack);

var _HeatmapTiledPixiTrack = __nested_webpack_require_3041396__(135);

var _HeatmapTiledPixiTrack2 = _interopRequireDefault(_HeatmapTiledPixiTrack);

var _Id2DTiledPixiTrack = __nested_webpack_require_3041396__(254);

var _Id2DTiledPixiTrack2 = _interopRequireDefault(_Id2DTiledPixiTrack);

var _IdHorizontal1DTiledPixiTrack = __nested_webpack_require_3041396__(347);

var _IdHorizontal1DTiledPixiTrack2 = _interopRequireDefault(_IdHorizontal1DTiledPixiTrack);

var _IdVertical1DTiledPixiTrack = __nested_webpack_require_3041396__(348);

var _IdVertical1DTiledPixiTrack2 = _interopRequireDefault(_IdVertical1DTiledPixiTrack);

var _TopAxisTrack = __nested_webpack_require_3041396__(350);

var _TopAxisTrack2 = _interopRequireDefault(_TopAxisTrack);

var _LeftAxisTrack = __nested_webpack_require_3041396__(351);

var _LeftAxisTrack2 = _interopRequireDefault(_LeftAxisTrack);

var _CombinedTrack = __nested_webpack_require_3041396__(256);

var _CombinedTrack2 = _interopRequireDefault(_CombinedTrack);

var _BedLikeTrack = __nested_webpack_require_3041396__(352);

var _BedLikeTrack2 = _interopRequireDefault(_BedLikeTrack);

var _OverlayTrack = __nested_webpack_require_3041396__(357);

var _OverlayTrack2 = _interopRequireDefault(_OverlayTrack);

var _HorizontalLine1DPixiTrack = __nested_webpack_require_3041396__(116);

var _HorizontalLine1DPixiTrack2 = _interopRequireDefault(_HorizontalLine1DPixiTrack);

var _HorizontalPoint1DPixiTrack = __nested_webpack_require_3041396__(358);

var _HorizontalPoint1DPixiTrack2 = _interopRequireDefault(_HorizontalPoint1DPixiTrack);

var _HorizontalMultivecTrack = __nested_webpack_require_3041396__(359);

var _HorizontalMultivecTrack2 = _interopRequireDefault(_HorizontalMultivecTrack);

var _BarTrack = __nested_webpack_require_3041396__(259);

var _BarTrack2 = _interopRequireDefault(_BarTrack);

var _DivergentBarTrack = __nested_webpack_require_3041396__(360);

var _DivergentBarTrack2 = _interopRequireDefault(_DivergentBarTrack);

var _Horizontal1dHeatmapTrack = __nested_webpack_require_3041396__(361);

var _Horizontal1dHeatmapTrack2 = _interopRequireDefault(_Horizontal1dHeatmapTrack);

var _CNVIntervalTrack = __nested_webpack_require_3041396__(362);

var _CNVIntervalTrack2 = _interopRequireDefault(_CNVIntervalTrack);

var _LeftTrackModifier = __nested_webpack_require_3041396__(631);

var _LeftTrackModifier2 = _interopRequireDefault(_LeftTrackModifier);

var _Track = __nested_webpack_require_3041396__(177);

var _Track2 = _interopRequireDefault(_Track);

var _HorizontalGeneAnnotationsTrack = __nested_webpack_require_3041396__(260);

var _HorizontalGeneAnnotationsTrack2 = _interopRequireDefault(_HorizontalGeneAnnotationsTrack);

var _ArrowheadDomainsTrack = __nested_webpack_require_3041396__(363);

var _ArrowheadDomainsTrack2 = _interopRequireDefault(_ArrowheadDomainsTrack);

var _Annotations2dTrack = __nested_webpack_require_3041396__(364);

var _Annotations2dTrack2 = _interopRequireDefault(_Annotations2dTrack);

var _Annotations1dTrack = __nested_webpack_require_3041396__(365);

var _Annotations1dTrack2 = _interopRequireDefault(_Annotations1dTrack);

var _Horizontal2DDomainsTrack = __nested_webpack_require_3041396__(366);

var _Horizontal2DDomainsTrack2 = _interopRequireDefault(_Horizontal2DDomainsTrack);

var _SquareMarkersTrack = __nested_webpack_require_3041396__(367);

var _SquareMarkersTrack2 = _interopRequireDefault(_SquareMarkersTrack);

var _Chromosome2DLabels = __nested_webpack_require_3041396__(368);

var _Chromosome2DLabels2 = _interopRequireDefault(_Chromosome2DLabels);

var _ChromosomeGrid = __nested_webpack_require_3041396__(369);

var _ChromosomeGrid2 = _interopRequireDefault(_ChromosomeGrid);

var _Chromosome2DAnnotations = __nested_webpack_require_3041396__(370);

var _Chromosome2DAnnotations2 = _interopRequireDefault(_Chromosome2DAnnotations);

var _HorizontalChromosomeLabels = __nested_webpack_require_3041396__(371);

var _HorizontalChromosomeLabels2 = _interopRequireDefault(_HorizontalChromosomeLabels);

var _HorizontalHeatmapTrack = __nested_webpack_require_3041396__(372);

var _HorizontalHeatmapTrack2 = _interopRequireDefault(_HorizontalHeatmapTrack);

var _UnknownPixiTrack = __nested_webpack_require_3041396__(635);

var _UnknownPixiTrack2 = _interopRequireDefault(_UnknownPixiTrack);

var _ValueIntervalTrack = __nested_webpack_require_3041396__(373);

var _ValueIntervalTrack2 = _interopRequireDefault(_ValueIntervalTrack);

var _ViewportTracker2D = __nested_webpack_require_3041396__(374);

var _ViewportTracker2D2 = _interopRequireDefault(_ViewportTracker2D);

var _ViewportTrackerHorizontal = __nested_webpack_require_3041396__(375);

var _ViewportTrackerHorizontal2 = _interopRequireDefault(_ViewportTrackerHorizontal);

var _ViewportTrackerVertical = __nested_webpack_require_3041396__(376);

var _ViewportTrackerVertical2 = _interopRequireDefault(_ViewportTrackerVertical);

var _HorizontalRule = __nested_webpack_require_3041396__(377);

var _HorizontalRule2 = _interopRequireDefault(_HorizontalRule);

var _VerticalRule = __nested_webpack_require_3041396__(262);

var _VerticalRule2 = _interopRequireDefault(_VerticalRule);

var _CrossRule = __nested_webpack_require_3041396__(378);

var _CrossRule2 = _interopRequireDefault(_CrossRule);

var _OSMTilesTrack = __nested_webpack_require_3041396__(141);

var _OSMTilesTrack2 = _interopRequireDefault(_OSMTilesTrack);

var _OSMTileIdsTrack = __nested_webpack_require_3041396__(379);

var _OSMTileIdsTrack2 = _interopRequireDefault(_OSMTileIdsTrack);

var _MapboxTilesTrack = __nested_webpack_require_3041396__(380);

var _MapboxTilesTrack2 = _interopRequireDefault(_MapboxTilesTrack);

var _RasterTilesTrack = __nested_webpack_require_3041396__(381);

var _RasterTilesTrack2 = _interopRequireDefault(_RasterTilesTrack);

var _SVGTrack = __nested_webpack_require_3041396__(80);

var _SVGTrack2 = _interopRequireDefault(_SVGTrack);

var _withPubSub = __nested_webpack_require_3041396__(69);

var _withPubSub2 = _interopRequireDefault(_withPubSub);

var _getDataFetcher = __nested_webpack_require_3041396__(382);

var _getDataFetcher2 = _interopRequireDefault(_getDataFetcher);

var _withTheme = __nested_webpack_require_3041396__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _utils = __nested_webpack_require_3041396__(10);

var _configs = __nested_webpack_require_3041396__(11);

__nested_webpack_require_3041396__(656);

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

// Configs


// Higher-order components
var SCROLL_TIMEOUT = 100;

// Styles


// Utils

var TrackRenderer = function (_React$Component) {
  (0, _inherits3['default'])(TrackRenderer, _React$Component);

  /**
   * Maintain a list of tracks, and re-render them whenever either
   * their size changes or the zoom level changes
   *
   * Zooming changes the domain of the scales.
   *
   * Resizing changes the range. Both trigger a rerender.
   */
  function TrackRenderer(props) {
    (0, _classCallCheck3['default'])(this, TrackRenderer);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (TrackRenderer.__proto__ || (0, _getPrototypeOf2['default'])(TrackRenderer)).call(this, props));

    _this.dragging = false; // is this element being dragged?
    _this.element = null;
    _this.closing = false;

    _this.yPositionOffset = 0;
    _this.xPositionOffset = 0;
    _this.scrollTop = 0;

    _this.scrollTimeout = null;
    _this.activeTransitions = 0;

    _this.zoomTransform = _d3Zoom.zoomIdentity;
    _this.windowScrolledBound = _this.windowScrolled.bind(_this);
    _this.zoomStartedBound = _this.zoomStarted.bind(_this);
    _this.zoomedBound = _this.zoomed.bind(_this);
    _this.zoomEndedBound = _this.zoomEnded.bind(_this);

    _this.uid = _slugid2['default'].nice();
    _this.viewUid = _this.props.uid;

    _this.availableForPlugins = _configs.AVAILABLE_FOR_PLUGINS;
    _this.availableForPlugins.services.pubSub = _this.props.pubSub;
    _this.availableForPlugins.services.pixiRenderer = _this.props.pixiRenderer;

    _this.mounted = false;

    // create a zoom behavior that we'll just use to transform selections
    // without having it fire an "onZoom" event
    _this.emptyZoomBehavior = (0, _d3Zoom.zoom)();

    // a lot of the updates in TrackRenderer happen in response to
    // componentWillReceiveProps so we need to perform them with the
    // newest set of props. When cWRP is called, this.props still contains
    // the old props, so we need to store them in a new variable
    _this.currentProps = props;
    _this.prevPropsStr = '';

    // catch any zooming behavior within all of the tracks in this plot
    // this.zoomTransform = zoomIdentity();
    _this.zoomBehavior = (0, _d3Zoom.zoom)().filter(function () {
      if (_d3Selection.event.target.classList.contains('no-zoom')) {
        return false;
      }
      if (_d3Selection.event.target.classList.contains('react-resizable-handle')) {
        return false;
      }
      return true;
    }).on('start', _this.zoomStartedBound).on('zoom', _this.zoomedBound).on('end', _this.zoomEndedBound);

    _this.zoomTransform = _d3Zoom.zoomIdentity;
    _this.prevZoomTransform = _d3Zoom.zoomIdentity;

    _this.initialXDomain = [0, 1];
    _this.initialYDomain = [0, 1];
    _this.xDomainLimits = [-Infinity, Infinity];
    _this.yDomainLimits = [-Infinity, Infinity];
    _this.zoomLimits = [0, Infinity];

    _this.prevCenterX = _this.currentProps.paddingLeft + _this.currentProps.leftWidth + _this.currentProps.centerWidth / 2;
    _this.prevCenterY = _this.currentProps.paddingTop + _this.currentProps.topHeight + _this.currentProps.centerHeight / 2;

    // The offset of the center from the original. Used to keep the scales centered on resize events
    _this.cumCenterXOffset = 0;
    _this.cumCenterYOffset = 0;

    _this.setUpInitialScales(_this.currentProps.initialXDomain, _this.currentProps.initialYDomain, _this.currentProps.xDomainLimits, _this.currentProps.yDomainLimits, _this.currentProps.zoomLimits);

    _this.setUpScales();

    // maintain a list of trackDefObjects which correspond to the input
    // tracks
    // Each object will contain a trackDef
    // {'top': 100, 'left': 50,... 'track': {'source': 'http:...', 'type': 'heatmap'}}
    // And a trackObject which will be responsible for rendering it
    _this.trackDefObjects = {};

    _this.metaTracks = {};

    _this.pubSubs = [];

    // if there's plugin tracks, they'll define new track
    // types and we'll want to use their information when
    // we look up the orientation of a track
    if (window.higlassTracksByType) {
      // Extend `TRACKS_INFO_BY_TYPE` with the configs of plugin tracks.
      (0, _keys2['default'])(window.higlassTracksByType).forEach(function (pluginTrackType) {
        _configs.TRACKS_INFO_BY_TYPE[pluginTrackType] = window.higlassTracksByType[pluginTrackType].config;
      });
    }

    _this.boundForwardEvent = _this.forwardEvent.bind(_this);
    _this.boundScrollEvent = _this.scrollEvent.bind(_this);
    _this.boundForwardContextMenu = _this.forwardContextMenu.bind(_this);
    _this.dispatchEventBound = _this.dispatchEvent.bind(_this);
    _this.zoomToDataPosHandlerBound = _this.zoomToDataPosHandler.bind(_this);
    _this.onScrollHandlerBound = _this.onScrollHandler.bind(_this);
    return _this;
  }

  // eslint-disable-next-line camelcase


  (0, _createClass3['default'])(TrackRenderer, [{
    key: 'UNSAFE_componentWillMount',
    value: function () {
      function UNSAFE_componentWillMount() {
        this.pubSubs = [];
        this.pubSubs.push(this.props.pubSub.subscribe('scroll', this.windowScrolledBound));
        this.pubSubs.push(this.props.pubSub.subscribe('app.event', this.dispatchEventBound));
        this.pubSubs.push(this.props.pubSub.subscribe('zoomToDataPos', this.zoomToDataPosHandlerBound));
        this.pubSubs.push(this.props.pubSub.subscribe('app.scroll', this.onScrollHandlerBound));
      }

      return UNSAFE_componentWillMount;
    }()
  }, {
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        this.elementPos = this.element.getBoundingClientRect();
        this.elementSelection = (0, _d3Selection.select)(this.element);
        this.svgTrackAreaSelection = (0, _d3Selection.select)(this.svgTrackArea);

        this.pStage = new _configs.GLOBALS.PIXI.Graphics();
        this.pMask = new _configs.GLOBALS.PIXI.Graphics();
        this.pOutline = new _configs.GLOBALS.PIXI.Graphics();
        this.pBackground = new _configs.GLOBALS.PIXI.Graphics();

        this.pStage.addChild(this.pMask);
        this.pStage.addChild(this.pOutline);

        this.currentProps.pixiStage.addChild(this.pStage);

        this.pStage.mask = this.pMask;

        if (!this.props.isRangeSelection) this.addZoom();

        // need to be mounted to make sure that all the renderers are
        // created before starting to draw tracks
        if (!this.currentProps.svgElement || !this.currentProps.canvasElement) {
          return;
        }

        this.svgElement = this.currentProps.svgElement;
        this.syncTrackObjects(this.currentProps.positionedTracks);
        this.syncMetaTracks(this.currentProps.metaTracks);

        this.currentProps.setCentersFunction(this.setCenter.bind(this));
        this.currentProps.registerDraggingChangedListener(this.draggingChanged.bind(this));

        this.draggingChanged(true);
        this.addEventTracker();

        // Init zoom and scale extent
        var transExt = [[this.xScale(this.xDomainLimits[0]), this.yScale(this.yDomainLimits[0])], [this.xScale(this.xDomainLimits[1]), this.yScale(this.yDomainLimits[1])]];

        var svgBBox = this.svgElement.getBoundingClientRect();

        var ext = [[Math.max(transExt[0][0], 0), Math.max(transExt[0][1], 0)], [Math.min(transExt[1][0], svgBBox.width), Math.min(transExt[1][1], svgBBox.height)]];

        this.zoomBehavior.extent(ext).translateExtent(transExt).scaleExtent(this.zoomLimits);
      }

      return componentDidMount;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(nextProps) {
        /**
         * The size of some tracks probably changed, so let's just
         * redraw them.
         */
        // don't initiate this component if it has nothing to draw on
        if (!nextProps.svgElement || !nextProps.canvasElement) {
          return;
        }

        var nextPropsStr = this.updatablePropsToString(nextProps);
        this.currentProps = nextProps;

        if (this.prevPropsStr === nextPropsStr) return;

        this.setBackground();

        for (var uid in this.trackDefObjects) {
          var track = this.trackDefObjects[uid].trackObject;

          track.delayDrawing = true;
        }

        this.prevPropsStr = nextPropsStr;

        this.setUpInitialScales(nextProps.initialXDomain, nextProps.initialYDomain, nextProps.xDomainLimits, nextProps.yDomainLimits, nextProps.zoomLimits);

        this.setUpScales(nextProps.width !== this.props.width || nextProps.height !== this.props.height);

        this.svgElement = nextProps.svgElement;

        var transExt = [[this.xScale(this.xDomainLimits[0]), this.yScale(this.yDomainLimits[0])], [this.xScale(this.xDomainLimits[1]), this.yScale(this.yDomainLimits[1])]];

        var svgBBox = this.svgElement.getBoundingClientRect();

        var ext = [[Math.max(transExt[0][0], 0), Math.max(transExt[0][1], 0)], [Math.min(transExt[1][0], svgBBox.width), Math.min(transExt[1][1], svgBBox.height)]];

        this.zoomBehavior.extent(ext).translateExtent(transExt).scaleExtent(this.zoomLimits);

        this.syncTrackObjects(nextProps.positionedTracks);
        this.syncMetaTracks(nextProps.metaTracks);

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(nextProps.positionedTracks), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var _track = _step.value;

            // tracks all the way down
            var options = _track.track.options;
            var trackObject = this.trackDefObjects[_track.track.uid].trackObject;
            trackObject.rerender(options);

            if (_track.track.hasOwnProperty('contents')) {
              var ctDefs = {};
              var _iteratorNormalCompletion2 = true;
              var _didIteratorError2 = false;
              var _iteratorError2 = undefined;

              try {
                for (var _iterator2 = (0, _getIterator3['default'])(_track.track.contents), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                  var ct = _step2.value;

                  ctDefs[ct.uid] = ct;
                }
              } catch (err) {
                _didIteratorError2 = true;
                _iteratorError2 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion2 && _iterator2['return']) {
                    _iterator2['return']();
                  }
                } finally {
                  if (_didIteratorError2) {
                    throw _iteratorError2;
                  }
                }
              }

              for (var _uid2 in trackObject.createdTracks) {
                trackObject.createdTracks[_uid2].rerender(ctDefs[_uid2].options);
              }
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        this.props.onNewTilesLoaded();

        for (var _uid in this.trackDefObjects) {
          var _track2 = this.trackDefObjects[_uid].trackObject;

          _track2.delayDrawing = false;
          _track2.draw();
        }
      }

      return UNSAFE_componentWillReceiveProps;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate(prevProps) {
        // If the initial domain changed, a new view config
        // probably has loaded. Reset the element's zoomTransform in this case.
        // In D3, an element’s transform is stored internally as element.__zoom
        if (this.props.initialXDomain[0] !== prevProps.initialXDomain[0] || this.props.initialXDomain[1] !== prevProps.initialXDomain[1] || this.props.initialYDomain[0] !== prevProps.initialYDomain[0] || this.props.initialYDomain[1] !== prevProps.initialYDomain[1]) {
          this.element.__zoom = _d3Zoom.zoomIdentity;
        }

        if (prevProps.isRangeSelection !== this.props.isRangeSelection) {
          if (this.props.isRangeSelection) {
            this.removeZoom();
          } else {
            this.addZoom();
          }
        }

        if (prevProps.zoomable !== this.props.zoomable) {
          if (this.props.zoomable) {
            this.addZoom();
          } else {
            this.removeZoom();
          }
        }

        this.addEventTracker();
      }

      return componentDidUpdate;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        var _this2 = this;

        /**
         * This view has been removed so we need to get rid of all the tracks it contains
         */
        this.mounted = false;
        this.removeTracks((0, _keys2['default'])(this.trackDefObjects));
        this.removeMetaTracks((0, _keys2['default'])(this.metaTracks));
        this.currentProps.removeDraggingChangedListener(this.draggingChanged);

        this.currentProps.pixiStage.removeChild(this.pStage);

        this.pMask.destroy(true);
        this.pStage.destroy(true);

        this.pubSubs.forEach(function (subscription) {
          return _this2.props.pubSub.unsubscribe(subscription);
        });
        this.pubSubs = [];

        this.removeEventTracker();
      }

      return componentWillUnmount;
    }()

    /* --------------------------- Custom Methods ----------------------------- */

    /**
     * Dispatch a forwarded event on the main DOM element
     *
     * @param  {Object}  e  Event to be dispatched.
     */

  }, {
    key: 'dispatchEvent',
    value: function () {
      function dispatchEvent(e) {
        if (e.sourceUid === this.uid && e.type !== 'contextmenu') {
          (0, _utils.forwardEvent)(e, this.element);
        }
      }

      return dispatchEvent;
    }()

    /**
     * Check of a view position (i.e., pixel coords) is within this view
     *
     * @param  {Number}  x  X position to be tested.
     * @param  {Number}  y  Y position to be tested.
     * @return  {Boolean}   If `true` position is within this view.
     */

  }, {
    key: 'isWithin',
    value: function () {
      function isWithin(x, y) {
        if (!this.element) return false;

        var withinX = x >= this.elementPos.left && x <= this.elementPos.width + this.elementPos.left;
        var withinY = y >= this.elementPos.top && y <= this.elementPos.height + this.elementPos.top;

        return withinX && withinY;
      }

      return isWithin;
    }()
  }, {
    key: 'zoomToDataPosHandler',
    value: function () {
      function zoomToDataPosHandler(_ref) {
        var pos = _ref.pos,
            animateTime = _ref.animateTime,
            isMercator = _ref.isMercator;

        this.zoomToDataPos.apply(this, (0, _toConsumableArray3['default'])(pos).concat([animateTime, isMercator]));
      }

      return zoomToDataPosHandler;
    }()
  }, {
    key: 'addZoom',
    value: function () {
      function addZoom() {
        if (!this.elementSelection || !this.currentProps.zoomable) return;

        this.elementSelection.call(this.zoomBehavior);
        this.zoomBehavior.transform(this.elementSelection, this.zoomTransform);
      }

      return addZoom;
    }()
  }, {
    key: 'removeZoom',
    value: function () {
      function removeZoom() {
        if (this.elementSelection) {
          this.zoomEnded();
          this.elementSelection.on('.zoom', null);
        }
      }

      return removeZoom;
    }()

    /*
     * Add a mask to make sure that the tracks displayed in this view
     * don't overflow its bounds.
     */

  }, {
    key: 'setMask',
    value: function () {
      function setMask() {
        this.pMask.clear();
        this.pMask.beginFill();
        this.pMask.drawRect(this.xPositionOffset, this.yPositionOffset, this.currentProps.width, this.currentProps.height);
        this.pMask.endFill();

        // show the bounds of this view
        /*
        this.pOutline.clear();
        this.pOutline.lineStyle(1, '#000', 1);
        this.pOutline.drawRect(
          this.xPositionOffset, this.yPositionOffset, this.currentProps.width, this.currentProps.height
        );
        */
      }

      return setMask;
    }()
  }, {
    key: 'setBackground',
    value: function () {
      function setBackground() {
        var defBgColor = this.props.theme === _configs.THEME_DARK ? 'black' : 'white';
        var bgColor = (0, _utils.colorToHex)(this.currentProps.viewOptions && this.currentProps.viewOptions.backgroundColor || defBgColor);

        this.pBackground.clear();
        this.pBackground.beginFill(bgColor);
        this.pBackground.drawRect(this.xPositionOffset, this.yPositionOffset, this.currentProps.width, this.currentProps.height);
        this.pBackground.endFill();
      }

      return setBackground;
    }()
  }, {
    key: 'windowScrolled',
    value: function () {
      function windowScrolled() {
        var _this3 = this;

        this.removeZoom();

        if (this.scrollTimeout) {
          clearTimeout(this.scrollTimeout);
        }

        this.scrollTimeout = setTimeout(function () {
          _this3.addZoom();
        }, SCROLL_TIMEOUT);
      }

      return windowScrolled;
    }()
  }, {
    key: 'setUpInitialScales',
    value: function () {
      function setUpInitialScales() {
        var initialXDomain = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [0, 1];
        var initialYDomain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0, 1];
        var xDomainLimits = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [-Infinity, Infinity];
        var yDomainLimits = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [-Infinity, Infinity];
        var zoomLimits = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [0, Infinity];

        // Make sure the initial domain is within the limits first
        zoomLimits[0] = zoomLimits[0] === null ? 0 : zoomLimits[0];
        zoomLimits[1] = zoomLimits[1] === null ? Infinity : zoomLimits[1];

        // make sure the two scales are equally wide:
        var xWidth = initialXDomain[1] - initialXDomain[0];
        var yCenter = (initialYDomain[0] + initialYDomain[1]) / 2;
        // initialYDomain = [yCenter - xWidth / 2, yCenter + xWidth / 2];

        // stretch out the y-scale so that views aren't distorted (i.e. maintain
        // a 1 to 1 ratio)
        initialYDomain[0] = yCenter - xWidth / 2;
        initialYDomain[1] = yCenter + xWidth / 2;

        // if the inital domains haven't changed, then we don't have to
        // worry about resetting anything
        // initial domains should only change when loading a new viewconfig
        if (initialXDomain[0] === this.initialXDomain[0] && initialXDomain[1] === this.initialXDomain[1] && initialYDomain[0] === this.initialYDomain[0] && initialYDomain[1] === this.initialYDomain[1] && xDomainLimits[0] === this.xDomainLimits[0] && xDomainLimits[1] === this.xDomainLimits[1] && yDomainLimits[0] === this.yDomainLimits[0] && yDomainLimits[1] === this.yDomainLimits[1] && zoomLimits[0] === this.zoomLimits[0] && zoomLimits[1] === this.zoomLimits[1]) return;

        // only update the initial domain
        this.initialXDomain = initialXDomain;
        this.initialYDomain = initialYDomain;
        this.xDomainLimits = xDomainLimits;
        this.yDomainLimits = yDomainLimits;
        this.zoomLimits = zoomLimits;

        // Reset the local record of the zoom transform to avoid
        // pan & zoom jumps when saving the viewconfig
        this.zoomTransform = _d3Zoom.zoomIdentity;
        this.prevZoomTransform = _d3Zoom.zoomIdentity;

        this.cumCenterYOffset = 0;
        this.cumCenterXOffset = 0;

        this.drawableToDomainX = (0, _d3Scale.scaleLinear)().domain([this.currentProps.paddingLeft + this.currentProps.leftWidth, this.currentProps.paddingLeft + this.currentProps.leftWidth + this.currentProps.centerWidth]).range([initialXDomain[0], initialXDomain[1]]);

        var startY = void 0;var endY = void 0;
        if (this.currentProps.centerWidth === 0) {
          // If the width of the center track is zero, we do not want to make startY and endY equal.
          startY = this.currentProps.paddingTop + this.currentProps.topHeight;
          endY = this.currentProps.paddingTop + this.currentProps.topHeight + this.currentProps.centerHeight;
        } else {
          startY = this.currentProps.paddingTop + this.currentProps.topHeight + this.currentProps.centerHeight / 2 - this.currentProps.centerWidth / 2;
          endY = this.currentProps.paddingTop + this.currentProps.topHeight + this.currentProps.centerHeight / 2 + this.currentProps.centerWidth / 2;
        }
        this.drawableToDomainY = (0, _d3Scale.scaleLinear)().domain([startY, endY]).range([initialYDomain[0], initialYDomain[1]]);

        this.prevCenterX = this.currentProps.paddingLeft + this.currentProps.leftWidth + this.currentProps.centerWidth / 2;
        this.prevCenterY = this.currentProps.paddingTop + this.currentProps.topHeight + this.currentProps.centerHeight / 2;
      }

      return setUpInitialScales;
    }()
  }, {
    key: 'updatablePropsToString',
    value: function () {
      function updatablePropsToString(props) {
        return (0, _stringify2['default'])({
          positionedTracks: props.positionedTracks,
          initialXDomain: props.initialXDomain,
          initialYDomain: props.initialYDomain,
          width: props.width,
          height: props.height,
          paddingLeft: props.paddingLeft,
          paddingTop: props.paddingTop,
          leftWidth: props.leftWidth,
          topHeight: props.topHeight,
          dragging: props.dragging,
          viewOptions: props.viewOptions
        });
      }

      return updatablePropsToString;
    }()
  }, {
    key: 'draggingChanged',
    value: function () {
      function draggingChanged(draggingStatus) {
        this.dragging = draggingStatus;

        this.timedUpdatePositionAndDimensions();
      }

      return draggingChanged;
    }()
  }, {
    key: 'setUpScales',
    value: function () {
      function setUpScales() {
        var notify = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        var currentCenterX = this.currentProps.paddingLeft + this.currentProps.leftWidth + this.currentProps.centerWidth / 2;
        var currentCenterY = this.currentProps.paddingTop + this.currentProps.topHeight + this.currentProps.centerHeight / 2;

        // we need to maintain two scales:
        // 1. the scale that is shown
        // 2. the scale that the zooming behavior acts on
        //
        // These need to be separated because the zoom behavior acts on a larger
        // region than the visible scale shows

        // if the window is resized, we don't want to change the scale, but we do
        // want to move the center point. this needs to be tempered by the zoom
        // factor so that we keep the visible center point in the center
        var centerDomainXOffset = (this.drawableToDomainX(currentCenterX) - this.drawableToDomainX(this.prevCenterX)) / this.zoomTransform.k;
        var centerDomainYOffset = (this.drawableToDomainY(currentCenterY) - this.drawableToDomainY(this.prevCenterY)) / this.zoomTransform.k;

        this.cumCenterYOffset += centerDomainYOffset;
        this.cumCenterXOffset += centerDomainXOffset;

        this.prevCenterY = currentCenterY;
        this.prevCenterX = currentCenterX;

        // the domain of the visible (not drawable area)
        var visibleXDomain = [this.drawableToDomainX(0) - this.cumCenterXOffset, this.drawableToDomainX(this.currentProps.width) - this.cumCenterXOffset];
        var visibleYDomain = [this.drawableToDomainY(0) - this.cumCenterYOffset, this.drawableToDomainY(this.currentProps.height) - this.cumCenterYOffset];

        // [drawableToDomain(0), drawableToDomain(1)]: the domain of the visible area
        // if the screen has been resized, then the domain width should remain the same

        // this.xScale should always span the region that the zoom behavior is being called on
        this.xScale = (0, _d3Scale.scaleLinear)().domain(visibleXDomain).range([0, this.currentProps.width]);

        this.yScale = (0, _d3Scale.scaleLinear)().domain(visibleYDomain).range([0, this.currentProps.height]);

        for (var uid in this.trackDefObjects) {
          var track = this.trackDefObjects[uid].trackObject;

          // e.g. when the track is resized... we want to redraw it
          track.refScalesChanged(this.xScale, this.yScale);
          // track.draw();
        }

        this.applyZoomTransform(notify);
      }

      return setUpScales;
    }()

    /**
     * Get a track's viewconf definition by its object
     */

  }, {
    key: 'getTrackDef',
    value: function () {
      function getTrackDef(trackObjectIn) {
        var trackDefItems = (0, _utils.dictItems)(this.trackDefObjects);

        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = undefined;

        try {
          for (var _iterator3 = (0, _getIterator3['default'])(trackDefItems), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
            var _ref2 = _step3.value;

            var _ref3 = (0, _slicedToArray3['default'])(_ref2, 2);

            var _ref3$ = _ref3[1];
            var trackDef = _ref3$.trackDef;
            var trackObject = _ref3$.trackObject;

            if (trackObject === trackObjectIn) {
              return trackDef.track;
            }
            if (trackDef.track.contents) {
              // this is a combined track
              var _iteratorNormalCompletion4 = true;
              var _didIteratorError4 = false;
              var _iteratorError4 = undefined;

              try {
                for (var _iterator4 = (0, _getIterator3['default'])(trackDef.track.contents), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                  var subTrackDef = _step4.value;

                  if (trackObject.createdTracks[subTrackDef.uid] === trackObjectIn) {
                    return subTrackDef;
                  }
                }
              } catch (err) {
                _didIteratorError4 = true;
                _iteratorError4 = err;
              } finally {
                try {
                  if (!_iteratorNormalCompletion4 && _iterator4['return']) {
                    _iterator4['return']();
                  }
                } finally {
                  if (_didIteratorError4) {
                    throw _iteratorError4;
                  }
                }
              }
            }
          }
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3['return']) {
              _iterator3['return']();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }

        return null;
      }

      return getTrackDef;
    }()

    /*
     * Fetch the trackObject for a track with a given ID
     */

  }, {
    key: 'getTrackObject',
    value: function () {
      function getTrackObject(trackId) {
        var trackDefItems = (0, _utils.dictItems)(this.trackDefObjects);

        for (var i = 0; i < trackDefItems.length; i++) {
          var uid = trackDefItems[i][0];
          var trackObject = trackDefItems[i][1].trackObject;

          if (uid === trackId) {
            return trackObject;
          }

          // maybe this track is in a combined track
          if (trackObject.createdTracks) {
            var createdTrackItems = (0, _utils.dictItems)(trackObject.createdTracks);

            for (var j = 0; j < createdTrackItems.length; j++) {
              var createdTrackUid = createdTrackItems[j][0];
              var createdTrackObject = createdTrackItems[j][1];

              if (createdTrackUid === trackId) {
                return createdTrackObject;
              }
            }
          }
        }

        return undefined;
      }

      return getTrackObject;
    }()
  }, {
    key: 'timedUpdatePositionAndDimensions',
    value: function () {
      function timedUpdatePositionAndDimensions() {
        if (this.closing || !this.element) return;

        this.elementPos = this.element.getBoundingClientRect();

        if (this.dragging) {
          this.yPositionOffset = this.element.getBoundingClientRect().top - this.currentProps.canvasElement.getBoundingClientRect().top + this.scrollTop;
          this.xPositionOffset = this.element.getBoundingClientRect().left - this.currentProps.canvasElement.getBoundingClientRect().left;

          this.setMask();
          this.setBackground();

          var updated = this.updateTrackPositions();

          if (updated) {
            // only redraw if positions changed
            this.applyZoomTransform(true);
          }

          requestAnimationFrame(this.timedUpdatePositionAndDimensions.bind(this));
        }
      }

      return timedUpdatePositionAndDimensions;
    }()
  }, {
    key: 'syncMetaTracks',
    value: function () {
      function syncMetaTracks(trackDefinitions) {
        var _this4 = this;

        var knownMetaTrackIds = (0, _keys2['default'])(this.metaTracks);
        var newMetaTracks = new _set2['default'](trackDefinitions.map(function (def) {
          return def.uid;
        }));

        // Add new meta tracks
        this.addMetaTracks(trackDefinitions.filter(function (def) {
          return !_this4.metaTracks[def.uid];
        }));

        // Update existing meta tracks
        this.updateMetaTracks(trackDefinitions.filter(function (def) {
          return _this4.metaTracks[def.uid];
        }));

        // Remove old meta tracks
        this.removeMetaTracks(knownMetaTrackIds.filter(function (def) {
          return !newMetaTracks.has(def);
        }));
      }

      return syncMetaTracks;
    }()
  }, {
    key: 'syncTrackObjects',
    value: function () {
      function syncTrackObjects(trackDefinitions) {
        /**
         * Make sure we have a track object for every passed track definition.
         *
         * If we get a track definition for which we have no Track object, we
         * create a new one.
         *
         * If we have a track object for which we have no definition, we remove
         * the object.
         *
         * All the others we ignore.
         *
         * Track definitions should be of the following form:
         *
         * { height:  100, width: 50, top: 30, left: 40, track: {...}}
         *
         * @param trackDefinitions: The definition of the track
         * @return: Nothing
         */
        this.prevTrackDefinitions = (0, _stringify2['default'])(trackDefinitions);

        var receivedTracksDict = {};
        for (var i = 0; i < trackDefinitions.length; i++) {
          receivedTracksDict[trackDefinitions[i].track.uid] = trackDefinitions[i];
        }

        var knownTracks = new _set2['default']((0, _keys2['default'])(this.trackDefObjects));
        var receivedTracks = new _set2['default']((0, _keys2['default'])(receivedTracksDict));

        // track definitions we don't have objects for
        var enterTrackDefs = new _set2['default']([].concat((0, _toConsumableArray3['default'])(receivedTracks)).filter(function (x) {
          return !knownTracks.has(x);
        }));

        // track objects for which there is no definition
        // (i.e. they no longer need to exist)
        var exitTracks = new _set2['default']([].concat((0, _toConsumableArray3['default'])(knownTracks)).filter(function (x) {
          return !receivedTracks.has(x);
        }));

        // we already have these tracks, but need to change their dimensions
        var updateTrackDefs = new _set2['default']([].concat((0, _toConsumableArray3['default'])(receivedTracks)).filter(function (x) {
          return knownTracks.has(x);
        }));

        // update existing tracks
        this.updateExistingTrackDefs([].concat((0, _toConsumableArray3['default'])(updateTrackDefs)).map(function (x) {
          return receivedTracksDict[x];
        }));

        // add new tracks and update them (setting dimensions and positions)
        this.addNewTracks([].concat((0, _toConsumableArray3['default'])(enterTrackDefs)).map(function (x) {
          return receivedTracksDict[x];
        }));
        this.updateExistingTrackDefs([].concat((0, _toConsumableArray3['default'])(enterTrackDefs)).map(function (x) {
          return receivedTracksDict[x];
        }));

        this.removeTracks([].concat((0, _toConsumableArray3['default'])(exitTracks)));
      }

      return syncTrackObjects;
    }()

    /**
     * Add new meta tracks
     *
     * @param  {Array}  metaTrackDefs  Definitions of meta tracks to be added.
     */

  }, {
    key: 'addMetaTracks',
    value: function () {
      function addMetaTracks(metaTrackDefs) {
        var _this5 = this;

        metaTrackDefs.filter(function (metaTrackDef) {
          return !_this5.metaTracks[metaTrackDef.uid];
        }).forEach(function (metaTrackDef) {
          _this5.metaTracks[metaTrackDef.uid] = {
            trackDef: metaTrackDef,
            trackObject: _this5.createMetaTrack(metaTrackDef)
          };
        });
      }

      return addMetaTracks;
    }()
  }, {
    key: 'addNewTracks',
    value: function () {
      function addNewTracks(newTrackDefinitions) {
        /**
         * We need to create new track objects for the given track
         * definitions.
         */
        if (!this.currentProps.pixiStage) {
          return;
        } // we need a pixi stage to start rendering
        // the parent component where it lives probably
        // hasn't been mounted yet

        for (var i = 0; i < newTrackDefinitions.length; i++) {
          var newTrackDef = newTrackDefinitions[i];
          var newTrackObj = this.createTrackObject(newTrackDef.track);

          // newTrackObj.refXScale(this.xScale);
          // newTrackObj.refYScale(this.yScale);

          newTrackObj.refScalesChanged(this.xScale, this.yScale);

          this.trackDefObjects[newTrackDef.track.uid] = {
            trackDef: newTrackDef,
            trackObject: newTrackObj
          };

          var zoomedXScale = this.zoomTransform.rescaleX(this.xScale);
          var zoomedYScale = this.zoomTransform.rescaleY(this.yScale);

          newTrackObj.setDimensions([newTrackDef.width, newTrackDef.height]);
          newTrackObj.zoomed(zoomedXScale, zoomedYScale);
        }

        // this could be replaced with a call that only applies the zoom
        // transform to the newly added tracks
        this.applyZoomTransform(false);
      }

      return addNewTracks;
    }()
  }, {
    key: 'updateMetaTracks',
    value: function () {
      function updateMetaTracks() {
        // Nothing
      }

      return updateMetaTracks;
    }()
  }, {
    key: 'updateExistingTrackDefs',
    value: function () {
      function updateExistingTrackDefs(newTrackDefs) {
        for (var i = 0; i < newTrackDefs.length; i++) {
          this.trackDefObjects[newTrackDefs[i].track.uid].trackDef = newTrackDefs[i];

          // if it's a CombinedTrack, we have to see if its contents have changed
          // e.g. somebody may have added a new Series
          if (newTrackDefs[i].track.type === 'combined') {
            this.trackDefObjects[newTrackDefs[i].track.uid].trackObject.updateContents(newTrackDefs[i].track.contents, this.createTrackObject.bind(this)).refScalesChanged(this.xScale, this.yScale);
          }
        }

        var updated = this.updateTrackPositions();
        // this.applyZoomTransform();
        if (updated) {
          // only redraw if positions changed
          this.applyZoomTransform(false);
        }
      }

      return updateExistingTrackDefs;
    }()
  }, {
    key: 'updateTrackPositions',
    value: function () {
      function updateTrackPositions() {
        var updated = false;

        for (var uid in this.trackDefObjects) {
          var trackDef = this.trackDefObjects[uid].trackDef;
          var trackObject = this.trackDefObjects[uid].trackObject;

          var prevPosition = trackObject.position;
          var prevDimensions = trackObject.dimensions;

          var newPosition = [this.xPositionOffset + trackDef.left, this.yPositionOffset + trackDef.top];
          var newDimensions = [trackDef.width, trackDef.height];

          // check if any of the track's positions have changed
          // before trying to update them

          if (!prevPosition || newPosition[0] !== prevPosition[0] || newPosition[1] !== prevPosition[1]) {
            trackObject.setPosition(newPosition);
            updated = true;
          }

          if (!prevDimensions || newDimensions[0] !== prevDimensions[0] || newDimensions[1] !== prevDimensions[1]) {
            trackObject.setDimensions(newDimensions);
            updated = true;
          }

          // const widthDifference = trackDef.width - this.currentProps.width;
          // const heightDifference = trackDef.height - this.currentProps.height;
        }

        // report on whether any track positions or dimensions have changed
        // so that downstream code can decide whether to redraw
        return updated;
      }

      return updateTrackPositions;
    }()
  }, {
    key: 'removeMetaTracks',
    value: function () {
      function removeMetaTracks(trackIds) {
        var _this6 = this;

        trackIds.forEach(function (id) {
          _this6.metaTracks[id].trackObject.remove();
          _this6.metaTracks[id] = undefined;
          delete _this6.metaTracks[id];
        });
      }

      return removeMetaTracks;
    }()
  }, {
    key: 'removeTracks',
    value: function () {
      function removeTracks(trackUids) {
        for (var i = 0; i < trackUids.length; i++) {
          this.trackDefObjects[trackUids[i]].trackObject.remove();
          delete this.trackDefObjects[trackUids[i]];
        }
      }

      return removeTracks;
    }()

    /**
     * Set the center of this view to a paticular X and Y coordinate
     * @param  {number}  centerX  Centeral X data? position.
     * @param  {number}  centerY  Central Y data? position.
     * @param  {number}  sourceK  Source zoom level? @Pete what's the source?
     * @param  {boolean}  notify  If `true` notify listeners that the scales
     *   have changed. This can be turned off to prevent circular updates when
     *   scales are locked.
     * @param  {boolean}  animate  If `true` transition smoothly from the
     *   current to the desired location.
     * @param  {number}  animateTime  Animation time in milliseconds. Only used
     *   when `animate` is true.
     */

  }, {
    key: 'setCenter',
    value: function () {
      function setCenter(centerX, centerY, sourceK) {
        var notify = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
        var animateTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;

        var _this7 = this;

        var xScale = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : this.xScale;
        var yScale = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : this.yScale;

        var refK = this.xScale.invert(1) - this.xScale.invert(0);

        var k = refK / sourceK;

        var middleViewX = this.currentProps.paddingLeft + this.currentProps.leftWidth + this.currentProps.centerWidth / 2;
        var middleViewY = this.currentProps.paddingTop + this.currentProps.topHeight + this.currentProps.centerHeight / 2;

        // After applying the zoom transform, the xScale of the target centerX
        // should be equal to the middle of the viewport
        // xScale(centerX) * k + translate[0] = middleViewX
        var translateX = middleViewX - xScale(centerX) * k;
        var translateY = middleViewY - yScale(centerY) * k;

        var last = void 0;

        var setZoom = function () {
          function setZoom() {
            var newTransform = _d3Zoom.zoomIdentity.translate(translateX, translateY).scale(k);

            _this7.zoomTransform = newTransform;
            _this7.emptyZoomBehavior.transform(_this7.elementSelection, newTransform);

            last = _this7.applyZoomTransform(notify);
          }

          return setZoom;
        }();

        if (animateTime) {
          var selection = this.elementSelection;

          this.activeTransitions += 1;

          if (!document.hidden) {
            // only transition if the window is hidden
            selection = selection.transition().duration(animateTime);
          }

          selection.call(this.zoomBehavior.transform, _d3Zoom.zoomIdentity.translate(translateX, translateY).scale(k)).on('end', function () {
            setZoom();
            _this7.activeTransitions -= 1;
          });
        } else {
          setZoom();
        }

        return last;
      }

      return setCenter;
    }()
  }, {
    key: 'valueScaleMove',
    value: function () {
      function valueScaleMove(movement) {
        // mouse wheel from zoom event
        // const cp = clientPoint(this.props.canvasElement, event.sourceEvent);
        var _iteratorNormalCompletion5 = true;
        var _didIteratorError5 = false;
        var _iteratorError5 = undefined;

        try {
          for (var _iterator5 = (0, _getIterator3['default'])(this.getTracksAtPosition.apply(this, (0, _toConsumableArray3['default'])(this.zoomStartPos))), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
            var track = _step5.value;

            track.movedY(movement);
          }
        } catch (err) {
          _didIteratorError5 = true;
          _iteratorError5 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion5 && _iterator5['return']) {
              _iterator5['return']();
            }
          } finally {
            if (_didIteratorError5) {
              throw _iteratorError5;
            }
          }
        }

        this.zoomTransform = this.zoomStartTransform;
      }

      return valueScaleMove;
    }()
  }, {
    key: 'valueScaleZoom',
    value: function () {
      function valueScaleZoom(orientation) {
        // mouse move probably from a drag event
        var mdy = _d3Selection.event.sourceEvent.deltaY;
        var mdm = _d3Selection.event.sourceEvent.deltaMode;

        var myWheelDelta = function () {
          function myWheelDelta(dy, dm) {
            return dy * (dm ? 120 : 1) / 500;
          }

          return myWheelDelta;
        }();
        var mwd = myWheelDelta(mdy, mdm);

        var cp = (0, _d3Selection.clientPoint)(this.props.canvasElement, _d3Selection.event.sourceEvent);

        var _iteratorNormalCompletion6 = true;
        var _didIteratorError6 = false;
        var _iteratorError6 = undefined;

        try {
          for (var _iterator6 = (0, _getIterator3['default'])(this.getTracksAtPosition.apply(this, (0, _toConsumableArray3['default'])(cp))), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
            var track = _step6.value;

            var yPos = orientation === '1d-horizontal' ? cp[1] - track.position[1] : cp[0] - track.position[0];
            track.zoomedY(yPos, Math.pow(2, mwd));
          }

          // reset the zoom transform
        } catch (err) {
          _didIteratorError6 = true;
          _iteratorError6 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion6 && _iterator6['return']) {
              _iterator6['return']();
            }
          } finally {
            if (_didIteratorError6) {
              throw _iteratorError6;
            }
          }
        }

        this.zoomTransform = this.zoomStartTransform;
      }

      return valueScaleZoom;
    }()

    /**
     * Respond to a zoom event.
     *
     * We need to update our local record of the zoom transform and apply it
     * to all the tracks.
     */

  }, {
    key: 'zoomed',
    value: function () {
      function zoomed() {
        // the orientation of the track where we started zooming
        // if it's a 1d-horizontal, then mousemove events shouldn't
        // move the center track vertically
        var trackOrientation = null;

        // see what orientation of track we're over so that we decide
        // whether to move the value scale or the position scale
        if (this.zoomStartPos) {
          var tracksAtZoomStart = this.getTracksAtPosition.apply(this, (0, _toConsumableArray3['default'])(this.zoomStartPos));
          if (tracksAtZoomStart.length) {
            var trackAtZoomStart = tracksAtZoomStart[0];
            var trackDef = this.getTrackDef(trackAtZoomStart);

            if (_configs.TRACKS_INFO_BY_TYPE[trackDef.type]) {
              // some track types (like overlay-track don't have a track info)
              trackOrientation = _configs.TRACKS_INFO_BY_TYPE[trackDef.type].orientation;
            }

            if (trackAtZoomStart instanceof _LeftTrackModifier2['default']) {
              // this is a LeftTrackModifier track so it's vertical
              trackOrientation = '1d-vertical';
            }
          }
        }

        if (trackOrientation && _d3Selection.event.sourceEvent) {
          // if somebody is holding down the shift key and is zooming over
          // a 1d track, try to apply value scale zooming
          if (_d3Selection.event.shiftKey || this.valueScaleZooming) {
            if (_d3Selection.event.sourceEvent.deltaY !== undefined) {
              this.valueScaleZoom(trackOrientation);
              return;
            }

            if (trackOrientation === '1d-horizontal') {
              this.valueScaleMove(_d3Selection.event.sourceEvent.movementY);
            } else if (trackOrientation === '1d-vertical') {
              this.valueScaleMove(_d3Selection.event.sourceEvent.movementX);
            }
          }

          // if somebody is dragging along a 1d track, do value scale moving
          if (trackOrientation === '1d-horizontal' && _d3Selection.event.sourceEvent.movementY) {
            this.valueScaleMove(_d3Selection.event.sourceEvent.movementY);
          } else if (trackOrientation === '1d-vertical' && _d3Selection.event.sourceEvent.movementX) {
            this.valueScaleMove(_d3Selection.event.sourceEvent.movementX);
          }
        }

        this.zoomTransform = !this.currentProps.zoomable ? _d3Zoom.zoomIdentity : _d3Selection.event.transform;

        var zooming = this.prevZoomTransform.k !== this.zoomTransform.k;

        // if there is dragging along a 1d track, only allow panning
        // along the axis of the track
        if (!zooming) {
          if (trackOrientation === '1d-horizontal') {
            // horizontal tracks shouldn't allow movement in the y direction
            // don't move along y axis
            this.zoomTransform = _d3Zoom.zoomIdentity.translate(this.zoomTransform.x, this.prevZoomTransform.y).scale(this.zoomTransform.k);
          } else if (trackOrientation === '1d-vertical') {
            // vertical tracks shouldn't allow movement in the x axis
            this.zoomTransform = _d3Zoom.zoomIdentity.translate(this.prevZoomTransform.x, this.zoomTransform.y).scale(this.zoomTransform.k);
          }

          this.element.__zoom = this.zoomTransform;
        }

        this.applyZoomTransform(true);

        this.prevZoomTransform = this.zoomTransform;
        this.props.pubSub.publish('app.zoom', _d3Selection.event);
        if (_d3Selection.event.sourceEvent) {
          _d3Selection.event.sourceEvent.stopPropagation();
          _d3Selection.event.sourceEvent.preventDefault();
        }
      }

      return zoomed;
    }()

    /**
     * Return a list of tracks under this position.
     *
     * The position should be relative to this.props.canvasElement.
     *
     * @param  {Number} x The query x position
     * @param  {Number} y The query y position
     * @return {Array}   An array of tracks at this position
     */

  }, {
    key: 'getTracksAtPosition',
    value: function () {
      function getTracksAtPosition(x, y) {
        var foundTracks = [];

        var tracksToVisit = [];

        for (var uid in this.trackDefObjects) {
          var track = this.trackDefObjects[uid].trackObject;

          if (track.childTracks) {
            tracksToVisit = tracksToVisit.concat(track.childTracks);
          } else {
            tracksToVisit.push(track);
          }
        }

        var _iteratorNormalCompletion7 = true;
        var _didIteratorError7 = false;
        var _iteratorError7 = undefined;

        try {
          for (var _iterator7 = (0, _getIterator3['default'])(tracksToVisit), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
            var _track3 = _step7.value;

            var withinX = _track3.position[0] <= x && x <= _track3.position[0] + _track3.dimensions[0];
            var withinY = _track3.position[1] <= y && y <= _track3.position[1] + _track3.dimensions[1];

            if (withinX && withinY) {
              foundTracks.push(_track3);
            }
          }
        } catch (err) {
          _didIteratorError7 = true;
          _iteratorError7 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion7 && _iterator7['return']) {
              _iterator7['return']();
            }
          } finally {
            if (_didIteratorError7) {
              throw _iteratorError7;
            }
          }
        }

        return foundTracks;
      }

      return getTracksAtPosition;
    }()
  }, {
    key: 'zoomStarted',
    value: function () {
      function zoomStarted() {
        this.zooming = true;

        if (_d3Selection.event.sourceEvent) {
          this.zoomStartPos = (0, _d3Selection.clientPoint)(this.props.canvasElement, _d3Selection.event.sourceEvent);

          if (_d3Selection.event.sourceEvent.shiftKey) {
            this.valueScaleZooming = true;
          }
        }

        // store the current transform because we'll need to
        // revert it if this turns out to be a value scale zoom
        this.zoomStartTransform = this.zoomTransform;
        this.props.pubSub.publish('app.zoomStart');
      }

      return zoomStarted;
    }()
  }, {
    key: 'zoomEnded',
    value: function () {
      function zoomEnded() {
        this.zooming = false;

        this.zoomStartPos = null;

        if (this.valueScaleZooming) {
          this.valueScaleZooming = false;
          this.element.__zoom = this.zoomStartTransform;
        }

        this.props.pubSub.publish('app.zoomEnd');
      }

      return zoomEnded;
    }()
  }, {
    key: 'applyZoomTransform',
    value: function () {
      function applyZoomTransform() {
        var notify = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

        var props = this.currentProps;
        var paddingleft = props.paddingLeft + props.leftWidth;
        var paddingTop = props.paddingTop + props.topHeight;

        // These props are apparently used elsewhere, for example the context menu
        this.zoomedXScale = this.zoomTransform.rescaleX(this.xScale);
        this.zoomedYScale = this.zoomTransform.rescaleY(this.yScale);

        var newXScale = (0, _d3Scale.scaleLinear)().domain([paddingleft, paddingleft + props.centerWidth].map(this.zoomedXScale.invert)).range([0, props.centerWidth]);

        var newYScale = (0, _d3Scale.scaleLinear)().domain([paddingTop, paddingTop + props.centerHeight].map(this.zoomedYScale.invert)).range([0, props.centerHeight]);

        for (var uid in this.trackDefObjects) {
          var track = this.trackDefObjects[uid].trackObject;
          var trackDef = this.trackDefObjects[uid].trackDef;

          var orientation = 'unknown';

          if (_configs.TRACKS_INFO_BY_TYPE[trackDef.track.type]) {
            orientation = _configs.TRACKS_INFO_BY_TYPE[trackDef.track.type].orientation;
          }

          if (orientation === 'whole') {
            // whole tracks need different scales which go beyond the ends of
            // center track and encompass the whole view
            var trackXScale = (0, _d3Scale.scaleLinear)().domain([props.paddingLeft, props.width - props.paddingLeft].map(this.zoomedXScale.invert)).range([0, props.width - 2 * props.paddingLeft]);

            var trackYScale = (0, _d3Scale.scaleLinear)().domain([props.paddingTop, props.height - props.paddingTop].map(this.zoomedYScale.invert)).range([0, props.height - 2 * props.paddingTop]);

            track.zoomed(trackXScale, trackYScale);
            continue;
          }

          if (this.trackDefObjects[uid].trackDef.track.position === 'gallery') {
            // gallery tracks need different scales which go beyond the ends of
            // center track and encompass the center view plus the gallery's width

            var _trackXScale = (0, _d3Scale.scaleLinear)().domain([props.paddingLeft + props.leftWidthNoGallery, props.paddingLeft + props.leftWidth + props.centerWidth + props.galleryDim].map(this.zoomedXScale.invert)).range([0, props.centerWidth + 2 * props.galleryDim]);

            var _trackYScale = (0, _d3Scale.scaleLinear)().domain([props.paddingTop + props.topHeightNoGallery, props.paddingTop + props.topHeight + props.centerHeight + props.galleryDim].map(this.zoomedYScale.invert)).range([0, props.centerHeight - 2 * props.galleryDim]);

            track.zoomed(_trackXScale.copy(), _trackYScale.copy(), this.zoomTransform.k);
            continue;
          }

          track.zoomed(newXScale.copy(), newYScale.copy(), this.zoomTransform.k, this.zoomTransform.x + this.xPositionOffset, this.zoomTransform.y + this.yPositionOffset, props.paddingLeft + props.leftWidth, props.paddingTop + props.topHeight);
        }

        this.currentXScale = newXScale;
        this.currentYScale = newYScale;

        if (notify) {
          this.currentProps.onScalesChanged(newXScale, newYScale);
        }

        return [newXScale, newYScale];
      }

      return applyZoomTransform;
    }()
  }, {
    key: 'createMetaTrack',
    value: function () {
      function createMetaTrack(track) {
        var _this8 = this;

        switch (track.type) {
          default:
            {
              // Check if a plugin track is available
              var pluginTrack = this.props.pluginTracks[track.type];

              if (pluginTrack && pluginTrack.isMetaTrack) {
                var context = {
                  getTrackObject: this.getTrackObject.bind(this),
                  onNewTilesLoaded: function () {
                    function onNewTilesLoaded() {
                      _this8.currentProps.onNewTilesLoaded(track.uid);
                    }

                    return onNewTilesLoaded;
                  }(),
                  definition: track
                };
                try {
                  return new pluginTrack.track( // eslint-disable-line new-cap
                  _configs.AVAILABLE_FOR_PLUGINS, context, track.options);
                } catch (e) {
                  console.error('Plugin meta track', track.type, 'failed to instantiate.', e);
                }
              }

              console.warn('Unknown meta track of type: ' + String(track.type));
              return new _UnknownPixiTrack2['default'](this.pStage, { name: 'Unknown Track Type', type: track.type }, function () {
                return _this8.currentProps.onNewTilesLoaded(track.uid);
              });
            }
        }
      }

      return createMetaTrack;
    }()
  }, {
    key: 'createTrackObject',
    value: function () {
      function createTrackObject(track) {
        var trackObject = this.createLocationAgnosticTrackObject(track);
        if (track.position === 'left' || track.position === 'right') {
          if (_configs.TRACKS_INFO_BY_TYPE[track.type].orientation === '1d-horizontal') {
            return new _LeftTrackModifier2['default'](trackObject);
          }
        }
        return trackObject;
      }

      return createTrackObject;
    }()
  }, {
    key: 'createLocationAgnosticTrackObject',
    value: function () {
      function createLocationAgnosticTrackObject(track) {
        var _this9 = this;

        var handleTilesetInfoReceived = function () {
          function handleTilesetInfoReceived(x) {
            _this9.currentProps.onTilesetInfoReceived(track.uid, x);
          }

          return handleTilesetInfoReceived;
        }();

        // See if this track has a data config section.
        // If it doesn't, we assume that it has the standard
        // server / tilesetUid sections
        // if the track has no data server, then this will just
        // be blank and we can go on our merry way
        var dataConfig = track.data;
        if (!dataConfig) {
          dataConfig = {
            server: (0, _utils.trimTrailingSlash)(track.server),
            tilesetUid: track.tilesetUid
          };
        }

        if (track.coordSystem) {
          dataConfig.coordSystem = track.coordSystem;
        }

        var dataFetcher = (0, _getDataFetcher2['default'])(dataConfig, this.props.pubSub, this.props.pluginDataFetchers);

        // To simplify the context creation via ES6 object shortcuts.
        var context = {
          id: track.uid,
          viewUid: this.viewUid,
          pubSub: this.props.pubSub,
          scene: this.pStage,
          dataConfig: dataConfig,
          dataFetcher: dataFetcher,
          getLockGroupExtrema: function () {
            function getLockGroupExtrema() {
              return _this9.currentProps.getLockGroupExtrema(track.uid);
            }

            return getLockGroupExtrema;
          }(),
          handleTilesetInfoReceived: handleTilesetInfoReceived,
          animate: function () {
            function animate() {
              _this9.currentProps.onNewTilesLoaded(track.uid);
            }

            return animate;
          }(),
          svgElement: this.svgElement,
          isValueScaleLocked: function () {
            function isValueScaleLocked() {
              return _this9.currentProps.isValueScaleLocked(track.uid);
            }

            return isValueScaleLocked;
          }(),
          onValueScaleChanged: function () {
            function onValueScaleChanged() {
              _this9.currentProps.onValueScaleChanged(track.uid);
            }

            return onValueScaleChanged;
          }(),
          onTrackOptionsChanged: function () {
            function onTrackOptionsChanged(newOptions) {
              _this9.currentProps.onTrackOptionsChanged(track.uid, newOptions);
            }

            return onTrackOptionsChanged;
          }(),
          onMouseMoveZoom: this.props.onMouseMoveZoom,
          chromInfoPath: track.chromInfoPath,
          isShowGlobalMousePosition: function () {
            function isShowGlobalMousePosition() {
              return _this9.props.isShowGlobalMousePosition;
            }

            return isShowGlobalMousePosition;
          }(),
          getTheme: function () {
            function getTheme() {
              return _this9.props.theme;
            }

            return getTheme;
          }()
        };

        // for horizontal and vertical rules
        if (track.y) {
          context.yPosition = track.y;
        }

        if (track.x) {
          context.xPosition = track.x;
        }

        // for viewport-projection-horizontal and viewport-projection-center
        if (track.projectionXDomain) {
          context.projectionXDomain = track.projectionXDomain;
        }

        // for viewport-projection-vertical and viewport-projection-center
        if (track.projectionYDomain) {
          context.projectionYDomain = track.projectionYDomain;
        }

        var options = track.options;

        switch (track.type) {
          case 'left-axis':
            return new _LeftAxisTrack2['default'](context, options);

          case 'top-axis':
            return new _TopAxisTrack2['default'](context, options);

          case 'heatmap':
            return new _HeatmapTiledPixiTrack2['default'](context, options);

          case 'multivec':
          case 'vector-heatmap':
          case 'horizontal-multivec': // legacy, included for backwards compatiblity
          case 'horizontal-vector-heatmap': // legacy, included for backwards compatiblity
          case 'vertical-multivec': // legacy, included for backwards compatiblity
          case 'vertical-vector-heatmap':
            // legacy, included for backwards compatiblity
            return new _HorizontalMultivecTrack2['default'](context, options);

          case '1d-heatmap':
          case 'horizontal-1d-heatmap': // legacy, included for backwards compatiblity
          case 'vertical-1d-heatmap':
            // legacy, included for backwards compatiblity
            return new _Horizontal1dHeatmapTrack2['default'](context, options);

          case 'line':
          case 'horizontal-line': // legacy, included for backwards compatiblity
          case 'vertical-line':
            // legacy, included for backwards compatiblity
            return new _HorizontalLine1DPixiTrack2['default'](context, options);

          case 'point':
          case 'horizontal-point': // legacy, included for backwards compatiblity
          case 'vertical-point':
            // legacy, included for backwards compatiblity
            return new _HorizontalPoint1DPixiTrack2['default'](context, options);

          case 'bar':
          case 'horizontal-bar': // legacy, included for backwards compatiblity
          case 'vertical-bar':
            // legacy, included for backwards compatiblity
            return new _BarTrack2['default'](context, options);

          case 'divergent-bar':
          case 'horizontal-divergent-bar': // legacy, included for backwards compatiblity
          case 'vertical-divergent-bar':
            // legacy, included for backwards compatiblity
            return new _DivergentBarTrack2['default'](context, options);

          case 'horizontal-1d-tiles':
            return new _IdHorizontal1DTiledPixiTrack2['default'](context, options);

          case 'vertical-1d-tiles':
            return new _IdVertical1DTiledPixiTrack2['default'](context, options);

          case '2d-tiles':
            return new _Id2DTiledPixiTrack2['default'](context, options);

          case 'stacked-interval':
          case 'top-stacked-interval': // legacy, included for backwards compatiblity
          case 'left-stacked-interval':
            // legacy, included for backwards compatiblity
            return new _CNVIntervalTrack2['default'](context, options);

          case 'viewport-projection-center':
            // TODO: Fix this so that these functions are defined somewhere else
            if (track.registerViewportChanged && track.removeViewportChanged && track.setDomainsCallback) {
              context.registerViewportChanged = track.registerViewportChanged;
              context.removeViewportChanged = track.removeViewportChanged;
              context.setDomainsCallback = track.setDomainsCallback;
              return new _ViewportTracker2D2['default'](context, options);
            }
            return new _Track2['default'](context, options);

          case 'viewport-projection-horizontal':
            // TODO: Fix this so that these functions are defined somewhere else
            if (track.registerViewportChanged && track.removeViewportChanged && track.setDomainsCallback) {
              context.registerViewportChanged = track.registerViewportChanged;
              context.removeViewportChanged = track.removeViewportChanged;
              context.setDomainsCallback = track.setDomainsCallback;
              return new _ViewportTrackerHorizontal2['default'](context, options);
            }
            return new _Track2['default'](context, options);

          case 'viewport-projection-vertical':
            // TODO: Fix this so that these functions are defined somewhere else
            if (track.registerViewportChanged && track.removeViewportChanged && track.setDomainsCallback) {
              context.registerViewportChanged = track.registerViewportChanged;
              context.removeViewportChanged = track.removeViewportChanged;
              context.setDomainsCallback = track.setDomainsCallback;
              return new _ViewportTrackerVertical2['default'](context, options);
            }
            return new _Track2['default'](context, options);

          case 'gene-annotations':
          case 'horizontal-gene-annotations': // legacy, included for backwards compatiblity
          case 'vertical-gene-annotations':
            // legacy, included for backwards compatiblity
            return new _HorizontalGeneAnnotationsTrack2['default'](context, options);

          case '2d-rectangle-domains':
          case 'arrowhead-domains':
            return new _ArrowheadDomainsTrack2['default'](context, options);

          case 'horizontal-1d-annotations':
            return new _Annotations1dTrack2['default'](context, options);

          case 'vertical-1d-annotations':
            // Fix this: LeftTrackModifier is doing a whole bunch of things not
            // needed by this track but the current setup is not consistent.
            return new _Annotations1dTrack2['default'](context, options, true);

          case '2d-annotations':
            return new _Annotations2dTrack2['default'](context, options);

          case 'linear-2d-rectangle-domains':
          case 'horizontal-2d-rectangle-domains': // legacy, included for backwards compatiblity
          case 'vertical-2d-rectangle-domains':
            // legacy, included for backwards compatiblity
            return new _Horizontal2DDomainsTrack2['default'](context, options);

          case 'square-markers':
            return new _SquareMarkersTrack2['default'](context, options);

          case 'combined':
            context.tracks = track.contents;
            context.createTrackObject = this.createTrackObject.bind(this);
            return new _CombinedTrack2['default'](context, options);

          case '2d-chromosome-labels':
            return new _Chromosome2DLabels2['default'](context, options);

          case 'horizontal-chromosome-grid':
            context.orientation = '1d-horizontal';
            return new _ChromosomeGrid2['default'](context, options);

          case 'vertical-chromosome-grid':
            context.orientation = '1d-vertical';
            return new _ChromosomeGrid2['default'](context, options);

          case '2d-chromosome-grid':
            return new _ChromosomeGrid2['default'](context, options);

          case 'chromosome-labels':
          case 'horizontal-chromosome-labels': // legacy, included for backwards compatiblity
          case 'vertical-chromosome-labels':
            // legacy, included for backwards compatiblity
            // chromInfoPath is passed in for backwards compatibility
            // it can be used to provide custom chromosome sizes
            return new _HorizontalChromosomeLabels2['default'](context, options);

          case 'linear-heatmap':
          case 'horizontal-heatmap': // legacy, included for backwards compatiblity
          case 'vertical-heatmap':
            // legacy, included for backwards compatiblity
            return new _HorizontalHeatmapTrack2['default'](context, options);

          case '2d-chromosome-annotations':
            return new _Chromosome2DAnnotations2['default'](context, options);

          case '1d-value-interval':
          case 'horizontal-1d-value-interval': // legacy, included for backwards compatiblity
          case 'vertical-1d-value-interval':
            // legacy, included for backwards compatiblity
            return new _ValueIntervalTrack2['default'](context, options);

          case 'osm':
          case 'osm-tiles':
            return new _OSMTilesTrack2['default'](context, options);

          case 'osm-2d-tile-ids':
            return new _OSMTileIdsTrack2['default'](context, options);

          case 'mapbox':
          case 'mapbox-tiles':
            return new _MapboxTilesTrack2['default'](context, options);

          case 'raster-tiles':
            return new _RasterTilesTrack2['default'](context, options);

          case 'bedlike':
          case 'vertical-bedlike':
            // legacy, included for backwards compatiblity
            return new _BedLikeTrack2['default'](context, options);

          case 'overlay-track':
            return new _OverlayTrack2['default'](context, options);

          case 'overlay-chromosome-grid-track':
            context.isOverlay = true;
            return new _ChromosomeGrid2['default'](context, options);

          case 'horizontal-rule':
            return new _HorizontalRule2['default'](context, options);

          case 'vertical-rule':
            return new _VerticalRule2['default'](context, options);

          case 'cross-rule':
            // This needs to be harmonized.
            context.x = track.x;
            context.y = track.y;
            return new _CrossRule2['default'](context, options);

          case 'simple-svg':
            return new _SVGTrack2['default'](context, options);
          case 'empty':
            return new _PixiTrack2['default'](context, options);

          default:
            {
              // Check if a plugin track is available
              var pluginTrack = this.props.pluginTracks[track.type];

              if (pluginTrack && !pluginTrack.isMetaTrack) {
                context.AVAILABLE_FOR_PLUGINS = _configs.AVAILABLE_FOR_PLUGINS;
                context.baseEl = this.baseEl;
                context.definition = track;

                if (track.registerViewportChanged && track.removeViewportChanged && track.setDomainsCallback) {
                  context.registerViewportChanged = track.registerViewportChanged;
                  context.removeViewportChanged = track.removeViewportChanged;
                  context.setDomainsCallback = track.setDomainsCallback;
                }

                try {
                  return new pluginTrack.track( // eslint-disable-line new-cap
                  _configs.AVAILABLE_FOR_PLUGINS, context, options);
                } catch (e) {
                  console.error('Plugin track', track.type, 'failed to instantiate.', e);
                }
              }

              console.warn('Unknown track type:', track.type);

              return new _UnknownPixiTrack2['default'](context, {
                name: 'Unknown Track Type',
                type: track.type
              });
            }
        }
      }

      return createLocationAgnosticTrackObject;
    }()

    /**
     * Zoom to a location given the data coordinates
     * @param   {number}  dataXStart  Data start X coordinate.
     * @param   {number}  dataXEnd  Data end X coordinate.
     * @param   {number}  dataYStart  Data start Y coordinate.
     * @param   {number}  dataYEnd  Data end Y coordinate.
     * @param   {number}  animateTime  Animation time in milliseconds.
     * @param   {function}  projector  If not `null` a projector function that
     *   provides adjusted x and y scales.
     */

  }, {
    key: 'zoomToDataPos',
    value: function () {
      function zoomToDataPos(dataXStart, dataXEnd, dataYStart, dataYEnd) {
        var animateTime = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 3000;
        var projector = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;

        var _scalesCenterAndK = (0, _utils.scalesCenterAndK)(this.xScale.copy().domain([dataXStart, dataXEnd]), this.yScale.copy().domain([dataYStart, dataYEnd])),
            _scalesCenterAndK2 = (0, _slicedToArray3['default'])(_scalesCenterAndK, 3),
            centerX = _scalesCenterAndK2[0],
            centerY = _scalesCenterAndK2[1],
            k = _scalesCenterAndK2[2];

        var projectedScales = projector ? projector(this.xScale, this.yScale) : [this.xScale, this.yScale];

        this.setCenter(centerX, centerY, k, false, animateTime, projectedScales[0], projectedScales[1]);
      }

      return zoomToDataPos;
    }()
  }, {
    key: 'forwardContextMenu',
    value: function () {
      function forwardContextMenu(e) {
        var _this10 = this;

        // Do never forward the contextmenu event when ALT is being hold down.
        if (this.props.disableTrackMenu || e.altKey) return;

        e.preventDefault();

        setTimeout(function () {
          // For right clicks only. Publish the contextmenu event
          _this10.props.pubSub.publish('contextmenu', e);
        }, 0);
      }

      return forwardContextMenu;
    }()
  }, {
    key: 'addEventTracker',
    value: function () {
      function addEventTracker() {
        if (!this.eventTracker || this.eventTracker === this.eventTrackerOld) return;
        if (!this.eventTrackerOld) this.eventTrackerOld = this.eventTracker;

        this.eventTracker = this.eventTrackerOld;

        this.eventTracker.addEventListener('click', this.boundForwardEvent);
        this.eventTracker.addEventListener('contextmenu', this.boundForwardContextMenu);
        this.eventTracker.addEventListener('dblclick', this.boundForwardEvent);
        this.eventTracker.addEventListener('wheel', this.boundForwardEvent);
        this.eventTracker.addEventListener('dragstart', this.boundForwardEvent);
        this.eventTracker.addEventListener('selectstart', this.boundForwardEvent);

        this.eventTracker.addEventListener('mouseover', this.boundForwardEvent);
        this.eventTracker.addEventListener('mouseenter', this.boundForwardEvent);
        this.eventTracker.addEventListener('mousedown', this.boundForwardEvent);
        this.eventTracker.addEventListener('mouseup', this.boundForwardEvent);
        this.eventTracker.addEventListener('mouseout', this.boundForwardEvent);
        this.eventTracker.addEventListener('mouseleave', this.boundForwardEvent);

        this.eventTracker.addEventListener('touchstart', this.boundForwardEvent);
        this.eventTracker.addEventListener('touchend', this.boundForwardEvent);
        this.eventTracker.addEventListener('touchmove', this.boundForwardEvent);
        this.eventTracker.addEventListener('touchcancel', this.boundForwardEvent);

        this.eventTracker.addEventListener('pointerover', this.boundForwardEvent);
        this.eventTracker.addEventListener('pointerenter', this.boundForwardEvent);
        this.eventTracker.addEventListener('pointerdown', this.boundForwardEvent);
        this.eventTracker.addEventListener('pointerup', this.boundForwardEvent);
        this.eventTracker.addEventListener('pointercancel', this.boundForwardEvent);
        this.eventTracker.addEventListener('pointerout', this.boundForwardEvent);
        this.eventTracker.addEventListener('pointerleave', this.boundForwardEvent);

        window.addEventListener('scroll', this.boundScrollEvent);
      }

      return addEventTracker;
    }()
  }, {
    key: 'removeEventTracker',
    value: function () {
      function removeEventTracker() {
        if (!this.eventTracker) return;

        this.eventTracker.removeEventListener('click', this.boundForwardEvent);
        this.eventTracker.removeEventListener('contextmenu', this.boundForwardContextMenu);
        this.eventTracker.removeEventListener('dblclick', this.boundForwardEvent);
        this.eventTracker.removeEventListener('wheel', this.boundForwardEvent);
        this.eventTracker.removeEventListener('dragstart', this.boundForwardEvent);
        this.eventTracker.removeEventListener('selectstart', this.boundForwardEvent);

        this.eventTracker.removeEventListener('mouseover', this.boundForwardEvent);
        this.eventTracker.removeEventListener('mouseenter', this.boundForwardEvent);
        this.eventTracker.removeEventListener('mousedown', this.boundForwardEvent);
        this.eventTracker.removeEventListener('mouseup', this.boundForwardEvent);
        this.eventTracker.removeEventListener('mouseout', this.boundForwardEvent);
        this.eventTracker.removeEventListener('mouseleave', this.boundForwardEvent);

        this.eventTracker.removeEventListener('touchstart', this.boundForwardEvent);
        this.eventTracker.removeEventListener('touchend', this.boundForwardEvent);
        this.eventTracker.removeEventListener('touchcancel', this.boundForwardEvent);

        this.eventTracker.removeEventListener('pointerover', this.boundForwardEvent);
        this.eventTracker.removeEventListener('pointerenter', this.boundForwardEvent);
        this.eventTracker.removeEventListener('pointerdown', this.boundForwardEvent);
        this.eventTracker.removeEventListener('pointerup', this.boundForwardEvent);
        this.eventTracker.removeEventListener('pointercancel', this.boundForwardEvent);
        this.eventTracker.removeEventListener('pointerout', this.boundForwardEvent);
        this.eventTracker.removeEventListener('pointerleave', this.boundForwardEvent);

        window.removeEventListener('scroll', this.boundScrollEvent);
      }

      return removeEventTracker;
    }()
  }, {
    key: 'scrollEvent',
    value: function () {
      function scrollEvent() {
        this.elementPos = this.element.getBoundingClientRect();
      }

      return scrollEvent;
    }()
  }, {
    key: 'forwardEvent',
    value: function () {
      function forwardEvent(e) {
        e.sourceUid = this.uid;
        e.forwarded = true;
        this.props.pubSub.publish('app.event', e);
      }

      return forwardEvent;
    }()
  }, {
    key: 'onScrollHandler',
    value: function () {
      function onScrollHandler(scrollTop) {
        this.scrollTop = scrollTop;
      }

      return onScrollHandler;
    }()

    /* ------------------------------- Render ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this11 = this;

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this11.baseEl = c;
              }

              return ref;
            }(),
            className: 'track-renderer-div TrackRenderer-module_track-renderer-3TM7n',
            style: {
              height: this.currentProps.height,
              width: this.currentProps.width
            }
          },
          _react2['default'].createElement('div', {
            ref: function () {
              function ref(c) {
                _this11.element = c;
              }

              return ref;
            }(),
            className: 'track-renderer-element TrackRenderer-module_track-renderer-element-2i16D'
          }),
          _react2['default'].createElement(
            'div',
            {
              ref: function () {
                function ref(c) {
                  _this11.eventTracker = c;
                }

                return ref;
              }(),
              className: 'track-renderer-events TrackRenderer-module_track-renderer-events-3tVM2'
            },
            this.currentProps.children
          )
        );
      }

      return render;
    }()
  }]);
  return TrackRenderer;
}(_react2['default'].Component);

TrackRenderer.defaultProps = {
  pluginDataFetchers: {},
  pluginTracks: {},
  canvasElement: null,
  centerHeight: 0,
  centerWidth: 0,
  children: [],
  galleryDim: 0,
  height: 0,
  initialXDomain: [],
  initialYDomain: [],
  isShowGlobalMousePosition: false,
  isRangeSelection: false,
  leftWidth: 0,
  leftWidthNoGallery: 0,
  paddingLeft: 0,
  paddingTop: 0,
  positionedTracks: [],
  topHeight: 0,
  topHeightNoGallery: 0,
  width: 0,
  metaTracks: []
};

TrackRenderer.propTypes = {
  canvasElement: _propTypes2['default'].object,
  centerHeight: _propTypes2['default'].number,
  centerWidth: _propTypes2['default'].number,
  children: _propTypes2['default'].array,
  disableTrackMenu: _propTypes2['default'].bool,
  galleryDim: _propTypes2['default'].number,
  height: _propTypes2['default'].number,
  initialXDomain: _propTypes2['default'].array,
  initialYDomain: _propTypes2['default'].array,
  isShowGlobalMousePosition: _propTypes2['default'].bool,
  isRangeSelection: _propTypes2['default'].bool,
  leftWidth: _propTypes2['default'].number,
  leftWidthNoGallery: _propTypes2['default'].number,
  paddingLeft: _propTypes2['default'].number,
  paddingTop: _propTypes2['default'].number,
  metaTracks: _propTypes2['default'].array,
  onMouseMoveZoom: _propTypes2['default'].func,
  onNewTilesLoaded: _propTypes2['default'].func.isRequired,
  onScalesChanged: _propTypes2['default'].func.isRequired,
  pixiRenderer: _propTypes2['default'].object.isRequired,
  pixiStage: _propTypes2['default'].object.isRequired,
  pluginDataFetchers: _propTypes2['default'].object,
  pluginTracks: _propTypes2['default'].object,
  positionedTracks: _propTypes2['default'].array,
  pubSub: _propTypes2['default'].object.isRequired,
  setCentersFunction: _propTypes2['default'].func,
  svgElement: _propTypes2['default'].object.isRequired,
  theme: _propTypes2['default'].symbol.isRequired,
  topHeight: _propTypes2['default'].number,
  topHeightNoGallery: _propTypes2['default'].number,
  viewOptions: _propTypes2['default'].object,
  width: _propTypes2['default'].number,
  xDomainLimits: _propTypes2['default'].array,
  yDomainLimits: _propTypes2['default'].array,
  valueScaleZoom: _propTypes2['default'].bool,
  zoomable: _propTypes2['default'].bool.isRequired,
  zoomDomain: _propTypes2['default'].array
};

exports['default'] = (0, _withPubSub2['default'])((0, _withTheme2['default'])(TrackRenderer));

/***/ }),
/* 614 */
/***/ (function(module, exports, __nested_webpack_require_3131855__) {

module.exports = { "default": __nested_webpack_require_3131855__(615), __esModule: true };

/***/ }),
/* 615 */
/***/ (function(module, exports, __nested_webpack_require_3132009__) {

__nested_webpack_require_3132009__(616);
var $Object = __nested_webpack_require_3132009__(12).Object;
module.exports = function getOwnPropertyDescriptor(it, key) {
  return $Object.getOwnPropertyDescriptor(it, key);
};


/***/ }),
/* 616 */
/***/ (function(module, exports, __nested_webpack_require_3132277__) {

// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __nested_webpack_require_3132277__(48);
var $getOwnPropertyDescriptor = __nested_webpack_require_3132277__(228).f;

__nested_webpack_require_3132277__(126)('getOwnPropertyDescriptor', function () {
  return function getOwnPropertyDescriptor(it, key) {
    return $getOwnPropertyDescriptor(toIObject(it), key);
  };
});


/***/ }),
/* 617 */
/***/ (function(module, exports, __nested_webpack_require_3132696__) {

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

// This method of obtaining a reference to the global object needs to be
// kept identical to the way it is obtained in runtime.js
var g = (function() { return this })() || Function("return this")();

// Use `getOwnPropertyNames` because not all browsers support calling
// `hasOwnProperty` on the global `self` object in a worker. See #183.
var hadRuntime = g.regeneratorRuntime &&
  Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0;

// Save the old regeneratorRuntime in case it needs to be restored later.
var oldRuntime = hadRuntime && g.regeneratorRuntime;

// Force reevalutation of runtime.js.
g.regeneratorRuntime = undefined;

module.exports = __nested_webpack_require_3132696__(618);

if (hadRuntime) {
  // Restore the original runtime.
  g.regeneratorRuntime = oldRuntime;
} else {
  // Remove the global property added by runtime.js.
  try {
    delete g.regeneratorRuntime;
  } catch(e) {
    g.regeneratorRuntime = undefined;
  }
}


/***/ }),
/* 618 */
/***/ (function(module, exports) {

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

!(function(global) {
  "use strict";

  var Op = Object.prototype;
  var hasOwn = Op.hasOwnProperty;
  var undefined; // More compressible than void 0.
  var $Symbol = typeof Symbol === "function" ? Symbol : {};
  var iteratorSymbol = $Symbol.iterator || "@@iterator";
  var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";

  var inModule = typeof module === "object";
  var runtime = global.regeneratorRuntime;
  if (runtime) {
    if (inModule) {
      // If regeneratorRuntime is defined globally and we're in a module,
      // make the exports object identical to regeneratorRuntime.
      module.exports = runtime;
    }
    // Don't bother evaluating the rest of this file if the runtime was
    // already defined globally.
    return;
  }

  // Define the runtime globally (as expected by generated code) as either
  // module.exports (if we're in a module) or a new, empty object.
  runtime = global.regeneratorRuntime = inModule ? module.exports : {};

  function wrap(innerFn, outerFn, self, tryLocsList) {
    // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
    var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
    var generator = Object.create(protoGenerator.prototype);
    var context = new Context(tryLocsList || []);

    // The ._invoke method unifies the implementations of the .next,
    // .throw, and .return methods.
    generator._invoke = makeInvokeMethod(innerFn, self, context);

    return generator;
  }
  runtime.wrap = wrap;

  // Try/catch helper to minimize deoptimizations. Returns a completion
  // record like context.tryEntries[i].completion. This interface could
  // have been (and was previously) designed to take a closure to be
  // invoked without arguments, but in all the cases we care about we
  // already have an existing method we want to call, so there's no need
  // to create a new function object. We can even get away with assuming
  // the method takes exactly one argument, since that happens to be true
  // in every case, so we don't have to touch the arguments object. The
  // only additional allocation required is the completion record, which
  // has a stable shape and so hopefully should be cheap to allocate.
  function tryCatch(fn, obj, arg) {
    try {
      return { type: "normal", arg: fn.call(obj, arg) };
    } catch (err) {
      return { type: "throw", arg: err };
    }
  }

  var GenStateSuspendedStart = "suspendedStart";
  var GenStateSuspendedYield = "suspendedYield";
  var GenStateExecuting = "executing";
  var GenStateCompleted = "completed";

  // Returning this object from the innerFn has the same effect as
  // breaking out of the dispatch switch statement.
  var ContinueSentinel = {};

  // Dummy constructor functions that we use as the .constructor and
  // .constructor.prototype properties for functions that return Generator
  // objects. For full spec compliance, you may wish to configure your
  // minifier not to mangle the names of these two functions.
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}

  // This is a polyfill for %IteratorPrototype% for environments that
  // don't natively support it.
  var IteratorPrototype = {};
  IteratorPrototype[iteratorSymbol] = function () {
    return this;
  };

  var getProto = Object.getPrototypeOf;
  var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  if (NativeIteratorPrototype &&
      NativeIteratorPrototype !== Op &&
      hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
    // This environment has a native %IteratorPrototype%; use it instead
    // of the polyfill.
    IteratorPrototype = NativeIteratorPrototype;
  }

  var Gp = GeneratorFunctionPrototype.prototype =
    Generator.prototype = Object.create(IteratorPrototype);
  GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  GeneratorFunctionPrototype.constructor = GeneratorFunction;
  GeneratorFunctionPrototype[toStringTagSymbol] =
    GeneratorFunction.displayName = "GeneratorFunction";

  // Helper for defining the .next, .throw, and .return methods of the
  // Iterator interface in terms of a single ._invoke method.
  function defineIteratorMethods(prototype) {
    ["next", "throw", "return"].forEach(function(method) {
      prototype[method] = function(arg) {
        return this._invoke(method, arg);
      };
    });
  }

  runtime.isGeneratorFunction = function(genFun) {
    var ctor = typeof genFun === "function" && genFun.constructor;
    return ctor
      ? ctor === GeneratorFunction ||
        // For the native GeneratorFunction constructor, the best we can
        // do is to check its .name property.
        (ctor.displayName || ctor.name) === "GeneratorFunction"
      : false;
  };

  runtime.mark = function(genFun) {
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
    } else {
      genFun.__proto__ = GeneratorFunctionPrototype;
      if (!(toStringTagSymbol in genFun)) {
        genFun[toStringTagSymbol] = "GeneratorFunction";
      }
    }
    genFun.prototype = Object.create(Gp);
    return genFun;
  };

  // Within the body of any async function, `await x` is transformed to
  // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  // `hasOwn.call(value, "__await")` to determine if the yielded value is
  // meant to be awaited.
  runtime.awrap = function(arg) {
    return { __await: arg };
  };

  function AsyncIterator(generator) {
    function invoke(method, arg, resolve, reject) {
      var record = tryCatch(generator[method], generator, arg);
      if (record.type === "throw") {
        reject(record.arg);
      } else {
        var result = record.arg;
        var value = result.value;
        if (value &&
            typeof value === "object" &&
            hasOwn.call(value, "__await")) {
          return Promise.resolve(value.__await).then(function(value) {
            invoke("next", value, resolve, reject);
          }, function(err) {
            invoke("throw", err, resolve, reject);
          });
        }

        return Promise.resolve(value).then(function(unwrapped) {
          // When a yielded Promise is resolved, its final value becomes
          // the .value of the Promise<{value,done}> result for the
          // current iteration. If the Promise is rejected, however, the
          // result for this iteration will be rejected with the same
          // reason. Note that rejections of yielded Promises are not
          // thrown back into the generator function, as is the case
          // when an awaited Promise is rejected. This difference in
          // behavior between yield and await is important, because it
          // allows the consumer to decide what to do with the yielded
          // rejection (swallow it and continue, manually .throw it back
          // into the generator, abandon iteration, whatever). With
          // await, by contrast, there is no opportunity to examine the
          // rejection reason outside the generator function, so the
          // only option is to throw it from the await expression, and
          // let the generator function handle the exception.
          result.value = unwrapped;
          resolve(result);
        }, reject);
      }
    }

    var previousPromise;

    function enqueue(method, arg) {
      function callInvokeWithMethodAndArg() {
        return new Promise(function(resolve, reject) {
          invoke(method, arg, resolve, reject);
        });
      }

      return previousPromise =
        // If enqueue has been called before, then we want to wait until
        // all previous Promises have been resolved before calling invoke,
        // so that results are always delivered in the correct order. If
        // enqueue has not been called before, then it is important to
        // call invoke immediately, without waiting on a callback to fire,
        // so that the async generator function has the opportunity to do
        // any necessary setup in a predictable way. This predictability
        // is why the Promise constructor synchronously invokes its
        // executor callback, and why async functions synchronously
        // execute code before the first await. Since we implement simple
        // async functions in terms of async generators, it is especially
        // important to get this right, even though it requires care.
        previousPromise ? previousPromise.then(
          callInvokeWithMethodAndArg,
          // Avoid propagating failures to Promises returned by later
          // invocations of the iterator.
          callInvokeWithMethodAndArg
        ) : callInvokeWithMethodAndArg();
    }

    // Define the unified helper method that is used to implement .next,
    // .throw, and .return (see defineIteratorMethods).
    this._invoke = enqueue;
  }

  defineIteratorMethods(AsyncIterator.prototype);
  AsyncIterator.prototype[asyncIteratorSymbol] = function () {
    return this;
  };
  runtime.AsyncIterator = AsyncIterator;

  // Note that simple async functions are implemented on top of
  // AsyncIterator objects; they just return a Promise for the value of
  // the final result produced by the iterator.
  runtime.async = function(innerFn, outerFn, self, tryLocsList) {
    var iter = new AsyncIterator(
      wrap(innerFn, outerFn, self, tryLocsList)
    );

    return runtime.isGeneratorFunction(outerFn)
      ? iter // If outerFn is a generator, return the full iterator.
      : iter.next().then(function(result) {
          return result.done ? result.value : iter.next();
        });
  };

  function makeInvokeMethod(innerFn, self, context) {
    var state = GenStateSuspendedStart;

    return function invoke(method, arg) {
      if (state === GenStateExecuting) {
        throw new Error("Generator is already running");
      }

      if (state === GenStateCompleted) {
        if (method === "throw") {
          throw arg;
        }

        // Be forgiving, per 25.3.3.3.3 of the spec:
        // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
        return doneResult();
      }

      context.method = method;
      context.arg = arg;

      while (true) {
        var delegate = context.delegate;
        if (delegate) {
          var delegateResult = maybeInvokeDelegate(delegate, context);
          if (delegateResult) {
            if (delegateResult === ContinueSentinel) continue;
            return delegateResult;
          }
        }

        if (context.method === "next") {
          // Setting context._sent for legacy support of Babel's
          // function.sent implementation.
          context.sent = context._sent = context.arg;

        } else if (context.method === "throw") {
          if (state === GenStateSuspendedStart) {
            state = GenStateCompleted;
            throw context.arg;
          }

          context.dispatchException(context.arg);

        } else if (context.method === "return") {
          context.abrupt("return", context.arg);
        }

        state = GenStateExecuting;

        var record = tryCatch(innerFn, self, context);
        if (record.type === "normal") {
          // If an exception is thrown from innerFn, we leave state ===
          // GenStateExecuting and loop back for another invocation.
          state = context.done
            ? GenStateCompleted
            : GenStateSuspendedYield;

          if (record.arg === ContinueSentinel) {
            continue;
          }

          return {
            value: record.arg,
            done: context.done
          };

        } else if (record.type === "throw") {
          state = GenStateCompleted;
          // Dispatch the exception by looping back around to the
          // context.dispatchException(context.arg) call above.
          context.method = "throw";
          context.arg = record.arg;
        }
      }
    };
  }

  // Call delegate.iterator[context.method](context.arg) and handle the
  // result, either by returning a { value, done } result from the
  // delegate iterator, or by modifying context.method and context.arg,
  // setting context.delegate to null, and returning the ContinueSentinel.
  function maybeInvokeDelegate(delegate, context) {
    var method = delegate.iterator[context.method];
    if (method === undefined) {
      // A .throw or .return when the delegate iterator has no .throw
      // method always terminates the yield* loop.
      context.delegate = null;

      if (context.method === "throw") {
        if (delegate.iterator.return) {
          // If the delegate iterator has a return method, give it a
          // chance to clean up.
          context.method = "return";
          context.arg = undefined;
          maybeInvokeDelegate(delegate, context);

          if (context.method === "throw") {
            // If maybeInvokeDelegate(context) changed context.method from
            // "return" to "throw", let that override the TypeError below.
            return ContinueSentinel;
          }
        }

        context.method = "throw";
        context.arg = new TypeError(
          "The iterator does not provide a 'throw' method");
      }

      return ContinueSentinel;
    }

    var record = tryCatch(method, delegate.iterator, context.arg);

    if (record.type === "throw") {
      context.method = "throw";
      context.arg = record.arg;
      context.delegate = null;
      return ContinueSentinel;
    }

    var info = record.arg;

    if (! info) {
      context.method = "throw";
      context.arg = new TypeError("iterator result is not an object");
      context.delegate = null;
      return ContinueSentinel;
    }

    if (info.done) {
      // Assign the result of the finished delegate to the temporary
      // variable specified by delegate.resultName (see delegateYield).
      context[delegate.resultName] = info.value;

      // Resume execution at the desired location (see delegateYield).
      context.next = delegate.nextLoc;

      // If context.method was "throw" but the delegate handled the
      // exception, let the outer generator proceed normally. If
      // context.method was "next", forget context.arg since it has been
      // "consumed" by the delegate iterator. If context.method was
      // "return", allow the original .return call to continue in the
      // outer generator.
      if (context.method !== "return") {
        context.method = "next";
        context.arg = undefined;
      }

    } else {
      // Re-yield the result returned by the delegate method.
      return info;
    }

    // The delegate iterator is finished, so forget it and continue with
    // the outer generator.
    context.delegate = null;
    return ContinueSentinel;
  }

  // Define Generator.prototype.{next,throw,return} in terms of the
  // unified ._invoke helper method.
  defineIteratorMethods(Gp);

  Gp[toStringTagSymbol] = "Generator";

  // A Generator should always return itself as the iterator object when the
  // @@iterator function is called on it. Some browsers' implementations of the
  // iterator prototype chain incorrectly implement this, causing the Generator
  // object to not be returned from this call. This ensures that doesn't happen.
  // See https://github.com/facebook/regenerator/issues/274 for more details.
  Gp[iteratorSymbol] = function() {
    return this;
  };

  Gp.toString = function() {
    return "[object Generator]";
  };

  function pushTryEntry(locs) {
    var entry = { tryLoc: locs[0] };

    if (1 in locs) {
      entry.catchLoc = locs[1];
    }

    if (2 in locs) {
      entry.finallyLoc = locs[2];
      entry.afterLoc = locs[3];
    }

    this.tryEntries.push(entry);
  }

  function resetTryEntry(entry) {
    var record = entry.completion || {};
    record.type = "normal";
    delete record.arg;
    entry.completion = record;
  }

  function Context(tryLocsList) {
    // The root entry object (effectively a try statement without a catch
    // or a finally block) gives us a place to store values thrown from
    // locations where there is no enclosing try statement.
    this.tryEntries = [{ tryLoc: "root" }];
    tryLocsList.forEach(pushTryEntry, this);
    this.reset(true);
  }

  runtime.keys = function(object) {
    var keys = [];
    for (var key in object) {
      keys.push(key);
    }
    keys.reverse();

    // Rather than returning an object with a next method, we keep
    // things simple and return the next function itself.
    return function next() {
      while (keys.length) {
        var key = keys.pop();
        if (key in object) {
          next.value = key;
          next.done = false;
          return next;
        }
      }

      // To avoid creating an additional object, we just hang the .value
      // and .done properties off the next function object itself. This
      // also ensures that the minifier will not anonymize the function.
      next.done = true;
      return next;
    };
  };

  function values(iterable) {
    if (iterable) {
      var iteratorMethod = iterable[iteratorSymbol];
      if (iteratorMethod) {
        return iteratorMethod.call(iterable);
      }

      if (typeof iterable.next === "function") {
        return iterable;
      }

      if (!isNaN(iterable.length)) {
        var i = -1, next = function next() {
          while (++i < iterable.length) {
            if (hasOwn.call(iterable, i)) {
              next.value = iterable[i];
              next.done = false;
              return next;
            }
          }

          next.value = undefined;
          next.done = true;

          return next;
        };

        return next.next = next;
      }
    }

    // Return an iterator with no values.
    return { next: doneResult };
  }
  runtime.values = values;

  function doneResult() {
    return { value: undefined, done: true };
  }

  Context.prototype = {
    constructor: Context,

    reset: function(skipTempReset) {
      this.prev = 0;
      this.next = 0;
      // Resetting context._sent for legacy support of Babel's
      // function.sent implementation.
      this.sent = this._sent = undefined;
      this.done = false;
      this.delegate = null;

      this.method = "next";
      this.arg = undefined;

      this.tryEntries.forEach(resetTryEntry);

      if (!skipTempReset) {
        for (var name in this) {
          // Not sure about the optimal order of these conditions:
          if (name.charAt(0) === "t" &&
              hasOwn.call(this, name) &&
              !isNaN(+name.slice(1))) {
            this[name] = undefined;
          }
        }
      }
    },

    stop: function() {
      this.done = true;

      var rootEntry = this.tryEntries[0];
      var rootRecord = rootEntry.completion;
      if (rootRecord.type === "throw") {
        throw rootRecord.arg;
      }

      return this.rval;
    },

    dispatchException: function(exception) {
      if (this.done) {
        throw exception;
      }

      var context = this;
      function handle(loc, caught) {
        record.type = "throw";
        record.arg = exception;
        context.next = loc;

        if (caught) {
          // If the dispatched exception was caught by a catch block,
          // then let that catch block handle the exception normally.
          context.method = "next";
          context.arg = undefined;
        }

        return !! caught;
      }

      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        var record = entry.completion;

        if (entry.tryLoc === "root") {
          // Exception thrown outside of any try block that could handle
          // it, so set the completion value of the entire function to
          // throw the exception.
          return handle("end");
        }

        if (entry.tryLoc <= this.prev) {
          var hasCatch = hasOwn.call(entry, "catchLoc");
          var hasFinally = hasOwn.call(entry, "finallyLoc");

          if (hasCatch && hasFinally) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            } else if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else if (hasCatch) {
            if (this.prev < entry.catchLoc) {
              return handle(entry.catchLoc, true);
            }

          } else if (hasFinally) {
            if (this.prev < entry.finallyLoc) {
              return handle(entry.finallyLoc);
            }

          } else {
            throw new Error("try statement without catch or finally");
          }
        }
      }
    },

    abrupt: function(type, arg) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc <= this.prev &&
            hasOwn.call(entry, "finallyLoc") &&
            this.prev < entry.finallyLoc) {
          var finallyEntry = entry;
          break;
        }
      }

      if (finallyEntry &&
          (type === "break" ||
           type === "continue") &&
          finallyEntry.tryLoc <= arg &&
          arg <= finallyEntry.finallyLoc) {
        // Ignore the finally entry if control is not jumping to a
        // location outside the try/catch block.
        finallyEntry = null;
      }

      var record = finallyEntry ? finallyEntry.completion : {};
      record.type = type;
      record.arg = arg;

      if (finallyEntry) {
        this.method = "next";
        this.next = finallyEntry.finallyLoc;
        return ContinueSentinel;
      }

      return this.complete(record);
    },

    complete: function(record, afterLoc) {
      if (record.type === "throw") {
        throw record.arg;
      }

      if (record.type === "break" ||
          record.type === "continue") {
        this.next = record.arg;
      } else if (record.type === "return") {
        this.rval = this.arg = record.arg;
        this.method = "return";
        this.next = "end";
      } else if (record.type === "normal" && afterLoc) {
        this.next = afterLoc;
      }

      return ContinueSentinel;
    },

    finish: function(finallyLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.finallyLoc === finallyLoc) {
          this.complete(entry.completion, entry.afterLoc);
          resetTryEntry(entry);
          return ContinueSentinel;
        }
      }
    },

    "catch": function(tryLoc) {
      for (var i = this.tryEntries.length - 1; i >= 0; --i) {
        var entry = this.tryEntries[i];
        if (entry.tryLoc === tryLoc) {
          var record = entry.completion;
          if (record.type === "throw") {
            var thrown = record.arg;
            resetTryEntry(entry);
          }
          return thrown;
        }
      }

      // The context.catch method must only be called with a location
      // argument that corresponds to a known catch block.
      throw new Error("illegal catch attempt");
    },

    delegateYield: function(iterable, resultName, nextLoc) {
      this.delegate = {
        iterator: values(iterable),
        resultName: resultName,
        nextLoc: nextLoc
      };

      if (this.method === "next") {
        // Deliberately forget the last sent value so that we don't
        // accidentally pass it on to the delegate.
        this.arg = undefined;
      }

      return ContinueSentinel;
    }
  };
})(
  // In sloppy mode, unbound `this` refers to the global object, fallback to
  // Function constructor if we're in global strict mode. That is sadly a form
  // of indirect eval which violates Content Security Policy.
  (function() { return this })() || Function("return this")()
);


/***/ }),
/* 619 */
/***/ (function(module, exports, __nested_webpack_require_3158090__) {

"use strict";


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

var _classCallCheck2 = __nested_webpack_require_3158090__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3158090__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

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

var BackgroundTaskScheduler = function () {
  function BackgroundTaskScheduler() {
    (0, _classCallCheck3["default"])(this, BackgroundTaskScheduler);

    this.taskList = [];
    this.taskHandle = null;
    this.requestIdleCallbackTimeout = 300;
  }

  (0, _createClass3["default"])(BackgroundTaskScheduler, [{
    key: "enqueueTask",
    value: function () {
      function enqueueTask(taskHandler, taskData) {
        var trackId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

        if (trackId === null) {
          this.taskList.push({
            handler: taskHandler,
            data: taskData
          });
        } else {
          // If a trackId is given we delete all previous tasks in the taskList of the same track
          // We only want to rerender the latest version of a track
          this.taskList = this.taskList.filter(function (task) {
            return task.trackId !== trackId;
          });

          this.taskList.push({
            handler: taskHandler,
            data: taskData,
            trackId: trackId
          });
        }

        if (!this.taskHandle) {
          this.taskHandle = requestIdleCallback(this.runTaskQueue.bind(this), {
            timeout: this.requestIdleCallbackTimeout
          });
        }
      }

      return enqueueTask;
    }()
  }, {
    key: "runTaskQueue",
    value: function () {
      function runTaskQueue(deadline) {
        while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && this.taskList.length) {
          var task = this.taskList.shift();

          if (task.data === null) {
            task.handler();
          } else {
            task.handler(task.data);
          }
        }

        if (this.taskList.length) {
          this.taskHandle = requestIdleCallback(this.runTaskQueue.bind(this), {
            timeout: this.requestIdleCallbackTimeout
          });
        } else {
          this.taskHandle = 0;
        }
      }

      return runTaskQueue;
    }()
  }]);
  return BackgroundTaskScheduler;
}();

var backgroundTaskScheduler = new BackgroundTaskScheduler();

exports["default"] = backgroundTaskScheduler;

/***/ }),
/* 620 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function dupe_array(count, value, i) {
  var c = count[i]|0
  if(c <= 0) {
    return []
  }
  var result = new Array(c), j
  if(i === count.length-1) {
    for(j=0; j<c; ++j) {
      result[j] = value
    }
  } else {
    for(j=0; j<c; ++j) {
      result[j] = dupe_array(count, value, i+1)
    }
  }
  return result
}

function dupe_number(count, value) {
  var result, i
  result = new Array(count)
  for(i=0; i<count; ++i) {
    result[i] = value
  }
  return result
}

function dupe(count, value) {
  if(typeof value === "undefined") {
    value = 0
  }
  switch(typeof count) {
    case "number":
      if(count > 0) {
        return dupe_number(count|0, value)
      }
    break
    case "object":
      if(typeof (count.length) === "number") {
        return dupe_array(count, value, 0)
      }
    break
  }
  return []
}

module.exports = dupe

/***/ }),
/* 621 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//This code is extracted from ndarray-sort
//It is inlined here as a temporary workaround

module.exports = wrapper;

var INSERT_SORT_CUTOFF = 32

function wrapper(data, n0) {
  if (n0 <= 4*INSERT_SORT_CUTOFF) {
    insertionSort(0, n0 - 1, data);
  } else {
    quickSort(0, n0 - 1, data);
  }
}

function insertionSort(left, right, data) {
  var ptr = 2*(left+1)
  for(var i=left+1; i<=right; ++i) {
    var a = data[ptr++]
    var b = data[ptr++]
    var j = i
    var jptr = ptr-2
    while(j-- > left) {
      var x = data[jptr-2]
      var y = data[jptr-1]
      if(x < a) {
        break
      } else if(x === a && y < b) {
        break
      }
      data[jptr]   = x
      data[jptr+1] = y
      jptr -= 2
    }
    data[jptr]   = a
    data[jptr+1] = b
  }
}

function swap(i, j, data) {
  i *= 2
  j *= 2
  var x = data[i]
  var y = data[i+1]
  data[i] = data[j]
  data[i+1] = data[j+1]
  data[j] = x
  data[j+1] = y
}

function move(i, j, data) {
  i *= 2
  j *= 2
  data[i] = data[j]
  data[i+1] = data[j+1]
}

function rotate(i, j, k, data) {
  i *= 2
  j *= 2
  k *= 2
  var x = data[i]
  var y = data[i+1]
  data[i] = data[j]
  data[i+1] = data[j+1]
  data[j] = data[k]
  data[j+1] = data[k+1]
  data[k] = x
  data[k+1] = y
}

function shufflePivot(i, j, px, py, data) {
  i *= 2
  j *= 2
  data[i] = data[j]
  data[j] = px
  data[i+1] = data[j+1]
  data[j+1] = py
}

function compare(i, j, data) {
  i *= 2
  j *= 2
  var x = data[i],
      y = data[j]
  if(x < y) {
    return false
  } else if(x === y) {
    return data[i+1] > data[j+1]
  }
  return true
}

function comparePivot(i, y, b, data) {
  i *= 2
  var x = data[i]
  if(x < y) {
    return true
  } else if(x === y) {
    return data[i+1] < b
  }
  return false
}

function quickSort(left, right, data) {
  var sixth = (right - left + 1) / 6 | 0, 
      index1 = left + sixth, 
      index5 = right - sixth, 
      index3 = left + right >> 1, 
      index2 = index3 - sixth, 
      index4 = index3 + sixth, 
      el1 = index1, 
      el2 = index2, 
      el3 = index3, 
      el4 = index4, 
      el5 = index5, 
      less = left + 1, 
      great = right - 1, 
      tmp = 0
  if(compare(el1, el2, data)) {
    tmp = el1
    el1 = el2
    el2 = tmp
  }
  if(compare(el4, el5, data)) {
    tmp = el4
    el4 = el5
    el5 = tmp
  }
  if(compare(el1, el3, data)) {
    tmp = el1
    el1 = el3
    el3 = tmp
  }
  if(compare(el2, el3, data)) {
    tmp = el2
    el2 = el3
    el3 = tmp
  }
  if(compare(el1, el4, data)) {
    tmp = el1
    el1 = el4
    el4 = tmp
  }
  if(compare(el3, el4, data)) {
    tmp = el3
    el3 = el4
    el4 = tmp
  }
  if(compare(el2, el5, data)) {
    tmp = el2
    el2 = el5
    el5 = tmp
  }
  if(compare(el2, el3, data)) {
    tmp = el2
    el2 = el3
    el3 = tmp
  }
  if(compare(el4, el5, data)) {
    tmp = el4
    el4 = el5
    el5 = tmp
  }

  var pivot1X = data[2*el2]
  var pivot1Y = data[2*el2+1]
  var pivot2X = data[2*el4]
  var pivot2Y = data[2*el4+1]

  var ptr0 = 2 * el1;
  var ptr2 = 2 * el3;
  var ptr4 = 2 * el5;
  var ptr5 = 2 * index1;
  var ptr6 = 2 * index3;
  var ptr7 = 2 * index5;
  for (var i1 = 0; i1 < 2; ++i1) {
    var x = data[ptr0+i1];
    var y = data[ptr2+i1];
    var z = data[ptr4+i1];
    data[ptr5+i1] = x;
    data[ptr6+i1] = y;
    data[ptr7+i1] = z;
  }

  move(index2, left, data)
  move(index4, right, data)
  for (var k = less; k <= great; ++k) {
    if (comparePivot(k, pivot1X, pivot1Y, data)) {
      if (k !== less) {
        swap(k, less, data)
      }
      ++less;
    } else {
      if (!comparePivot(k, pivot2X, pivot2Y, data)) {
        while (true) {
          if (!comparePivot(great, pivot2X, pivot2Y, data)) {
            if (--great < k) {
              break;
            }
            continue;
          } else {
            if (comparePivot(great, pivot1X, pivot1Y, data)) {
              rotate(k, less, great, data)
              ++less;
              --great;
            } else {
              swap(k, great, data)
              --great;
            }
            break;
          }
        }
      }
    }
  }
  shufflePivot(left, less-1, pivot1X, pivot1Y, data)
  shufflePivot(right, great+1, pivot2X, pivot2Y, data)
  if (less - 2 - left <= INSERT_SORT_CUTOFF) {
    insertionSort(left, less - 2, data);
  } else {
    quickSort(left, less - 2, data);
  }
  if (right - (great + 2) <= INSERT_SORT_CUTOFF) {
    insertionSort(great + 2, right, data);
  } else {
    quickSort(great + 2, right, data);
  }
  if (great - less <= INSERT_SORT_CUTOFF) {
    insertionSort(less, great, data);
  } else {
    quickSort(less, great, data);
  }
}

/***/ }),
/* 622 */
/***/ (function(module, exports, __nested_webpack_require_3166385__) {

"use strict";


module.exports = boxIntersectIter

var pool = __nested_webpack_require_3166385__(257)
var bits = __nested_webpack_require_3166385__(258)
var bruteForce = __nested_webpack_require_3166385__(623)
var bruteForcePartial = bruteForce.partial
var bruteForceFull = bruteForce.full
var sweep = __nested_webpack_require_3166385__(353)
var findMedian = __nested_webpack_require_3166385__(624)
var genPartition = __nested_webpack_require_3166385__(354)

//Twiddle parameters
var BRUTE_FORCE_CUTOFF    = 128       //Cut off for brute force search
var SCAN_CUTOFF           = (1<<22)   //Cut off for two way scan
var SCAN_COMPLETE_CUTOFF  = (1<<22)  

//Partition functions
var partitionInteriorContainsInterval = genPartition(
  '!(lo>=p0)&&!(p1>=hi)', 
  ['p0', 'p1'])

var partitionStartEqual = genPartition(
  'lo===p0',
  ['p0'])

var partitionStartLessThan = genPartition(
  'lo<p0',
  ['p0'])

var partitionEndLessThanEqual = genPartition(
  'hi<=p0',
  ['p0'])

var partitionContainsPoint = genPartition(
  'lo<=p0&&p0<=hi',
  ['p0'])

var partitionContainsPointProper = genPartition(
  'lo<p0&&p0<=hi',
  ['p0'])

//Frame size for iterative loop
var IFRAME_SIZE = 6
var DFRAME_SIZE = 2

//Data for box statck
var INIT_CAPACITY = 1024
var BOX_ISTACK  = pool.mallocInt32(INIT_CAPACITY)
var BOX_DSTACK  = pool.mallocDouble(INIT_CAPACITY)

//Initialize iterative loop queue
function iterInit(d, count) {
  var levels = (8 * bits.log2(count+1) * (d+1))|0
  var maxInts = bits.nextPow2(IFRAME_SIZE*levels)
  if(BOX_ISTACK.length < maxInts) {
    pool.free(BOX_ISTACK)
    BOX_ISTACK = pool.mallocInt32(maxInts)
  }
  var maxDoubles = bits.nextPow2(DFRAME_SIZE*levels)
  if(BOX_DSTACK.length < maxDoubles) {
    pool.free(BOX_DSTACK)
    BOX_DSTACK = pool.mallocDouble(maxDoubles)
  }
}

//Append item to queue
function iterPush(ptr,
  axis, 
  redStart, redEnd, 
  blueStart, blueEnd, 
  state, 
  lo, hi) {

  var iptr = IFRAME_SIZE * ptr
  BOX_ISTACK[iptr]   = axis
  BOX_ISTACK[iptr+1] = redStart
  BOX_ISTACK[iptr+2] = redEnd
  BOX_ISTACK[iptr+3] = blueStart
  BOX_ISTACK[iptr+4] = blueEnd
  BOX_ISTACK[iptr+5] = state

  var dptr = DFRAME_SIZE * ptr
  BOX_DSTACK[dptr]   = lo
  BOX_DSTACK[dptr+1] = hi
}

//Special case:  Intersect single point with list of intervals
function onePointPartial(
  d, axis, visit, flip,
  redStart, redEnd, red, redIndex,
  blueOffset, blue, blueId) {

  var elemSize = 2 * d
  var bluePtr  = blueOffset * elemSize
  var blueX    = blue[bluePtr + axis]

red_loop:
  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
    var r0 = red[redPtr+axis]
    var r1 = red[redPtr+axis+d]
    if(blueX < r0 || r1 < blueX) {
      continue
    }
    if(flip && blueX === r0) {
      continue
    }
    var redId = redIndex[i]
    for(var j=axis+1; j<d; ++j) {
      var r0 = red[redPtr+j]
      var r1 = red[redPtr+j+d]
      var b0 = blue[bluePtr+j]
      var b1 = blue[bluePtr+j+d]
      if(r1 < b0 || b1 < r0) {
        continue red_loop
      }
    }
    var retval
    if(flip) {
      retval = visit(blueId, redId)
    } else {
      retval = visit(redId, blueId)
    }
    if(retval !== void 0) {
      return retval
    }
  }
}

//Special case:  Intersect one point with list of intervals
function onePointFull(
  d, axis, visit,
  redStart, redEnd, red, redIndex,
  blueOffset, blue, blueId) {

  var elemSize = 2 * d
  var bluePtr  = blueOffset * elemSize
  var blueX    = blue[bluePtr + axis]

red_loop:
  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
    var redId = redIndex[i]
    if(redId === blueId) {
      continue
    }
    var r0 = red[redPtr+axis]
    var r1 = red[redPtr+axis+d]
    if(blueX < r0 || r1 < blueX) {
      continue
    }
    for(var j=axis+1; j<d; ++j) {
      var r0 = red[redPtr+j]
      var r1 = red[redPtr+j+d]
      var b0 = blue[bluePtr+j]
      var b1 = blue[bluePtr+j+d]
      if(r1 < b0 || b1 < r0) {
        continue red_loop
      }
    }
    var retval = visit(redId, blueId)
    if(retval !== void 0) {
      return retval
    }
  }
}

//The main box intersection routine
function boxIntersectIter(
  d, visit, initFull,
  xSize, xBoxes, xIndex,
  ySize, yBoxes, yIndex) {

  //Reserve memory for stack
  iterInit(d, xSize + ySize)

  var top  = 0
  var elemSize = 2 * d
  var retval

  iterPush(top++,
      0,
      0, xSize,
      0, ySize,
      initFull ? 16 : 0, 
      -Infinity, Infinity)
  if(!initFull) {
    iterPush(top++,
      0,
      0, ySize,
      0, xSize,
      1, 
      -Infinity, Infinity)
  }

  while(top > 0) {
    top  -= 1

    var iptr = top * IFRAME_SIZE
    var axis      = BOX_ISTACK[iptr]
    var redStart  = BOX_ISTACK[iptr+1]
    var redEnd    = BOX_ISTACK[iptr+2]
    var blueStart = BOX_ISTACK[iptr+3]
    var blueEnd   = BOX_ISTACK[iptr+4]
    var state     = BOX_ISTACK[iptr+5]

    var dptr = top * DFRAME_SIZE
    var lo        = BOX_DSTACK[dptr]
    var hi        = BOX_DSTACK[dptr+1]

    //Unpack state info
    var flip      = (state & 1)
    var full      = !!(state & 16)

    //Unpack indices
    var red       = xBoxes
    var redIndex  = xIndex
    var blue      = yBoxes
    var blueIndex = yIndex
    if(flip) {
      red         = yBoxes
      redIndex    = yIndex
      blue        = xBoxes
      blueIndex   = xIndex
    }

    if(state & 2) {
      redEnd = partitionStartLessThan(
        d, axis,
        redStart, redEnd, red, redIndex,
        hi)
      if(redStart >= redEnd) {
        continue
      }
    }
    if(state & 4) {
      redStart = partitionEndLessThanEqual(
        d, axis,
        redStart, redEnd, red, redIndex,
        lo)
      if(redStart >= redEnd) {
        continue
      }
    }
    
    var redCount  = redEnd  - redStart
    var blueCount = blueEnd - blueStart

    if(full) {
      if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) {
        retval = sweep.scanComplete(
          d, axis, visit, 
          redStart, redEnd, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      }
    } else {
      if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) {
        //If input small, then use brute force
        retval = bruteForcePartial(
            d, axis, visit, flip,
            redStart,  redEnd,  red,  redIndex,
            blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      } else if(d * redCount * blueCount < SCAN_CUTOFF) {
        //If input medium sized, then use sweep and prune
        retval = sweep.scanBipartite(
          d, axis, visit, flip, 
          redStart, redEnd, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
        continue
      }
    }
    
    //First, find all red intervals whose interior contains (lo,hi)
    var red0 = partitionInteriorContainsInterval(
      d, axis, 
      redStart, redEnd, red, redIndex,
      lo, hi)

    //Lower dimensional case
    if(redStart < red0) {

      if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) {
        //Special case for small inputs: use brute force
        retval = bruteForceFull(
          d, axis+1, visit,
          redStart, red0, red, redIndex,
          blueStart, blueEnd, blue, blueIndex)
        if(retval !== void 0) {
          return retval
        }
      } else if(axis === d-2) {
        if(flip) {
          retval = sweep.sweepBipartite(
            d, visit,
            blueStart, blueEnd, blue, blueIndex,
            redStart, red0, red, redIndex)
        } else {
          retval = sweep.sweepBipartite(
            d, visit,
            redStart, red0, red, redIndex,
            blueStart, blueEnd, blue, blueIndex)
        }
        if(retval !== void 0) {
          return retval
        }
      } else {
        iterPush(top++,
          axis+1,
          redStart, red0,
          blueStart, blueEnd,
          flip,
          -Infinity, Infinity)
        iterPush(top++,
          axis+1,
          blueStart, blueEnd,
          redStart, red0,
          flip^1,
          -Infinity, Infinity)
      }
    }

    //Divide and conquer phase
    if(red0 < redEnd) {

      //Cut blue into 3 parts:
      //
      //  Points < mid point
      //  Points = mid point
      //  Points > mid point
      //
      var blue0 = findMedian(
        d, axis, 
        blueStart, blueEnd, blue, blueIndex)
      var mid = blue[elemSize * blue0 + axis]
      var blue1 = partitionStartEqual(
        d, axis,
        blue0, blueEnd, blue, blueIndex,
        mid)

      //Right case
      if(blue1 < blueEnd) {
        iterPush(top++,
          axis,
          red0, redEnd,
          blue1, blueEnd,
          (flip|4) + (full ? 16 : 0),
          mid, hi)
      }

      //Left case
      if(blueStart < blue0) {
        iterPush(top++,
          axis,
          red0, redEnd,
          blueStart, blue0,
          (flip|2) + (full ? 16 : 0),
          lo, mid)
      }

      //Center case (the hard part)
      if(blue0 + 1 === blue1) {
        //Optimization: Range with exactly 1 point, use a brute force scan
        if(full) {
          retval = onePointFull(
            d, axis, visit,
            red0, redEnd, red, redIndex,
            blue0, blue, blueIndex[blue0])
        } else {
          retval = onePointPartial(
            d, axis, visit, flip,
            red0, redEnd, red, redIndex,
            blue0, blue, blueIndex[blue0])
        }
        if(retval !== void 0) {
          return retval
        }
      } else if(blue0 < blue1) {
        var red1
        if(full) {
          //If full intersection, need to handle special case
          red1 = partitionContainsPoint(
            d, axis,
            red0, redEnd, red, redIndex,
            mid)
          if(red0 < red1) {
            var redX = partitionStartEqual(
              d, axis,
              red0, red1, red, redIndex,
              mid)
            if(axis === d-2) {
              //Degenerate sweep intersection:
              //  [red0, redX] with [blue0, blue1]
              if(red0 < redX) {
                retval = sweep.sweepComplete(
                  d, visit,
                  red0, redX, red, redIndex,
                  blue0, blue1, blue, blueIndex)
                if(retval !== void 0) {
                  return retval
                }
              }

              //Normal sweep intersection:
              //  [redX, red1] with [blue0, blue1]
              if(redX < red1) {
                retval = sweep.sweepBipartite(
                  d, visit,
                  redX, red1, red, redIndex,
                  blue0, blue1, blue, blueIndex)
                if(retval !== void 0) {
                  return retval
                }
              }
            } else {
              if(red0 < redX) {
                iterPush(top++,
                  axis+1,
                  red0, redX,
                  blue0, blue1,
                  16,
                  -Infinity, Infinity)
              }
              if(redX < red1) {
                iterPush(top++,
                  axis+1,
                  redX, red1,
                  blue0, blue1,
                  0,
                  -Infinity, Infinity)
                iterPush(top++,
                  axis+1,
                  blue0, blue1,
                  redX, red1,
                  1,
                  -Infinity, Infinity)
              }
            }
          }
        } else {
          if(flip) {
            red1 = partitionContainsPointProper(
              d, axis,
              red0, redEnd, red, redIndex,
              mid)
          } else {
            red1 = partitionContainsPoint(
              d, axis,
              red0, redEnd, red, redIndex,
              mid)
          }
          if(red0 < red1) {
            if(axis === d-2) {
              if(flip) {
                retval = sweep.sweepBipartite(
                  d, visit,
                  blue0, blue1, blue, blueIndex,
                  red0, red1, red, redIndex)
              } else {
                retval = sweep.sweepBipartite(
                  d, visit,
                  red0, red1, red, redIndex,
                  blue0, blue1, blue, blueIndex)
              }
            } else {
              iterPush(top++,
                axis+1,
                red0, red1,
                blue0, blue1,
                flip,
                -Infinity, Infinity)
              iterPush(top++,
                axis+1,
                blue0, blue1,
                red0, red1,
                flip^1,
                -Infinity, Infinity)
            }
          }
        }
      }
    }
  }
}

/***/ }),
/* 623 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var DIMENSION   = 'd'
var AXIS        = 'ax'
var VISIT       = 'vv'
var FLIP        = 'fp'

var ELEM_SIZE   = 'es'

var RED_START   = 'rs'
var RED_END     = 're'
var RED_BOXES   = 'rb'
var RED_INDEX   = 'ri'
var RED_PTR     = 'rp'

var BLUE_START  = 'bs'
var BLUE_END    = 'be'
var BLUE_BOXES  = 'bb'
var BLUE_INDEX  = 'bi'
var BLUE_PTR    = 'bp'

var RETVAL      = 'rv'

var INNER_LABEL = 'Q'

var ARGS = [
  DIMENSION,
  AXIS,
  VISIT,
  RED_START,
  RED_END,
  RED_BOXES,
  RED_INDEX,
  BLUE_START,
  BLUE_END,
  BLUE_BOXES,
  BLUE_INDEX
]

function generateBruteForce(redMajor, flip, full) {
  var funcName = 'bruteForce' + 
    (redMajor ? 'Red' : 'Blue') + 
    (flip ? 'Flip' : '') +
    (full ? 'Full' : '')

  var code = ['function ', funcName, '(', ARGS.join(), '){',
    'var ', ELEM_SIZE, '=2*', DIMENSION, ';']

  var redLoop = 
    'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' +
        'i<' + RED_END +';' +
        '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' +
        'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' +
            'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' +
            'xi=' + RED_INDEX + '[i];'

  var blueLoop = 
    'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' +
        'j<' + BLUE_END + ';' +
        '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' +
        'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' +
            (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') +
            'yi=' + BLUE_INDEX + '[j];'

  if(redMajor) {
    code.push(redLoop, INNER_LABEL, ':', blueLoop)
  } else {
    code.push(blueLoop, INNER_LABEL, ':', redLoop)
  }

  if(full) {
    code.push('if(y1<x0||x1<y0)continue;')
  } else if(flip) {
    code.push('if(y0<=x0||x1<y0)continue;')
  } else {
    code.push('if(y0<x0||x1<y0)continue;')
  }

  code.push('for(var k='+AXIS+'+1;k<'+DIMENSION+';++k){'+
    'var r0='+RED_BOXES+'[k+'+RED_PTR+'],'+
        'r1='+RED_BOXES+'[k+'+DIMENSION+'+'+RED_PTR+'],'+
        'b0='+BLUE_BOXES+'[k+'+BLUE_PTR+'],'+
        'b1='+BLUE_BOXES+'[k+'+DIMENSION+'+'+BLUE_PTR+'];'+
      'if(r1<b0||b1<r0)continue ' + INNER_LABEL + ';}' +
      'var ' + RETVAL + '=' + VISIT + '(')

  if(flip) {
    code.push('yi,xi')
  } else {
    code.push('xi,yi')
  }

  code.push(');if(' + RETVAL + '!==void 0)return ' + RETVAL + ';}}}')

  return {
    name: funcName, 
    code: code.join('')
  }
}

function bruteForcePlanner(full) {
  var funcName = 'bruteForce' + (full ? 'Full' : 'Partial')
  var prefix = []
  var fargs = ARGS.slice()
  if(!full) {
    fargs.splice(3, 0, FLIP)
  }

  var code = ['function ' + funcName + '(' + fargs.join() + '){']

  function invoke(redMajor, flip) {
    var res = generateBruteForce(redMajor, flip, full)
    prefix.push(res.code)
    code.push('return ' + res.name + '(' + ARGS.join() + ');')
  }

  code.push('if(' + RED_END + '-' + RED_START + '>' +
                    BLUE_END + '-' + BLUE_START + '){')

  if(full) {
    invoke(true, false)
    code.push('}else{')
    invoke(false, false)
  } else {
    code.push('if(' + FLIP + '){')
    invoke(true, true)
    code.push('}else{')
    invoke(true, false)
    code.push('}}else{if(' + FLIP + '){')
    invoke(false, true)
    code.push('}else{')
    invoke(false, false)
    code.push('}')
  }
  code.push('}}return ' + funcName)

  var codeStr = prefix.join('') + code.join('')
  var proc = new Function(codeStr)
  return proc()
}


exports.partial = bruteForcePlanner(false)
exports.full    = bruteForcePlanner(true)

/***/ }),
/* 624 */
/***/ (function(module, exports, __nested_webpack_require_3182868__) {

"use strict";


module.exports = findMedian

var genPartition = __nested_webpack_require_3182868__(354)

var partitionStartLessThan = genPartition('lo<p0', ['p0'])

var PARTITION_THRESHOLD = 8   //Cut off for using insertion sort in findMedian

//Base case for median finding:  Use insertion sort
function insertionSort(d, axis, start, end, boxes, ids) {
  var elemSize = 2 * d
  var boxPtr = elemSize * (start+1) + axis
  for(var i=start+1; i<end; ++i, boxPtr+=elemSize) {
    var x = boxes[boxPtr]
    for(var j=i, ptr=elemSize*(i-1); 
        j>start && boxes[ptr+axis] > x; 
        --j, ptr-=elemSize) {
      //Swap
      var aPtr = ptr
      var bPtr = ptr+elemSize
      for(var k=0; k<elemSize; ++k, ++aPtr, ++bPtr) {
        var y = boxes[aPtr]
        boxes[aPtr] = boxes[bPtr]
        boxes[bPtr] = y
      }
      var tmp = ids[j]
      ids[j] = ids[j-1]
      ids[j-1] = tmp
    }
  }
}

//Find median using quick select algorithm
//  takes O(n) time with high probability
function findMedian(d, axis, start, end, boxes, ids) {
  if(end <= start+1) {
    return start
  }

  var lo       = start
  var hi       = end
  var mid      = ((end + start) >>> 1)
  var elemSize = 2*d
  var pivot    = mid
  var value    = boxes[elemSize*mid+axis]
  
  while(lo < hi) {
    if(hi - lo < PARTITION_THRESHOLD) {
      insertionSort(d, axis, lo, hi, boxes, ids)
      value = boxes[elemSize*mid+axis]
      break
    }
    
    //Select pivot using median-of-3
    var count  = hi - lo
    var pivot0 = (Math.random()*count+lo)|0
    var value0 = boxes[elemSize*pivot0 + axis]
    var pivot1 = (Math.random()*count+lo)|0
    var value1 = boxes[elemSize*pivot1 + axis]
    var pivot2 = (Math.random()*count+lo)|0
    var value2 = boxes[elemSize*pivot2 + axis]
    if(value0 <= value1) {
      if(value2 >= value1) {
        pivot = pivot1
        value = value1
      } else if(value0 >= value2) {
        pivot = pivot0
        value = value0
      } else {
        pivot = pivot2
        value = value2
      }
    } else {
      if(value1 >= value2) {
        pivot = pivot1
        value = value1
      } else if(value2 >= value0) {
        pivot = pivot0
        value = value0
      } else {
        pivot = pivot2
        value = value2
      }
    }

    //Swap pivot to end of array
    var aPtr = elemSize * (hi-1)
    var bPtr = elemSize * pivot
    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
      var x = boxes[aPtr]
      boxes[aPtr] = boxes[bPtr]
      boxes[bPtr] = x
    }
    var y = ids[hi-1]
    ids[hi-1] = ids[pivot]
    ids[pivot] = y

    //Partition using pivot
    pivot = partitionStartLessThan(
      d, axis, 
      lo, hi-1, boxes, ids,
      value)

    //Swap pivot back
    var aPtr = elemSize * (hi-1)
    var bPtr = elemSize * pivot
    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
      var x = boxes[aPtr]
      boxes[aPtr] = boxes[bPtr]
      boxes[bPtr] = x
    }
    var y = ids[hi-1]
    ids[hi-1] = ids[pivot]
    ids[pivot] = y

    //Swap pivot to last pivot
    if(mid < pivot) {
      hi = pivot-1
      while(lo < hi && 
        boxes[elemSize*(hi-1)+axis] === value) {
        hi -= 1
      }
      hi += 1
    } else if(pivot < mid) {
      lo = pivot + 1
      while(lo < hi &&
        boxes[elemSize*lo+axis] === value) {
        lo += 1
      }
    } else {
      break
    }
  }

  //Make sure pivot is at start
  return partitionStartLessThan(
    d, axis, 
    start, mid, boxes, ids,
    boxes[elemSize*mid+axis])
}

/***/ }),
/* 625 */
/***/ (function(module, exports, __nested_webpack_require_3186413__) {

"use strict";


var twoProduct = __nested_webpack_require_3186413__(356)
var robustSum = __nested_webpack_require_3186413__(626)
var robustScale = __nested_webpack_require_3186413__(627)
var robustSubtract = __nested_webpack_require_3186413__(629)

var NUM_EXPAND = 5

var EPSILON     = 1.1102230246251565e-16
var ERRBOUND3   = (3.0 + 16.0 * EPSILON) * EPSILON
var ERRBOUND4   = (7.0 + 56.0 * EPSILON) * EPSILON

function cofactor(m, c) {
  var result = new Array(m.length-1)
  for(var i=1; i<m.length; ++i) {
    var r = result[i-1] = new Array(m.length-1)
    for(var j=0,k=0; j<m.length; ++j) {
      if(j === c) {
        continue
      }
      r[k++] = m[i][j]
    }
  }
  return result
}

function matrix(n) {
  var result = new Array(n)
  for(var i=0; i<n; ++i) {
    result[i] = new Array(n)
    for(var j=0; j<n; ++j) {
      result[i][j] = ["m", j, "[", (n-i-1), "]"].join("")
    }
  }
  return result
}

function sign(n) {
  if(n & 1) {
    return "-"
  }
  return ""
}

function generateSum(expr) {
  if(expr.length === 1) {
    return expr[0]
  } else if(expr.length === 2) {
    return ["sum(", expr[0], ",", expr[1], ")"].join("")
  } else {
    var m = expr.length>>1
    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
  }
}

function determinant(m) {
  if(m.length === 2) {
    return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")]
  } else {
    var expr = []
    for(var i=0; i<m.length; ++i) {
      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
    }
    return expr
  }
}

function orientation(n) {
  var pos = []
  var neg = []
  var m = matrix(n)
  var args = []
  for(var i=0; i<n; ++i) {
    if((i&1)===0) {
      pos.push.apply(pos, determinant(cofactor(m, i)))
    } else {
      neg.push.apply(neg, determinant(cofactor(m, i)))
    }
    args.push("m" + i)
  }
  var posExpr = generateSum(pos)
  var negExpr = generateSum(neg)
  var funcName = "orientation" + n + "Exact"
  var code = ["function ", funcName, "(", args.join(), "){var p=", posExpr, ",n=", negExpr, ",d=sub(p,n);\
return d[d.length-1];};return ", funcName].join("")
  var proc = new Function("sum", "prod", "scale", "sub", code)
  return proc(robustSum, twoProduct, robustScale, robustSubtract)
}

var orientation3Exact = orientation(3)
var orientation4Exact = orientation(4)

var CACHED = [
  function orientation0() { return 0 },
  function orientation1() { return 0 },
  function orientation2(a, b) { 
    return b[0] - a[0]
  },
  function orientation3(a, b, c) {
    var l = (a[1] - c[1]) * (b[0] - c[0])
    var r = (a[0] - c[0]) * (b[1] - c[1])
    var det = l - r
    var s
    if(l > 0) {
      if(r <= 0) {
        return det
      } else {
        s = l + r
      }
    } else if(l < 0) {
      if(r >= 0) {
        return det
      } else {
        s = -(l + r)
      }
    } else {
      return det
    }
    var tol = ERRBOUND3 * s
    if(det >= tol || det <= -tol) {
      return det
    }
    return orientation3Exact(a, b, c)
  },
  function orientation4(a,b,c,d) {
    var adx = a[0] - d[0]
    var bdx = b[0] - d[0]
    var cdx = c[0] - d[0]
    var ady = a[1] - d[1]
    var bdy = b[1] - d[1]
    var cdy = c[1] - d[1]
    var adz = a[2] - d[2]
    var bdz = b[2] - d[2]
    var cdz = c[2] - d[2]
    var bdxcdy = bdx * cdy
    var cdxbdy = cdx * bdy
    var cdxady = cdx * ady
    var adxcdy = adx * cdy
    var adxbdy = adx * bdy
    var bdxady = bdx * ady
    var det = adz * (bdxcdy - cdxbdy) 
            + bdz * (cdxady - adxcdy)
            + cdz * (adxbdy - bdxady)
    var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz)
                  + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz)
                  + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz)
    var tol = ERRBOUND4 * permanent
    if ((det > tol) || (-det > tol)) {
      return det
    }
    return orientation4Exact(a,b,c,d)
  }
]

function slowOrient(args) {
  var proc = CACHED[args.length]
  if(!proc) {
    proc = CACHED[args.length] = orientation(args.length)
  }
  return proc.apply(undefined, args)
}

function generateOrientationProc() {
  while(CACHED.length <= NUM_EXPAND) {
    CACHED.push(orientation(CACHED.length))
  }
  var args = []
  var procArgs = ["slow"]
  for(var i=0; i<=NUM_EXPAND; ++i) {
    args.push("a" + i)
    procArgs.push("o" + i)
  }
  var code = [
    "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
  ]
  for(var i=2; i<=NUM_EXPAND; ++i) {
    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
  }
  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return getOrientation")
  procArgs.push(code.join(""))

  var proc = Function.apply(undefined, procArgs)
  module.exports = proc.apply(undefined, [slowOrient].concat(CACHED))
  for(var i=0; i<=NUM_EXPAND; ++i) {
    module.exports[i] = CACHED[i]
  }
}

generateOrientationProc()

/***/ }),
/* 626 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = linearExpansionSum

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b
  var bv = x - a
  var av = x - bv
  var br = b - bv
  var ar = a - av
  var y = ar + br
  if(y) {
    return [y, x]
  }
  return [x]
}

function linearExpansionSum(e, f) {
  var ne = e.length|0
  var nf = f.length|0
  if(ne === 1 && nf === 1) {
    return scalarScalar(e[0], f[0])
  }
  var n = ne + nf
  var g = new Array(n)
  var count = 0
  var eptr = 0
  var fptr = 0
  var abs = Math.abs
  var ei = e[eptr]
  var ea = abs(ei)
  var fi = f[fptr]
  var fa = abs(fi)
  var a, b
  if(ea < fa) {
    b = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    b = fi
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
      fa = abs(fi)
    }
  }
  if((eptr < ne && ea < fa) || (fptr >= nf)) {
    a = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    a = fi
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
      fa = abs(fi)
    }
  }
  var x = a + b
  var bv = x - a
  var y = b - bv
  var q0 = y
  var q1 = x
  var _x, _bv, _av, _br, _ar
  while(eptr < ne && fptr < nf) {
    if(ea < fa) {
      a = ei
      eptr += 1
      if(eptr < ne) {
        ei = e[eptr]
        ea = abs(ei)
      }
    } else {
      a = fi
      fptr += 1
      if(fptr < nf) {
        fi = f[fptr]
        fa = abs(fi)
      }
    }
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
  }
  while(eptr < ne) {
    a = ei
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
    }
  }
  while(fptr < nf) {
    a = fi
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    } 
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    fptr += 1
    if(fptr < nf) {
      fi = f[fptr]
    }
  }
  if(q0) {
    g[count++] = q0
  }
  if(q1) {
    g[count++] = q1
  }
  if(!count) {
    g[count++] = 0.0  
  }
  g.length = count
  return g
}

/***/ }),
/* 627 */
/***/ (function(module, exports, __nested_webpack_require_3193995__) {

"use strict";


var twoProduct = __nested_webpack_require_3193995__(356)
var twoSum = __nested_webpack_require_3193995__(628)

module.exports = scaleLinearExpansion

function scaleLinearExpansion(e, scale) {
  var n = e.length
  if(n === 1) {
    var ts = twoProduct(e[0], scale)
    if(ts[0]) {
      return ts
    }
    return [ ts[1] ]
  }
  var g = new Array(2 * n)
  var q = [0.1, 0.1]
  var t = [0.1, 0.1]
  var count = 0
  twoProduct(e[0], scale, q)
  if(q[0]) {
    g[count++] = q[0]
  }
  for(var i=1; i<n; ++i) {
    twoProduct(e[i], scale, t)
    var pq = q[1]
    twoSum(pq, t[0], q)
    if(q[0]) {
      g[count++] = q[0]
    }
    var a = t[1]
    var b = q[1]
    var x = a + b
    var bv = x - a
    var y = b - bv
    q[1] = x
    if(y) {
      g[count++] = y
    }
  }
  if(q[1]) {
    g[count++] = q[1]
  }
  if(count === 0) {
    g[count++] = 0.0
  }
  g.length = count
  return g
}

/***/ }),
/* 628 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = fastTwoSum

function fastTwoSum(a, b, result) {
	var x = a + b
	var bv = x - a
	var av = x - bv
	var br = b - bv
	var ar = a - av
	if(result) {
		result[0] = ar + br
		result[1] = x
		return result
	}
	return [ar+br, x]
}

/***/ }),
/* 629 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = robustSubtract

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b
  var bv = x - a
  var av = x - bv
  var br = b - bv
  var ar = a - av
  var y = ar + br
  if(y) {
    return [y, x]
  }
  return [x]
}

function robustSubtract(e, f) {
  var ne = e.length|0
  var nf = f.length|0
  if(ne === 1 && nf === 1) {
    return scalarScalar(e[0], -f[0])
  }
  var n = ne + nf
  var g = new Array(n)
  var count = 0
  var eptr = 0
  var fptr = 0
  var abs = Math.abs
  var ei = e[eptr]
  var ea = abs(ei)
  var fi = -f[fptr]
  var fa = abs(fi)
  var a, b
  if(ea < fa) {
    b = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    b = fi
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
      fa = abs(fi)
    }
  }
  if((eptr < ne && ea < fa) || (fptr >= nf)) {
    a = ei
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
      ea = abs(ei)
    }
  } else {
    a = fi
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
      fa = abs(fi)
    }
  }
  var x = a + b
  var bv = x - a
  var y = b - bv
  var q0 = y
  var q1 = x
  var _x, _bv, _av, _br, _ar
  while(eptr < ne && fptr < nf) {
    if(ea < fa) {
      a = ei
      eptr += 1
      if(eptr < ne) {
        ei = e[eptr]
        ea = abs(ei)
      }
    } else {
      a = fi
      fptr += 1
      if(fptr < nf) {
        fi = -f[fptr]
        fa = abs(fi)
      }
    }
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
  }
  while(eptr < ne) {
    a = ei
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    }
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    eptr += 1
    if(eptr < ne) {
      ei = e[eptr]
    }
  }
  while(fptr < nf) {
    a = fi
    b = q0
    x = a + b
    bv = x - a
    y = b - bv
    if(y) {
      g[count++] = y
    } 
    _x = q1 + x
    _bv = _x - q1
    _av = _x - _bv
    _br = x - _bv
    _ar = q1 - _av
    q0 = _ar + _br
    q1 = _x
    fptr += 1
    if(fptr < nf) {
      fi = -f[fptr]
    }
  }
  if(q0) {
    g[count++] = q0
  }
  if(q1) {
    g[count++] = q1
  }
  if(!count) {
    g[count++] = 0.0  
  }
  g.length = count
  return g
}

/***/ }),
/* 630 */
/***/ (function(module, exports, __nested_webpack_require_3197775__) {

"use strict";


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

var _selectedItemsToSize = __nested_webpack_require_3197775__(139);

var _selectedItemsToSize2 = _interopRequireDefault(_selectedItemsToSize);

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

function cumsum(values) {
  var sum = 0;
  var result = [];
  values.forEach(function (v) {
    sum += +v || 0;
    result.push(sum);
  });
  return Float64Array.from(result);
}

/**
 * Compute the cumulative normalized weights associated with a
 * potentially 2d array of selected item indices.
 * @param {array} selectedItems The 1d or 2d array of items or groups of items.
 * @param {boolean} withRelativeSize Does a group of indices count as 1 unit size
 * or is its size relative to the group size?
 * @returns {number[]} The array of cumulative weights, one for each item.
 * Sums to 1 before the cumulative sum step (i.e. the final array element will be 1).
 */
var selectedItemsToCumWeights = function selectedItemsToCumWeights(selectedItems, withRelativeSize) {
  var totalLength = (0, _selectedItemsToSize2['default'])(selectedItems, withRelativeSize);
  return cumsum(selectedItems.map(function (d) {
    return (Array.isArray(d) && withRelativeSize ? d.length : 1) / totalLength;
  }));
};

exports['default'] = selectedItemsToCumWeights;

/***/ }),
/* 631 */
/***/ (function(module, exports, __nested_webpack_require_3199214__) {

"use strict";


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

var _classCallCheck2 = __nested_webpack_require_3199214__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3199214__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _configs = __nested_webpack_require_3199214__(11);

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

var LeftTrackModifier = function () {
  function LeftTrackModifier(originalTrack) {
    (0, _classCallCheck3['default'])(this, LeftTrackModifier);

    this.scene = originalTrack.scene;

    this.originalTrack = originalTrack;
    this.pBase = new _configs.GLOBALS.PIXI.Graphics();

    this.scene.removeChild(originalTrack.pBase);
    this.scene.addChild(this.pBase);

    this.moveToOrigin = new _configs.GLOBALS.PIXI.Graphics();
    this.moveToOrigin.addChild(originalTrack.pBase);

    this.pBase.addChild(this.moveToOrigin);

    this.moveToOrigin.rotation = Math.PI / 2;

    // Indicate that the track has been flipped. This is generally the same as
    // `originalTrack.flipText` but `flipText` is semantically not that clear
    originalTrack.isLeftModified = true;

    // If the original track has text labels, we need to flip
    // them horizontally, otherwise they'll be mirrored.
    originalTrack.flipText = true;
    this.svgOutput = null;

    if (originalTrack.gBase && originalTrack.gMain) {
      this.originalTrack.gBase.attr('transform', 'translate(' + String(this.moveToOrigin.position.x) + ',' + String(this.moveToOrigin.position.y) + ')\n                             rotate(90)\n                             scale(' + String(this.moveToOrigin.scale.x) + ',' + String(this.moveToOrigin.scale.y) + ')');
      this.originalTrack.gMain.attr('transform', 'translate(' + String(this.originalTrack.pBase.position.x) + ',' + String(this.originalTrack.pBase.position.y) + ')');
    }
  }

  (0, _createClass3['default'])(LeftTrackModifier, [{
    key: 'remove',
    value: function () {
      function remove() {
        this.originalTrack.remove();

        this.pBase.clear();
        this.scene.removeChild(this.pBase);
      }

      return remove;
    }()
  }, {
    key: 'setDimensions',
    value: function () {
      function setDimensions(newDimensions) {
        this.dimensions = newDimensions;

        var reversedDimensions = [newDimensions[1], newDimensions[0]];

        this.originalTrack.setDimensions(reversedDimensions);
      }

      return setDimensions;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        this.position = newPosition;

        this.originalTrack.setPosition(newPosition);

        this.originalTrack.pBase.position.x = -this.originalTrack.position[0];
        this.originalTrack.pBase.position.y = -this.originalTrack.position[1];

        this.moveToOrigin.scale.y = -1;
        this.moveToOrigin.scale.x = 1;
        this.moveToOrigin.position.x = this.originalTrack.position[0];
        this.moveToOrigin.position.y = this.originalTrack.position[1];

        if (this.originalTrack.gMain) {
          this.originalTrack.gBase.attr('transform', 'translate(' + String(this.moveToOrigin.position.x) + ',' + String(this.moveToOrigin.position.y) + ')\n                                 rotate(90)\n                                 scale(' + String(this.moveToOrigin.scale.x) + ',' + String(this.moveToOrigin.scale.y) + ')');
          this.originalTrack.gMain.attr('transform', 'translate(' + String(this.originalTrack.pBase.position.x) + ',' + String(this.originalTrack.pBase.position.y) + ')');
        }
      }

      return setPosition;
    }()
  }, {
    key: 'refXScale',
    value: function () {
      function refXScale(_) {
        /**
         * Either get or set the reference xScale
         */
        if (!arguments.length) {
          return this.originalTrack._refYScale;
        }

        this.originalTrack._refXScale = _;

        return this;
      }

      return refXScale;
    }()
  }, {
    key: 'refYScale',
    value: function () {
      function refYScale(_) {
        /**
         * Either get or set the reference yScale
         */
        if (!arguments.length) {
          return this.originalTrack._refXScale;
        }

        this.originalTrack._refYScale = _;

        return this;
      }

      return refYScale;
    }()
  }, {
    key: 'xScale',
    value: function () {
      function xScale(_) {
        /**
         * Either get or set the xScale
         */
        if (!arguments.length) {
          return this.originalTrack._xScale;
        }

        this.originalTrack._yScale = _;

        return this;
      }

      return xScale;
    }()
  }, {
    key: 'yScale',
    value: function () {
      function yScale(_) {
        /**
         * Either get or set the yScale
         */
        if (!arguments.length) {
          return this.originalTrack._yScale;
        }

        this.originalTrack._xScale = _;

        return this;
      }

      return yScale;
    }()
  }, {
    key: 'getMouseOverHtml',
    value: function () {
      function getMouseOverHtml(trackX, trackY) {
        return this.originalTrack.getMouseOverHtml(trackY, trackX);
      }

      return getMouseOverHtml;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        this.originalTrack.draw();
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        var k = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
        var tx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
        var ty = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
        var xPositionOffset = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
        var yPositionOffset = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;

        this.xScale(newXScale);
        this.yScale(newYScale);

        if (this.originalTrack.leftTrackZoomed) {
          if (this.originalTrack.refreshTiles) {
            // some tracks don't have refreshTiles (e.g. PixiTrack)
            this.originalTrack.refreshTiles();
          }
          // the track implements its own left-oriented zooming and scrolling
          this.originalTrack.leftTrackZoomed(newXScale, newYScale, k, tx, ty);
          this.originalTrack.draw();
          return;
        }

        var offset = this.originalTrack._xScale(0) - k * this.originalTrack._refXScale(0);
        this.originalTrack.pMobile.position.x = offset + this.originalTrack.position[0];
        this.originalTrack.pMobile.position.y = this.originalTrack.position[1] + this.originalTrack.dimensions[1];

        this.originalTrack.pMobile.scale.x = k;
        this.originalTrack.pMobile.scale.y = k;

        if (this.originalTrack.options.oneDHeatmapFlipped) {
          this.originalTrack.pMobile.scale.y = -k;
          this.originalTrack.pMobile.position.y = this.originalTrack.position[1];
        }

        if (this.originalTrack.leftTrackDraw) {
          // if the track implements leftTrackDraw we just redraw the track and
          // won't call the track's zoomed method
          if (this.originalTrack.refreshTiles) {
            this.originalTrack.refreshTiles();
          }
          this.originalTrack.leftTrackDraw();
          return;
        }

        this.originalTrack.zoomed(this.xScale(), this.yScale());
      }

      return zoomed;
    }()
  }, {
    key: 'zoomedY',
    value: function () {
      function zoomedY(yPos, kMultiplier) {
        this.originalTrack.zoomedY(yPos, kMultiplier);
      }

      return zoomedY;
    }()
  }, {
    key: 'movedY',
    value: function () {
      function movedY(dY) {
        this.originalTrack.movedY(dY);
      }

      return movedY;
    }()
  }, {
    key: 'refScalesChanged',
    value: function () {
      function refScalesChanged(refXScale, refYScale) {
        this.originalTrack.refScalesChanged(refYScale, refXScale);
      }

      return refScalesChanged;
    }()
  }, {
    key: 'rerender',
    value: function () {
      function rerender(options) {
        this.originalTrack.rerender(options);
      }

      return rerender;
    }()
  }, {
    key: 'exportSVG',
    value: function () {
      function exportSVG() {
        var output = document.createElement('g');
        output.setAttribute('transform', 'translate(' + String(this.moveToOrigin.position.x) + ',' + String(this.moveToOrigin.position.y) + ')\n                             rotate(90)\n                             scale(' + String(this.moveToOrigin.scale.x) + ',' + String(this.moveToOrigin.scale.y) + ')');

        if (this.originalTrack.exportSVG) {
          var g = document.createElement('g');
          g.setAttribute('transform', 'translate(' + String(this.originalTrack.pBase.position.x) + ', ' + String(this.originalTrack.pBase.position.y) + ')');

          g.appendChild(this.originalTrack.exportSVG()[0]);
          output.appendChild(g);
        }

        return [output, output];
      }

      return exportSVG;
    }()
  }, {
    key: 'respondsToPosition',
    value: function () {
      function respondsToPosition(x, y) {
        return x >= this.position[0] && x <= this.dimensions[0] + this.position[0] && y >= this.position[1] && y <= this.dimensions[1] + this.position[1];
      }

      return respondsToPosition;
    }()
  }]);
  return LeftTrackModifier;
}(); // Configs


exports['default'] = LeftTrackModifier;

/***/ }),
/* 632 */
/***/ (function(module, exports, __nested_webpack_require_3208911__) {

module.exports = { "default": __nested_webpack_require_3208911__(633), __esModule: true };

/***/ }),
/* 633 */
/***/ (function(module, exports, __nested_webpack_require_3209065__) {

__nested_webpack_require_3209065__(634);
module.exports = __nested_webpack_require_3209065__(12).Number.isInteger;


/***/ }),
/* 634 */
/***/ (function(module, exports, __nested_webpack_require_3209229__) {

// 20.1.2.3 Number.isInteger(number)
var $export = __nested_webpack_require_3209229__(16);

$export($export.S, 'Number', { isInteger: __nested_webpack_require_3209229__(178) });


/***/ }),
/* 635 */
/***/ (function(module, exports, __nested_webpack_require_3209456__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3209456__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3209456__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3209456__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3209456__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3209456__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _PixiTrack2 = __nested_webpack_require_3209456__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

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

var UnknownPixiTrack = function (_PixiTrack) {
  (0, _inherits3['default'])(UnknownPixiTrack, _PixiTrack);

  function UnknownPixiTrack(context, options) {
    (0, _classCallCheck3['default'])(this, UnknownPixiTrack);

    // so that the tests checking for retrieved tilesetInfo pass
    var _this = (0, _possibleConstructorReturn3['default'])(this, (UnknownPixiTrack.__proto__ || (0, _getPrototypeOf2['default'])(UnknownPixiTrack)).call(this, context, options));

    _this.tilesetInfo = {};

    _this.errorTextText = 'Unknown track type: ' + String(options.type);
    return _this;
  }

  (0, _createClass3['default'])(UnknownPixiTrack, [{
    key: 'zoomed',
    value: function () {
      function zoomed() {
        this.draw();
      }

      return zoomed;
    }()
  }]);
  return UnknownPixiTrack;
}(_PixiTrack3['default']);

exports['default'] = UnknownPixiTrack;

/***/ }),
/* 636 */
/***/ (function(module, exports, __nested_webpack_require_3211262__) {

module.exports = { "default": __nested_webpack_require_3211262__(637), __esModule: true };

/***/ }),
/* 637 */
/***/ (function(module, exports, __nested_webpack_require_3211416__) {

__nested_webpack_require_3211416__(638);
module.exports = __nested_webpack_require_3211416__(168).f('hasInstance');


/***/ }),
/* 638 */
/***/ (function(module, exports, __nested_webpack_require_3211581__) {

"use strict";

var isObject = __nested_webpack_require_3211581__(33);
var getPrototypeOf = __nested_webpack_require_3211581__(128);
var HAS_INSTANCE = __nested_webpack_require_3211581__(21)('hasInstance');
var FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if (!(HAS_INSTANCE in FunctionProto)) __nested_webpack_require_3211581__(32).f(FunctionProto, HAS_INSTANCE, { value: function (O) {
  if (typeof this != 'function' || !isObject(O)) return false;
  if (!isObject(this.prototype)) return O instanceof this;
  // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
  while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
  return false;
} });


/***/ }),
/* 639 */
/***/ (function(module, exports, __nested_webpack_require_3212331__) {

module.exports = { "default": __nested_webpack_require_3212331__(640), __esModule: true };

/***/ }),
/* 640 */
/***/ (function(module, exports, __nested_webpack_require_3212485__) {

__nested_webpack_require_3212485__(164);
__nested_webpack_require_3212485__(61);
__nested_webpack_require_3212485__(76);
__nested_webpack_require_3212485__(641);
__nested_webpack_require_3212485__(642);
__nested_webpack_require_3212485__(643);
__nested_webpack_require_3212485__(644);
module.exports = __nested_webpack_require_3212485__(12).Map;


/***/ }),
/* 641 */
/***/ (function(module, exports, __nested_webpack_require_3212790__) {

"use strict";

var strong = __nested_webpack_require_3212790__(333);
var validate = __nested_webpack_require_3212790__(238);
var MAP = 'Map';

// 23.1 Map Objects
module.exports = __nested_webpack_require_3212790__(334)(MAP, function (get) {
  return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
  // 23.1.3.6 Map.prototype.get(key)
  get: function get(key) {
    var entry = strong.getEntry(validate(this, MAP), key);
    return entry && entry.v;
  },
  // 23.1.3.9 Map.prototype.set(key, value)
  set: function set(key, value) {
    return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
  }
}, strong, true);


/***/ }),
/* 642 */
/***/ (function(module, exports, __nested_webpack_require_3213496__) {

// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __nested_webpack_require_3213496__(16);

$export($export.P + $export.R, 'Map', { toJSON: __nested_webpack_require_3213496__(335)('Map') });


/***/ }),
/* 643 */
/***/ (function(module, exports, __nested_webpack_require_3213758__) {

// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of
__nested_webpack_require_3213758__(336)('Map');


/***/ }),
/* 644 */
/***/ (function(module, exports, __nested_webpack_require_3213931__) {

// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from
__nested_webpack_require_3213931__(337)('Map');


/***/ }),
/* 645 */
/***/ (function(module, exports, __nested_webpack_require_3214106__) {

"use strict";
// Top level file is just a mixin of submodules & constants


var assign    = __nested_webpack_require_3214106__(82).assign;

var deflate   = __nested_webpack_require_3214106__(646);
var inflate   = __nested_webpack_require_3214106__(649);
var constants = __nested_webpack_require_3214106__(388);

var pako = {};

assign(pako, deflate, inflate, constants);

module.exports = pako;


/***/ }),
/* 646 */
/***/ (function(module, exports, __nested_webpack_require_3214520__) {

"use strict";



var zlib_deflate = __nested_webpack_require_3214520__(647);
var utils        = __nested_webpack_require_3214520__(82);
var strings      = __nested_webpack_require_3214520__(386);
var msg          = __nested_webpack_require_3214520__(263);
var ZStream      = __nested_webpack_require_3214520__(387);

var toString = Object.prototype.toString;

/* Public constants ==========================================================*/
/* ===========================================================================*/

var Z_NO_FLUSH      = 0;
var Z_FINISH        = 4;

var Z_OK            = 0;
var Z_STREAM_END    = 1;
var Z_SYNC_FLUSH    = 2;

var Z_DEFAULT_COMPRESSION = -1;

var Z_DEFAULT_STRATEGY    = 0;

var Z_DEFLATED  = 8;

/* ===========================================================================*/


/**
 * class Deflate
 *
 * Generic JS-style wrapper for zlib calls. If you don't need
 * streaming behaviour - use more simple functions: [[deflate]],
 * [[deflateRaw]] and [[gzip]].
 **/

/* internal
 * Deflate.chunks -> Array
 *
 * Chunks of output data, if [[Deflate#onData]] not overridden.
 **/

/**
 * Deflate.result -> Uint8Array|Array
 *
 * Compressed result, generated by default [[Deflate#onData]]
 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
 * push a chunk with explicit flush (call [[Deflate#push]] with
 * `Z_SYNC_FLUSH` param).
 **/

/**
 * Deflate.err -> Number
 *
 * Error code after deflate finished. 0 (Z_OK) on success.
 * You will not need it in real life, because deflate errors
 * are possible only on wrong options or bad `onData` / `onEnd`
 * custom handlers.
 **/

/**
 * Deflate.msg -> String
 *
 * Error message, if [[Deflate.err]] != 0
 **/


/**
 * new Deflate(options)
 * - options (Object): zlib deflate options.
 *
 * Creates new deflator instance with specified params. Throws exception
 * on bad params. Supported options:
 *
 * - `level`
 * - `windowBits`
 * - `memLevel`
 * - `strategy`
 * - `dictionary`
 *
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
 * for more information on these.
 *
 * Additional options, for internal needs:
 *
 * - `chunkSize` - size of generated data chunks (16K by default)
 * - `raw` (Boolean) - do raw deflate
 * - `gzip` (Boolean) - create gzip wrapper
 * - `to` (String) - if equal to 'string', then result will be "binary string"
 *    (each char code [0..255])
 * - `header` (Object) - custom header for gzip
 *   - `text` (Boolean) - true if compressed data believed to be text
 *   - `time` (Number) - modification time, unix timestamp
 *   - `os` (Number) - operation system code
 *   - `extra` (Array) - array of bytes with extra data (max 65536)
 *   - `name` (String) - file name (binary string)
 *   - `comment` (String) - comment (binary string)
 *   - `hcrc` (Boolean) - true if header crc should be added
 *
 * ##### Example:
 *
 * ```javascript
 * var pako = require('pako')
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
 *
 * var deflate = new pako.Deflate({ level: 3});
 *
 * deflate.push(chunk1, false);
 * deflate.push(chunk2, true);  // true -> last chunk
 *
 * if (deflate.err) { throw new Error(deflate.err); }
 *
 * console.log(deflate.result);
 * ```
 **/
function Deflate(options) {
  if (!(this instanceof Deflate)) return new Deflate(options);

  this.options = utils.assign({
    level: Z_DEFAULT_COMPRESSION,
    method: Z_DEFLATED,
    chunkSize: 16384,
    windowBits: 15,
    memLevel: 8,
    strategy: Z_DEFAULT_STRATEGY,
    to: ''
  }, options || {});

  var opt = this.options;

  if (opt.raw && (opt.windowBits > 0)) {
    opt.windowBits = -opt.windowBits;
  }

  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
    opt.windowBits += 16;
  }

  this.err    = 0;      // error code, if happens (0 = Z_OK)
  this.msg    = '';     // error message
  this.ended  = false;  // used to avoid multiple onEnd() calls
  this.chunks = [];     // chunks of compressed data

  this.strm = new ZStream();
  this.strm.avail_out = 0;

  var status = zlib_deflate.deflateInit2(
    this.strm,
    opt.level,
    opt.method,
    opt.windowBits,
    opt.memLevel,
    opt.strategy
  );

  if (status !== Z_OK) {
    throw new Error(msg[status]);
  }

  if (opt.header) {
    zlib_deflate.deflateSetHeader(this.strm, opt.header);
  }

  if (opt.dictionary) {
    var dict;
    // Convert data if needed
    if (typeof opt.dictionary === 'string') {
      // If we need to compress text, change encoding to utf8.
      dict = strings.string2buf(opt.dictionary);
    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
      dict = new Uint8Array(opt.dictionary);
    } else {
      dict = opt.dictionary;
    }

    status = zlib_deflate.deflateSetDictionary(this.strm, dict);

    if (status !== Z_OK) {
      throw new Error(msg[status]);
    }

    this._dict_set = true;
  }
}

/**
 * Deflate#push(data[, mode]) -> Boolean
 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
 *   converted to utf8 byte sequence.
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
 *
 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
 * new compressed chunks. Returns `true` on success. The last data block must have
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
 * can use mode Z_SYNC_FLUSH, keeping the compression context.
 *
 * On fail call [[Deflate#onEnd]] with error code and return false.
 *
 * We strongly recommend to use `Uint8Array` on input for best speed (output
 * array format is detected automatically). Also, don't skip last param and always
 * use the same type in your code (boolean or number). That will improve JS speed.
 *
 * For regular `Array`-s make sure all elements are [0..255].
 *
 * ##### Example
 *
 * ```javascript
 * push(chunk, false); // push one of data chunks
 * ...
 * push(chunk, true);  // push last chunk
 * ```
 **/
Deflate.prototype.push = function (data, mode) {
  var strm = this.strm;
  var chunkSize = this.options.chunkSize;
  var status, _mode;

  if (this.ended) { return false; }

  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);

  // Convert data if needed
  if (typeof data === 'string') {
    // If we need to compress text, change encoding to utf8.
    strm.input = strings.string2buf(data);
  } else if (toString.call(data) === '[object ArrayBuffer]') {
    strm.input = new Uint8Array(data);
  } else {
    strm.input = data;
  }

  strm.next_in = 0;
  strm.avail_in = strm.input.length;

  do {
    if (strm.avail_out === 0) {
      strm.output = new utils.Buf8(chunkSize);
      strm.next_out = 0;
      strm.avail_out = chunkSize;
    }
    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */

    if (status !== Z_STREAM_END && status !== Z_OK) {
      this.onEnd(status);
      this.ended = true;
      return false;
    }
    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
      if (this.options.to === 'string') {
        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
      } else {
        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
      }
    }
  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);

  // Finalize on the last chunk.
  if (_mode === Z_FINISH) {
    status = zlib_deflate.deflateEnd(this.strm);
    this.onEnd(status);
    this.ended = true;
    return status === Z_OK;
  }

  // callback interim results if Z_SYNC_FLUSH.
  if (_mode === Z_SYNC_FLUSH) {
    this.onEnd(Z_OK);
    strm.avail_out = 0;
    return true;
  }

  return true;
};


/**
 * Deflate#onData(chunk) -> Void
 * - chunk (Uint8Array|Array|String): output data. Type of array depends
 *   on js engine support. When string output requested, each chunk
 *   will be string.
 *
 * By default, stores data blocks in `chunks[]` property and glue
 * those in `onEnd`. Override this handler, if you need another behaviour.
 **/
Deflate.prototype.onData = function (chunk) {
  this.chunks.push(chunk);
};


/**
 * Deflate#onEnd(status) -> Void
 * - status (Number): deflate status. 0 (Z_OK) on success,
 *   other if not.
 *
 * Called once after you tell deflate that the input stream is
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
 * or if an error happened. By default - join collected chunks,
 * free memory and fill `results` / `err` properties.
 **/
Deflate.prototype.onEnd = function (status) {
  // On success - join
  if (status === Z_OK) {
    if (this.options.to === 'string') {
      this.result = this.chunks.join('');
    } else {
      this.result = utils.flattenChunks(this.chunks);
    }
  }
  this.chunks = [];
  this.err = status;
  this.msg = this.strm.msg;
};


/**
 * deflate(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to compress.
 * - options (Object): zlib deflate options.
 *
 * Compress `data` with deflate algorithm and `options`.
 *
 * Supported options are:
 *
 * - level
 * - windowBits
 * - memLevel
 * - strategy
 * - dictionary
 *
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
 * for more information on these.
 *
 * Sugar (options):
 *
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
 *   negative windowBits implicitly.
 * - `to` (String) - if equal to 'string', then result will be "binary string"
 *    (each char code [0..255])
 *
 * ##### Example:
 *
 * ```javascript
 * var pako = require('pako')
 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
 *
 * console.log(pako.deflate(data));
 * ```
 **/
function deflate(input, options) {
  var deflator = new Deflate(options);

  deflator.push(input, true);

  // That will never happens, if you don't cheat with options :)
  if (deflator.err) { throw deflator.msg || msg[deflator.err]; }

  return deflator.result;
}


/**
 * deflateRaw(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to compress.
 * - options (Object): zlib deflate options.
 *
 * The same as [[deflate]], but creates raw data, without wrapper
 * (header and adler32 crc).
 **/
function deflateRaw(input, options) {
  options = options || {};
  options.raw = true;
  return deflate(input, options);
}


/**
 * gzip(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to compress.
 * - options (Object): zlib deflate options.
 *
 * The same as [[deflate]], but create gzip wrapper instead of
 * deflate one.
 **/
function gzip(input, options) {
  options = options || {};
  options.gzip = true;
  return deflate(input, options);
}


exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;


/***/ }),
/* 647 */
/***/ (function(module, exports, __nested_webpack_require_3225666__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

var utils   = __nested_webpack_require_3225666__(82);
var trees   = __nested_webpack_require_3225666__(648);
var adler32 = __nested_webpack_require_3225666__(384);
var crc32   = __nested_webpack_require_3225666__(385);
var msg     = __nested_webpack_require_3225666__(263);

/* Public constants ==========================================================*/
/* ===========================================================================*/


/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH      = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH    = 2;
var Z_FULL_FLUSH    = 3;
var Z_FINISH        = 4;
var Z_BLOCK         = 5;
//var Z_TREES         = 6;


/* Return codes for the compression/decompression functions. Negative values
 * are errors, positive values are used for special but normal events.
 */
var Z_OK            = 0;
var Z_STREAM_END    = 1;
//var Z_NEED_DICT     = 2;
//var Z_ERRNO         = -1;
var Z_STREAM_ERROR  = -2;
var Z_DATA_ERROR    = -3;
//var Z_MEM_ERROR     = -4;
var Z_BUF_ERROR     = -5;
//var Z_VERSION_ERROR = -6;


/* compression levels */
//var Z_NO_COMPRESSION      = 0;
//var Z_BEST_SPEED          = 1;
//var Z_BEST_COMPRESSION    = 9;
var Z_DEFAULT_COMPRESSION = -1;


var Z_FILTERED            = 1;
var Z_HUFFMAN_ONLY        = 2;
var Z_RLE                 = 3;
var Z_FIXED               = 4;
var Z_DEFAULT_STRATEGY    = 0;

/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY              = 0;
//var Z_TEXT                = 1;
//var Z_ASCII               = 1; // = Z_TEXT
var Z_UNKNOWN             = 2;


/* The deflate compression method */
var Z_DEFLATED  = 8;

/*============================================================================*/


var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;


var LENGTH_CODES  = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS      = 256;
/* number of literal bytes 0..255 */
var L_CODES       = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES       = 30;
/* number of distance codes */
var BL_CODES      = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE     = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS  = 15;
/* All codes must not exceed MAX_BITS bits */

var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);

var PRESET_DICT = 0x20;

var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;

var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE     = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */

var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.

function err(strm, errorCode) {
  strm.msg = msg[errorCode];
  return errorCode;
}

function rank(f) {
  return ((f) << 1) - ((f) > 4 ? 9 : 0);
}

function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }


/* =========================================================================
 * Flush as much pending output as possible. All deflate() output goes
 * through this function so some applications may wish to modify it
 * to avoid allocating a large strm->output buffer and copying into it.
 * (See also read_buf()).
 */
function flush_pending(strm) {
  var s = strm.state;

  //_tr_flush_bits(s);
  var len = s.pending;
  if (len > strm.avail_out) {
    len = strm.avail_out;
  }
  if (len === 0) { return; }

  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  strm.next_out += len;
  s.pending_out += len;
  strm.total_out += len;
  strm.avail_out -= len;
  s.pending -= len;
  if (s.pending === 0) {
    s.pending_out = 0;
  }
}


function flush_block_only(s, last) {
  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  s.block_start = s.strstart;
  flush_pending(s.strm);
}


function put_byte(s, b) {
  s.pending_buf[s.pending++] = b;
}


/* =========================================================================
 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
 * IN assertion: the stream state is correct and there is enough room in
 * pending_buf.
 */
function putShortMSB(s, b) {
//  put_byte(s, (Byte)(b >> 8));
//  put_byte(s, (Byte)(b & 0xff));
  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  s.pending_buf[s.pending++] = b & 0xff;
}


/* ===========================================================================
 * Read a new buffer from the current input stream, update the adler32
 * and total number of bytes read.  All deflate() input goes through
 * this function so some applications may wish to modify it to avoid
 * allocating a large strm->input buffer and copying from it.
 * (See also flush_pending()).
 */
function read_buf(strm, buf, start, size) {
  var len = strm.avail_in;

  if (len > size) { len = size; }
  if (len === 0) { return 0; }

  strm.avail_in -= len;

  // zmemcpy(buf, strm->next_in, len);
  utils.arraySet(buf, strm.input, strm.next_in, len, start);
  if (strm.state.wrap === 1) {
    strm.adler = adler32(strm.adler, buf, len, start);
  }

  else if (strm.state.wrap === 2) {
    strm.adler = crc32(strm.adler, buf, len, start);
  }

  strm.next_in += len;
  strm.total_in += len;

  return len;
}


/* ===========================================================================
 * Set match_start to the longest match starting at the given string and
 * return its length. Matches shorter or equal to prev_length are discarded,
 * in which case the result is equal to prev_length and match_start is
 * garbage.
 * IN assertions: cur_match is the head of the hash chain for the current
 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
 * OUT assertion: the match length is not greater than s->lookahead.
 */
function longest_match(s, cur_match) {
  var chain_length = s.max_chain_length;      /* max hash chain length */
  var scan = s.strstart; /* current string */
  var match;                       /* matched string */
  var len;                           /* length of current match */
  var best_len = s.prev_length;              /* best match length so far */
  var nice_match = s.nice_match;             /* stop if match long enough */
  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;

  var _win = s.window; // shortcut

  var wmask = s.w_mask;
  var prev  = s.prev;

  /* Stop when cur_match becomes <= limit. To simplify the code,
   * we prevent matches with the string of window index 0.
   */

  var strend = s.strstart + MAX_MATCH;
  var scan_end1  = _win[scan + best_len - 1];
  var scan_end   = _win[scan + best_len];

  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
   * It is easy to get rid of this optimization if necessary.
   */
  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");

  /* Do not waste too much time if we already have a good match: */
  if (s.prev_length >= s.good_match) {
    chain_length >>= 2;
  }
  /* Do not look for matches beyond the end of the input. This is necessary
   * to make deflate deterministic.
   */
  if (nice_match > s.lookahead) { nice_match = s.lookahead; }

  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");

  do {
    // Assert(cur_match < s->strstart, "no future");
    match = cur_match;

    /* Skip to next match if the match length cannot increase
     * or if the match length is less than 2.  Note that the checks below
     * for insufficient lookahead only occur occasionally for performance
     * reasons.  Therefore uninitialized memory will be accessed, and
     * conditional jumps will be made that depend on those values.
     * However the length of the match is limited to the lookahead, so
     * the output of deflate is not affected by the uninitialized values.
     */

    if (_win[match + best_len]     !== scan_end  ||
        _win[match + best_len - 1] !== scan_end1 ||
        _win[match]                !== _win[scan] ||
        _win[++match]              !== _win[scan + 1]) {
      continue;
    }

    /* The check at best_len-1 can be removed because it will be made
     * again later. (This heuristic is not always a win.)
     * It is not necessary to compare scan[2] and match[2] since they
     * are always equal when the other bytes match, given that
     * the hash keys are equal and that HASH_BITS >= 8.
     */
    scan += 2;
    match++;
    // Assert(*scan == *match, "match[2]?");

    /* We check for insufficient lookahead only every 8th comparison;
     * the 256th check will be made at strstart+258.
     */
    do {
      /*jshint noempty:false*/
    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
             scan < strend);

    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");

    len = MAX_MATCH - (strend - scan);
    scan = strend - MAX_MATCH;

    if (len > best_len) {
      s.match_start = cur_match;
      best_len = len;
      if (len >= nice_match) {
        break;
      }
      scan_end1  = _win[scan + best_len - 1];
      scan_end   = _win[scan + best_len];
    }
  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);

  if (best_len <= s.lookahead) {
    return best_len;
  }
  return s.lookahead;
}


/* ===========================================================================
 * Fill the window when the lookahead becomes insufficient.
 * Updates strstart and lookahead.
 *
 * IN assertion: lookahead < MIN_LOOKAHEAD
 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
 *    At least one byte has been read, or avail_in == 0; reads are
 *    performed for at least two bytes (required for the zip translate_eol
 *    option -- not supported here).
 */
function fill_window(s) {
  var _w_size = s.w_size;
  var p, n, m, more, str;

  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");

  do {
    more = s.window_size - s.lookahead - s.strstart;

    // JS ints have 32 bit, block below not needed
    /* Deal with !@#$% 64K limit: */
    //if (sizeof(int) <= 2) {
    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
    //        more = wsize;
    //
    //  } else if (more == (unsigned)(-1)) {
    //        /* Very unlikely, but possible on 16 bit machine if
    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
    //         */
    //        more--;
    //    }
    //}


    /* If the window is almost full and there is insufficient lookahead,
     * move the upper half to the lower one to make room in the upper half.
     */
    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {

      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
      s.match_start -= _w_size;
      s.strstart -= _w_size;
      /* we now have strstart >= MAX_DIST */
      s.block_start -= _w_size;

      /* Slide the hash table (could be avoided with 32 bit values
       at the expense of memory usage). We slide even when level == 0
       to keep the hash table consistent if we switch back to level > 0
       later. (Using level 0 permanently is not an optimal usage of
       zlib, so we don't care about this pathological case.)
       */

      n = s.hash_size;
      p = n;
      do {
        m = s.head[--p];
        s.head[p] = (m >= _w_size ? m - _w_size : 0);
      } while (--n);

      n = _w_size;
      p = n;
      do {
        m = s.prev[--p];
        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
        /* If n is not on any hash chain, prev[n] is garbage but
         * its value will never be used.
         */
      } while (--n);

      more += _w_size;
    }
    if (s.strm.avail_in === 0) {
      break;
    }

    /* If there was no sliding:
     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
     *    more == window_size - lookahead - strstart
     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
     * => more >= window_size - 2*WSIZE + 2
     * In the BIG_MEM or MMAP case (not yet supported),
     *   window_size == input_size + MIN_LOOKAHEAD  &&
     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
     * Otherwise, window_size == 2*WSIZE so more >= 2.
     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
     */
    //Assert(more >= 2, "more < 2");
    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
    s.lookahead += n;

    /* Initialize the hash value now that we have some input: */
    if (s.lookahead + s.insert >= MIN_MATCH) {
      str = s.strstart - s.insert;
      s.ins_h = s.window[str];

      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
//        Call update_hash() MIN_MATCH-3 more times
//#endif
      while (s.insert) {
        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;

        s.prev[str & s.w_mask] = s.head[s.ins_h];
        s.head[s.ins_h] = str;
        str++;
        s.insert--;
        if (s.lookahead + s.insert < MIN_MATCH) {
          break;
        }
      }
    }
    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
     * but this is not important since only literal bytes will be emitted.
     */

  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);

  /* If the WIN_INIT bytes after the end of the current data have never been
   * written, then zero those bytes in order to avoid memory check reports of
   * the use of uninitialized (or uninitialised as Julian writes) bytes by
   * the longest match routines.  Update the high water mark for the next
   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
   */
//  if (s.high_water < s.window_size) {
//    var curr = s.strstart + s.lookahead;
//    var init = 0;
//
//    if (s.high_water < curr) {
//      /* Previous high water mark below current data -- zero WIN_INIT
//       * bytes or up to end of window, whichever is less.
//       */
//      init = s.window_size - curr;
//      if (init > WIN_INIT)
//        init = WIN_INIT;
//      zmemzero(s->window + curr, (unsigned)init);
//      s->high_water = curr + init;
//    }
//    else if (s->high_water < (ulg)curr + WIN_INIT) {
//      /* High water mark at or above current data, but below current data
//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
//       * to end of window, whichever is less.
//       */
//      init = (ulg)curr + WIN_INIT - s->high_water;
//      if (init > s->window_size - s->high_water)
//        init = s->window_size - s->high_water;
//      zmemzero(s->window + s->high_water, (unsigned)init);
//      s->high_water += init;
//    }
//  }
//
//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
//    "not enough room for search");
}

/* ===========================================================================
 * Copy without compression as much as possible from the input stream, return
 * the current block state.
 * This function does not insert new strings in the dictionary since
 * uncompressible data is probably not useful. This function is used
 * only for the level=0 compression option.
 * NOTE: this function should be optimized to avoid extra copying from
 * window to pending_buf.
 */
function deflate_stored(s, flush) {
  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
   * to pending_buf_size, and each stored block has a 5 byte header:
   */
  var max_block_size = 0xffff;

  if (max_block_size > s.pending_buf_size - 5) {
    max_block_size = s.pending_buf_size - 5;
  }

  /* Copy as much as possible from input to output: */
  for (;;) {
    /* Fill the window as much as possible: */
    if (s.lookahead <= 1) {

      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
      //  s->block_start >= (long)s->w_size, "slide too late");
//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
//        s.block_start >= s.w_size)) {
//        throw  new Error("slide too late");
//      }

      fill_window(s);
      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }

      if (s.lookahead === 0) {
        break;
      }
      /* flush the current block */
    }
    //Assert(s->block_start >= 0L, "block gone");
//    if (s.block_start < 0) throw new Error("block gone");

    s.strstart += s.lookahead;
    s.lookahead = 0;

    /* Emit a stored block if pending_buf will be full: */
    var max_start = s.block_start + max_block_size;

    if (s.strstart === 0 || s.strstart >= max_start) {
      /* strstart == 0 is possible when wraparound on 16-bit machine */
      s.lookahead = s.strstart - max_start;
      s.strstart = max_start;
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/


    }
    /* Flush if we may have to slide, otherwise block_start may become
     * negative and the data will be gone:
     */
    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }

  s.insert = 0;

  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }

  if (s.strstart > s.block_start) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }

  return BS_NEED_MORE;
}

/* ===========================================================================
 * Compress as much as possible from the input stream, return the current
 * block state.
 * This function does not perform lazy evaluation of matches and inserts
 * new strings in the dictionary only for unmatched strings or for short
 * matches. It is used only for the fast compression options.
 */
function deflate_fast(s, flush) {
  var hash_head;        /* head of the hash chain */
  var bflush;           /* set if current block must be flushed */

  for (;;) {
    /* Make sure that we always have enough lookahead, except
     * at the end of the input file. We need MAX_MATCH bytes
     * for the next match, plus MIN_MATCH bytes to insert the
     * string following the next match.
     */
    if (s.lookahead < MIN_LOOKAHEAD) {
      fill_window(s);
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s.lookahead === 0) {
        break; /* flush the current block */
      }
    }

    /* Insert the string window[strstart .. strstart+2] in the
     * dictionary, and set hash_head to the head of the hash chain:
     */
    hash_head = 0/*NIL*/;
    if (s.lookahead >= MIN_MATCH) {
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
      s.head[s.ins_h] = s.strstart;
      /***/
    }

    /* Find the longest match, discarding those <= prev_length.
     * At this point we have always match_length < MIN_MATCH
     */
    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
      /* To simplify the code, we prevent matches with the string
       * of window index 0 (in particular we have to avoid a match
       * of the string with itself at the start of the input file).
       */
      s.match_length = longest_match(s, hash_head);
      /* longest_match() sets match_start */
    }
    if (s.match_length >= MIN_MATCH) {
      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only

      /*** _tr_tally_dist(s, s.strstart - s.match_start,
                     s.match_length - MIN_MATCH, bflush); ***/
      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);

      s.lookahead -= s.match_length;

      /* Insert new strings in the hash table only if the match length
       * is not too large. This saves time but degrades compression.
       */
      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
        s.match_length--; /* string at strstart already in table */
        do {
          s.strstart++;
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = s.strstart;
          /***/
          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
           * always MIN_MATCH bytes ahead.
           */
        } while (--s.match_length !== 0);
        s.strstart++;
      } else
      {
        s.strstart += s.match_length;
        s.match_length = 0;
        s.ins_h = s.window[s.strstart];
        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;

//#if MIN_MATCH != 3
//                Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
         * matter since it will be recomputed at next deflate call.
         */
      }
    } else {
      /* No match, output a literal byte */
      //Tracevv((stderr,"%c", s.window[s.strstart]));
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);

      s.lookahead--;
      s.strstart++;
    }
    if (bflush) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }
  s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }
  return BS_BLOCK_DONE;
}

/* ===========================================================================
 * Same as above, but achieves better compression. We use a lazy
 * evaluation for matches: a match is finally adopted only if there is
 * no better match at the next window position.
 */
function deflate_slow(s, flush) {
  var hash_head;          /* head of hash chain */
  var bflush;              /* set if current block must be flushed */

  var max_insert;

  /* Process the input block. */
  for (;;) {
    /* Make sure that we always have enough lookahead, except
     * at the end of the input file. We need MAX_MATCH bytes
     * for the next match, plus MIN_MATCH bytes to insert the
     * string following the next match.
     */
    if (s.lookahead < MIN_LOOKAHEAD) {
      fill_window(s);
      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s.lookahead === 0) { break; } /* flush the current block */
    }

    /* Insert the string window[strstart .. strstart+2] in the
     * dictionary, and set hash_head to the head of the hash chain:
     */
    hash_head = 0/*NIL*/;
    if (s.lookahead >= MIN_MATCH) {
      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
      s.head[s.ins_h] = s.strstart;
      /***/
    }

    /* Find the longest match, discarding those <= prev_length.
     */
    s.prev_length = s.match_length;
    s.prev_match = s.match_start;
    s.match_length = MIN_MATCH - 1;

    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
        s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
      /* To simplify the code, we prevent matches with the string
       * of window index 0 (in particular we have to avoid a match
       * of the string with itself at the start of the input file).
       */
      s.match_length = longest_match(s, hash_head);
      /* longest_match() sets match_start */

      if (s.match_length <= 5 &&
         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {

        /* If prev_match is also MIN_MATCH, match_start is garbage
         * but we will ignore the current match anyway.
         */
        s.match_length = MIN_MATCH - 1;
      }
    }
    /* If there was a match at the previous step and the current
     * match is not better, output the previous match:
     */
    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
      max_insert = s.strstart + s.lookahead - MIN_MATCH;
      /* Do not insert strings in hash table beyond this. */

      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);

      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
                     s.prev_length - MIN_MATCH, bflush);***/
      bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
      /* Insert in hash table all strings up to the end of the match.
       * strstart-1 and strstart are already inserted. If there is not
       * enough lookahead, the last two strings are not inserted in
       * the hash table.
       */
      s.lookahead -= s.prev_length - 1;
      s.prev_length -= 2;
      do {
        if (++s.strstart <= max_insert) {
          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
          s.head[s.ins_h] = s.strstart;
          /***/
        }
      } while (--s.prev_length !== 0);
      s.match_available = 0;
      s.match_length = MIN_MATCH - 1;
      s.strstart++;

      if (bflush) {
        /*** FLUSH_BLOCK(s, 0); ***/
        flush_block_only(s, false);
        if (s.strm.avail_out === 0) {
          return BS_NEED_MORE;
        }
        /***/
      }

    } else if (s.match_available) {
      /* If there was no match at the previous position, output a
       * single literal. If there was a match but the current match
       * is longer, truncate the previous match to a single literal.
       */
      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);

      if (bflush) {
        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
        flush_block_only(s, false);
        /***/
      }
      s.strstart++;
      s.lookahead--;
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
    } else {
      /* There is no previous match to compare with, wait for
       * the next step to decide.
       */
      s.match_available = 1;
      s.strstart++;
      s.lookahead--;
    }
  }
  //Assert (flush != Z_NO_FLUSH, "no flush?");
  if (s.match_available) {
    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
    bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);

    s.match_available = 0;
  }
  s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }

  return BS_BLOCK_DONE;
}


/* ===========================================================================
 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
 * deflate switches away from Z_RLE.)
 */
function deflate_rle(s, flush) {
  var bflush;            /* set if current block must be flushed */
  var prev;              /* byte at distance one to match */
  var scan, strend;      /* scan goes up to strend for length of run */

  var _win = s.window;

  for (;;) {
    /* Make sure that we always have enough lookahead, except
     * at the end of the input file. We need MAX_MATCH bytes
     * for the longest run, plus one for the unrolled loop.
     */
    if (s.lookahead <= MAX_MATCH) {
      fill_window(s);
      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
        return BS_NEED_MORE;
      }
      if (s.lookahead === 0) { break; } /* flush the current block */
    }

    /* See how many times the previous byte repeats */
    s.match_length = 0;
    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
      scan = s.strstart - 1;
      prev = _win[scan];
      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
        strend = s.strstart + MAX_MATCH;
        do {
          /*jshint noempty:false*/
        } while (prev === _win[++scan] && prev === _win[++scan] &&
                 prev === _win[++scan] && prev === _win[++scan] &&
                 prev === _win[++scan] && prev === _win[++scan] &&
                 prev === _win[++scan] && prev === _win[++scan] &&
                 scan < strend);
        s.match_length = MAX_MATCH - (strend - scan);
        if (s.match_length > s.lookahead) {
          s.match_length = s.lookahead;
        }
      }
      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
    }

    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
    if (s.match_length >= MIN_MATCH) {
      //check_match(s, s.strstart, s.strstart - 1, s.match_length);

      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);

      s.lookahead -= s.match_length;
      s.strstart += s.match_length;
      s.match_length = 0;
    } else {
      /* No match, output a literal byte */
      //Tracevv((stderr,"%c", s->window[s->strstart]));
      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);

      s.lookahead--;
      s.strstart++;
    }
    if (bflush) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }
  s.insert = 0;
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }
  return BS_BLOCK_DONE;
}

/* ===========================================================================
 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
 * (It will be regenerated if this run of deflate switches away from Huffman.)
 */
function deflate_huff(s, flush) {
  var bflush;             /* set if current block must be flushed */

  for (;;) {
    /* Make sure that we have a literal to write. */
    if (s.lookahead === 0) {
      fill_window(s);
      if (s.lookahead === 0) {
        if (flush === Z_NO_FLUSH) {
          return BS_NEED_MORE;
        }
        break;      /* flush the current block */
      }
    }

    /* Output a literal byte */
    s.match_length = 0;
    //Tracevv((stderr,"%c", s->window[s->strstart]));
    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
    s.lookahead--;
    s.strstart++;
    if (bflush) {
      /*** FLUSH_BLOCK(s, 0); ***/
      flush_block_only(s, false);
      if (s.strm.avail_out === 0) {
        return BS_NEED_MORE;
      }
      /***/
    }
  }
  s.insert = 0;
  if (flush === Z_FINISH) {
    /*** FLUSH_BLOCK(s, 1); ***/
    flush_block_only(s, true);
    if (s.strm.avail_out === 0) {
      return BS_FINISH_STARTED;
    }
    /***/
    return BS_FINISH_DONE;
  }
  if (s.last_lit) {
    /*** FLUSH_BLOCK(s, 0); ***/
    flush_block_only(s, false);
    if (s.strm.avail_out === 0) {
      return BS_NEED_MORE;
    }
    /***/
  }
  return BS_BLOCK_DONE;
}

/* Values for max_lazy_match, good_match and max_chain_length, depending on
 * the desired pack level (0..9). The values given below have been tuned to
 * exclude worst case performance for pathological files. Better values may be
 * found for specific files.
 */
function Config(good_length, max_lazy, nice_length, max_chain, func) {
  this.good_length = good_length;
  this.max_lazy = max_lazy;
  this.nice_length = nice_length;
  this.max_chain = max_chain;
  this.func = func;
}

var configuration_table;

configuration_table = [
  /*      good lazy nice chain */
  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */

  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
];


/* ===========================================================================
 * Initialize the "longest match" routines for a new zlib stream
 */
function lm_init(s) {
  s.window_size = 2 * s.w_size;

  /*** CLEAR_HASH(s); ***/
  zero(s.head); // Fill with NIL (= 0);

  /* Set the default configuration parameters:
   */
  s.max_lazy_match = configuration_table[s.level].max_lazy;
  s.good_match = configuration_table[s.level].good_length;
  s.nice_match = configuration_table[s.level].nice_length;
  s.max_chain_length = configuration_table[s.level].max_chain;

  s.strstart = 0;
  s.block_start = 0;
  s.lookahead = 0;
  s.insert = 0;
  s.match_length = s.prev_length = MIN_MATCH - 1;
  s.match_available = 0;
  s.ins_h = 0;
}


function DeflateState() {
  this.strm = null;            /* pointer back to this zlib stream */
  this.status = 0;            /* as the name implies */
  this.pending_buf = null;      /* output still pending */
  this.pending_buf_size = 0;  /* size of pending_buf */
  this.pending_out = 0;       /* next pending byte to output to the stream */
  this.pending = 0;           /* nb of bytes in the pending buffer */
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  this.gzhead = null;         /* gzip header information to write */
  this.gzindex = 0;           /* where in extra, name, or comment */
  this.method = Z_DEFLATED; /* can only be DEFLATED */
  this.last_flush = -1;   /* value of flush param for previous deflate call */

  this.w_size = 0;  /* LZ77 window size (32K by default) */
  this.w_bits = 0;  /* log2(w_size)  (8..16) */
  this.w_mask = 0;  /* w_size - 1 */

  this.window = null;
  /* Sliding window. Input bytes are read into the second half of the window,
   * and move to the first half later to keep a dictionary of at least wSize
   * bytes. With this organization, matches are limited to a distance of
   * wSize-MAX_MATCH bytes, but this ensures that IO is always
   * performed with a length multiple of the block size.
   */

  this.window_size = 0;
  /* Actual size of window: 2*wSize, except when the user input buffer
   * is directly used as sliding window.
   */

  this.prev = null;
  /* Link to older string with same hash index. To limit the size of this
   * array to 64K, this link is maintained only for the last 32K strings.
   * An index in this array is thus a window index modulo 32K.
   */

  this.head = null;   /* Heads of the hash chains or NIL. */

  this.ins_h = 0;       /* hash index of string to be inserted */
  this.hash_size = 0;   /* number of elements in hash table */
  this.hash_bits = 0;   /* log2(hash_size) */
  this.hash_mask = 0;   /* hash_size-1 */

  this.hash_shift = 0;
  /* Number of bits by which ins_h must be shifted at each input
   * step. It must be such that after MIN_MATCH steps, the oldest
   * byte no longer takes part in the hash key, that is:
   *   hash_shift * MIN_MATCH >= hash_bits
   */

  this.block_start = 0;
  /* Window position at the beginning of the current output block. Gets
   * negative when the window is moved backwards.
   */

  this.match_length = 0;      /* length of best match */
  this.prev_match = 0;        /* previous match */
  this.match_available = 0;   /* set if previous match exists */
  this.strstart = 0;          /* start of string to insert */
  this.match_start = 0;       /* start of matching string */
  this.lookahead = 0;         /* number of valid bytes ahead in window */

  this.prev_length = 0;
  /* Length of the best match at previous step. Matches not greater than this
   * are discarded. This is used in the lazy match evaluation.
   */

  this.max_chain_length = 0;
  /* To speed up deflation, hash chains are never searched beyond this
   * length.  A higher limit improves compression ratio but degrades the
   * speed.
   */

  this.max_lazy_match = 0;
  /* Attempt to find a better match only when the current match is strictly
   * smaller than this value. This mechanism is used only for compression
   * levels >= 4.
   */
  // That's alias to max_lazy_match, don't use directly
  //this.max_insert_length = 0;
  /* Insert new strings in the hash table only if the match length is not
   * greater than this length. This saves time but degrades compression.
   * max_insert_length is used only for compression levels <= 3.
   */

  this.level = 0;     /* compression level (1..9) */
  this.strategy = 0;  /* favor or force Huffman coding*/

  this.good_match = 0;
  /* Use a faster search when the previous match is longer than this */

  this.nice_match = 0; /* Stop searching when current match exceeds this */

              /* used by trees.c: */

  /* Didn't use ct_data typedef below to suppress compiler warning */

  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */

  // Use flat array of DOUBLE size, with interleaved fata,
  // because JS does not support effective
  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
  this.dyn_dtree  = new utils.Buf16((2 * D_CODES + 1) * 2);
  this.bl_tree    = new utils.Buf16((2 * BL_CODES + 1) * 2);
  zero(this.dyn_ltree);
  zero(this.dyn_dtree);
  zero(this.bl_tree);

  this.l_desc   = null;         /* desc. for literal tree */
  this.d_desc   = null;         /* desc. for distance tree */
  this.bl_desc  = null;         /* desc. for bit length tree */

  //ush bl_count[MAX_BITS+1];
  this.bl_count = new utils.Buf16(MAX_BITS + 1);
  /* number of codes at each bit length for an optimal tree */

  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
  this.heap = new utils.Buf16(2 * L_CODES + 1);  /* heap used to build the Huffman trees */
  zero(this.heap);

  this.heap_len = 0;               /* number of elements in the heap */
  this.heap_max = 0;               /* element of largest frequency */
  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
   * The same heap array is used to build all trees.
   */

  this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  zero(this.depth);
  /* Depth of each subtree used as tie breaker for trees of equal frequency
   */

  this.l_buf = 0;          /* buffer index for literals or lengths */

  this.lit_bufsize = 0;
  /* Size of match buffer for literals/lengths.  There are 4 reasons for
   * limiting lit_bufsize to 64K:
   *   - frequencies can be kept in 16 bit counters
   *   - if compression is not successful for the first block, all input
   *     data is still in the window so we can still emit a stored block even
   *     when input comes from standard input.  (This can also be done for
   *     all blocks if lit_bufsize is not greater than 32K.)
   *   - if compression is not successful for a file smaller than 64K, we can
   *     even emit a stored file instead of a stored block (saving 5 bytes).
   *     This is applicable only for zip (not gzip or zlib).
   *   - creating new Huffman trees less frequently may not provide fast
   *     adaptation to changes in the input data statistics. (Take for
   *     example a binary file with poorly compressible code followed by
   *     a highly compressible string table.) Smaller buffer sizes give
   *     fast adaptation but have of course the overhead of transmitting
   *     trees more frequently.
   *   - I can't count above 4
   */

  this.last_lit = 0;      /* running index in l_buf */

  this.d_buf = 0;
  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
   * the same number of elements. To use different lengths, an extra flag
   * array would be necessary.
   */

  this.opt_len = 0;       /* bit length of current block with optimal trees */
  this.static_len = 0;    /* bit length of current block with static trees */
  this.matches = 0;       /* number of string matches in current block */
  this.insert = 0;        /* bytes at end of window left to insert */


  this.bi_buf = 0;
  /* Output buffer. bits are inserted starting at the bottom (least
   * significant bits).
   */
  this.bi_valid = 0;
  /* Number of valid bits in bi_buf.  All bits above the last valid bit
   * are always zero.
   */

  // Used for window memory init. We safely ignore it for JS. That makes
  // sense only for pointers and memory check tools.
  //this.high_water = 0;
  /* High water mark offset in window for initialized bytes -- bytes above
   * this are set to zero in order to avoid memory check warnings when
   * longest match routines access bytes past the input.  This is then
   * updated to the new high water mark.
   */
}


function deflateResetKeep(strm) {
  var s;

  if (!strm || !strm.state) {
    return err(strm, Z_STREAM_ERROR);
  }

  strm.total_in = strm.total_out = 0;
  strm.data_type = Z_UNKNOWN;

  s = strm.state;
  s.pending = 0;
  s.pending_out = 0;

  if (s.wrap < 0) {
    s.wrap = -s.wrap;
    /* was made negative by deflate(..., Z_FINISH); */
  }
  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  strm.adler = (s.wrap === 2) ?
    0  // crc32(0, Z_NULL, 0)
  :
    1; // adler32(0, Z_NULL, 0)
  s.last_flush = Z_NO_FLUSH;
  trees._tr_init(s);
  return Z_OK;
}


function deflateReset(strm) {
  var ret = deflateResetKeep(strm);
  if (ret === Z_OK) {
    lm_init(strm.state);
  }
  return ret;
}


function deflateSetHeader(strm, head) {
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  strm.state.gzhead = head;
  return Z_OK;
}


function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  if (!strm) { // === Z_NULL
    return Z_STREAM_ERROR;
  }
  var wrap = 1;

  if (level === Z_DEFAULT_COMPRESSION) {
    level = 6;
  }

  if (windowBits < 0) { /* suppress zlib wrapper */
    wrap = 0;
    windowBits = -windowBits;
  }

  else if (windowBits > 15) {
    wrap = 2;           /* write gzip wrapper instead */
    windowBits -= 16;
  }


  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
    strategy < 0 || strategy > Z_FIXED) {
    return err(strm, Z_STREAM_ERROR);
  }


  if (windowBits === 8) {
    windowBits = 9;
  }
  /* until 256-byte window bug fixed */

  var s = new DeflateState();

  strm.state = s;
  s.strm = strm;

  s.wrap = wrap;
  s.gzhead = null;
  s.w_bits = windowBits;
  s.w_size = 1 << s.w_bits;
  s.w_mask = s.w_size - 1;

  s.hash_bits = memLevel + 7;
  s.hash_size = 1 << s.hash_bits;
  s.hash_mask = s.hash_size - 1;
  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);

  s.window = new utils.Buf8(s.w_size * 2);
  s.head = new utils.Buf16(s.hash_size);
  s.prev = new utils.Buf16(s.w_size);

  // Don't need mem init magic for JS.
  //s.high_water = 0;  /* nothing written to s->window yet */

  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */

  s.pending_buf_size = s.lit_bufsize * 4;

  //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  //s->pending_buf = (uchf *) overlay;
  s.pending_buf = new utils.Buf8(s.pending_buf_size);

  // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  s.d_buf = 1 * s.lit_bufsize;

  //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  s.l_buf = (1 + 2) * s.lit_bufsize;

  s.level = level;
  s.strategy = strategy;
  s.method = method;

  return deflateReset(strm);
}

function deflateInit(strm, level) {
  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}


function deflate(strm, flush) {
  var old_flush, s;
  var beg, val; // for gzip header write only

  if (!strm || !strm.state ||
    flush > Z_BLOCK || flush < 0) {
    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  }

  s = strm.state;

  if (!strm.output ||
      (!strm.input && strm.avail_in !== 0) ||
      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  }

  s.strm = strm; /* just in case */
  old_flush = s.last_flush;
  s.last_flush = flush;

  /* Write the header */
  if (s.status === INIT_STATE) {

    if (s.wrap === 2) { // GZIP header
      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
      put_byte(s, 31);
      put_byte(s, 139);
      put_byte(s, 8);
      if (!s.gzhead) { // s->gzhead == Z_NULL
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, 0);
        put_byte(s, s.level === 9 ? 2 :
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                     4 : 0));
        put_byte(s, OS_CODE);
        s.status = BUSY_STATE;
      }
      else {
        put_byte(s, (s.gzhead.text ? 1 : 0) +
                    (s.gzhead.hcrc ? 2 : 0) +
                    (!s.gzhead.extra ? 0 : 4) +
                    (!s.gzhead.name ? 0 : 8) +
                    (!s.gzhead.comment ? 0 : 16)
        );
        put_byte(s, s.gzhead.time & 0xff);
        put_byte(s, (s.gzhead.time >> 8) & 0xff);
        put_byte(s, (s.gzhead.time >> 16) & 0xff);
        put_byte(s, (s.gzhead.time >> 24) & 0xff);
        put_byte(s, s.level === 9 ? 2 :
                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
                     4 : 0));
        put_byte(s, s.gzhead.os & 0xff);
        if (s.gzhead.extra && s.gzhead.extra.length) {
          put_byte(s, s.gzhead.extra.length & 0xff);
          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
        }
        if (s.gzhead.hcrc) {
          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
        }
        s.gzindex = 0;
        s.status = EXTRA_STATE;
      }
    }
    else // DEFLATE header
    {
      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
      var level_flags = -1;

      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
        level_flags = 0;
      } else if (s.level < 6) {
        level_flags = 1;
      } else if (s.level === 6) {
        level_flags = 2;
      } else {
        level_flags = 3;
      }
      header |= (level_flags << 6);
      if (s.strstart !== 0) { header |= PRESET_DICT; }
      header += 31 - (header % 31);

      s.status = BUSY_STATE;
      putShortMSB(s, header);

      /* Save the adler32 of the preset dictionary: */
      if (s.strstart !== 0) {
        putShortMSB(s, strm.adler >>> 16);
        putShortMSB(s, strm.adler & 0xffff);
      }
      strm.adler = 1; // adler32(0L, Z_NULL, 0);
    }
  }

//#ifdef GZIP
  if (s.status === EXTRA_STATE) {
    if (s.gzhead.extra/* != Z_NULL*/) {
      beg = s.pending;  /* start of bytes to update crc */

      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
        if (s.pending === s.pending_buf_size) {
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s.pending;
          if (s.pending === s.pending_buf_size) {
            break;
          }
        }
        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
        s.gzindex++;
      }
      if (s.gzhead.hcrc && s.pending > beg) {
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
      }
      if (s.gzindex === s.gzhead.extra.length) {
        s.gzindex = 0;
        s.status = NAME_STATE;
      }
    }
    else {
      s.status = NAME_STATE;
    }
  }
  if (s.status === NAME_STATE) {
    if (s.gzhead.name/* != Z_NULL*/) {
      beg = s.pending;  /* start of bytes to update crc */
      //int val;

      do {
        if (s.pending === s.pending_buf_size) {
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s.pending;
          if (s.pending === s.pending_buf_size) {
            val = 1;
            break;
          }
        }
        // JS specific: little magic to add zero terminator to end of string
        if (s.gzindex < s.gzhead.name.length) {
          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
        } else {
          val = 0;
        }
        put_byte(s, val);
      } while (val !== 0);

      if (s.gzhead.hcrc && s.pending > beg) {
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
      }
      if (val === 0) {
        s.gzindex = 0;
        s.status = COMMENT_STATE;
      }
    }
    else {
      s.status = COMMENT_STATE;
    }
  }
  if (s.status === COMMENT_STATE) {
    if (s.gzhead.comment/* != Z_NULL*/) {
      beg = s.pending;  /* start of bytes to update crc */
      //int val;

      do {
        if (s.pending === s.pending_buf_size) {
          if (s.gzhead.hcrc && s.pending > beg) {
            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
          }
          flush_pending(strm);
          beg = s.pending;
          if (s.pending === s.pending_buf_size) {
            val = 1;
            break;
          }
        }
        // JS specific: little magic to add zero terminator to end of string
        if (s.gzindex < s.gzhead.comment.length) {
          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
        } else {
          val = 0;
        }
        put_byte(s, val);
      } while (val !== 0);

      if (s.gzhead.hcrc && s.pending > beg) {
        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
      }
      if (val === 0) {
        s.status = HCRC_STATE;
      }
    }
    else {
      s.status = HCRC_STATE;
    }
  }
  if (s.status === HCRC_STATE) {
    if (s.gzhead.hcrc) {
      if (s.pending + 2 > s.pending_buf_size) {
        flush_pending(strm);
      }
      if (s.pending + 2 <= s.pending_buf_size) {
        put_byte(s, strm.adler & 0xff);
        put_byte(s, (strm.adler >> 8) & 0xff);
        strm.adler = 0; //crc32(0L, Z_NULL, 0);
        s.status = BUSY_STATE;
      }
    }
    else {
      s.status = BUSY_STATE;
    }
  }
//#endif

  /* Flush as much pending output as possible */
  if (s.pending !== 0) {
    flush_pending(strm);
    if (strm.avail_out === 0) {
      /* Since avail_out is 0, deflate will be called again with
       * more output space, but possibly with both pending and
       * avail_in equal to zero. There won't be anything to do,
       * but this is not an error situation so make sure we
       * return OK instead of BUF_ERROR at next call of deflate:
       */
      s.last_flush = -1;
      return Z_OK;
    }

    /* Make sure there is something to do and avoid duplicate consecutive
     * flushes. For repeated and useless calls with Z_FINISH, we keep
     * returning Z_STREAM_END instead of Z_BUF_ERROR.
     */
  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
    flush !== Z_FINISH) {
    return err(strm, Z_BUF_ERROR);
  }

  /* User must not provide more input after the first FINISH: */
  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
    return err(strm, Z_BUF_ERROR);
  }

  /* Start a new block or continue the current one.
   */
  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
        configuration_table[s.level].func(s, flush));

    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
      s.status = FINISH_STATE;
    }
    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
      if (strm.avail_out === 0) {
        s.last_flush = -1;
        /* avoid BUF_ERROR next call, see above */
      }
      return Z_OK;
      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
       * of deflate should use the same flush parameter to make sure
       * that the flush is complete. So we don't have to output an
       * empty block here, this will be done at next call. This also
       * ensures that for a very small output buffer, we emit at most
       * one empty block.
       */
    }
    if (bstate === BS_BLOCK_DONE) {
      if (flush === Z_PARTIAL_FLUSH) {
        trees._tr_align(s);
      }
      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */

        trees._tr_stored_block(s, 0, 0, false);
        /* For a full flush, this empty block will be recognized
         * as a special marker by inflate_sync().
         */
        if (flush === Z_FULL_FLUSH) {
          /*** CLEAR_HASH(s); ***/             /* forget history */
          zero(s.head); // Fill with NIL (= 0);

          if (s.lookahead === 0) {
            s.strstart = 0;
            s.block_start = 0;
            s.insert = 0;
          }
        }
      }
      flush_pending(strm);
      if (strm.avail_out === 0) {
        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
        return Z_OK;
      }
    }
  }
  //Assert(strm->avail_out > 0, "bug2");
  //if (strm.avail_out <= 0) { throw new Error("bug2");}

  if (flush !== Z_FINISH) { return Z_OK; }
  if (s.wrap <= 0) { return Z_STREAM_END; }

  /* Write the trailer */
  if (s.wrap === 2) {
    put_byte(s, strm.adler & 0xff);
    put_byte(s, (strm.adler >> 8) & 0xff);
    put_byte(s, (strm.adler >> 16) & 0xff);
    put_byte(s, (strm.adler >> 24) & 0xff);
    put_byte(s, strm.total_in & 0xff);
    put_byte(s, (strm.total_in >> 8) & 0xff);
    put_byte(s, (strm.total_in >> 16) & 0xff);
    put_byte(s, (strm.total_in >> 24) & 0xff);
  }
  else
  {
    putShortMSB(s, strm.adler >>> 16);
    putShortMSB(s, strm.adler & 0xffff);
  }

  flush_pending(strm);
  /* If avail_out is zero, the application will call deflate again
   * to flush the rest.
   */
  if (s.wrap > 0) { s.wrap = -s.wrap; }
  /* write the trailer only once! */
  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}

function deflateEnd(strm) {
  var status;

  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
    return Z_STREAM_ERROR;
  }

  status = strm.state.status;
  if (status !== INIT_STATE &&
    status !== EXTRA_STATE &&
    status !== NAME_STATE &&
    status !== COMMENT_STATE &&
    status !== HCRC_STATE &&
    status !== BUSY_STATE &&
    status !== FINISH_STATE
  ) {
    return err(strm, Z_STREAM_ERROR);
  }

  strm.state = null;

  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}


/* =========================================================================
 * Initializes the compression dictionary from the given byte
 * sequence without producing any compressed output.
 */
function deflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;

  var s;
  var str, n;
  var wrap;
  var avail;
  var next;
  var input;
  var tmpDict;

  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
    return Z_STREAM_ERROR;
  }

  s = strm.state;
  wrap = s.wrap;

  if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
    return Z_STREAM_ERROR;
  }

  /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  if (wrap === 1) {
    /* adler32(strm->adler, dictionary, dictLength); */
    strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  }

  s.wrap = 0;   /* avoid computing Adler-32 in read_buf */

  /* if dictionary would fill window, just replace the history */
  if (dictLength >= s.w_size) {
    if (wrap === 0) {            /* already empty otherwise */
      /*** CLEAR_HASH(s); ***/
      zero(s.head); // Fill with NIL (= 0);
      s.strstart = 0;
      s.block_start = 0;
      s.insert = 0;
    }
    /* use the tail */
    // dictionary = dictionary.slice(dictLength - s.w_size);
    tmpDict = new utils.Buf8(s.w_size);
    utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
    dictionary = tmpDict;
    dictLength = s.w_size;
  }
  /* insert dictionary into window and hash */
  avail = strm.avail_in;
  next = strm.next_in;
  input = strm.input;
  strm.avail_in = dictLength;
  strm.next_in = 0;
  strm.input = dictionary;
  fill_window(s);
  while (s.lookahead >= MIN_MATCH) {
    str = s.strstart;
    n = s.lookahead - (MIN_MATCH - 1);
    do {
      /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;

      s.prev[str & s.w_mask] = s.head[s.ins_h];

      s.head[s.ins_h] = str;
      str++;
    } while (--n);
    s.strstart = str;
    s.lookahead = MIN_MATCH - 1;
    fill_window(s);
  }
  s.strstart += s.lookahead;
  s.block_start = s.strstart;
  s.insert = s.lookahead;
  s.lookahead = 0;
  s.match_length = s.prev_length = MIN_MATCH - 1;
  s.match_available = 0;
  strm.next_in = next;
  strm.input = input;
  strm.avail_in = avail;
  s.wrap = wrap;
  return Z_OK;
}


exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateInfo = 'pako deflate (from Nodeca project)';

/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/


/***/ }),
/* 648 */
/***/ (function(module, exports, __nested_webpack_require_3286946__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

/* eslint-disable space-unary-ops */

var utils = __nested_webpack_require_3286946__(82);

/* Public constants ==========================================================*/
/* ===========================================================================*/


//var Z_FILTERED          = 1;
//var Z_HUFFMAN_ONLY      = 2;
//var Z_RLE               = 3;
var Z_FIXED               = 4;
//var Z_DEFAULT_STRATEGY  = 0;

/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY              = 0;
var Z_TEXT                = 1;
//var Z_ASCII             = 1; // = Z_TEXT
var Z_UNKNOWN             = 2;

/*============================================================================*/


function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }

// From zutil.h

var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES    = 2;
/* The three kinds of block type */

var MIN_MATCH    = 3;
var MAX_MATCH    = 258;
/* The minimum and maximum match lengths */

// From deflate.h
/* ===========================================================================
 * Internal compression state.
 */

var LENGTH_CODES  = 29;
/* number of length codes, not counting the special END_BLOCK code */

var LITERALS      = 256;
/* number of literal bytes 0..255 */

var L_CODES       = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */

var D_CODES       = 30;
/* number of distance codes */

var BL_CODES      = 19;
/* number of codes used to transfer the bit lengths */

var HEAP_SIZE     = 2 * L_CODES + 1;
/* maximum heap size */

var MAX_BITS      = 15;
/* All codes must not exceed MAX_BITS bits */

var Buf_size      = 16;
/* size of bit buffer in bi_buf */


/* ===========================================================================
 * Constants
 */

var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */

var END_BLOCK   = 256;
/* end of block literal code */

var REP_3_6     = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */

var REPZ_3_10   = 17;
/* repeat a zero length 3-10 times  (3 bits of repeat count) */

var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times  (7 bits of repeat count) */

/* eslint-disable comma-spacing,array-bracket-spacing */
var extra_lbits =   /* extra bits for each length code */
  [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];

var extra_dbits =   /* extra bits for each distance code */
  [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];

var extra_blbits =  /* extra bits for each bit length code */
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];

var bl_order =
  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* eslint-enable comma-spacing,array-bracket-spacing */

/* The lengths of the bit length codes are sent in order of decreasing
 * probability, to avoid transmitting the lengths for unused bit length codes.
 */

/* ===========================================================================
 * Local data. These are initialized only once.
 */

// We pre-fill arrays with 0 to avoid uninitialized gaps

var DIST_CODE_LEN = 512; /* see definition of array dist_code below */

// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
var static_ltree  = new Array((L_CODES + 2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
 * need for the L_CODES extra codes used during heap construction. However
 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
 * below).
 */

var static_dtree  = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
 * 5 bits.)
 */

var _dist_code    = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
 * 3 .. 258, the last 256 values correspond to the top 8 bits of
 * the 15 bit distances.
 */

var _length_code  = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */

var base_length   = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */

var base_dist     = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */


function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {

  this.static_tree  = static_tree;  /* static tree or NULL */
  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
  this.extra_base   = extra_base;   /* base index for extra_bits */
  this.elems        = elems;        /* max number of elements in the tree */
  this.max_length   = max_length;   /* max bit length for the codes */

  // show if `static_tree` has data or dummy - needed for monomorphic objects
  this.has_stree    = static_tree && static_tree.length;
}


var static_l_desc;
var static_d_desc;
var static_bl_desc;


function TreeDesc(dyn_tree, stat_desc) {
  this.dyn_tree = dyn_tree;     /* the dynamic tree */
  this.max_code = 0;            /* largest code with non zero frequency */
  this.stat_desc = stat_desc;   /* the corresponding static tree */
}



function d_code(dist) {
  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}


/* ===========================================================================
 * Output a short LSB first on the stream.
 * IN assertion: there is enough room in pendingBuf.
 */
function put_short(s, w) {
//    put_byte(s, (uch)((w) & 0xff));
//    put_byte(s, (uch)((ush)(w) >> 8));
  s.pending_buf[s.pending++] = (w) & 0xff;
  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}


/* ===========================================================================
 * Send a value on a given number of bits.
 * IN assertion: length <= 16 and value fits in length bits.
 */
function send_bits(s, value, length) {
  if (s.bi_valid > (Buf_size - length)) {
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
    put_short(s, s.bi_buf);
    s.bi_buf = value >> (Buf_size - s.bi_valid);
    s.bi_valid += length - Buf_size;
  } else {
    s.bi_buf |= (value << s.bi_valid) & 0xffff;
    s.bi_valid += length;
  }
}


function send_code(s, c, tree) {
  send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
}


/* ===========================================================================
 * Reverse the first len bits of a code, using straightforward code (a faster
 * method would use a table)
 * IN assertion: 1 <= len <= 15
 */
function bi_reverse(code, len) {
  var res = 0;
  do {
    res |= code & 1;
    code >>>= 1;
    res <<= 1;
  } while (--len > 0);
  return res >>> 1;
}


/* ===========================================================================
 * Flush the bit buffer, keeping at most 7 bits in it.
 */
function bi_flush(s) {
  if (s.bi_valid === 16) {
    put_short(s, s.bi_buf);
    s.bi_buf = 0;
    s.bi_valid = 0;

  } else if (s.bi_valid >= 8) {
    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
    s.bi_buf >>= 8;
    s.bi_valid -= 8;
  }
}


/* ===========================================================================
 * Compute the optimal bit lengths for a tree and update the total bit length
 * for the current block.
 * IN assertion: the fields freq and dad are set, heap[heap_max] and
 *    above are the tree nodes sorted by increasing frequency.
 * OUT assertions: the field len is set to the optimal bit length, the
 *     array bl_count contains the frequencies for each bit length.
 *     The length opt_len is updated; static_len is also updated if stree is
 *     not null.
 */
function gen_bitlen(s, desc)
//    deflate_state *s;
//    tree_desc *desc;    /* the tree descriptor */
{
  var tree            = desc.dyn_tree;
  var max_code        = desc.max_code;
  var stree           = desc.stat_desc.static_tree;
  var has_stree       = desc.stat_desc.has_stree;
  var extra           = desc.stat_desc.extra_bits;
  var base            = desc.stat_desc.extra_base;
  var max_length      = desc.stat_desc.max_length;
  var h;              /* heap index */
  var n, m;           /* iterate over the tree elements */
  var bits;           /* bit length */
  var xbits;          /* extra bits */
  var f;              /* frequency */
  var overflow = 0;   /* number of elements with bit length too large */

  for (bits = 0; bits <= MAX_BITS; bits++) {
    s.bl_count[bits] = 0;
  }

  /* In a first pass, compute the optimal bit lengths (which may
   * overflow in the case of the bit length tree).
   */
  tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */

  for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
    n = s.heap[h];
    bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
    if (bits > max_length) {
      bits = max_length;
      overflow++;
    }
    tree[n * 2 + 1]/*.Len*/ = bits;
    /* We overwrite tree[n].Dad which is no longer needed */

    if (n > max_code) { continue; } /* not a leaf node */

    s.bl_count[bits]++;
    xbits = 0;
    if (n >= base) {
      xbits = extra[n - base];
    }
    f = tree[n * 2]/*.Freq*/;
    s.opt_len += f * (bits + xbits);
    if (has_stree) {
      s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
    }
  }
  if (overflow === 0) { return; }

  // Trace((stderr,"\nbit length overflow\n"));
  /* This happens for example on obj2 and pic of the Calgary corpus */

  /* Find the first bit length which could increase: */
  do {
    bits = max_length - 1;
    while (s.bl_count[bits] === 0) { bits--; }
    s.bl_count[bits]--;      /* move one leaf down the tree */
    s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
    s.bl_count[max_length]--;
    /* The brother of the overflow item also moves one step up,
     * but this does not affect bl_count[max_length]
     */
    overflow -= 2;
  } while (overflow > 0);

  /* Now recompute all bit lengths, scanning in increasing frequency.
   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
   * lengths instead of fixing only the wrong ones. This idea is taken
   * from 'ar' written by Haruhiko Okumura.)
   */
  for (bits = max_length; bits !== 0; bits--) {
    n = s.bl_count[bits];
    while (n !== 0) {
      m = s.heap[--h];
      if (m > max_code) { continue; }
      if (tree[m * 2 + 1]/*.Len*/ !== bits) {
        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
        s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
        tree[m * 2 + 1]/*.Len*/ = bits;
      }
      n--;
    }
  }
}


/* ===========================================================================
 * Generate the codes for a given tree and bit counts (which need not be
 * optimal).
 * IN assertion: the array bl_count contains the bit length statistics for
 * the given tree and the field len is set for all tree elements.
 * OUT assertion: the field code is set for all tree elements of non
 *     zero code length.
 */
function gen_codes(tree, max_code, bl_count)
//    ct_data *tree;             /* the tree to decorate */
//    int max_code;              /* largest code with non zero frequency */
//    ushf *bl_count;            /* number of codes at each bit length */
{
  var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  var code = 0;              /* running code value */
  var bits;                  /* bit index */
  var n;                     /* code index */

  /* The distribution counts are first used to generate the code values
   * without bit reversal.
   */
  for (bits = 1; bits <= MAX_BITS; bits++) {
    next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  }
  /* Check that the bit counts in bl_count are consistent. The last code
   * must be all ones.
   */
  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  //        "inconsistent bit counts");
  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));

  for (n = 0;  n <= max_code; n++) {
    var len = tree[n * 2 + 1]/*.Len*/;
    if (len === 0) { continue; }
    /* Now reverse the bits */
    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);

    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  }
}


/* ===========================================================================
 * Initialize the various 'constant' tables.
 */
function tr_static_init() {
  var n;        /* iterates over tree elements */
  var bits;     /* bit counter */
  var length;   /* length value */
  var code;     /* code value */
  var dist;     /* distance index */
  var bl_count = new Array(MAX_BITS + 1);
  /* number of codes at each bit length for an optimal tree */

  // do check in _tr_init()
  //if (static_init_done) return;

  /* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
  static_l_desc.static_tree = static_ltree;
  static_l_desc.extra_bits = extra_lbits;
  static_d_desc.static_tree = static_dtree;
  static_d_desc.extra_bits = extra_dbits;
  static_bl_desc.extra_bits = extra_blbits;
#endif*/

  /* Initialize the mapping length (0..255) -> length code (0..28) */
  length = 0;
  for (code = 0; code < LENGTH_CODES - 1; code++) {
    base_length[code] = length;
    for (n = 0; n < (1 << extra_lbits[code]); n++) {
      _length_code[length++] = code;
    }
  }
  //Assert (length == 256, "tr_static_init: length != 256");
  /* Note that the length 255 (match length 258) can be represented
   * in two different ways: code 284 + 5 bits or code 285, so we
   * overwrite length_code[255] to use the best encoding:
   */
  _length_code[length - 1] = code;

  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  dist = 0;
  for (code = 0; code < 16; code++) {
    base_dist[code] = dist;
    for (n = 0; n < (1 << extra_dbits[code]); n++) {
      _dist_code[dist++] = code;
    }
  }
  //Assert (dist == 256, "tr_static_init: dist != 256");
  dist >>= 7; /* from now on, all distances are divided by 128 */
  for (; code < D_CODES; code++) {
    base_dist[code] = dist << 7;
    for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
      _dist_code[256 + dist++] = code;
    }
  }
  //Assert (dist == 256, "tr_static_init: 256+dist != 512");

  /* Construct the codes of the static literal tree */
  for (bits = 0; bits <= MAX_BITS; bits++) {
    bl_count[bits] = 0;
  }

  n = 0;
  while (n <= 143) {
    static_ltree[n * 2 + 1]/*.Len*/ = 8;
    n++;
    bl_count[8]++;
  }
  while (n <= 255) {
    static_ltree[n * 2 + 1]/*.Len*/ = 9;
    n++;
    bl_count[9]++;
  }
  while (n <= 279) {
    static_ltree[n * 2 + 1]/*.Len*/ = 7;
    n++;
    bl_count[7]++;
  }
  while (n <= 287) {
    static_ltree[n * 2 + 1]/*.Len*/ = 8;
    n++;
    bl_count[8]++;
  }
  /* Codes 286 and 287 do not exist, but we must include them in the
   * tree construction to get a canonical Huffman tree (longest code
   * all ones)
   */
  gen_codes(static_ltree, L_CODES + 1, bl_count);

  /* The static distance tree is trivial: */
  for (n = 0; n < D_CODES; n++) {
    static_dtree[n * 2 + 1]/*.Len*/ = 5;
    static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  }

  // Now data ready and we can init static trees
  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
  static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);

  //static_init_done = true;
}


/* ===========================================================================
 * Initialize a new block.
 */
function init_block(s) {
  var n; /* iterates over tree elements */

  /* Initialize the trees. */
  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }

  s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  s.opt_len = s.static_len = 0;
  s.last_lit = s.matches = 0;
}


/* ===========================================================================
 * Flush the bit buffer and align the output on a byte boundary
 */
function bi_windup(s)
{
  if (s.bi_valid > 8) {
    put_short(s, s.bi_buf);
  } else if (s.bi_valid > 0) {
    //put_byte(s, (Byte)s->bi_buf);
    s.pending_buf[s.pending++] = s.bi_buf;
  }
  s.bi_buf = 0;
  s.bi_valid = 0;
}

/* ===========================================================================
 * Copy a stored block, storing first the length and its
 * one's complement if requested.
 */
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf    *buf;    /* the input data */
//unsigned len;     /* its length */
//int      header;  /* true if block header must be written */
{
  bi_windup(s);        /* align on byte boundary */

  if (header) {
    put_short(s, len);
    put_short(s, ~len);
  }
//  while (len--) {
//    put_byte(s, *buf++);
//  }
  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  s.pending += len;
}

/* ===========================================================================
 * Compares to subtrees, using the tree depth as tie breaker when
 * the subtrees have equal frequency. This minimizes the worst case length.
 */
function smaller(tree, n, m, depth) {
  var _n2 = n * 2;
  var _m2 = m * 2;
  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}

/* ===========================================================================
 * Restore the heap property by moving down the tree starting at node k,
 * exchanging a node with the smallest of its two sons if necessary, stopping
 * when the heap property is re-established (each father smaller than its
 * two sons).
 */
function pqdownheap(s, tree, k)
//    deflate_state *s;
//    ct_data *tree;  /* the tree to restore */
//    int k;               /* node to move down */
{
  var v = s.heap[k];
  var j = k << 1;  /* left son of k */
  while (j <= s.heap_len) {
    /* Set j to the smallest of the two sons: */
    if (j < s.heap_len &&
      smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
      j++;
    }
    /* Exit if v is smaller than both sons */
    if (smaller(tree, v, s.heap[j], s.depth)) { break; }

    /* Exchange v with the smallest son */
    s.heap[k] = s.heap[j];
    k = j;

    /* And continue down the tree, setting j to the left son of k */
    j <<= 1;
  }
  s.heap[k] = v;
}


// inlined manually
// var SMALLEST = 1;

/* ===========================================================================
 * Send the block data compressed using the given Huffman trees
 */
function compress_block(s, ltree, dtree)
//    deflate_state *s;
//    const ct_data *ltree; /* literal tree */
//    const ct_data *dtree; /* distance tree */
{
  var dist;           /* distance of matched string */
  var lc;             /* match length or unmatched char (if dist == 0) */
  var lx = 0;         /* running index in l_buf */
  var code;           /* the code to send */
  var extra;          /* number of extra bits to send */

  if (s.last_lit !== 0) {
    do {
      dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
      lc = s.pending_buf[s.l_buf + lx];
      lx++;

      if (dist === 0) {
        send_code(s, lc, ltree); /* send a literal byte */
        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
      } else {
        /* Here, lc is the match length - MIN_MATCH */
        code = _length_code[lc];
        send_code(s, code + LITERALS + 1, ltree); /* send the length code */
        extra = extra_lbits[code];
        if (extra !== 0) {
          lc -= base_length[code];
          send_bits(s, lc, extra);       /* send the extra length bits */
        }
        dist--; /* dist is now the match distance - 1 */
        code = d_code(dist);
        //Assert (code < D_CODES, "bad d_code");

        send_code(s, code, dtree);       /* send the distance code */
        extra = extra_dbits[code];
        if (extra !== 0) {
          dist -= base_dist[code];
          send_bits(s, dist, extra);   /* send the extra distance bits */
        }
      } /* literal or match pair ? */

      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
      //       "pendingBuf overflow");

    } while (lx < s.last_lit);
  }

  send_code(s, END_BLOCK, ltree);
}


/* ===========================================================================
 * Construct one Huffman tree and assigns the code bit strings and lengths.
 * Update the total bit length for the current block.
 * IN assertion: the field freq is set for all tree elements.
 * OUT assertions: the fields len and code are set to the optimal bit length
 *     and corresponding code. The length opt_len is updated; static_len is
 *     also updated if stree is not null. The field max_code is set.
 */
function build_tree(s, desc)
//    deflate_state *s;
//    tree_desc *desc; /* the tree descriptor */
{
  var tree     = desc.dyn_tree;
  var stree    = desc.stat_desc.static_tree;
  var has_stree = desc.stat_desc.has_stree;
  var elems    = desc.stat_desc.elems;
  var n, m;          /* iterate over heap elements */
  var max_code = -1; /* largest code with non zero frequency */
  var node;          /* new node being created */

  /* Construct the initial heap, with least frequent element in
   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
   * heap[0] is not used.
   */
  s.heap_len = 0;
  s.heap_max = HEAP_SIZE;

  for (n = 0; n < elems; n++) {
    if (tree[n * 2]/*.Freq*/ !== 0) {
      s.heap[++s.heap_len] = max_code = n;
      s.depth[n] = 0;

    } else {
      tree[n * 2 + 1]/*.Len*/ = 0;
    }
  }

  /* The pkzip format requires that at least one distance code exists,
   * and that at least one bit should be sent even if there is only one
   * possible code. So to avoid special checks later on we force at least
   * two codes of non zero frequency.
   */
  while (s.heap_len < 2) {
    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
    tree[node * 2]/*.Freq*/ = 1;
    s.depth[node] = 0;
    s.opt_len--;

    if (has_stree) {
      s.static_len -= stree[node * 2 + 1]/*.Len*/;
    }
    /* node is 0 or 1 so it does not have extra bits */
  }
  desc.max_code = max_code;

  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
   * establish sub-heaps of increasing lengths:
   */
  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }

  /* Construct the Huffman tree by repeatedly combining the least two
   * frequent nodes.
   */
  node = elems;              /* next internal node of the tree */
  do {
    //pqremove(s, tree, n);  /* n = node of least frequency */
    /*** pqremove ***/
    n = s.heap[1/*SMALLEST*/];
    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
    pqdownheap(s, tree, 1/*SMALLEST*/);
    /***/

    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */

    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
    s.heap[--s.heap_max] = m;

    /* Create a new node father of n and m */
    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
    tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;

    /* and insert the new node in the heap */
    s.heap[1/*SMALLEST*/] = node++;
    pqdownheap(s, tree, 1/*SMALLEST*/);

  } while (s.heap_len >= 2);

  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];

  /* At this point, the fields freq and dad are set. We can now
   * generate the bit lengths.
   */
  gen_bitlen(s, desc);

  /* The field len is now set, we can generate the bit codes */
  gen_codes(tree, max_code, s.bl_count);
}


/* ===========================================================================
 * Scan a literal or distance tree to determine the frequencies of the codes
 * in the bit length tree.
 */
function scan_tree(s, tree, max_code)
//    deflate_state *s;
//    ct_data *tree;   /* the tree to be scanned */
//    int max_code;    /* and its largest code of non zero frequency */
{
  var n;                     /* iterates over all tree elements */
  var prevlen = -1;          /* last emitted length */
  var curlen;                /* length of current code */

  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */

  var count = 0;             /* repeat count of the current code */
  var max_count = 7;         /* max repeat count */
  var min_count = 4;         /* min repeat count */

  if (nextlen === 0) {
    max_count = 138;
    min_count = 3;
  }
  tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */

  for (n = 0; n <= max_code; n++) {
    curlen = nextlen;
    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;

    if (++count < max_count && curlen === nextlen) {
      continue;

    } else if (count < min_count) {
      s.bl_tree[curlen * 2]/*.Freq*/ += count;

    } else if (curlen !== 0) {

      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
      s.bl_tree[REP_3_6 * 2]/*.Freq*/++;

    } else if (count <= 10) {
      s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;

    } else {
      s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
    }

    count = 0;
    prevlen = curlen;

    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;

    } else if (curlen === nextlen) {
      max_count = 6;
      min_count = 3;

    } else {
      max_count = 7;
      min_count = 4;
    }
  }
}


/* ===========================================================================
 * Send a literal or distance tree in compressed form, using the codes in
 * bl_tree.
 */
function send_tree(s, tree, max_code)
//    deflate_state *s;
//    ct_data *tree; /* the tree to be scanned */
//    int max_code;       /* and its largest code of non zero frequency */
{
  var n;                     /* iterates over all tree elements */
  var prevlen = -1;          /* last emitted length */
  var curlen;                /* length of current code */

  var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */

  var count = 0;             /* repeat count of the current code */
  var max_count = 7;         /* max repeat count */
  var min_count = 4;         /* min repeat count */

  /* tree[max_code+1].Len = -1; */  /* guard already set */
  if (nextlen === 0) {
    max_count = 138;
    min_count = 3;
  }

  for (n = 0; n <= max_code; n++) {
    curlen = nextlen;
    nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;

    if (++count < max_count && curlen === nextlen) {
      continue;

    } else if (count < min_count) {
      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);

    } else if (curlen !== 0) {
      if (curlen !== prevlen) {
        send_code(s, curlen, s.bl_tree);
        count--;
      }
      //Assert(count >= 3 && count <= 6, " 3_6?");
      send_code(s, REP_3_6, s.bl_tree);
      send_bits(s, count - 3, 2);

    } else if (count <= 10) {
      send_code(s, REPZ_3_10, s.bl_tree);
      send_bits(s, count - 3, 3);

    } else {
      send_code(s, REPZ_11_138, s.bl_tree);
      send_bits(s, count - 11, 7);
    }

    count = 0;
    prevlen = curlen;
    if (nextlen === 0) {
      max_count = 138;
      min_count = 3;

    } else if (curlen === nextlen) {
      max_count = 6;
      min_count = 3;

    } else {
      max_count = 7;
      min_count = 4;
    }
  }
}


/* ===========================================================================
 * Construct the Huffman tree for the bit lengths and return the index in
 * bl_order of the last bit length code to send.
 */
function build_bl_tree(s) {
  var max_blindex;  /* index of last bit length code of non zero freq */

  /* Determine the bit length frequencies for literal and distance trees */
  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);

  /* Build the bit length tree: */
  build_tree(s, s.bl_desc);
  /* opt_len now includes the length of the tree representations, except
   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
   */

  /* Determine the number of bit length codes to send. The pkzip format
   * requires that at least 4 bit length codes be sent. (appnote.txt says
   * 3 but the actual value used is 4.)
   */
  for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
    if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
      break;
    }
  }
  /* Update opt_len to include the bit length tree and counts */
  s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  //        s->opt_len, s->static_len));

  return max_blindex;
}


/* ===========================================================================
 * Send the header for a block using dynamic Huffman trees: the counts, the
 * lengths of the bit length codes, the literal tree and the distance tree.
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
 */
function send_all_trees(s, lcodes, dcodes, blcodes)
//    deflate_state *s;
//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
  var rank;                    /* index in bl_order */

  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  //        "too many codes");
  //Tracev((stderr, "\nbl counts: "));
  send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  send_bits(s, dcodes - 1,   5);
  send_bits(s, blcodes - 4,  4); /* not -3 as stated in appnote.txt */
  for (rank = 0; rank < blcodes; rank++) {
    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
    send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  }
  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));

  send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));

  send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}


/* ===========================================================================
 * Check if the data type is TEXT or BINARY, using the following algorithm:
 * - TEXT if the two conditions below are satisfied:
 *    a) There are no non-portable control characters belonging to the
 *       "black list" (0..6, 14..25, 28..31).
 *    b) There is at least one printable character belonging to the
 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
 * - BINARY otherwise.
 * - The following partially-portable control characters form a
 *   "gray list" that is ignored in this detection algorithm:
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
 * IN assertion: the fields Freq of dyn_ltree are set.
 */
function detect_data_type(s) {
  /* black_mask is the bit mask of black-listed bytes
   * set bits 0..6, 14..25, and 28..31
   * 0xf3ffc07f = binary 11110011111111111100000001111111
   */
  var black_mask = 0xf3ffc07f;
  var n;

  /* Check for non-textual ("black-listed") bytes. */
  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
    if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
      return Z_BINARY;
    }
  }

  /* Check for textual ("white-listed") bytes. */
  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
    return Z_TEXT;
  }
  for (n = 32; n < LITERALS; n++) {
    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
      return Z_TEXT;
    }
  }

  /* There are no "black-listed" or "white-listed" bytes:
   * this stream either is empty or has tolerated ("gray-listed") bytes only.
   */
  return Z_BINARY;
}


var static_init_done = false;

/* ===========================================================================
 * Initialize the tree data structures for a new zlib stream.
 */
function _tr_init(s)
{

  if (!static_init_done) {
    tr_static_init();
    static_init_done = true;
  }

  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);

  s.bi_buf = 0;
  s.bi_valid = 0;

  /* Initialize the first block of the first file: */
  init_block(s);
}


/* ===========================================================================
 * Send a stored block
 */
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf;       /* input block */
//ulg stored_len;   /* length of input block */
//int last;         /* one if this is the last block for a file */
{
  send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3);    /* send block type */
  copy_block(s, buf, stored_len, true); /* with header */
}


/* ===========================================================================
 * Send one empty static block to give enough lookahead for inflate.
 * This takes 10 bits, of which 7 may remain in the bit buffer.
 */
function _tr_align(s) {
  send_bits(s, STATIC_TREES << 1, 3);
  send_code(s, END_BLOCK, static_ltree);
  bi_flush(s);
}


/* ===========================================================================
 * Determine the best encoding for the current block: dynamic trees, static
 * trees or store, and output the encoded block to the zip file.
 */
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf;       /* input block, or NULL if too old */
//ulg stored_len;   /* length of input block */
//int last;         /* one if this is the last block for a file */
{
  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
  var max_blindex = 0;        /* index of last bit length code of non zero freq */

  /* Build the Huffman trees unless a stored block is forced */
  if (s.level > 0) {

    /* Check if the file is binary or text */
    if (s.strm.data_type === Z_UNKNOWN) {
      s.strm.data_type = detect_data_type(s);
    }

    /* Construct the literal and distance trees */
    build_tree(s, s.l_desc);
    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
    //        s->static_len));

    build_tree(s, s.d_desc);
    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
    //        s->static_len));
    /* At this point, opt_len and static_len are the total bit lengths of
     * the compressed block data, excluding the tree representations.
     */

    /* Build the bit length tree for the above two trees, and get the index
     * in bl_order of the last bit length code to send.
     */
    max_blindex = build_bl_tree(s);

    /* Determine the best encoding. Compute the block lengths in bytes. */
    opt_lenb = (s.opt_len + 3 + 7) >>> 3;
    static_lenb = (s.static_len + 3 + 7) >>> 3;

    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
    //        s->last_lit));

    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }

  } else {
    // Assert(buf != (char*)0, "lost buf");
    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  }

  if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
    /* 4: two words for the lengths */

    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
     * Otherwise we can't have processed more than WSIZE input bytes since
     * the last block flush, because compression would have been
     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
     * transform a block into a stored block.
     */
    _tr_stored_block(s, buf, stored_len, last);

  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {

    send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
    compress_block(s, static_ltree, static_dtree);

  } else {
    send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
    send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
    compress_block(s, s.dyn_ltree, s.dyn_dtree);
  }
  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  /* The above check is made mod 2^32, for files larger than 512 MB
   * and uLong implemented on 32 bits.
   */
  init_block(s);

  if (last) {
    bi_windup(s);
  }
  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  //       s->compressed_len-7*last));
}

/* ===========================================================================
 * Save the match info and tally the frequency counts. Return true if
 * the current block must be flushed.
 */
function _tr_tally(s, dist, lc)
//    deflate_state *s;
//    unsigned dist;  /* distance of matched string */
//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
  //var out_length, in_length, dcode;

  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;

  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  s.last_lit++;

  if (dist === 0) {
    /* lc is the unmatched char */
    s.dyn_ltree[lc * 2]/*.Freq*/++;
  } else {
    s.matches++;
    /* Here, lc is the match length - MIN_MATCH */
    dist--;             /* dist = match distance - 1 */
    //Assert((ush)dist < (ush)MAX_DIST(s) &&
    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");

    s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  }

// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility

//#ifdef TRUNCATE_BLOCK
//  /* Try to guess if it is profitable to stop the current block here */
//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
//    /* Compute an upper bound for the compressed length */
//    out_length = s.last_lit*8;
//    in_length = s.strstart - s.block_start;
//
//    for (dcode = 0; dcode < D_CODES; dcode++) {
//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
//    }
//    out_length >>>= 3;
//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
//    //       s->last_lit, in_length, out_length,
//    //       100L - out_length*100L/in_length));
//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
//      return true;
//    }
//  }
//#endif

  return (s.last_lit === s.lit_bufsize - 1);
  /* We avoid equality with lit_bufsize because of wraparound at 64K
   * on 16 bit machines and because stored blocks are restricted to
   * 64K-1 bytes.
   */
}

exports._tr_init  = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block  = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;


/***/ }),
/* 649 */
/***/ (function(module, exports, __nested_webpack_require_3326902__) {

"use strict";



var zlib_inflate = __nested_webpack_require_3326902__(650);
var utils        = __nested_webpack_require_3326902__(82);
var strings      = __nested_webpack_require_3326902__(386);
var c            = __nested_webpack_require_3326902__(388);
var msg          = __nested_webpack_require_3326902__(263);
var ZStream      = __nested_webpack_require_3326902__(387);
var GZheader     = __nested_webpack_require_3326902__(653);

var toString = Object.prototype.toString;

/**
 * class Inflate
 *
 * Generic JS-style wrapper for zlib calls. If you don't need
 * streaming behaviour - use more simple functions: [[inflate]]
 * and [[inflateRaw]].
 **/

/* internal
 * inflate.chunks -> Array
 *
 * Chunks of output data, if [[Inflate#onData]] not overridden.
 **/

/**
 * Inflate.result -> Uint8Array|Array|String
 *
 * Uncompressed result, generated by default [[Inflate#onData]]
 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
 * push a chunk with explicit flush (call [[Inflate#push]] with
 * `Z_SYNC_FLUSH` param).
 **/

/**
 * Inflate.err -> Number
 *
 * Error code after inflate finished. 0 (Z_OK) on success.
 * Should be checked if broken data possible.
 **/

/**
 * Inflate.msg -> String
 *
 * Error message, if [[Inflate.err]] != 0
 **/


/**
 * new Inflate(options)
 * - options (Object): zlib inflate options.
 *
 * Creates new inflator instance with specified params. Throws exception
 * on bad params. Supported options:
 *
 * - `windowBits`
 * - `dictionary`
 *
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
 * for more information on these.
 *
 * Additional options, for internal needs:
 *
 * - `chunkSize` - size of generated data chunks (16K by default)
 * - `raw` (Boolean) - do raw inflate
 * - `to` (String) - if equal to 'string', then result will be converted
 *   from utf8 to utf16 (javascript) string. When string output requested,
 *   chunk length can differ from `chunkSize`, depending on content.
 *
 * By default, when no options set, autodetect deflate/gzip data format via
 * wrapper header.
 *
 * ##### Example:
 *
 * ```javascript
 * var pako = require('pako')
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
 *
 * var inflate = new pako.Inflate({ level: 3});
 *
 * inflate.push(chunk1, false);
 * inflate.push(chunk2, true);  // true -> last chunk
 *
 * if (inflate.err) { throw new Error(inflate.err); }
 *
 * console.log(inflate.result);
 * ```
 **/
function Inflate(options) {
  if (!(this instanceof Inflate)) return new Inflate(options);

  this.options = utils.assign({
    chunkSize: 16384,
    windowBits: 0,
    to: ''
  }, options || {});

  var opt = this.options;

  // Force window size for `raw` data, if not set directly,
  // because we have no header for autodetect.
  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
    opt.windowBits = -opt.windowBits;
    if (opt.windowBits === 0) { opt.windowBits = -15; }
  }

  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
      !(options && options.windowBits)) {
    opt.windowBits += 32;
  }

  // Gzip header has no info about windows size, we can do autodetect only
  // for deflate. So, if window size not set, force it to max when gzip possible
  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
    // bit 3 (16) -> gzipped data
    // bit 4 (32) -> autodetect gzip/deflate
    if ((opt.windowBits & 15) === 0) {
      opt.windowBits |= 15;
    }
  }

  this.err    = 0;      // error code, if happens (0 = Z_OK)
  this.msg    = '';     // error message
  this.ended  = false;  // used to avoid multiple onEnd() calls
  this.chunks = [];     // chunks of compressed data

  this.strm   = new ZStream();
  this.strm.avail_out = 0;

  var status  = zlib_inflate.inflateInit2(
    this.strm,
    opt.windowBits
  );

  if (status !== c.Z_OK) {
    throw new Error(msg[status]);
  }

  this.header = new GZheader();

  zlib_inflate.inflateGetHeader(this.strm, this.header);

  // Setup dictionary
  if (opt.dictionary) {
    // Convert data if needed
    if (typeof opt.dictionary === 'string') {
      opt.dictionary = strings.string2buf(opt.dictionary);
    } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
      opt.dictionary = new Uint8Array(opt.dictionary);
    }
    if (opt.raw) { //In raw mode we need to set the dictionary early
      status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary);
      if (status !== c.Z_OK) {
        throw new Error(msg[status]);
      }
    }
  }
}

/**
 * Inflate#push(data[, mode]) -> Boolean
 * - data (Uint8Array|Array|ArrayBuffer|String): input data
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
 *
 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
 * new output chunks. Returns `true` on success. The last data block must have
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
 *
 * On fail call [[Inflate#onEnd]] with error code and return false.
 *
 * We strongly recommend to use `Uint8Array` on input for best speed (output
 * format is detected automatically). Also, don't skip last param and always
 * use the same type in your code (boolean or number). That will improve JS speed.
 *
 * For regular `Array`-s make sure all elements are [0..255].
 *
 * ##### Example
 *
 * ```javascript
 * push(chunk, false); // push one of data chunks
 * ...
 * push(chunk, true);  // push last chunk
 * ```
 **/
Inflate.prototype.push = function (data, mode) {
  var strm = this.strm;
  var chunkSize = this.options.chunkSize;
  var dictionary = this.options.dictionary;
  var status, _mode;
  var next_out_utf8, tail, utf8str;

  // Flag to properly process Z_BUF_ERROR on testing inflate call
  // when we check that all output data was flushed.
  var allowBufError = false;

  if (this.ended) { return false; }
  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);

  // Convert data if needed
  if (typeof data === 'string') {
    // Only binary strings can be decompressed on practice
    strm.input = strings.binstring2buf(data);
  } else if (toString.call(data) === '[object ArrayBuffer]') {
    strm.input = new Uint8Array(data);
  } else {
    strm.input = data;
  }

  strm.next_in = 0;
  strm.avail_in = strm.input.length;

  do {
    if (strm.avail_out === 0) {
      strm.output = new utils.Buf8(chunkSize);
      strm.next_out = 0;
      strm.avail_out = chunkSize;
    }

    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */

    if (status === c.Z_NEED_DICT && dictionary) {
      status = zlib_inflate.inflateSetDictionary(this.strm, dictionary);
    }

    if (status === c.Z_BUF_ERROR && allowBufError === true) {
      status = c.Z_OK;
      allowBufError = false;
    }

    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
      this.onEnd(status);
      this.ended = true;
      return false;
    }

    if (strm.next_out) {
      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {

        if (this.options.to === 'string') {

          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);

          tail = strm.next_out - next_out_utf8;
          utf8str = strings.buf2string(strm.output, next_out_utf8);

          // move tail
          strm.next_out = tail;
          strm.avail_out = chunkSize - tail;
          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }

          this.onData(utf8str);

        } else {
          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
        }
      }
    }

    // When no more input data, we should check that internal inflate buffers
    // are flushed. The only way to do it when avail_out = 0 - run one more
    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
    // Here we set flag to process this error properly.
    //
    // NOTE. Deflate does not return error in this case and does not needs such
    // logic.
    if (strm.avail_in === 0 && strm.avail_out === 0) {
      allowBufError = true;
    }

  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);

  if (status === c.Z_STREAM_END) {
    _mode = c.Z_FINISH;
  }

  // Finalize on the last chunk.
  if (_mode === c.Z_FINISH) {
    status = zlib_inflate.inflateEnd(this.strm);
    this.onEnd(status);
    this.ended = true;
    return status === c.Z_OK;
  }

  // callback interim results if Z_SYNC_FLUSH.
  if (_mode === c.Z_SYNC_FLUSH) {
    this.onEnd(c.Z_OK);
    strm.avail_out = 0;
    return true;
  }

  return true;
};


/**
 * Inflate#onData(chunk) -> Void
 * - chunk (Uint8Array|Array|String): output data. Type of array depends
 *   on js engine support. When string output requested, each chunk
 *   will be string.
 *
 * By default, stores data blocks in `chunks[]` property and glue
 * those in `onEnd`. Override this handler, if you need another behaviour.
 **/
Inflate.prototype.onData = function (chunk) {
  this.chunks.push(chunk);
};


/**
 * Inflate#onEnd(status) -> Void
 * - status (Number): inflate status. 0 (Z_OK) on success,
 *   other if not.
 *
 * Called either after you tell inflate that the input stream is
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
 * or if an error happened. By default - join collected chunks,
 * free memory and fill `results` / `err` properties.
 **/
Inflate.prototype.onEnd = function (status) {
  // On success - join
  if (status === c.Z_OK) {
    if (this.options.to === 'string') {
      // Glue & convert here, until we teach pako to send
      // utf8 aligned strings to onData
      this.result = this.chunks.join('');
    } else {
      this.result = utils.flattenChunks(this.chunks);
    }
  }
  this.chunks = [];
  this.err = status;
  this.msg = this.strm.msg;
};


/**
 * inflate(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to decompress.
 * - options (Object): zlib inflate options.
 *
 * Decompress `data` with inflate/ungzip and `options`. Autodetect
 * format via wrapper header by default. That's why we don't provide
 * separate `ungzip` method.
 *
 * Supported options are:
 *
 * - windowBits
 *
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
 * for more information.
 *
 * Sugar (options):
 *
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
 *   negative windowBits implicitly.
 * - `to` (String) - if equal to 'string', then result will be converted
 *   from utf8 to utf16 (javascript) string. When string output requested,
 *   chunk length can differ from `chunkSize`, depending on content.
 *
 *
 * ##### Example:
 *
 * ```javascript
 * var pako = require('pako')
 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
 *   , output;
 *
 * try {
 *   output = pako.inflate(input);
 * } catch (err)
 *   console.log(err);
 * }
 * ```
 **/
function inflate(input, options) {
  var inflator = new Inflate(options);

  inflator.push(input, true);

  // That will never happens, if you don't cheat with options :)
  if (inflator.err) { throw inflator.msg || msg[inflator.err]; }

  return inflator.result;
}


/**
 * inflateRaw(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to decompress.
 * - options (Object): zlib inflate options.
 *
 * The same as [[inflate]], but creates raw data, without wrapper
 * (header and adler32 crc).
 **/
function inflateRaw(input, options) {
  options = options || {};
  options.raw = true;
  return inflate(input, options);
}


/**
 * ungzip(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to decompress.
 * - options (Object): zlib inflate options.
 *
 * Just shortcut to [[inflate]], because it autodetects format
 * by header.content. Done for convenience.
 **/


exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip  = inflate;


/***/ }),
/* 650 */
/***/ (function(module, exports, __nested_webpack_require_3339381__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

var utils         = __nested_webpack_require_3339381__(82);
var adler32       = __nested_webpack_require_3339381__(384);
var crc32         = __nested_webpack_require_3339381__(385);
var inflate_fast  = __nested_webpack_require_3339381__(651);
var inflate_table = __nested_webpack_require_3339381__(652);

var CODES = 0;
var LENS = 1;
var DISTS = 2;

/* Public constants ==========================================================*/
/* ===========================================================================*/


/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH      = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH    = 2;
//var Z_FULL_FLUSH    = 3;
var Z_FINISH        = 4;
var Z_BLOCK         = 5;
var Z_TREES         = 6;


/* Return codes for the compression/decompression functions. Negative values
 * are errors, positive values are used for special but normal events.
 */
var Z_OK            = 0;
var Z_STREAM_END    = 1;
var Z_NEED_DICT     = 2;
//var Z_ERRNO         = -1;
var Z_STREAM_ERROR  = -2;
var Z_DATA_ERROR    = -3;
var Z_MEM_ERROR     = -4;
var Z_BUF_ERROR     = -5;
//var Z_VERSION_ERROR = -6;

/* The deflate compression method */
var Z_DEFLATED  = 8;


/* STATES ====================================================================*/
/* ===========================================================================*/


var    HEAD = 1;       /* i: waiting for magic header */
var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
var    TIME = 3;       /* i: waiting for modification time (gzip) */
var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
var    NAME = 7;       /* i: waiting for end of file name (gzip) */
var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
var    HCRC = 9;       /* i: waiting for header crc (gzip) */
var    DICTID = 10;    /* i: waiting for dictionary check value */
var    DICT = 11;      /* waiting for inflateSetDictionary() call */
var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
var        STORED = 14;    /* i: waiting for stored size (length and complement) */
var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
var        LENLENS = 18;   /* i: waiting for code length code lengths */
var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
var            LEN = 21;       /* i: waiting for length/lit/eob code */
var            LENEXT = 22;    /* i: waiting for length extra bits */
var            DIST = 23;      /* i: waiting for distance code */
var            DISTEXT = 24;   /* i: waiting for distance extra bits */
var            MATCH = 25;     /* o: waiting for output space to copy string */
var            LIT = 26;       /* o: waiting for output space to write literal */
var    CHECK = 27;     /* i: waiting for 32-bit check value */
var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
var    DONE = 29;      /* finished check, done -- remain here until reset */
var    BAD = 30;       /* got a data error -- remain here until reset */
var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */

/* ===========================================================================*/



var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);

var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;


function zswap32(q) {
  return  (((q >>> 24) & 0xff) +
          ((q >>> 8) & 0xff00) +
          ((q & 0xff00) << 8) +
          ((q & 0xff) << 24));
}


function InflateState() {
  this.mode = 0;             /* current inflate mode */
  this.last = false;          /* true if processing last block */
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  this.havedict = false;      /* true if dictionary provided */
  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
  this.check = 0;             /* protected copy of check value */
  this.total = 0;             /* protected copy of output count */
  // TODO: may be {}
  this.head = null;           /* where to save gzip header information */

  /* sliding window */
  this.wbits = 0;             /* log base 2 of requested window size */
  this.wsize = 0;             /* window size or zero if not using window */
  this.whave = 0;             /* valid bytes in the window */
  this.wnext = 0;             /* window write index */
  this.window = null;         /* allocated sliding window, if needed */

  /* bit accumulator */
  this.hold = 0;              /* input bit accumulator */
  this.bits = 0;              /* number of bits in "in" */

  /* for string and stored block copying */
  this.length = 0;            /* literal or length of data to copy */
  this.offset = 0;            /* distance back to copy string from */

  /* for table and code decoding */
  this.extra = 0;             /* extra bits needed */

  /* fixed and dynamic code tables */
  this.lencode = null;          /* starting table for length/literal codes */
  this.distcode = null;         /* starting table for distance codes */
  this.lenbits = 0;           /* index bits for lencode */
  this.distbits = 0;          /* index bits for distcode */

  /* dynamic table building */
  this.ncode = 0;             /* number of code length code lengths */
  this.nlen = 0;              /* number of length code lengths */
  this.ndist = 0;             /* number of distance code lengths */
  this.have = 0;              /* number of code lengths in lens[] */
  this.next = null;              /* next available space in codes[] */

  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  this.work = new utils.Buf16(288); /* work area for code table building */

  /*
   because we don't have pointers in js, we use lencode and distcode directly
   as buffers so we don't need codes
  */
  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
  this.sane = 0;                   /* if false, allow invalid distance too far */
  this.back = 0;                   /* bits back of last unprocessed length/lit */
  this.was = 0;                    /* initial length of match */
}

function inflateResetKeep(strm) {
  var state;

  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  strm.total_in = strm.total_out = state.total = 0;
  strm.msg = ''; /*Z_NULL*/
  if (state.wrap) {       /* to support ill-conceived Java test suite */
    strm.adler = state.wrap & 1;
  }
  state.mode = HEAD;
  state.last = 0;
  state.havedict = 0;
  state.dmax = 32768;
  state.head = null/*Z_NULL*/;
  state.hold = 0;
  state.bits = 0;
  //state.lencode = state.distcode = state.next = state.codes;
  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);

  state.sane = 1;
  state.back = -1;
  //Tracev((stderr, "inflate: reset\n"));
  return Z_OK;
}

function inflateReset(strm) {
  var state;

  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  state.wsize = 0;
  state.whave = 0;
  state.wnext = 0;
  return inflateResetKeep(strm);

}

function inflateReset2(strm, windowBits) {
  var wrap;
  var state;

  /* get the state */
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;

  /* extract wrap request from windowBits parameter */
  if (windowBits < 0) {
    wrap = 0;
    windowBits = -windowBits;
  }
  else {
    wrap = (windowBits >> 4) + 1;
    if (windowBits < 48) {
      windowBits &= 15;
    }
  }

  /* set number of window bits, free window if different */
  if (windowBits && (windowBits < 8 || windowBits > 15)) {
    return Z_STREAM_ERROR;
  }
  if (state.window !== null && state.wbits !== windowBits) {
    state.window = null;
  }

  /* update state and reset the rest of it */
  state.wrap = wrap;
  state.wbits = windowBits;
  return inflateReset(strm);
}

function inflateInit2(strm, windowBits) {
  var ret;
  var state;

  if (!strm) { return Z_STREAM_ERROR; }
  //strm.msg = Z_NULL;                 /* in case we return an error */

  state = new InflateState();

  //if (state === Z_NULL) return Z_MEM_ERROR;
  //Tracev((stderr, "inflate: allocated\n"));
  strm.state = state;
  state.window = null/*Z_NULL*/;
  ret = inflateReset2(strm, windowBits);
  if (ret !== Z_OK) {
    strm.state = null/*Z_NULL*/;
  }
  return ret;
}

function inflateInit(strm) {
  return inflateInit2(strm, DEF_WBITS);
}


/*
 Return state with length and distance decoding tables and index sizes set to
 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
 If BUILDFIXED is defined, then instead this routine builds the tables the
 first time it's called, and returns those tables the first time and
 thereafter.  This reduces the size of the code by about 2K bytes, in
 exchange for a little execution time.  However, BUILDFIXED should not be
 used for threaded applications, since the rewriting of the tables and virgin
 may not be thread-safe.
 */
var virgin = true;

var lenfix, distfix; // We have no pointers in JS, so keep tables separate

function fixedtables(state) {
  /* build fixed huffman tables if first call (may not be thread safe) */
  if (virgin) {
    var sym;

    lenfix = new utils.Buf32(512);
    distfix = new utils.Buf32(32);

    /* literal/length table */
    sym = 0;
    while (sym < 144) { state.lens[sym++] = 8; }
    while (sym < 256) { state.lens[sym++] = 9; }
    while (sym < 280) { state.lens[sym++] = 7; }
    while (sym < 288) { state.lens[sym++] = 8; }

    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });

    /* distance table */
    sym = 0;
    while (sym < 32) { state.lens[sym++] = 5; }

    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });

    /* do this just once */
    virgin = false;
  }

  state.lencode = lenfix;
  state.lenbits = 9;
  state.distcode = distfix;
  state.distbits = 5;
}


/*
 Update the window with the last wsize (normally 32K) bytes written before
 returning.  If window does not exist yet, create it.  This is only called
 when a window is already in use, or when output has been written during this
 inflate call, but the end of the deflate stream has not been reached yet.
 It is also called to create a window for dictionary data when a dictionary
 is loaded.

 Providing output buffers larger than 32K to inflate() should provide a speed
 advantage, since only the last 32K of output is copied to the sliding window
 upon return from inflate(), and since all distances after the first 32K of
 output will fall in the output data, making match copies simpler and faster.
 The advantage may be dependent on the size of the processor's data caches.
 */
function updatewindow(strm, src, end, copy) {
  var dist;
  var state = strm.state;

  /* if it hasn't been done already, allocate space for the window */
  if (state.window === null) {
    state.wsize = 1 << state.wbits;
    state.wnext = 0;
    state.whave = 0;

    state.window = new utils.Buf8(state.wsize);
  }

  /* copy state->wsize or less output bytes into the circular window */
  if (copy >= state.wsize) {
    utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
    state.wnext = 0;
    state.whave = state.wsize;
  }
  else {
    dist = state.wsize - state.wnext;
    if (dist > copy) {
      dist = copy;
    }
    //zmemcpy(state->window + state->wnext, end - copy, dist);
    utils.arraySet(state.window, src, end - copy, dist, state.wnext);
    copy -= dist;
    if (copy) {
      //zmemcpy(state->window, end - copy, copy);
      utils.arraySet(state.window, src, end - copy, copy, 0);
      state.wnext = copy;
      state.whave = state.wsize;
    }
    else {
      state.wnext += dist;
      if (state.wnext === state.wsize) { state.wnext = 0; }
      if (state.whave < state.wsize) { state.whave += dist; }
    }
  }
  return 0;
}

function inflate(strm, flush) {
  var state;
  var input, output;          // input/output buffers
  var next;                   /* next input INDEX */
  var put;                    /* next output INDEX */
  var have, left;             /* available input and output */
  var hold;                   /* bit buffer */
  var bits;                   /* bits in bit buffer */
  var _in, _out;              /* save starting available input and output */
  var copy;                   /* number of stored or match bytes to copy */
  var from;                   /* where to copy match bytes from */
  var from_source;
  var here = 0;               /* current decoding table entry */
  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  //var last;                   /* parent table entry */
  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  var len;                    /* length to copy for repeats, bits to drop */
  var ret;                    /* return code */
  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
  var opts;

  var n; // temporary var for NEED_BITS

  var order = /* permutation of code lengths */
    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];


  if (!strm || !strm.state || !strm.output ||
      (!strm.input && strm.avail_in !== 0)) {
    return Z_STREAM_ERROR;
  }

  state = strm.state;
  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */


  //--- LOAD() ---
  put = strm.next_out;
  output = strm.output;
  left = strm.avail_out;
  next = strm.next_in;
  input = strm.input;
  have = strm.avail_in;
  hold = state.hold;
  bits = state.bits;
  //---

  _in = have;
  _out = left;
  ret = Z_OK;

  inf_leave: // goto emulation
  for (;;) {
    switch (state.mode) {
      case HEAD:
        if (state.wrap === 0) {
          state.mode = TYPEDO;
          break;
        }
        //=== NEEDBITS(16);
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
          state.check = 0/*crc32(0L, Z_NULL, 0)*/;
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//

          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = FLAGS;
          break;
        }
        state.flags = 0;           /* expect zlib header */
        if (state.head) {
          state.head.done = false;
        }
        if (!(state.wrap & 1) ||   /* check if zlib header allowed */
          (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
          strm.msg = 'incorrect header check';
          state.mode = BAD;
          break;
        }
        if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
          strm.msg = 'unknown compression method';
          state.mode = BAD;
          break;
        }
        //--- DROPBITS(4) ---//
        hold >>>= 4;
        bits -= 4;
        //---//
        len = (hold & 0x0f)/*BITS(4)*/ + 8;
        if (state.wbits === 0) {
          state.wbits = len;
        }
        else if (len > state.wbits) {
          strm.msg = 'invalid window size';
          state.mode = BAD;
          break;
        }
        state.dmax = 1 << len;
        //Tracev((stderr, "inflate:   zlib header ok\n"));
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
        state.mode = hold & 0x200 ? DICTID : TYPE;
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        break;
      case FLAGS:
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.flags = hold;
        if ((state.flags & 0xff) !== Z_DEFLATED) {
          strm.msg = 'unknown compression method';
          state.mode = BAD;
          break;
        }
        if (state.flags & 0xe000) {
          strm.msg = 'unknown header flags set';
          state.mode = BAD;
          break;
        }
        if (state.head) {
          state.head.text = ((hold >> 8) & 1);
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = TIME;
        /* falls through */
      case TIME:
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (state.head) {
          state.head.time = hold;
        }
        if (state.flags & 0x0200) {
          //=== CRC4(state.check, hold)
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          hbuf[2] = (hold >>> 16) & 0xff;
          hbuf[3] = (hold >>> 24) & 0xff;
          state.check = crc32(state.check, hbuf, 4, 0);
          //===
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = OS;
        /* falls through */
      case OS:
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (state.head) {
          state.head.xflags = (hold & 0xff);
          state.head.os = (hold >> 8);
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = EXLEN;
        /* falls through */
      case EXLEN:
        if (state.flags & 0x0400) {
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.length = hold;
          if (state.head) {
            state.head.extra_len = hold;
          }
          if (state.flags & 0x0200) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
        }
        else if (state.head) {
          state.head.extra = null/*Z_NULL*/;
        }
        state.mode = EXTRA;
        /* falls through */
      case EXTRA:
        if (state.flags & 0x0400) {
          copy = state.length;
          if (copy > have) { copy = have; }
          if (copy) {
            if (state.head) {
              len = state.head.extra_len - state.length;
              if (!state.head.extra) {
                // Use untyped array for more convenient processing later
                state.head.extra = new Array(state.head.extra_len);
              }
              utils.arraySet(
                state.head.extra,
                input,
                next,
                // extra field is limited to 65536 bytes
                // - no need for additional size check
                copy,
                /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                len
              );
              //zmemcpy(state.head.extra + len, next,
              //        len + copy > state.head.extra_max ?
              //        state.head.extra_max - len : copy);
            }
            if (state.flags & 0x0200) {
              state.check = crc32(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            state.length -= copy;
          }
          if (state.length) { break inf_leave; }
        }
        state.length = 0;
        state.mode = NAME;
        /* falls through */
      case NAME:
        if (state.flags & 0x0800) {
          if (have === 0) { break inf_leave; }
          copy = 0;
          do {
            // TODO: 2 or 1 bytes?
            len = input[next + copy++];
            /* use constant limit because in js we should not preallocate memory */
            if (state.head && len &&
                (state.length < 65536 /*state.head.name_max*/)) {
              state.head.name += String.fromCharCode(len);
            }
          } while (len && copy < have);

          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          if (len) { break inf_leave; }
        }
        else if (state.head) {
          state.head.name = null;
        }
        state.length = 0;
        state.mode = COMMENT;
        /* falls through */
      case COMMENT:
        if (state.flags & 0x1000) {
          if (have === 0) { break inf_leave; }
          copy = 0;
          do {
            len = input[next + copy++];
            /* use constant limit because in js we should not preallocate memory */
            if (state.head && len &&
                (state.length < 65536 /*state.head.comm_max*/)) {
              state.head.comment += String.fromCharCode(len);
            }
          } while (len && copy < have);
          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          if (len) { break inf_leave; }
        }
        else if (state.head) {
          state.head.comment = null;
        }
        state.mode = HCRC;
        /* falls through */
      case HCRC:
        if (state.flags & 0x0200) {
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (hold !== (state.check & 0xffff)) {
            strm.msg = 'header crc mismatch';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
        }
        if (state.head) {
          state.head.hcrc = ((state.flags >> 9) & 1);
          state.head.done = true;
        }
        strm.adler = state.check = 0;
        state.mode = TYPE;
        break;
      case DICTID:
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        strm.adler = state.check = zswap32(hold);
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = DICT;
        /* falls through */
      case DICT:
        if (state.havedict === 0) {
          //--- RESTORE() ---
          strm.next_out = put;
          strm.avail_out = left;
          strm.next_in = next;
          strm.avail_in = have;
          state.hold = hold;
          state.bits = bits;
          //---
          return Z_NEED_DICT;
        }
        strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
        state.mode = TYPE;
        /* falls through */
      case TYPE:
        if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case TYPEDO:
        if (state.last) {
          //--- BYTEBITS() ---//
          hold >>>= bits & 7;
          bits -= bits & 7;
          //---//
          state.mode = CHECK;
          break;
        }
        //=== NEEDBITS(3); */
        while (bits < 3) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.last = (hold & 0x01)/*BITS(1)*/;
        //--- DROPBITS(1) ---//
        hold >>>= 1;
        bits -= 1;
        //---//

        switch ((hold & 0x03)/*BITS(2)*/) {
          case 0:                             /* stored block */
            //Tracev((stderr, "inflate:     stored block%s\n",
            //        state.last ? " (last)" : ""));
            state.mode = STORED;
            break;
          case 1:                             /* fixed block */
            fixedtables(state);
            //Tracev((stderr, "inflate:     fixed codes block%s\n",
            //        state.last ? " (last)" : ""));
            state.mode = LEN_;             /* decode codes */
            if (flush === Z_TREES) {
              //--- DROPBITS(2) ---//
              hold >>>= 2;
              bits -= 2;
              //---//
              break inf_leave;
            }
            break;
          case 2:                             /* dynamic block */
            //Tracev((stderr, "inflate:     dynamic codes block%s\n",
            //        state.last ? " (last)" : ""));
            state.mode = TABLE;
            break;
          case 3:
            strm.msg = 'invalid block type';
            state.mode = BAD;
        }
        //--- DROPBITS(2) ---//
        hold >>>= 2;
        bits -= 2;
        //---//
        break;
      case STORED:
        //--- BYTEBITS() ---// /* go to byte boundary */
        hold >>>= bits & 7;
        bits -= bits & 7;
        //---//
        //=== NEEDBITS(32); */
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
          strm.msg = 'invalid stored block lengths';
          state.mode = BAD;
          break;
        }
        state.length = hold & 0xffff;
        //Tracev((stderr, "inflate:       stored length %u\n",
        //        state.length));
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = COPY_;
        if (flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case COPY_:
        state.mode = COPY;
        /* falls through */
      case COPY:
        copy = state.length;
        if (copy) {
          if (copy > have) { copy = have; }
          if (copy > left) { copy = left; }
          if (copy === 0) { break inf_leave; }
          //--- zmemcpy(put, next, copy); ---
          utils.arraySet(output, input, next, copy, put);
          //---//
          have -= copy;
          next += copy;
          left -= copy;
          put += copy;
          state.length -= copy;
          break;
        }
        //Tracev((stderr, "inflate:       stored end\n"));
        state.mode = TYPE;
        break;
      case TABLE:
        //=== NEEDBITS(14); */
        while (bits < 14) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
        //--- DROPBITS(5) ---//
        hold >>>= 5;
        bits -= 5;
        //---//
        state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
        //--- DROPBITS(5) ---//
        hold >>>= 5;
        bits -= 5;
        //---//
        state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
        //--- DROPBITS(4) ---//
        hold >>>= 4;
        bits -= 4;
        //---//
//#ifndef PKZIP_BUG_WORKAROUND
        if (state.nlen > 286 || state.ndist > 30) {
          strm.msg = 'too many length or distance symbols';
          state.mode = BAD;
          break;
        }
//#endif
        //Tracev((stderr, "inflate:       table sizes ok\n"));
        state.have = 0;
        state.mode = LENLENS;
        /* falls through */
      case LENLENS:
        while (state.have < state.ncode) {
          //=== NEEDBITS(3);
          while (bits < 3) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
          //--- DROPBITS(3) ---//
          hold >>>= 3;
          bits -= 3;
          //---//
        }
        while (state.have < 19) {
          state.lens[order[state.have++]] = 0;
        }
        // We have separate tables & no pointers. 2 commented lines below not needed.
        //state.next = state.codes;
        //state.lencode = state.next;
        // Switch to use dynamic table
        state.lencode = state.lendyn;
        state.lenbits = 7;

        opts = { bits: state.lenbits };
        ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
        state.lenbits = opts.bits;

        if (ret) {
          strm.msg = 'invalid code lengths set';
          state.mode = BAD;
          break;
        }
        //Tracev((stderr, "inflate:       code lengths ok\n"));
        state.have = 0;
        state.mode = CODELENS;
        /* falls through */
      case CODELENS:
        while (state.have < state.nlen + state.ndist) {
          for (;;) {
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if (here_val < 16) {
            //--- DROPBITS(here.bits) ---//
            hold >>>= here_bits;
            bits -= here_bits;
            //---//
            state.lens[state.have++] = here_val;
          }
          else {
            if (here_val === 16) {
              //=== NEEDBITS(here.bits + 2);
              n = here_bits + 2;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              if (state.have === 0) {
                strm.msg = 'invalid bit length repeat';
                state.mode = BAD;
                break;
              }
              len = state.lens[state.have - 1];
              copy = 3 + (hold & 0x03);//BITS(2);
              //--- DROPBITS(2) ---//
              hold >>>= 2;
              bits -= 2;
              //---//
            }
            else if (here_val === 17) {
              //=== NEEDBITS(here.bits + 3);
              n = here_bits + 3;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              len = 0;
              copy = 3 + (hold & 0x07);//BITS(3);
              //--- DROPBITS(3) ---//
              hold >>>= 3;
              bits -= 3;
              //---//
            }
            else {
              //=== NEEDBITS(here.bits + 7);
              n = here_bits + 7;
              while (bits < n) {
                if (have === 0) { break inf_leave; }
                have--;
                hold += input[next++] << bits;
                bits += 8;
              }
              //===//
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              len = 0;
              copy = 11 + (hold & 0x7f);//BITS(7);
              //--- DROPBITS(7) ---//
              hold >>>= 7;
              bits -= 7;
              //---//
            }
            if (state.have + copy > state.nlen + state.ndist) {
              strm.msg = 'invalid bit length repeat';
              state.mode = BAD;
              break;
            }
            while (copy--) {
              state.lens[state.have++] = len;
            }
          }
        }

        /* handle error breaks in while */
        if (state.mode === BAD) { break; }

        /* check for end-of-block code (better have one) */
        if (state.lens[256] === 0) {
          strm.msg = 'invalid code -- missing end-of-block';
          state.mode = BAD;
          break;
        }

        /* build code tables -- note: do not change the lenbits or distbits
           values here (9 and 6) without reading the comments in inftrees.h
           concerning the ENOUGH constants, which depend on those values */
        state.lenbits = 9;

        opts = { bits: state.lenbits };
        ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
        // We have separate tables & no pointers. 2 commented lines below not needed.
        // state.next_index = opts.table_index;
        state.lenbits = opts.bits;
        // state.lencode = state.next;

        if (ret) {
          strm.msg = 'invalid literal/lengths set';
          state.mode = BAD;
          break;
        }

        state.distbits = 6;
        //state.distcode.copy(state.codes);
        // Switch to use dynamic table
        state.distcode = state.distdyn;
        opts = { bits: state.distbits };
        ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
        // We have separate tables & no pointers. 2 commented lines below not needed.
        // state.next_index = opts.table_index;
        state.distbits = opts.bits;
        // state.distcode = state.next;

        if (ret) {
          strm.msg = 'invalid distances set';
          state.mode = BAD;
          break;
        }
        //Tracev((stderr, 'inflate:       codes ok\n'));
        state.mode = LEN_;
        if (flush === Z_TREES) { break inf_leave; }
        /* falls through */
      case LEN_:
        state.mode = LEN;
        /* falls through */
      case LEN:
        if (have >= 6 && left >= 258) {
          //--- RESTORE() ---
          strm.next_out = put;
          strm.avail_out = left;
          strm.next_in = next;
          strm.avail_in = have;
          state.hold = hold;
          state.bits = bits;
          //---
          inflate_fast(strm, _out);
          //--- LOAD() ---
          put = strm.next_out;
          output = strm.output;
          left = strm.avail_out;
          next = strm.next_in;
          input = strm.input;
          have = strm.avail_in;
          hold = state.hold;
          bits = state.bits;
          //---

          if (state.mode === TYPE) {
            state.back = -1;
          }
          break;
        }
        state.back = 0;
        for (;;) {
          here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if (here_bits <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if (here_op && (here_op & 0xf0) === 0) {
          last_bits = here_bits;
          last_op = here_op;
          last_val = here_val;
          for (;;) {
            here = state.lencode[last_val +
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((last_bits + here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          //--- DROPBITS(last.bits) ---//
          hold >>>= last_bits;
          bits -= last_bits;
          //---//
          state.back += last_bits;
        }
        //--- DROPBITS(here.bits) ---//
        hold >>>= here_bits;
        bits -= here_bits;
        //---//
        state.back += here_bits;
        state.length = here_val;
        if (here_op === 0) {
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          state.mode = LIT;
          break;
        }
        if (here_op & 32) {
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.back = -1;
          state.mode = TYPE;
          break;
        }
        if (here_op & 64) {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD;
          break;
        }
        state.extra = here_op & 15;
        state.mode = LENEXT;
        /* falls through */
      case LENEXT:
        if (state.extra) {
          //=== NEEDBITS(state.extra);
          n = state.extra;
          while (bits < n) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
          //--- DROPBITS(state.extra) ---//
          hold >>>= state.extra;
          bits -= state.extra;
          //---//
          state.back += state.extra;
        }
        //Tracevv((stderr, "inflate:         length %u\n", state.length));
        state.was = state.length;
        state.mode = DIST;
        /* falls through */
      case DIST:
        for (;;) {
          here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if ((here_bits) <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if ((here_op & 0xf0) === 0) {
          last_bits = here_bits;
          last_op = here_op;
          last_val = here_val;
          for (;;) {
            here = state.distcode[last_val +
                    ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((last_bits + here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          //--- DROPBITS(last.bits) ---//
          hold >>>= last_bits;
          bits -= last_bits;
          //---//
          state.back += last_bits;
        }
        //--- DROPBITS(here.bits) ---//
        hold >>>= here_bits;
        bits -= here_bits;
        //---//
        state.back += here_bits;
        if (here_op & 64) {
          strm.msg = 'invalid distance code';
          state.mode = BAD;
          break;
        }
        state.offset = here_val;
        state.extra = (here_op) & 15;
        state.mode = DISTEXT;
        /* falls through */
      case DISTEXT:
        if (state.extra) {
          //=== NEEDBITS(state.extra);
          n = state.extra;
          while (bits < n) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
          //--- DROPBITS(state.extra) ---//
          hold >>>= state.extra;
          bits -= state.extra;
          //---//
          state.back += state.extra;
        }
//#ifdef INFLATE_STRICT
        if (state.offset > state.dmax) {
          strm.msg = 'invalid distance too far back';
          state.mode = BAD;
          break;
        }
//#endif
        //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
        state.mode = MATCH;
        /* falls through */
      case MATCH:
        if (left === 0) { break inf_leave; }
        copy = _out - left;
        if (state.offset > copy) {         /* copy from window */
          copy = state.offset - copy;
          if (copy > state.whave) {
            if (state.sane) {
              strm.msg = 'invalid distance too far back';
              state.mode = BAD;
              break;
            }
// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//          Trace((stderr, "inflate.c too far\n"));
//          copy -= state.whave;
//          if (copy > state.length) { copy = state.length; }
//          if (copy > left) { copy = left; }
//          left -= copy;
//          state.length -= copy;
//          do {
//            output[put++] = 0;
//          } while (--copy);
//          if (state.length === 0) { state.mode = LEN; }
//          break;
//#endif
          }
          if (copy > state.wnext) {
            copy -= state.wnext;
            from = state.wsize - copy;
          }
          else {
            from = state.wnext - copy;
          }
          if (copy > state.length) { copy = state.length; }
          from_source = state.window;
        }
        else {                              /* copy from output */
          from_source = output;
          from = put - state.offset;
          copy = state.length;
        }
        if (copy > left) { copy = left; }
        left -= copy;
        state.length -= copy;
        do {
          output[put++] = from_source[from++];
        } while (--copy);
        if (state.length === 0) { state.mode = LEN; }
        break;
      case LIT:
        if (left === 0) { break inf_leave; }
        output[put++] = state.length;
        left--;
        state.mode = LEN;
        break;
      case CHECK:
        if (state.wrap) {
          //=== NEEDBITS(32);
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            // Use '|' instead of '+' to make sure that result is signed
            hold |= input[next++] << bits;
            bits += 8;
          }
          //===//
          _out -= left;
          strm.total_out += _out;
          state.total += _out;
          if (_out) {
            strm.adler = state.check =
                /*UPDATE(state.check, put - _out, _out);*/
                (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));

          }
          _out = left;
          // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
          if ((state.flags ? hold : zswap32(hold)) !== state.check) {
            strm.msg = 'incorrect data check';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          //Tracev((stderr, "inflate:   check matches trailer\n"));
        }
        state.mode = LENGTH;
        /* falls through */
      case LENGTH:
        if (state.wrap && state.flags) {
          //=== NEEDBITS(32);
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (hold !== (state.total & 0xffffffff)) {
            strm.msg = 'incorrect length check';
            state.mode = BAD;
            break;
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          //Tracev((stderr, "inflate:   length matches trailer\n"));
        }
        state.mode = DONE;
        /* falls through */
      case DONE:
        ret = Z_STREAM_END;
        break inf_leave;
      case BAD:
        ret = Z_DATA_ERROR;
        break inf_leave;
      case MEM:
        return Z_MEM_ERROR;
      case SYNC:
        /* falls through */
      default:
        return Z_STREAM_ERROR;
    }
  }

  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"

  /*
     Return from inflate(), updating the total counts and the check value.
     If there was no progress during the inflate() call, return a buffer
     error.  Call updatewindow() to create and/or update the window state.
     Note: a memory error from inflate() is non-recoverable.
   */

  //--- RESTORE() ---
  strm.next_out = put;
  strm.avail_out = left;
  strm.next_in = next;
  strm.avail_in = have;
  state.hold = hold;
  state.bits = bits;
  //---

  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                      (state.mode < CHECK || flush !== Z_FINISH))) {
    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
      state.mode = MEM;
      return Z_MEM_ERROR;
    }
  }
  _in -= strm.avail_in;
  _out -= strm.avail_out;
  strm.total_in += _in;
  strm.total_out += _out;
  state.total += _out;
  if (state.wrap && _out) {
    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  }
  strm.data_type = state.bits + (state.last ? 64 : 0) +
                    (state.mode === TYPE ? 128 : 0) +
                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
    ret = Z_BUF_ERROR;
  }
  return ret;
}

function inflateEnd(strm) {

  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
    return Z_STREAM_ERROR;
  }

  var state = strm.state;
  if (state.window) {
    state.window = null;
  }
  strm.state = null;
  return Z_OK;
}

function inflateGetHeader(strm, head) {
  var state;

  /* check state */
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }

  /* save header structure */
  state.head = head;
  head.done = false;
  return Z_OK;
}

function inflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;

  var state;
  var dictid;
  var ret;

  /* check state */
  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  state = strm.state;

  if (state.wrap !== 0 && state.mode !== DICT) {
    return Z_STREAM_ERROR;
  }

  /* check for correct dictionary identifier */
  if (state.mode === DICT) {
    dictid = 1; /* adler32(0, null, 0)*/
    /* dictid = adler32(dictid, dictionary, dictLength); */
    dictid = adler32(dictid, dictionary, dictLength, 0);
    if (dictid !== state.check) {
      return Z_DATA_ERROR;
    }
  }
  /* copy dictionary to window using updatewindow(), which will amend the
   existing dictionary if appropriate */
  ret = updatewindow(strm, dictionary, dictLength, dictLength);
  if (ret) {
    state.mode = MEM;
    return Z_MEM_ERROR;
  }
  state.havedict = 1;
  // Tracev((stderr, "inflate:   dictionary set\n"));
  return Z_OK;
}

exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateInfo = 'pako inflate (from Nodeca project)';

/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/


/***/ }),
/* 651 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

// See state defs from inflate.js
var BAD = 30;       /* got a data error -- remain here until reset */
var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */

/*
   Decode literal, length, and distance codes and write out the resulting
   literal and match bytes until either not enough input or output is
   available, an end-of-block is encountered, or a data error is encountered.
   When large enough input and output buffers are supplied to inflate(), for
   example, a 16K input buffer and a 64K output buffer, more than 95% of the
   inflate execution time is spent in this routine.

   Entry assumptions:

        state.mode === LEN
        strm.avail_in >= 6
        strm.avail_out >= 258
        start >= strm.avail_out
        state.bits < 8

   On return, state.mode is one of:

        LEN -- ran out of enough output space or enough available input
        TYPE -- reached end of block code, inflate() to interpret next block
        BAD -- error in block data

   Notes:

    - The maximum input bits used by a length/distance pair is 15 bits for the
      length code, 5 bits for the length extra, 15 bits for the distance code,
      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
      Therefore if strm.avail_in >= 6, then there is enough input to avoid
      checking for available input while decoding.

    - The maximum bytes that a single length/distance pair can output is 258
      bytes, which is the maximum length that can be coded.  inflate_fast()
      requires strm.avail_out >= 258 for each loop to avoid checking for
      output space.
 */
module.exports = function inflate_fast(strm, start) {
  var state;
  var _in;                    /* local strm.input */
  var last;                   /* have enough input while in < last */
  var _out;                   /* local strm.output */
  var beg;                    /* inflate()'s initial strm.output */
  var end;                    /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
  var dmax;                   /* maximum distance from zlib header */
//#endif
  var wsize;                  /* window size or zero if not using window */
  var whave;                  /* valid bytes in the window */
  var wnext;                  /* window write index */
  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  var s_window;               /* allocated sliding window, if wsize != 0 */
  var hold;                   /* local strm.hold */
  var bits;                   /* local strm.bits */
  var lcode;                  /* local strm.lencode */
  var dcode;                  /* local strm.distcode */
  var lmask;                  /* mask for first level of length codes */
  var dmask;                  /* mask for first level of distance codes */
  var here;                   /* retrieved table entry */
  var op;                     /* code bits, operation, extra bits, or */
                              /*  window position, window bytes to copy */
  var len;                    /* match length, unused bytes */
  var dist;                   /* match distance */
  var from;                   /* where to copy match from */
  var from_source;


  var input, output; // JS specific, because we have no pointers

  /* copy state to local variables */
  state = strm.state;
  //here = state.here;
  _in = strm.next_in;
  input = strm.input;
  last = _in + (strm.avail_in - 5);
  _out = strm.next_out;
  output = strm.output;
  beg = _out - (start - strm.avail_out);
  end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
  dmax = state.dmax;
//#endif
  wsize = state.wsize;
  whave = state.whave;
  wnext = state.wnext;
  s_window = state.window;
  hold = state.hold;
  bits = state.bits;
  lcode = state.lencode;
  dcode = state.distcode;
  lmask = (1 << state.lenbits) - 1;
  dmask = (1 << state.distbits) - 1;


  /* decode literals and length/distances until end-of-block or not enough
     input data or output space */

  top:
  do {
    if (bits < 15) {
      hold += input[_in++] << bits;
      bits += 8;
      hold += input[_in++] << bits;
      bits += 8;
    }

    here = lcode[hold & lmask];

    dolen:
    for (;;) { // Goto emulation
      op = here >>> 24/*here.bits*/;
      hold >>>= op;
      bits -= op;
      op = (here >>> 16) & 0xff/*here.op*/;
      if (op === 0) {                          /* literal */
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
        //        "inflate:         literal '%c'\n" :
        //        "inflate:         literal 0x%02x\n", here.val));
        output[_out++] = here & 0xffff/*here.val*/;
      }
      else if (op & 16) {                     /* length base */
        len = here & 0xffff/*here.val*/;
        op &= 15;                           /* number of extra bits */
        if (op) {
          if (bits < op) {
            hold += input[_in++] << bits;
            bits += 8;
          }
          len += hold & ((1 << op) - 1);
          hold >>>= op;
          bits -= op;
        }
        //Tracevv((stderr, "inflate:         length %u\n", len));
        if (bits < 15) {
          hold += input[_in++] << bits;
          bits += 8;
          hold += input[_in++] << bits;
          bits += 8;
        }
        here = dcode[hold & dmask];

        dodist:
        for (;;) { // goto emulation
          op = here >>> 24/*here.bits*/;
          hold >>>= op;
          bits -= op;
          op = (here >>> 16) & 0xff/*here.op*/;

          if (op & 16) {                      /* distance base */
            dist = here & 0xffff/*here.val*/;
            op &= 15;                       /* number of extra bits */
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
              }
            }
            dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
            if (dist > dmax) {
              strm.msg = 'invalid distance too far back';
              state.mode = BAD;
              break top;
            }
//#endif
            hold >>>= op;
            bits -= op;
            //Tracevv((stderr, "inflate:         distance %u\n", dist));
            op = _out - beg;                /* max distance in output */
            if (dist > op) {                /* see if copy from window */
              op = dist - op;               /* distance back in window */
              if (op > whave) {
                if (state.sane) {
                  strm.msg = 'invalid distance too far back';
                  state.mode = BAD;
                  break top;
                }

// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//                if (len <= op - whave) {
//                  do {
//                    output[_out++] = 0;
//                  } while (--len);
//                  continue top;
//                }
//                len -= op - whave;
//                do {
//                  output[_out++] = 0;
//                } while (--op > whave);
//                if (op === 0) {
//                  from = _out - dist;
//                  do {
//                    output[_out++] = output[from++];
//                  } while (--len);
//                  continue top;
//                }
//#endif
              }
              from = 0; // window index
              from_source = s_window;
              if (wnext === 0) {           /* very common case */
                from += wsize - op;
                if (op < len) {         /* some from window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = _out - dist;  /* rest from output */
                  from_source = output;
                }
              }
              else if (wnext < op) {      /* wrap around window */
                from += wsize + wnext - op;
                op -= wnext;
                if (op < len) {         /* some from end of window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = 0;
                  if (wnext < len) {  /* some from start of window */
                    op = wnext;
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;      /* rest from output */
                    from_source = output;
                  }
                }
              }
              else {                      /* contiguous in window */
                from += wnext - op;
                if (op < len) {         /* some from window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = _out - dist;  /* rest from output */
                  from_source = output;
                }
              }
              while (len > 2) {
                output[_out++] = from_source[from++];
                output[_out++] = from_source[from++];
                output[_out++] = from_source[from++];
                len -= 3;
              }
              if (len) {
                output[_out++] = from_source[from++];
                if (len > 1) {
                  output[_out++] = from_source[from++];
                }
              }
            }
            else {
              from = _out - dist;          /* copy direct from output */
              do {                        /* minimum length is three */
                output[_out++] = output[from++];
                output[_out++] = output[from++];
                output[_out++] = output[from++];
                len -= 3;
              } while (len > 2);
              if (len) {
                output[_out++] = output[from++];
                if (len > 1) {
                  output[_out++] = output[from++];
                }
              }
            }
          }
          else if ((op & 64) === 0) {          /* 2nd level distance code */
            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
            continue dodist;
          }
          else {
            strm.msg = 'invalid distance code';
            state.mode = BAD;
            break top;
          }

          break; // need to emulate goto via "continue"
        }
      }
      else if ((op & 64) === 0) {              /* 2nd level length code */
        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
        continue dolen;
      }
      else if (op & 32) {                     /* end-of-block */
        //Tracevv((stderr, "inflate:         end of block\n"));
        state.mode = TYPE;
        break top;
      }
      else {
        strm.msg = 'invalid literal/length code';
        state.mode = BAD;
        break top;
      }

      break; // need to emulate goto via "continue"
    }
  } while (_in < last && _out < end);

  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  len = bits >> 3;
  _in -= len;
  bits -= len << 3;
  hold &= (1 << bits) - 1;

  /* update state and return */
  strm.next_in = _in;
  strm.next_out = _out;
  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  state.hold = hold;
  state.bits = bits;
  return;
};


/***/ }),
/* 652 */
/***/ (function(module, exports, __nested_webpack_require_3402507__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

var utils = __nested_webpack_require_3402507__(82);

var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

var CODES = 0;
var LENS = 1;
var DISTS = 2;

var lbase = [ /* Length codes 257..285 base */
  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];

var lext = [ /* Length codes 257..285 extra */
  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];

var dbase = [ /* Distance codes 0..29 base */
  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  8193, 12289, 16385, 24577, 0, 0
];

var dext = [ /* Distance codes 0..29 extra */
  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  28, 28, 29, 29, 64, 64
];

module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
  var bits = opts.bits;
      //here = opts.here; /* table entry for duplication */

  var len = 0;               /* a code's length in bits */
  var sym = 0;               /* index of code symbols */
  var min = 0, max = 0;          /* minimum and maximum code lengths */
  var root = 0;              /* number of index bits for root table */
  var curr = 0;              /* number of index bits for current table */
  var drop = 0;              /* code bits to drop for sub-table */
  var left = 0;                   /* number of prefix codes available */
  var used = 0;              /* code entries in table used */
  var huff = 0;              /* Huffman code */
  var incr;              /* for incrementing code, index */
  var fill;              /* index for replicating entries */
  var low;               /* low bits for current root entry */
  var mask;              /* mask for low root bits */
  var next;             /* next available space in table */
  var base = null;     /* base value table to use */
  var base_index = 0;
//  var shoextra;    /* extra bits table to use */
  var end;                    /* use base and extra for symbol > end */
  var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
  var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
  var extra = null;
  var extra_index = 0;

  var here_bits, here_op, here_val;

  /*
   Process a set of code lengths to create a canonical Huffman code.  The
   code lengths are lens[0..codes-1].  Each length corresponds to the
   symbols 0..codes-1.  The Huffman code is generated by first sorting the
   symbols by length from short to long, and retaining the symbol order
   for codes with equal lengths.  Then the code starts with all zero bits
   for the first code of the shortest length, and the codes are integer
   increments for the same length, and zeros are appended as the length
   increases.  For the deflate format, these bits are stored backwards
   from their more natural integer increment ordering, and so when the
   decoding tables are built in the large loop below, the integer codes
   are incremented backwards.

   This routine assumes, but does not check, that all of the entries in
   lens[] are in the range 0..MAXBITS.  The caller must assure this.
   1..MAXBITS is interpreted as that code length.  zero means that that
   symbol does not occur in this code.

   The codes are sorted by computing a count of codes for each length,
   creating from that a table of starting indices for each length in the
   sorted table, and then entering the symbols in order in the sorted
   table.  The sorted table is work[], with that space being provided by
   the caller.

   The length counts are used for other purposes as well, i.e. finding
   the minimum and maximum length codes, determining if there are any
   codes at all, checking for a valid set of lengths, and looking ahead
   at length counts to determine sub-table sizes when building the
   decoding tables.
   */

  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  for (len = 0; len <= MAXBITS; len++) {
    count[len] = 0;
  }
  for (sym = 0; sym < codes; sym++) {
    count[lens[lens_index + sym]]++;
  }

  /* bound code lengths, force root to be within code lengths */
  root = bits;
  for (max = MAXBITS; max >= 1; max--) {
    if (count[max] !== 0) { break; }
  }
  if (root > max) {
    root = max;
  }
  if (max === 0) {                     /* no symbols to code at all */
    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
    table[table_index++] = (1 << 24) | (64 << 16) | 0;


    //table.op[opts.table_index] = 64;
    //table.bits[opts.table_index] = 1;
    //table.val[opts.table_index++] = 0;
    table[table_index++] = (1 << 24) | (64 << 16) | 0;

    opts.bits = 1;
    return 0;     /* no symbols, but wait for decoding to report error */
  }
  for (min = 1; min < max; min++) {
    if (count[min] !== 0) { break; }
  }
  if (root < min) {
    root = min;
  }

  /* check for an over-subscribed or incomplete set of lengths */
  left = 1;
  for (len = 1; len <= MAXBITS; len++) {
    left <<= 1;
    left -= count[len];
    if (left < 0) {
      return -1;
    }        /* over-subscribed */
  }
  if (left > 0 && (type === CODES || max !== 1)) {
    return -1;                      /* incomplete set */
  }

  /* generate offsets into symbol table for each length for sorting */
  offs[1] = 0;
  for (len = 1; len < MAXBITS; len++) {
    offs[len + 1] = offs[len] + count[len];
  }

  /* sort symbols by length, by symbol order within each length */
  for (sym = 0; sym < codes; sym++) {
    if (lens[lens_index + sym] !== 0) {
      work[offs[lens[lens_index + sym]]++] = sym;
    }
  }

  /*
   Create and fill in decoding tables.  In this loop, the table being
   filled is at next and has curr index bits.  The code being used is huff
   with length len.  That code is converted to an index by dropping drop
   bits off of the bottom.  For codes where len is less than drop + curr,
   those top drop + curr - len bits are incremented through all values to
   fill the table with replicated entries.

   root is the number of index bits for the root table.  When len exceeds
   root, sub-tables are created pointed to by the root entry with an index
   of the low root bits of huff.  This is saved in low to check for when a
   new sub-table should be started.  drop is zero when the root table is
   being filled, and drop is root when sub-tables are being filled.

   When a new sub-table is needed, it is necessary to look ahead in the
   code lengths to determine what size sub-table is needed.  The length
   counts are used for this, and so count[] is decremented as codes are
   entered in the tables.

   used keeps track of how many table entries have been allocated from the
   provided *table space.  It is checked for LENS and DIST tables against
   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
   the initial root table size constants.  See the comments in inftrees.h
   for more information.

   sym increments through all symbols, and the loop terminates when
   all codes of length max, i.e. all codes, have been processed.  This
   routine permits incomplete codes, so another loop after this one fills
   in the rest of the decoding tables with invalid code markers.
   */

  /* set up for code type */
  // poor man optimization - use if-else instead of switch,
  // to avoid deopts in old v8
  if (type === CODES) {
    base = extra = work;    /* dummy value--not used */
    end = 19;

  } else if (type === LENS) {
    base = lbase;
    base_index -= 257;
    extra = lext;
    extra_index -= 257;
    end = 256;

  } else {                    /* DISTS */
    base = dbase;
    extra = dext;
    end = -1;
  }

  /* initialize opts for loop */
  huff = 0;                   /* starting code */
  sym = 0;                    /* starting code symbol */
  len = min;                  /* starting code length */
  next = table_index;              /* current table to fill in */
  curr = root;                /* current table index bits */
  drop = 0;                   /* current bits to drop from code for index */
  low = -1;                   /* trigger new sub-table when len > root */
  used = 1 << root;          /* use root table entries */
  mask = used - 1;            /* mask for comparing low */

  /* check available table space */
  if ((type === LENS && used > ENOUGH_LENS) ||
    (type === DISTS && used > ENOUGH_DISTS)) {
    return 1;
  }

  /* process all codes and make table entries */
  for (;;) {
    /* create table entry */
    here_bits = len - drop;
    if (work[sym] < end) {
      here_op = 0;
      here_val = work[sym];
    }
    else if (work[sym] > end) {
      here_op = extra[extra_index + work[sym]];
      here_val = base[base_index + work[sym]];
    }
    else {
      here_op = 32 + 64;         /* end of block */
      here_val = 0;
    }

    /* replicate for those indices with low len bits equal to huff */
    incr = 1 << (len - drop);
    fill = 1 << curr;
    min = fill;                 /* save offset to next table */
    do {
      fill -= incr;
      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
    } while (fill !== 0);

    /* backwards increment the len-bit code huff */
    incr = 1 << (len - 1);
    while (huff & incr) {
      incr >>= 1;
    }
    if (incr !== 0) {
      huff &= incr - 1;
      huff += incr;
    } else {
      huff = 0;
    }

    /* go to next symbol, update count, len */
    sym++;
    if (--count[len] === 0) {
      if (len === max) { break; }
      len = lens[lens_index + work[sym]];
    }

    /* create new sub-table if needed */
    if (len > root && (huff & mask) !== low) {
      /* if first time, transition to sub-tables */
      if (drop === 0) {
        drop = root;
      }

      /* increment past last table */
      next += min;            /* here min is 1 << curr */

      /* determine length of next table */
      curr = len - drop;
      left = 1 << curr;
      while (curr + drop < max) {
        left -= count[curr + drop];
        if (left <= 0) { break; }
        curr++;
        left <<= 1;
      }

      /* check for enough space */
      used += 1 << curr;
      if ((type === LENS && used > ENOUGH_LENS) ||
        (type === DISTS && used > ENOUGH_DISTS)) {
        return 1;
      }

      /* point entry in root table to sub-table */
      low = huff & mask;
      /*table.op[low] = curr;
      table.bits[low] = root;
      table.val[low] = next - opts.table_index;*/
      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
    }
  }

  /* fill in remaining table entry if code is incomplete (guaranteed to have
   at most one remaining entry, since if the code is incomplete, the
   maximum code length that was allowed to get this far is one bit) */
  if (huff !== 0) {
    //table.op[next + huff] = 64;            /* invalid code marker */
    //table.bits[next + huff] = len - drop;
    //table.val[next + huff] = 0;
    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  }

  /* set return parameters */
  //opts.table_index += used;
  opts.bits = root;
  return 0;
};


/***/ }),
/* 653 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
//   claim that you wrote the original software. If you use this software
//   in a product, an acknowledgment in the product documentation would be
//   appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
//   misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.

function GZheader() {
  /* true if compressed data believed to be text */
  this.text       = 0;
  /* modification time */
  this.time       = 0;
  /* extra flags (not used when writing a gzip file) */
  this.xflags     = 0;
  /* operating system */
  this.os         = 0;
  /* pointer to extra field or Z_NULL if none */
  this.extra      = null;
  /* extra field length (valid if extra != Z_NULL) */
  this.extra_len  = 0; // Actually, we don't need it in JS,
                       // but leave for few code modifications

  //
  // Setup limits is not necessary because in js we should not preallocate memory
  // for inflate use constant limit in 65536 bytes
  //

  /* space at extra (only when reading header) */
  // this.extra_max  = 0;
  /* pointer to zero-terminated file name or Z_NULL */
  this.name       = '';
  /* space at name (only when reading header) */
  // this.name_max   = 0;
  /* pointer to zero-terminated comment or Z_NULL */
  this.comment    = '';
  /* space at comment (only when reading header) */
  // this.comm_max   = 0;
  /* true if there was or will be a header crc */
  this.hcrc       = 0;
  /* true when done reading gzip header (not used when writing a gzip file) */
  this.done       = false;
}

module.exports = GZheader;


/***/ }),
/* 654 */
/***/ (function(module, exports, __nested_webpack_require_3417404__) {

"use strict";
/* eslint no-div-regex: 0*/



const MONTHS = __nested_webpack_require_3417404__(655);

function genbankToJson(sequence) {
  if (typeof sequence !== 'string') {
    throw new TypeError('sequence must be a string');
  }

  var resultsArray = [];
  var result;
  var currentFeatureNote;

  // Genbank specification: https://www.ncbi.nlm.nih.gov/Sitemap/samplerecord.html
  var genbankAnnotationKey = {
    // Contains in order: locus name, sequence length, molecule type (e.g. DNA), genbank division (see 1-18 below), modification date
    // locus definition has changed with time, use accession number for a unique identifier
    LOCUS_TAG: 'LOCUS',
    DEFINITION_TAG: 'DEFINITION',
    // Accession tag
    // Example: Z78533
    ACCESSION_TAG: 'ACCESSION',
    // The version tag contains 2 informations
    // The accession number with a revision
    // The GI (GenInfo Identifier), a ncbi sequential number
    // Example: Z78533.1  GI:2765658
    // Unicity garanteed with respect to sequence. If 1 nucleotide changes, the version is different.
    VERSION_TAG: 'VERSION',
    KEYWORDS_TAG: 'KEYWORDS',
    // SEGMENT_TAG:"SEGMENT"
    // Source is free text
    SOURCE_TAG: 'SOURCE',
    ORGANISM_TAG: 'ORGANISM',
    REFERENCE_TAG: 'REFERENCE',
    AUTHORS_TAG: 'AUTHORS',
    CONSORTIUM_TAG: 'CONSRTM',
    TITLE_TAG: 'TITLE',
    // Can be multiple journal tags
    JOURNAL_TAG: 'JOURNAL',
    PUBMED_TAG: 'PUBMED',
    REMARK_TAG: 'REMARK',
    FEATURES_TAG: 'FEATURES',
    BASE_COUNT_TAG: 'BASE COUNT',
    // CONTIG_TAG: "CONTIG"
    ORIGIN_TAG: 'ORIGIN',
    END_SEQUENCE_TAG: '//'
  };

  // Genbank divisions
  //   1. PRI - primate sequences
  //   2. ROD - rodent sequences
  //   3. MAM - other mammalian sequences
  //   4. VRT - other vertebrate sequences
  //   5. INV - invertebrate sequences
  //   6. PLN - plant, fungal, and algal sequences
  //   7. BCT - bacterial sequences
  //   8. VRL - viral sequences
  //   9. PHG - bacteriophage sequences
  // 10. SYN - synthetic sequences
  // 11. UNA - unannotated sequences
  // 12. EST - EST sequences (expressed sequence tags)
  // 13. PAT - patent sequences
  // 14. STS - STS sequences (sequence tagged sites)
  // 15. GSS - GSS sequences (genome survey sequences)
  // 16. HTG - HTG sequences (high-throughput genomic sequences)
  // 17. HTC - unfinished high-throughput cDNA sequencing
  // 18. ENV - environmental sampling sequences

  var lines = sequence.split(/\r?\n/);
  var fieldName;
  let subFieldType;
  var featureLocationIndentation;

  if (lines === null) {
    throw new Error('sequence file is empty');
  }
  var hasFoundLocus = false;

  for (let line of lines) {
    if (line === null) break;
    var lineFieldName = getLineFieldName(line);
    var val = getLineVal(line);
    var isSubKey = isSubKeyword(line);
    var isKey = isKeyword(line);

    if (lineFieldName === genbankAnnotationKey.END_SEQUENCE_TAG || isKey) {
      fieldName = lineFieldName;
      subFieldType = null;
    } else if (isSubKey) {
      subFieldType = lineFieldName;
    }
    // IGNORE LINES: DO NOT EVEN PROCESS
    if (line.trim() === '' || lineFieldName === ';') {
      continue;
    }

    if (!hasFoundLocus && fieldName !== genbankAnnotationKey.LOCUS_TAG) {
      // 'Genbank files must start with a LOCUS tag so this must not be a genbank'
      break;
    }

    switch (fieldName) {
      case genbankAnnotationKey.LOCUS_TAG:
        hasFoundLocus = true;
        parseLocus(line);
        break;
      case genbankAnnotationKey.FEATURES_TAG:
        parseFeatures(line, lineFieldName, val);
        break;
      case genbankAnnotationKey.ORIGIN_TAG:
        parseOrigin(line, lineFieldName);
        break;
      case genbankAnnotationKey.DEFINITION_TAG:
      case genbankAnnotationKey.ACCESSION_TAG:
      case genbankAnnotationKey.VERSION_TAG:
      case genbankAnnotationKey.KEYWORDS_TAG:
        parseMultiLineField(fieldName, line, fieldName.toLowerCase());
        break;
      case genbankAnnotationKey.SOURCE_TAG:
        if (subFieldType === genbankAnnotationKey.ORGANISM_TAG) {
          parseMultiLineField(subFieldType, line, 'organism');
        } else {
          parseMultiLineField(lineFieldName, line, 'source');
        }
        break;
      case genbankAnnotationKey.REFERENCE_TAG:
        if (lineFieldName === genbankAnnotationKey.REFERENCE_TAG) {
          const ref = result.references || [];
          result.references = ref;
          ref.push({});
        }
        parseReference(line, subFieldType);
        break;
      case genbankAnnotationKey.END_SEQUENCE_TAG:
        endSeq();
        break;
      default:
        // Unhandled tag
        break;
    }
  }

  // catch the case where we've successfully started a sequence and parsed it, but endSeq isn't called correctly
  if (resultsArray[resultsArray.length - 1] !== result) {
    // current result isn't in resultsArray yet
    // so we call endSeq here
    endSeq();
  }
  return resultsArray;

  function endSeq() {
    // do some post processing clean-up
    postProcessCurSeq();
    // push the result into the resultsArray
    resultsArray.push(result);
  }

  function getCurrentFeature() {
    return result.features[result.features.length - 1];
  }

  function postProcessCurSeq() {
    if (result && result.features) {
      for (var i = 0; i < result.features.length; i++) {
        result.features[i] = postProcessGenbankFeature(result.features[i]);
      }
    }
  }

  function parseOrigin(line, key) {
    if (key !== genbankAnnotationKey.ORIGIN_TAG) {
      var newLine = line.replace(/[\s]*[0-9]*/g, '');
      result.sequence += newLine;
    }
  }

  function parseLocus(line) {
    result = {
      features: [],
      name: 'Untitled sequence',
      sequence: ''
    };
    line = removeFieldName(genbankAnnotationKey.LOCUS_TAG, line);
    const m = line.match(
      /^([^\s]+)\s+(\d+)\s+bp\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)$/
    );
    let locusName = m[1];
    let size = +m[2];
    let moleculeType = m[3];
    let circular = m[4] === 'circular';
    let genbankDivision = m[5];

    const seq = result;
    seq.circular = circular;
    seq.moleculeType = moleculeType;
    seq.genbankDivision = genbankDivision;
    const dateMatch = m[6].match(/^(\d{2})-(.{3})-(\d{4})$/);
    const date = new Date();
    date.setFullYear(+dateMatch[3]);
    date.setUTCMonth(MONTHS.indexOf(dateMatch[2].toUpperCase()));
    date.setDate(+dateMatch[1]);
    date.setUTCHours(12);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    seq.date = date.toISOString();
    seq.name = locusName;
    seq.size = size;
  }

  function removeFieldName(fieldName, line) {
    line = line.replace(/^\s*/, '');
    if (line.indexOf(fieldName) === 0) {
      line = line.replace(fieldName, '');
    }
    return line.trim();
  }

  function parseReference(line, subType) {
    const refs = result.references;
    let lastRef = refs[refs.length - 1];
    if (!subType) {
      parseMultiLineField(
        genbankAnnotationKey.REFERENCE_TAG,
        line,
        'description',
        lastRef
      );
    } else {
      parseMultiLineField(subType, line, subType.toLowerCase(), lastRef);
    }
  }

  var lastLineWasFeaturesTag;
  var lastLineWasLocation;
  function parseFeatures(line, key, val) {
    var strand;
    // FOR THE MAIN FEATURES LOCATION/QUALIFIER LINE
    if (key === genbankAnnotationKey.FEATURES_TAG) {
      lastLineWasFeaturesTag = true;
      return;
    }

    if (lastLineWasFeaturesTag) {
      // we need to get the indentation of feature locations
      featureLocationIndentation = getLengthOfWhiteSpaceBeforeStartOfLetters(
        line
      );
      // set lastLineWasFeaturesTag to false
      lastLineWasFeaturesTag = false;
    }

    // FOR LOCATION && QUALIFIER LINES
    if (isFeatureLineRunon(line, featureLocationIndentation)) {
      // the line is a continuation of the above line
      if (lastLineWasLocation) {
        // the last line was a location, so the run-on line is expected to be a feature location as well
        parseFeatureLocation(line.trim());
        lastLineWasLocation = true;
      } else {
        // the last line was a note
        if (currentFeatureNote) {
          // append to the currentFeatureNote
          currentFeatureNote[
            currentFeatureNote.length - 1
          ] += line.trim().replace(/"/g, '');
        }
        lastLineWasLocation = false;
      }
    } else {
      // New Element/Qualifier lines. Not runon lines.
      if (isNote(line)) {
        // is a new Feature Element (e.g. source, CDS) in the form of  "[\s] KEY  SEQLOCATION"
        // is a FeatureQualifier in the /KEY="BLAH" format; could be multiple per Element
        // Check that feature did not get skipped for missing location
        if (getCurrentFeature()) {
          parseFeatureNote(line);
          lastLineWasLocation = false;
        }
      } else {
        // the line is a location, so we make a new feature from it
        if (val.match(/complement/g)) {
          strand = -1;
        } else {
          strand = 1;
        }

        newFeature();
        var feat = getCurrentFeature();
        feat.type = key;
        feat.strand = strand;

        parseFeatureLocation(val);
        lastLineWasLocation = true;
      }
    }
  }

  function newFeature() {
    result.features.push({
      locations: [],
      notes: {}
    });
  }

  function isNote(line) {
    var qual = false;
    /* if (line.charAt(21) === "/") {//T.H. Hard coded method
           qual = true;
         }*/
    if (
      line
        .trim()
        .charAt(0)
        .match(/\//)
    ) {
      // searches based on looking for / in beginning of line
      qual = true;
    } else if (line.match(/^[\s]*\/[\w]+=[\S]+/)) {
      // searches based on "   /key=BLAH" regex
      qual = true;
    }
    return qual;
  }

  function parseFeatureLocation(locStr) {
    locStr = locStr.trim();
    var locArr = [];
    locStr.replace(/(\d+)/g, function (string, match) {
      locArr.push(match);
    });
    let feat = getCurrentFeature();
    feat.start = +locArr[0];
    feat.end = +locArr[1];
  }

  function parseFeatureNote(line) {
    var newLine, lineArr;

    newLine = line.trim();
    newLine = newLine.replace(/^\/|"$/g, '');
    lineArr = newLine.split(/="|=/);

    var val = lineArr[1];

    if (val) {
      val = val.replace(/\\/g, ' ');

      if (line.match(/="/g)) {
        val = val.replace(/".*/g, '');
      } else if (val.match(/^\d+$/g)) {
        val = +val;
      }
    }
    var key = lineArr[0];
    var currentNotes = getCurrentFeature().notes;
    if (currentNotes[key]) {
      // array already exists, so push value into it
      currentNotes[key].push(val);
    } else {
      // array doesn't exist yet, so create it and populate it with the value
      currentNotes[key] = [val];
    }
    currentFeatureNote = currentNotes[key];
  }

  function getLineFieldName(line) {
    var arr;
    line = line.replace(/^[\s]*/, '');

    if (line.indexOf('=') < 0) {
      arr = line.split(/[\s]+/);
    } else {
      arr = line.split(/=/);
    }

    return arr[0];
  }

  function parseMultiLineField(fieldName, line, resultKey, r) {
    r = r || result;
    let fieldValue = removeFieldName(fieldName, line);
    r[resultKey] = r[resultKey] ? `${r[resultKey]} ` : '';
    r[resultKey] += fieldValue;
  }

  function getLineVal(line) {
    var arr;

    if (line.indexOf('=') < 0) {
      line = line.replace(/^[\s]*[\S]+[\s]+|[\s]+$/, '');
      line = line.trim();
      return line;
    } else {
      arr = line.split(/=/);
      return arr[1];
    }
  }

  function isKeyword(line) {
    var isKey = false;
    if (line.substr(0, 10).match(/^[\S]+/)) {
      isKey = true;
    }
    return isKey;
  }

  function isSubKeyword(line) {
    var isSubKey = false;
    if (line.substr(0, 10).match(/^[\s]+[\S]+/)) {
      isSubKey = true;
    }
    return isSubKey;
  }

  function postProcessGenbankFeature(feat) {
    if (feat.notes.label) {
      feat.name = feat.notes.label[0];
    } else if (feat.notes.gene) {
      feat.name = feat.notes.gene[0];
    } else if (feat.notes.ApEinfo_label) {
      feat.name = feat.notes.ApEinfo_label[0];
    } else if (feat.notes.name) {
      feat.name = feat.notes.name[0];
    } else if (feat.notes.organism) {
      feat.name = feat.notes.organism[0];
    } else if (feat.notes.locus_tag) {
      feat.name = feat.notes.locus_tag[0];
    } else if (feat.notes.note) {
      feat.name = feat.notes.note[0];
    } else {
      feat.name = 'Untitled Feature';
    }
    feat.name = typeof feat.name === 'string' ? feat.name : String(feat.name);
    return feat;
  }
}

function isFeatureLineRunon(line, featureLocationIndentation) {
  var indentationOfLine = getLengthOfWhiteSpaceBeforeStartOfLetters(line);
  if (featureLocationIndentation === indentationOfLine) {
    // the feature location indentation calculated right after the feature tag
    // cannot be the same as the indentation of the line
    //
    // FEATURES             Location/Qualifiers
    //     rep_origin      complement(1074..3302)
    // 01234  <-- this is the indentation we're talking about
    return false; // the line is NOT a run on
  }

  var trimmed = line.trim();
  if (trimmed.charAt(0).match(/\//)) {
    // the first char in the trimmed line cannot be a /
    return false; // the line is NOT a run on
  }
  // the line is a run on
  return true;
  // run-on line example:
  // FEATURES             Location/Qualifiers
  //     rep_origin      complement(1074..3302)
  //                 /label=pSC101**
  //                 /note="REP_ORIGIN REP_ORIGIN pSC101* aka pMPP6, gives plasm
  //                 id number 3 -4 copies per cell, BglII site in pSC101* ori h <--run-on line!
  //                 as been dele ted by quick change agatcT changed to agatcA g <--run-on line!
  //                 iving pSC101* * pSC101* aka pMPP6, gives plasmid number 3-4 <--run-on line!
  //                 copies p er cell, BglII site in pSC101* ori has been delet  <--run-on line!
  //                 ed by quic k change agatcT changed to agatcA giving pSC101* <--run-on line!
  //                 * [pBbS0a-RFP]"                                             <--run-on line!
  //                 /gene="SC101** Ori"
  //                 /note="pSC101* aka pMPP6, gives plasmid number 3-4 copies p
  //                 er cell, BglII site in pSC101* ori has been deleted by qui
  //                 c k change agatcT changed to agatcA giving pSC101**"
  //                 /vntifkey="33"
}

function getLengthOfWhiteSpaceBeforeStartOfLetters(string) {
  var match = /^\s*/.exec(string);
  if (match !== null) {
    return match[0].length;
  } else {
    return 0;
  }
}

module.exports = genbankToJson;


/***/ }),
/* 655 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = [
  'JAN',
  'FEB',
  'MAR',
  'APR',
  'MAY',
  'JUN',
  'JUL',
  'AUG',
  'SEP',
  'OCT',
  'NOV',
  'DEC'
];


/***/ }),
/* 656 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"track-renderer":"TrackRenderer-module_track-renderer-3TM7n","track-renderer-element":"TrackRenderer-module_track-renderer-element-2i16D","track-renderer-events":"TrackRenderer-module_track-renderer-events-3tVM2"};

/***/ }),
/* 657 */
/***/ (function(module, exports, __nested_webpack_require_3432877__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_3432877__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _getPrototypeOf = __nested_webpack_require_3432877__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3432877__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3432877__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3432877__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3432877__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_3432877__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3432877__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Dialog = __nested_webpack_require_3432877__(169);

var _Dialog2 = _interopRequireDefault(_Dialog);

var _TilesetFinder = __nested_webpack_require_3432877__(658);

var _TilesetFinder2 = _interopRequireDefault(_TilesetFinder);

var _PlotTypeChooser = __nested_webpack_require_3432877__(661);

var _PlotTypeChooser2 = _interopRequireDefault(_PlotTypeChooser);

var _configs = __nested_webpack_require_3432877__(11);

var _utils = __nested_webpack_require_3432877__(10);

__nested_webpack_require_3432877__(663);

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

// Utils
var AddTrackDialog = function (_React$Component) {
  (0, _inherits3['default'])(AddTrackDialog, _React$Component);

  function AddTrackDialog(props) {
    (0, _classCallCheck3['default'])(this, AddTrackDialog);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (AddTrackDialog.__proto__ || (0, _getPrototypeOf2['default'])(AddTrackDialog)).call(this, props));

    _this.options = {};

    _this.state = {
      selectedTilesets: [{ datatype: 'none' }],
      allTracksSameDatatype: true // Do all selected tracks have the same datatype
    };

    _this.handleSubmitBound = _this.handleSubmit.bind(_this);

    _this.handleTilesetPickerDoubleClickBound = _this.handleTilesetPickerDoubleClick.bind(_this);
    _this.selectedTilesetsChangedBound = _this.selectedTilesetsChanged.bind(_this);
    return _this;
  }

  /**
   * Get the track available track orientations for the given
   * track position. Generally "top" or "bottom" equal "1d-horizontal",
   * "left" or "right" correspond to "1d-vertical" and "center" means "2d".
   *
   * Arguments
   * ---------
   *  position: string
   *
   * Returns
   * -------
   *
   *  A string containing the track orientation.
   */


  (0, _createClass3['default'])(AddTrackDialog, [{
    key: 'getOrientation',
    value: function () {
      function getOrientation(position) {
        var orientation = null;

        if (position === 'top' || position === 'bottom') {
          orientation = '1d-horizontal';
        } else if (position === 'left' || position === 'right') {
          orientation = '1d-vertical';
        } else {
          orientation = '2d';
        }

        return orientation;
      }

      return getOrientation;
    }()
  }, {
    key: 'handleSubmit',
    value: function () {
      function handleSubmit(evt) {
        if (evt) evt.preventDefault();

        this.props.onTracksChosen(this.state.selectedTilesets, this.props.position, this.props.host);
      }

      return handleSubmit;
    }()

    /**
     * The user double clicked a tileset in the tileset finder dialog.
     * This means that only one is selected.
     *
     * Arguments
     * ---------
     *  tileset: { uuid: 'CXCX', filetype: 'cooler' ....}
     */

  }, {
    key: 'handleTilesetPickerDoubleClick',
    value: function () {
      function handleTilesetPickerDoubleClick(tileset) {
        this.selectedTilesetsChanged([tileset]);

        // should iterate over the selected tilesets
        this.props.onTracksChosen(this.state.selectedTilesets, this.props.position, this.props.host);
      }

      return handleTilesetPickerDoubleClick;
    }()
  }, {
    key: 'handleOptionsChanged',
    value: function () {
      function handleOptionsChanged(newOptions) {
        this.options = newOptions;
      }

      return handleOptionsChanged;
    }()
  }, {
    key: 'handlePlotTypeSelected',
    value: function () {
      function handlePlotTypeSelected(newPlotType) {
        var selectedTilesets = this.state.selectedTilesets;
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {

          for (var _iterator = (0, _getIterator3['default'])(selectedTilesets), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var tileset = _step.value;

            tileset.type = newPlotType;
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        this.selectedPlotType = newPlotType;

        this.setState({
          selectedTilesets: selectedTilesets
        });
      }

      return handlePlotTypeSelected;
    }()
  }, {
    key: 'selectedTilesetsChanged',
    value: function () {
      function selectedTilesetsChanged(selectedTilesetsIn) {
        var selectedTilesets = null;

        if (selectedTilesetsIn.length === 0) {
          // no tilesets are selected
          selectedTilesets = [{ datatype: 'none' }];
        } else {
          selectedTilesets = selectedTilesetsIn;
        }

        var allTracksSameDatatype = true;
        var firstDatatype = selectedTilesets[0].datatype;
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])(selectedTilesets), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var tileset = _step2.value;

            if (tileset.datatype !== firstDatatype) {
              allTracksSameDatatype = false;
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        if (allTracksSameDatatype) {
          // only one datatype is present in the set of selected tilesets
          var _iteratorNormalCompletion3 = true;
          var _didIteratorError3 = false;
          var _iteratorError3 = undefined;

          try {
            for (var _iterator3 = (0, _getIterator3['default'])(selectedTilesets), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
              var _tileset = _step3.value;

              _tileset.type = this.selectedPlotType;
            }
          } catch (err) {
            _didIteratorError3 = true;
            _iteratorError3 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion3 && _iterator3['return']) {
                _iterator3['return']();
              }
            } finally {
              if (_didIteratorError3) {
                throw _iteratorError3;
              }
            }
          }
        } else {
          // more than one dataype present, we assign the default track type
          // to each tileset
          var _iteratorNormalCompletion4 = true;
          var _didIteratorError4 = false;
          var _iteratorError4 = undefined;

          try {
            for (var _iterator4 = (0, _getIterator3['default'])(selectedTilesets), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
              var _tileset2 = _step4.value;

              var datatypes = [_tileset2.datatype];
              var orientation = this.getOrientation(this.props.position);

              if (_tileset2.filetype === 'cooler') {
                datatypes = [_tileset2.datatype, 'chromsizes'];
              }

              var availableTrackTypes = (0, _configs.AVAILABLE_TRACK_TYPES)([datatypes], orientation);
              var defaultTrackType = (0, _utils.getDefaultTrackForDatatype)(datatypes[0], this.props.position, availableTrackTypes);

              _tileset2.type = defaultTrackType.type;
            }
          } catch (err) {
            _didIteratorError4 = true;
            _iteratorError4 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion4 && _iterator4['return']) {
                _iterator4['return']();
              }
            } finally {
              if (_didIteratorError4) {
                throw _iteratorError4;
              }
            }
          }
        }

        this.setState({ selectedTilesets: selectedTilesets, allTracksSameDatatype: allTracksSameDatatype });
      }

      return selectedTilesetsChanged;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var orientation = this.getOrientation(this.props.position);

        var form = _react2['default'].createElement(
          'div',
          null,
          _react2['default'].createElement(_TilesetFinder2['default']
          // Only for testing purposes
          , { ref: function () {
              function ref(c) {
                _this2.tilesetFinder = c;
              }

              return ref;
            }(),
            datatype: this.props.datatype,
            onDoubleClick: this.handleTilesetPickerDoubleClick.bind(this),
            onTracksChosen: function () {
              function onTracksChosen(value) {
                return _this2.props.onTracksChosen(value, _this2.props.position);
              }

              return onTracksChosen;
            }(),
            orientation: orientation,
            selectedTilesetChanged: this.selectedTilesetsChanged.bind(this),
            trackSourceServers: this.props.trackSourceServers
          })
        );

        return _react2['default'].createElement(
          _Dialog2['default'],
          {
            maxHeight: true,
            okayTitle: 'Submit',
            onCancel: this.props.onCancel,
            onOkay: this.handleSubmitBound,
            title: 'Add Track'
          },
          form,
          _react2['default'].createElement(_PlotTypeChooser2['default']
          // Only for testing purposes
          , { ref: function () {
              function ref(c) {
                _this2.plotTypeChooser = c;
              }

              return ref;
            }(),
            allTracksSameDatatype: this.state.allTracksSameDatatype,
            datatypes: this.state.selectedTilesets.map(function (x) {
              if (x.filetype === 'cooler') {
                // cooler files can also supply chromsizes
                return [x.datatype, 'chromsizes'];
              }

              return [x.datatype];
            }),
            onPlotTypeSelected: this.handlePlotTypeSelected.bind(this),
            orientation: orientation,
            position: this.props.position
          })
        );
      }

      return render;
    }()
  }]);
  return AddTrackDialog;
}(_react2['default'].Component);

// Styles


// Configs


AddTrackDialog.defaultProps = {
  position: 'top'
};

AddTrackDialog.propTypes = {
  datatype: _propTypes2['default'].string.isRequired,
  host: _propTypes2['default'].string.isRequired,
  onCancel: _propTypes2['default'].func.isRequired,
  onTracksChosen: _propTypes2['default'].func.isRequired,
  position: _propTypes2['default'].string,
  trackSourceServers: _propTypes2['default'].array.isRequired
};

exports['default'] = AddTrackDialog;

/***/ }),
/* 658 */
/***/ (function(module, exports, __nested_webpack_require_3445228__) {

"use strict";


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

var _stringify = __nested_webpack_require_3445228__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _getIterator2 = __nested_webpack_require_3445228__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _toConsumableArray2 = __nested_webpack_require_3445228__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _set = __nested_webpack_require_3445228__(38);

var _set2 = _interopRequireDefault(_set);

var _keys = __nested_webpack_require_3445228__(18);

var _keys2 = _interopRequireDefault(_keys);

var _assign = __nested_webpack_require_3445228__(44);

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = __nested_webpack_require_3445228__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3445228__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3445228__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3445228__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3445228__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_3445228__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3445228__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _slugid = __nested_webpack_require_3445228__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _reactCheckboxTree = __nested_webpack_require_3445228__(659);

var _reactCheckboxTree2 = _interopRequireDefault(_reactCheckboxTree);

var _services = __nested_webpack_require_3445228__(24);

__nested_webpack_require_3445228__(660);

var _withPubSub = __nested_webpack_require_3445228__(69);

var _withPubSub2 = _interopRequireDefault(_withPubSub);

var _configs = __nested_webpack_require_3445228__(11);

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

var TilesetFinder = function (_React$Component) {
  (0, _inherits3['default'])(TilesetFinder, _React$Component);

  function TilesetFinder(props) {
    (0, _classCallCheck3['default'])(this, TilesetFinder);

    // this.localTracks = TRACKS_INFO.filter

    // local tracks are ones that don't have a filetype associated with them
    var _this = (0, _possibleConstructorReturn3['default'])(this, (TilesetFinder.__proto__ || (0, _getPrototypeOf2['default'])(TilesetFinder)).call(this, props));

    _this.localTracks = _configs.TRACKS_INFO.filter(function (x) {
      return x.local && !x.hidden;
    }).map(function (x) {
      var y = (0, _assign2['default'])({}, x);
      y.datatype = x.datatype[0];
      return y;
    });

    _this.augmentedTracksInfo = _configs.TRACKS_INFO;
    if (window.higlassTracksByType) {
      (0, _keys2['default'])(window.higlassTracksByType).forEach(function (pluginTrackType) {
        _this.augmentedTracksInfo.push(window.higlassTracksByType[pluginTrackType].config);
      });
    }

    if (props.datatype) {
      _this.localTracks = _this.localTracks.filter(function (x) {
        return x.datatype[0] === props.datatype;
      });
    } else {
      _this.localTracks = _this.localTracks.filter(function (x) {
        return x.orientation === _this.props.orientation;
      });
    }

    _this.localTracks.forEach(function (x) {
      x.uuid = _slugid2['default'].nice();
    });

    var newOptions = _this.prepareNewEntries('', _this.localTracks, {});
    var availableTilesetKeys = (0, _keys2['default'])(newOptions);
    var selectedUuid = availableTilesetKeys.length ? [availableTilesetKeys[0]] : null;
    _this.mounted = false;

    _this.state = {
      selectedUuid: selectedUuid,
      options: newOptions,
      filter: '',
      checked: [],
      expanded: []
    };

    _this.requestTilesetLists();
    return _this;
  }

  (0, _createClass3['default'])(TilesetFinder, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        // we want to query for a list of tracks that are compatible with this
        // track orientation

        this.mounted = true;

        this.requestTilesetLists();
        this.searchBox.focus();
      }

      return componentDidMount;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        this.mounted = false;
      }

      return componentWillUnmount;
    }()
  }, {
    key: 'prepareNewEntries',
    value: function () {
      function prepareNewEntries(sourceServer, newEntries, existingOptions) {
        var _this2 = this;

        /**
         * Add meta data to new tileset entries before adding
         * them to the list of available options.
         */
        var newOptions = existingOptions;

        var entries = newEntries.map(function (ne) {
          var ane = (0, _assign2['default'])({}, ne, {
            server: sourceServer,
            tilesetUid: ne.uuid,
            serverUidKey: _this2.serverUidKey(sourceServer, ne.uuid),
            datatype: ne.datatype,
            name: ne.name,
            uid: _slugid2['default'].nice()
          });

          return ane;
        });

        entries.forEach(function (ne) {
          newOptions[ne.serverUidKey] = ne;
        });

        return newOptions;
      }

      return prepareNewEntries;
    }()
  }, {
    key: 'serverUidKey',
    value: function () {
      function serverUidKey(server, uid) {
        /**
         * Create a key for a server and uid
         */
        return String(server) + '/' + String(uid);
      }

      return serverUidKey;
    }()
  }, {
    key: 'requestTilesetLists',
    value: function () {
      function requestTilesetLists() {
        var _this3 = this;

        var datatypesQuery = null;

        if (this.props.datatype) {
          datatypesQuery = 'dt=' + String(this.props.datatype);
        } else {
          var _ref;

          var datatypes = new _set2['default']((_ref = []).concat.apply(_ref, (0, _toConsumableArray3['default'])(this.augmentedTracksInfo.filter(function (x) {
            return x.datatype;
          }).filter(function (x) {
            return x.orientation === _this3.props.orientation || _this3.props.orientation === '1d-vertical' && x.orientation === '1d-horizontal';
          }).map(function (x) {
            return x.datatype;
          }))));

          datatypesQuery = [].concat((0, _toConsumableArray3['default'])(datatypes)).map(function (x) {
            return 'dt=' + String(x);
          }).join('&');
        }

        if (!this.props.trackSourceServers) {
          console.warn('No track source servers specified in the viewconf');
          return;
        }

        this.props.trackSourceServers.forEach(function (sourceServer) {
          _services.tileProxy.json(String(sourceServer) + '/tilesets/?limit=10000&' + String(datatypesQuery), function (error, data) {
            if (error) {
              console.error('ERROR:', error);
            } else {
              var newOptions = _this3.prepareNewEntries(sourceServer, data.results, _this3.state.options);
              var availableTilesetKeys = (0, _keys2['default'])(newOptions);
              var selectedUuid = _this3.state.selectedUuid;

              // if there isn't a selected tileset, select the first received one

              if (!selectedUuid) {
                selectedUuid = availableTilesetKeys.length ? [availableTilesetKeys[0]] : null;
                var selectedTileset = _this3.state.options[selectedUuid[0]];
                _this3.props.selectedTilesetChanged([selectedTileset]);
              }

              if (_this3.mounted) {
                _this3.setState({
                  selectedUuid: selectedUuid,
                  options: newOptions
                });
              }
            }
          }, _this3.props.pubSub);
        });
      }

      return requestTilesetLists;
    }()

    /**
     * Double clicked on an element. Should be selected
     * and this window will be closed.
     */

  }, {
    key: 'handleOptionDoubleClick',
    value: function () {
      function handleOptionDoubleClick(x /* , y */) {
        var value = this.state.options[x.target.value];
        this.props.onDoubleClick(value);
      }

      return handleOptionDoubleClick;
    }()
  }, {
    key: 'handleSelectedOptions',
    value: function () {
      function handleSelectedOptions(selectedOptions) {
        var selectedValues = [];
        var selectedTilesets = [];

        // I don't know why selectedOptions.map doesn't work
        for (var i = 0; i < selectedOptions.length; i++) {
          selectedValues.push(selectedOptions[i]);
          selectedTilesets.push(this.state.options[selectedOptions[i]]);
        }

        this.props.selectedTilesetChanged(selectedTilesets);

        this.setState({ selectedUuid: selectedValues });
      }

      return handleSelectedOptions;
    }()
  }, {
    key: 'handleSelect',
    value: function () {
      function handleSelect() {
        var selectedOptions = this.multiSelect.selectedOptions;

        var selectedOptionsList = [];

        for (var i = 0; i < selectedOptions.length; i++) {
          var selectedOption = selectedOptions[i];
          selectedOptionsList.push(selectedOption.value);
        }

        this.handleSelectedOptions(selectedOptionsList);
      }

      return handleSelect;
    }()
  }, {
    key: 'handleSearchChange',
    value: function () {
      function handleSearchChange() {
        var domElement = this.searchBox;

        this.setState({ filter: domElement.value });
      }

      return handleSearchChange;
    }()

    /*
     * Create the nested checkbox tree by partitioning the
     * list of available datasets according to their group
     *
     * @param {object} datasetsDict A dictionary of id -> tileset
     *  def mappings
     * @param {string} filter A string to filter the results by
     * @returns {array} A list of items that define the nested checkbox
     *  structure
     *  {
     *    'name': 'blah',
     *    'value': 'blah',
     *    'children': [],
     *  }
     */

  }, {
    key: 'partitionByGroup',
    value: function () {
      function partitionByGroup(datasetsDict, filter) {
        var itemsByGroup = {
          '': {
            name: '',
            value: '',
            children: []
          }
        };

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])((0, _keys2['default'])(datasetsDict)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var uuid = _step.value;

            var item = datasetsDict[uuid];

            if (!item.name.toLowerCase().includes(filter)) {
              continue;
            }

            if ('project_name' in item) {
              var _group = item.project_name;

              if (!(_group in itemsByGroup)) {
                itemsByGroup[_group] = {
                  value: _group,
                  label: _group,
                  children: []
                };
              }

              itemsByGroup[_group].children.push({
                label: item.name,
                value: uuid
              });
            } else {
              itemsByGroup[''].children.push({
                label: item.name,
                value: uuid
              });
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var allItems = itemsByGroup[''].children;
        // coollapse the group lists into one list of objects
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])((0, _keys2['default'])(itemsByGroup)), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var group = _step2.value;

            if (group !== '') {
              itemsByGroup[group].children.sort(function (a, b) {
                return a.label.toLowerCase().localeCompare(b.label.toLowerCase(), 'en');
              });

              allItems.push(itemsByGroup[group]);
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        allItems.sort(function (a, b) {
          return a.label.toLowerCase().localeCompare(b.label.toLowerCase(), 'en');
        });

        return allItems;
      }

      return partitionByGroup;
    }()
  }, {
    key: 'handleChecked',
    value: function () {
      function handleChecked(checked) {
        this.handleSelectedOptions(checked);

        this.setState({ checked: checked });
      }

      return handleChecked;
    }()
  }, {
    key: 'handleExpanded',
    value: function () {
      function handleExpanded(expanded) {
        this.setState({ expanded: expanded });
      }

      return handleExpanded;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this4 = this;

        var optionsList = [];
        for (var key in this.state.options) {
          optionsList.push(this.state.options[key]);
        }

        var nestedItems = this.partitionByGroup(this.state.options, this.state.filter);
        var svgStyle = {
          width: 15,
          height: 15,
          top: 2,
          right: 2,
          position: 'relative'
        };

        var halfSvgStyle = JSON.parse((0, _stringify2['default'])(svgStyle));
        halfSvgStyle.opacity = 0.5;

        var form = _react2['default'].createElement(
          'form',
          {
            onSubmit: function () {
              function onSubmit(evt) {
                evt.preventDefault();
              }

              return onSubmit;
            }()
          },
          _react2['default'].createElement(
            'div',
            { className: 'tileset-finder-search-bar' },
            _react2['default'].createElement(
              'span',
              { className: 'tileset-finder-label' },
              'Select tileset:'
            ),
            _react2['default'].createElement('input', {
              ref: function () {
                function ref(c) {
                  _this4.searchBox = c;
                }

                return ref;
              }(),
              className: 'tileset-finder-search-box',
              onChange: this.handleSearchChange.bind(this),
              placeholder: 'Search Term',
              type: 'text'
            })
          ),
          _react2['default'].createElement(
            'div',
            {
              className: 'tileset-finder-checkbox-tree TilesetFinder_tileset-finder-checkbox-tree-2MsEs'
            },
            _react2['default'].createElement(_reactCheckboxTree2['default'], {
              checked: this.state.checked,
              expanded: this.state.expanded,
              icons: {
                uncheck: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#square_o' })
                ),
                check: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#check_square_o' })
                ),
                halfCheck: _react2['default'].createElement(
                  'svg',
                  { style: halfSvgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#check_square_o' })
                ),
                leaf: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#file_o' })
                ),
                expandClose: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#chevron_right' })
                ),
                expandOpen: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#chevron_down' })
                ),
                parentClose: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#folder_o' })
                ),
                parentOpen: _react2['default'].createElement(
                  'svg',
                  { style: svgStyle },
                  _react2['default'].createElement('use', { xlinkHref: '#folder_open_o' })
                )
              },
              nodes: nestedItems,
              onCheck: this.handleChecked.bind(this),
              onExpand: this.handleExpanded.bind(this)
            })
          )
        );

        return _react2['default'].createElement(
          'div',
          null,
          form
        );
      }

      return render;
    }()
  }]);
  return TilesetFinder;
}(_react2['default'].Component);

// Configs


TilesetFinder.propTypes = {
  datatype: _propTypes2['default'].string,
  orientation: _propTypes2['default'].string,
  onDoubleClick: _propTypes2['default'].func,
  pubSub: _propTypes2['default'].object.isRequired,
  selectedTilesetChanged: _propTypes2['default'].func,
  trackSourceServers: _propTypes2['default'].array
};

exports['default'] = (0, _withPubSub2['default'])(TilesetFinder);

/***/ }),
/* 659 */
/***/ (function(module, exports, __nested_webpack_require_3463668__) {

/*! react-checkbox-tree - v1.5.1 | 2019 */
!function(e,t){  true?module.exports=t(__nested_webpack_require_3463668__(1)):0}(window,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=27)}([function(e,t,n){e.exports=n(96)()},function(t,n){t.exports=e},function(e,t,n){var r=n(16),o="object"==typeof self&&self&&self.Object===Object&&self,a=r||o||Function("return this")();e.exports=a},function(e,t,n){var r=n(41),o=n(47);e.exports=function(e,t){var n=o(e,t);return r(n)?n:void 0}},function(e,t,n){var r=n(31),o=n(32),a=n(33),i=n(34),c=n(35);function l(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}l.prototype.clear=r,l.prototype.delete=o,l.prototype.get=a,l.prototype.has=i,l.prototype.set=c,e.exports=l},function(e,t,n){var r=n(14);e.exports=function(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}},function(e,t,n){var r=n(12),o=n(43),a=n(44),i="[object Null]",c="[object Undefined]",l=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?c:i:l&&l in Object(e)?o(e):a(e)}},function(e,t,n){var r=n(3)(Object,"create");e.exports=r},function(e,t,n){var r=n(56);e.exports=function(e,t){var n=e.__data__;return r(t)?n["string"==typeof t?"string":"hash"]:n.map}},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,n){var r;
/*!
  Copyright (c) 2017 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
/*!
  Copyright (c) 2017 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
!function(){"use strict";var n={}.hasOwnProperty;function o(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var a=typeof r;if("string"===a||"number"===a)e.push(r);else if(Array.isArray(r)&&r.length){var i=o.apply(null,r);i&&e.push(i)}else if("object"===a)for(var c in r)n.call(r,c)&&r[c]&&e.push(c)}}return e.join(" ")}e.exports?(o.default=o,e.exports=o):void 0===(r=function(){return o}.apply(t,[]))||(e.exports=r)}()},function(e,t,n){var r=n(3)(n(2),"Map");e.exports=r},function(e,t,n){var r=n(2).Symbol;e.exports=r},function(e,t){var n=Array.isArray;e.exports=n},function(e,t){e.exports=function(e,t){return e===t||e!=e&&t!=t}},function(e,t,n){var r=n(6),o=n(17),a="[object AsyncFunction]",i="[object Function]",c="[object GeneratorFunction]",l="[object Proxy]";e.exports=function(e){if(!o(e))return!1;var t=r(e);return t==i||t==c||t==a||t==l}},function(e,t,n){(function(t){var n="object"==typeof t&&t&&t.Object===Object&&t;e.exports=n}).call(this,n(42))},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t){var n=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return n.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},function(e,t,n){var r=n(48),o=n(55),a=n(57),i=n(58),c=n(59);function l(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}l.prototype.clear=r,l.prototype.delete=o,l.prototype.get=a,l.prototype.has=i,l.prototype.set=c,e.exports=l},function(e,t,n){var r=n(60),o=n(63),a=n(64),i=1,c=2;e.exports=function(e,t,n,l,u,s){var p=n&i,f=e.length,d=t.length;if(f!=d&&!(p&&d>f))return!1;var h=s.get(e);if(h&&s.get(t))return h==t;var b=-1,y=!0,v=n&c?new r:void 0;for(s.set(e,t),s.set(t,e);++b<f;){var x=e[b],m=t[b];if(l)var g=p?l(m,x,b,t,e,s):l(x,m,b,e,t,s);if(void 0!==g){if(g)continue;y=!1;break}if(v){if(!o(t,function(e,t){if(!a(v,t)&&(x===e||u(x,e,n,l,s)))return v.push(t)})){y=!1;break}}else if(x!==m&&!u(x,m,n,l,s)){y=!1;break}}return s.delete(e),s.delete(t),y}},function(e,t,n){(function(e){var r=n(2),o=n(81),a=t&&!t.nodeType&&t,i=a&&"object"==typeof e&&e&&!e.nodeType&&e,c=i&&i.exports===a?r.Buffer:void 0,l=(c?c.isBuffer:void 0)||o;e.exports=l}).call(this,n(22)(e))},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){var r=n(83),o=n(84),a=n(85),i=a&&a.isTypedArray,c=i?o(i):r;e.exports=c},function(e,t){var n=9007199254740991;e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}},function(e,t,n){var r=n(28);e.exports=function(e,t){return r(e,t)}},function(e,t,n){var r=self.crypto||self.msCrypto;e.exports=function(e){e=e||21;for(var t="",n=r.getRandomValues(new Uint8Array(e));0<e--;)t+="Uint8ArdomValuesObj012345679BCDEFGHIJKLMNPQRSTWXYZ_cfghkpqvwxyz-"[63&n[e]];return t}},function(e,t,n){e.exports=n(98).default},function(e,t,n){var r=n(29),o=n(9);e.exports=function e(t,n,a,i,c){return t===n||(null==t||null==n||!o(t)&&!o(n)?t!=t&&n!=n:r(t,n,a,i,e,c))}},function(e,t,n){var r=n(30),o=n(20),a=n(65),i=n(69),c=n(91),l=n(13),u=n(21),s=n(23),p=1,f="[object Arguments]",d="[object Array]",h="[object Object]",b=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,y,v,x){var m=l(e),g=l(t),k=m?d:c(e),_=g?d:c(t),O=(k=k==f?h:k)==h,j=(_=_==f?h:_)==h,w=k==_;if(w&&u(e)){if(!u(t))return!1;m=!0,O=!1}if(w&&!O)return x||(x=new r),m||s(e)?o(e,t,n,y,v,x):a(e,t,k,n,y,v,x);if(!(n&p)){var C=O&&b.call(e,"__wrapped__"),E=j&&b.call(t,"__wrapped__");if(C||E){var P=C?e.value():e,N=E?t.value():t;return x||(x=new r),v(P,N,n,y,x)}}return!!w&&(x||(x=new r),i(e,t,n,y,v,x))}},function(e,t,n){var r=n(4),o=n(36),a=n(37),i=n(38),c=n(39),l=n(40);function u(e){var t=this.__data__=new r(e);this.size=t.size}u.prototype.clear=o,u.prototype.delete=a,u.prototype.get=i,u.prototype.has=c,u.prototype.set=l,e.exports=u},function(e,t){e.exports=function(){this.__data__=[],this.size=0}},function(e,t,n){var r=n(5),o=Array.prototype.splice;e.exports=function(e){var t=this.__data__,n=r(t,e);return!(n<0||(n==t.length-1?t.pop():o.call(t,n,1),--this.size,0))}},function(e,t,n){var r=n(5);e.exports=function(e){var t=this.__data__,n=r(t,e);return n<0?void 0:t[n][1]}},function(e,t,n){var r=n(5);e.exports=function(e){return r(this.__data__,e)>-1}},function(e,t,n){var r=n(5);e.exports=function(e,t){var n=this.__data__,o=r(n,e);return o<0?(++this.size,n.push([e,t])):n[o][1]=t,this}},function(e,t,n){var r=n(4);e.exports=function(){this.__data__=new r,this.size=0}},function(e,t){e.exports=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}},function(e,t){e.exports=function(e){return this.__data__.get(e)}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t,n){var r=n(4),o=n(11),a=n(19),i=200;e.exports=function(e,t){var n=this.__data__;if(n instanceof r){var c=n.__data__;if(!o||c.length<i-1)return c.push([e,t]),this.size=++n.size,this;n=this.__data__=new a(c)}return n.set(e,t),this.size=n.size,this}},function(e,t,n){var r=n(15),o=n(45),a=n(17),i=n(18),c=/^\[object .+?Constructor\]$/,l=Function.prototype,u=Object.prototype,s=l.toString,p=u.hasOwnProperty,f=RegExp("^"+s.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!a(e)||o(e))&&(r(e)?f:c).test(i(e))}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){var r=n(12),o=Object.prototype,a=o.hasOwnProperty,i=o.toString,c=r?r.toStringTag:void 0;e.exports=function(e){var t=a.call(e,c),n=e[c];try{e[c]=void 0;var r=!0}catch(e){}var o=i.call(e);return r&&(t?e[c]=n:delete e[c]),o}},function(e,t){var n=Object.prototype.toString;e.exports=function(e){return n.call(e)}},function(e,t,n){var r,o=n(46),a=(r=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";e.exports=function(e){return!!a&&a in e}},function(e,t,n){var r=n(2)["__core-js_shared__"];e.exports=r},function(e,t){e.exports=function(e,t){return null==e?void 0:e[t]}},function(e,t,n){var r=n(49),o=n(4),a=n(11);e.exports=function(){this.size=0,this.__data__={hash:new r,map:new(a||o),string:new r}}},function(e,t,n){var r=n(50),o=n(51),a=n(52),i=n(53),c=n(54);function l(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}l.prototype.clear=r,l.prototype.delete=o,l.prototype.get=a,l.prototype.has=i,l.prototype.set=c,e.exports=l},function(e,t,n){var r=n(7);e.exports=function(){this.__data__=r?r(null):{},this.size=0}},function(e,t){e.exports=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}},function(e,t,n){var r=n(7),o="__lodash_hash_undefined__",a=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;if(r){var n=t[e];return n===o?void 0:n}return a.call(t,e)?t[e]:void 0}},function(e,t,n){var r=n(7),o=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return r?void 0!==t[e]:o.call(t,e)}},function(e,t,n){var r=n(7),o="__lodash_hash_undefined__";e.exports=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=r&&void 0===t?o:t,this}},function(e,t,n){var r=n(8);e.exports=function(e){var t=r(this,e).delete(e);return this.size-=t?1:0,t}},function(e,t){e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},function(e,t,n){var r=n(8);e.exports=function(e){return r(this,e).get(e)}},function(e,t,n){var r=n(8);e.exports=function(e){return r(this,e).has(e)}},function(e,t,n){var r=n(8);e.exports=function(e,t){var n=r(this,e),o=n.size;return n.set(e,t),this.size+=n.size==o?0:1,this}},function(e,t,n){var r=n(19),o=n(61),a=n(62);function i(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new r;++t<n;)this.add(e[t])}i.prototype.add=i.prototype.push=o,i.prototype.has=a,e.exports=i},function(e,t){var n="__lodash_hash_undefined__";e.exports=function(e){return this.__data__.set(e,n),this}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}},function(e,t){e.exports=function(e,t){return e.has(t)}},function(e,t,n){var r=n(12),o=n(66),a=n(14),i=n(20),c=n(67),l=n(68),u=1,s=2,p="[object Boolean]",f="[object Date]",d="[object Error]",h="[object Map]",b="[object Number]",y="[object RegExp]",v="[object Set]",x="[object String]",m="[object Symbol]",g="[object ArrayBuffer]",k="[object DataView]",_=r?r.prototype:void 0,O=_?_.valueOf:void 0;e.exports=function(e,t,n,r,_,j,w){switch(n){case k:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case g:return!(e.byteLength!=t.byteLength||!j(new o(e),new o(t)));case p:case f:case b:return a(+e,+t);case d:return e.name==t.name&&e.message==t.message;case y:case x:return e==t+"";case h:var C=c;case v:var E=r&u;if(C||(C=l),e.size!=t.size&&!E)return!1;var P=w.get(e);if(P)return P==t;r|=s,w.set(e,t);var N=i(C(e),C(t),r,_,j,w);return w.delete(e),N;case m:if(O)return O.call(e)==O.call(t)}return!1}},function(e,t,n){var r=n(2).Uint8Array;e.exports=r},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}},function(e,t,n){var r=n(70),o=1,a=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,i,c,l){var u=n&o,s=r(e),p=s.length;if(p!=r(t).length&&!u)return!1;for(var f=p;f--;){var d=s[f];if(!(u?d in t:a.call(t,d)))return!1}var h=l.get(e);if(h&&l.get(t))return h==t;var b=!0;l.set(e,t),l.set(t,e);for(var y=u;++f<p;){var v=e[d=s[f]],x=t[d];if(i)var m=u?i(x,v,d,t,e,l):i(v,x,d,e,t,l);if(!(void 0===m?v===x||c(v,x,n,i,l):m)){b=!1;break}y||(y="constructor"==d)}if(b&&!y){var g=e.constructor,k=t.constructor;g!=k&&"constructor"in e&&"constructor"in t&&!("function"==typeof g&&g instanceof g&&"function"==typeof k&&k instanceof k)&&(b=!1)}return l.delete(e),l.delete(t),b}},function(e,t,n){var r=n(71),o=n(73),a=n(76);e.exports=function(e){return r(e,a,o)}},function(e,t,n){var r=n(72),o=n(13);e.exports=function(e,t,n){var a=t(e);return o(e)?a:r(a,n(e))}},function(e,t){e.exports=function(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}},function(e,t,n){var r=n(74),o=n(75),a=Object.prototype.propertyIsEnumerable,i=Object.getOwnPropertySymbols,c=i?function(e){return null==e?[]:(e=Object(e),r(i(e),function(t){return a.call(e,t)}))}:o;e.exports=c},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,o=0,a=[];++n<r;){var i=e[n];t(i,n,e)&&(a[o++]=i)}return a}},function(e,t){e.exports=function(){return[]}},function(e,t,n){var r=n(77),o=n(86),a=n(90);e.exports=function(e){return a(e)?r(e):o(e)}},function(e,t,n){var r=n(78),o=n(79),a=n(13),i=n(21),c=n(82),l=n(23),u=Object.prototype.hasOwnProperty;e.exports=function(e,t){var n=a(e),s=!n&&o(e),p=!n&&!s&&i(e),f=!n&&!s&&!p&&l(e),d=n||s||p||f,h=d?r(e.length,String):[],b=h.length;for(var y in e)!t&&!u.call(e,y)||d&&("length"==y||p&&("offset"==y||"parent"==y)||f&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||c(y,b))||h.push(y);return h}},function(e,t){e.exports=function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}},function(e,t,n){var r=n(80),o=n(9),a=Object.prototype,i=a.hasOwnProperty,c=a.propertyIsEnumerable,l=r(function(){return arguments}())?r:function(e){return o(e)&&i.call(e,"callee")&&!c.call(e,"callee")};e.exports=l},function(e,t,n){var r=n(6),o=n(9),a="[object Arguments]";e.exports=function(e){return o(e)&&r(e)==a}},function(e,t){e.exports=function(){return!1}},function(e,t){var n=9007199254740991,r=/^(?:0|[1-9]\d*)$/;e.exports=function(e,t){var o=typeof e;return!!(t=null==t?n:t)&&("number"==o||"symbol"!=o&&r.test(e))&&e>-1&&e%1==0&&e<t}},function(e,t,n){var r=n(6),o=n(24),a=n(9),i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1,e.exports=function(e){return a(e)&&o(e.length)&&!!i[r(e)]}},function(e,t){e.exports=function(e){return function(t){return e(t)}}},function(e,t,n){(function(e){var r=n(16),o=t&&!t.nodeType&&t,a=o&&"object"==typeof e&&e&&!e.nodeType&&e,i=a&&a.exports===o&&r.process,c=function(){try{var e=a&&a.require&&a.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=c}).call(this,n(22)(e))},function(e,t,n){var r=n(87),o=n(88),a=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return o(e);var t=[];for(var n in Object(e))a.call(e,n)&&"constructor"!=n&&t.push(n);return t}},function(e,t){var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},function(e,t,n){var r=n(89)(Object.keys,Object);e.exports=r},function(e,t){e.exports=function(e,t){return function(n){return e(t(n))}}},function(e,t,n){var r=n(15),o=n(24);e.exports=function(e){return null!=e&&o(e.length)&&!r(e)}},function(e,t,n){var r=n(92),o=n(11),a=n(93),i=n(94),c=n(95),l=n(6),u=n(18),s=u(r),p=u(o),f=u(a),d=u(i),h=u(c),b=l;(r&&"[object DataView]"!=b(new r(new ArrayBuffer(1)))||o&&"[object Map]"!=b(new o)||a&&"[object Promise]"!=b(a.resolve())||i&&"[object Set]"!=b(new i)||c&&"[object WeakMap]"!=b(new c))&&(b=function(e){var t=l(e),n="[object Object]"==t?e.constructor:void 0,r=n?u(n):"";if(r)switch(r){case s:return"[object DataView]";case p:return"[object Map]";case f:return"[object Promise]";case d:return"[object Set]";case h:return"[object WeakMap]"}return t}),e.exports=b},function(e,t,n){var r=n(3)(n(2),"DataView");e.exports=r},function(e,t,n){var r=n(3)(n(2),"Promise");e.exports=r},function(e,t,n){var r=n(3)(n(2),"Set");e.exports=r},function(e,t,n){var r=n(3)(n(2),"WeakMap");e.exports=r},function(e,t,n){"use strict";var r=n(97);function o(){}e.exports=function(){function e(e,t,n,o,a,i){if(i!==r){var c=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw c.name="Invariant Violation",c}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=o,n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";n.r(t);var r=n(10),o=n.n(r),a=n(25),i=n.n(a),c=n(26),l=n.n(c),u=n(0),s=n.n(u),p=n(1),f=n.n(p);function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function h(){return(h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function b(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function y(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function v(e,t){return!t||"object"!==d(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function x(e){return(x=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,t){return(m=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function g(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var k=function(e){function t(){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),v(this,x(t).apply(this,arguments))}var n,r,o;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&m(e,t)}(t,f.a.PureComponent),n=t,(r=[{key:"render",value:function(){var e=this.props,t=e.children,n=e.title,r=b(e,["children","title"]);return f.a.createElement("button",h({"aria-label":n,title:n,type:"button"},r),t)}}])&&y(n.prototype,r),o&&y(n,o),t}();g(k,"propTypes",{children:s.a.node.isRequired,title:s.a.string}),g(k,"defaultProps",{title:null});var _=k;function O(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function j(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var w=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.props=t,this.flatNodes=n}var t,n,r;return t=e,(n=[{key:"setProps",value:function(e){this.props=e}},{key:"clone",value:function(){var t=this,n={};return Object.keys(this.flatNodes).forEach(function(e){var r=t.flatNodes[e];n[e]=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){O(e,t,n[t])})}return e}({},r)}),new e(this.props,n)}},{key:"getNode",value:function(e){return this.flatNodes[e]}},{key:"flattenNodes",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(Array.isArray(e)&&0!==e.length){var o=this.props,a=o.disabled,i=o.noCascade;e.forEach(function(e,o){var c=t.nodeHasChildren(e);t.flatNodes[e.value]={label:e.label,value:e.value,children:e.children,parent:n,isParent:c,isLeaf:!c,showCheckbox:void 0===e.showCheckbox||e.showCheckbox,disabled:t.getDisabledState(e,n,a,i),treeDepth:r,index:o},t.flattenNodes(e.children,e,r+1)})}}},{key:"nodeHasChildren",value:function(e){return Array.isArray(e.children)&&e.children.length>0}},{key:"getDisabledState",value:function(e,t,n,r){return!!n||(!(r||!t.disabled)||Boolean(e.disabled))}},{key:"deserializeLists",value:function(e){var t=this,n=["checked","expanded"];Object.keys(this.flatNodes).forEach(function(e){n.forEach(function(n){t.flatNodes[e][n]=!1})}),n.forEach(function(n){e[n].forEach(function(e){void 0!==t.flatNodes[e]&&(t.flatNodes[e][n]=!0)})})}},{key:"serializeList",value:function(e){var t=this,n=[];return Object.keys(this.flatNodes).forEach(function(r){t.flatNodes[r][e]&&n.push(r)}),n}},{key:"expandAllNodes",value:function(e){var t=this;return Object.keys(this.flatNodes).forEach(function(n){t.flatNodes[n].isParent&&(t.flatNodes[n].expanded=e)}),this}},{key:"toggleChecked",value:function(e,t,n){var r=this,o=this.flatNodes[e.value];if(o.isLeaf||n){if(e.disabled)return this;this.toggleNode(e.value,"checked",t)}else o.children.forEach(function(e){r.toggleChecked(e,t,n)});return this}},{key:"toggleNode",value:function(e,t,n){return this.flatNodes[e][t]=n,this}}])&&j(t.prototype,n),r&&j(t,r),e}();function C(e){return(C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function E(){return(E=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function P(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function N(e,t){return!t||"object"!==C(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function S(e){return(S=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function A(e,t){return(A=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function T(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var R=function(e){function t(){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),N(this,S(t).apply(this,arguments))}var n,r,o;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&A(e,t)}(t,f.a.PureComponent),n=t,(r=[{key:"componentDidMount",value:function(){this.updateDeterminateProperty()}},{key:"componentDidUpdate",value:function(){this.updateDeterminateProperty()}},{key:"updateDeterminateProperty",value:function(){var e=this.props.indeterminate;this.checkbox.indeterminate=e}},{key:"render",value:function(){var e=this,t=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){T(e,t,n[t])})}return e}({},this.props);return delete t.indeterminate,f.a.createElement("input",E({},t,{ref:function(t){e.checkbox=t},type:"checkbox"}))}}])&&P(n.prototype,r),o&&P(n,o),t}();T(R,"propTypes",{indeterminate:s.a.bool}),T(R,"defaultProps",{indeterminate:!1});var I=R,L=s.a.shape({check:s.a.node,uncheck:s.a.node,halfCheck:s.a.node,expandClose:s.a.node,expandOpen:s.a.node,expandAll:s.a.node,collapseAll:s.a.node,parentClose:s.a.node,parentOpen:s.a.node,leaf:s.a.node}),z=s.a.shape({collapseAll:s.a.string.isRequired,expandAll:s.a.string.isRequired,toggle:s.a.string.isRequired});function q(e){return(q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function D(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function M(e){return(M=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function B(e,t){return(B=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function U(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var H=function(e){function t(e){var n,r,o;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),r=this,(n=!(o=M(t).call(this,e))||"object"!==q(o)&&"function"!=typeof o?F(r):o).onCheck=n.onCheck.bind(F(F(n))),n.onClick=n.onClick.bind(F(F(n))),n.onExpand=n.onExpand.bind(F(F(n))),n}var n,r,a;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&B(e,t)}(t,f.a.Component),n=t,(r=[{key:"onCheck",value:function(){var e=this.props,t=e.value,n=e.onCheck;n({value:t,checked:this.getCheckState({toggle:!0})})}},{key:"onClick",value:function(){var e=this.props,t=e.expandOnClick,n=e.isParent,r=e.value,o=e.onClick;n&&t&&this.onExpand(),o({value:r,checked:this.getCheckState({toggle:!1})})}},{key:"onExpand",value:function(){var e=this.props,t=e.expanded,n=e.value,r=e.onExpand;r({value:n,expanded:!t})}},{key:"getCheckState",value:function(e){var t=e.toggle,n=this.props,r=n.checked,o=n.optimisticToggle;return!(0!==r||!t)||(1===r&&!t||2===r&&o)}},{key:"renderCollapseButton",value:function(){var e=this.props,t=e.expandDisabled,n=e.isLeaf,r=e.lang;return n?f.a.createElement("span",{className:"rct-collapse"},f.a.createElement("span",{className:"rct-icon"})):f.a.createElement(_,{className:"rct-collapse rct-collapse-btn",disabled:t,title:r.toggle,onClick:this.onExpand},this.renderCollapseIcon())}},{key:"renderCollapseIcon",value:function(){var e=this.props,t=e.expanded,n=e.icons,r=n.expandClose,o=n.expandOpen;return t?o:r}},{key:"renderCheckboxIcon",value:function(){var e=this.props,t=e.checked,n=e.icons,r=n.uncheck,o=n.check,a=n.halfCheck;return 0===t?r:1===t?o:a}},{key:"renderNodeIcon",value:function(){var e=this.props,t=e.expanded,n=e.icon,r=e.icons,o=r.leaf,a=r.parentClose,i=r.parentOpen,c=e.isLeaf;return null!==n?n:c?o:t?i:a}},{key:"renderBareLabel",value:function(e){var t=this.props,n=t.onClick,r=t.title,o=null!==n;return f.a.createElement("span",{className:"rct-bare-label",title:r},o?f.a.createElement("span",{className:"rct-node-clickable",onClick:this.onClick,onKeyPress:this.onClick,role:"button",tabIndex:0},e):e)}},{key:"renderCheckboxLabel",value:function(e){var t=this.props,n=t.checked,r=t.disabled,o=t.title,a=t.treeId,i=t.value,c=null!==t.onClick,l="".concat(a,"-").concat(String(i).split(" ").join("_")),u=[f.a.createElement("label",{key:0,htmlFor:l,title:o},f.a.createElement(I,{checked:1===n,disabled:r,id:l,indeterminate:2===n,onClick:this.onCheck,onChange:function(){}}),f.a.createElement("span",{className:"rct-checkbox"},this.renderCheckboxIcon()),c?null:e)];return c&&u.push(f.a.createElement("span",{key:1,className:"rct-node-clickable",onClick:this.onClick,onKeyPress:this.onClick,role:"link",tabIndex:0},e)),u}},{key:"renderLabel",value:function(){var e=this.props,t=e.label,n=e.showCheckbox,r=[e.showNodeIcon?f.a.createElement("span",{key:0,className:"rct-node-icon"},this.renderNodeIcon()):null,f.a.createElement("span",{key:1,className:"rct-title"},t)];return n?this.renderCheckboxLabel(r):this.renderBareLabel(r)}},{key:"renderChildren",value:function(){return this.props.expanded?this.props.children:null}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.disabled,r=e.expanded,a=e.isLeaf,i=o()({"rct-node":!0,"rct-node-leaf":a,"rct-node-parent":!a,"rct-node-expanded":!a&&r,"rct-node-collapsed":!a&&!r,"rct-disabled":n},t);return f.a.createElement("li",{className:i},f.a.createElement("span",{className:"rct-text"},this.renderCollapseButton(),this.renderLabel()),this.renderChildren())}}])&&D(n.prototype,r),a&&D(n,a),t}();U(H,"propTypes",{checked:s.a.number.isRequired,disabled:s.a.bool.isRequired,expandDisabled:s.a.bool.isRequired,expanded:s.a.bool.isRequired,icons:L.isRequired,isLeaf:s.a.bool.isRequired,isParent:s.a.bool.isRequired,label:s.a.node.isRequired,lang:z.isRequired,optimisticToggle:s.a.bool.isRequired,showNodeIcon:s.a.bool.isRequired,treeId:s.a.string.isRequired,value:s.a.oneOfType([s.a.string,s.a.number]).isRequired,onCheck:s.a.func.isRequired,onExpand:s.a.func.isRequired,children:s.a.node,className:s.a.string,expandOnClick:s.a.bool,icon:s.a.node,showCheckbox:s.a.bool,title:s.a.string,onClick:s.a.func}),U(H,"defaultProps",{children:null,className:null,expandOnClick:!1,icon:null,showCheckbox:!0,title:null,onClick:function(){}});var V=H,$=s.a.oneOfType([s.a.arrayOf(s.a.string),s.a.arrayOf(s.a.number)]);function W(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var J={label:s.a.node.isRequired,value:s.a.oneOfType([s.a.string,s.a.number]).isRequired,disabled:s.a.bool,icon:s.a.node,showCheckbox:s.a.bool,title:s.a.string},K=s.a.oneOfType([s.a.shape(J),s.a.shape(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){W(e,t,n[t])})}return e}({},J,{children:s.a.arrayOf(J).isRequired}))]);function G(e){return(G="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Y(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){te(e,t,n[t])})}return e}function Q(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function X(e){return(X=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function Z(e,t){return(Z=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function ee(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function te(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var ne=function(e){function t(e){var n,r,o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),r=this,n=!(o=X(t).call(this,e))||"object"!==G(o)&&"function"!=typeof o?ee(r):o;var a=new w(e);return a.flattenNodes(e.nodes),a.deserializeLists({checked:e.checked,expanded:e.expanded}),n.state={id:e.id||"rct-".concat(l()(7)),model:a,prevProps:e},n.onCheck=n.onCheck.bind(ee(ee(n))),n.onExpand=n.onExpand.bind(ee(ee(n))),n.onNodeClick=n.onNodeClick.bind(ee(ee(n))),n.onExpandAll=n.onExpandAll.bind(ee(ee(n))),n.onCollapseAll=n.onCollapseAll.bind(ee(ee(n))),n}var n,r,a;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Z(e,t)}(t,f.a.Component),n=t,a=[{key:"getDerivedStateFromProps",value:function(e,t){var n=t.model,r=t.prevProps,o=e.disabled,a=e.id,c=e.nodes,l=Y({},t,{prevProps:e});return n.setProps(e),i()(r.nodes,c)&&r.disabled===o||n.flattenNodes(c),null!==a&&(l=Y({},l,{id:a})),n.deserializeLists({checked:e.checked,expanded:e.expanded}),l}}],(r=[{key:"onCheck",value:function(e){var t=this.props,n=t.noCascade,r=t.onCheck,o=this.state.model.clone(),a=o.getNode(e.value);o.toggleChecked(e,e.checked,n),r(o.serializeList("checked"),Y({},a,e))}},{key:"onExpand",value:function(e){var t=this.props.onExpand,n=this.state.model.clone(),r=n.getNode(e.value);n.toggleNode(e.value,"expanded",e.expanded),t(n.serializeList("expanded"),Y({},r,e))}},{key:"onNodeClick",value:function(e){(0,this.props.onClick)(Y({},this.state.model.getNode(e.value),e))}},{key:"onExpandAll",value:function(){this.expandAllNodes()}},{key:"onCollapseAll",value:function(){this.expandAllNodes(!1)}},{key:"expandAllNodes",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];(0,this.props.onExpand)(this.state.model.clone().expandAllNodes(e).serializeList("expanded"))}},{key:"determineShallowCheckState",value:function(e,t){var n=this.state.model.getNode(e.value);return n.isLeaf||t?n.checked?1:0:this.isEveryChildChecked(e)?1:this.isSomeChildChecked(e)?2:0}},{key:"isEveryChildChecked",value:function(e){var t=this;return e.children.every(function(e){return 1===t.state.model.getNode(e.value).checkState})}},{key:"isSomeChildChecked",value:function(e){var t=this;return e.children.some(function(e){return t.state.model.getNode(e.value).checkState>0})}},{key:"renderTreeNodes",value:function(e){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=this.props,a=o.expandDisabled,i=o.expandOnClick,c=o.icons,l=o.lang,u=o.noCascade,s=o.onClick,p=o.onlyLeafCheckboxes,d=o.optimisticToggle,h=o.showNodeTitle,b=o.showNodeIcon,y=this.state,v=y.id,x=y.model,m=t.defaultProps.icons,g=e.map(function(e){var t=e.value,o=x.getNode(e.value),y=o.isParent?n.renderTreeNodes(e.children,e):null;o.checkState=n.determineShallowCheckState(e,u);var g=p?o.isLeaf:o.showCheckbox;return!r.value||x.getNode(r.value).expanded?f.a.createElement(V,{key:t,checked:o.checkState,className:e.className,disabled:o.disabled,expandDisabled:a,expandOnClick:i,expanded:o.expanded,icon:e.icon,icons:Y({},m,c),label:e.label,lang:l,optimisticToggle:d,isLeaf:o.isLeaf,isParent:o.isParent,showCheckbox:g,showNodeIcon:b,title:h?e.title||e.label:e.title,treeId:v,value:e.value,onCheck:n.onCheck,onClick:s&&n.onNodeClick,onExpand:n.onExpand},y):null});return f.a.createElement("ol",null,g)}},{key:"renderExpandAll",value:function(){var e=this.props,t=e.icons,n=t.expandAll,r=t.collapseAll,o=e.lang;return e.showExpandAll?f.a.createElement("div",{className:"rct-options"},f.a.createElement(_,{className:"rct-option rct-option-expand-all",title:o.expandAll,onClick:this.onExpandAll},n),f.a.createElement(_,{className:"rct-option rct-option-collapse-all",title:o.collapseAll,onClick:this.onCollapseAll},r)):null}},{key:"renderHiddenInput",value:function(){var e=this.props,t=e.name,n=e.nameAsArray;return void 0===t?null:n?this.renderArrayHiddenInput():this.renderJoinedHiddenInput()}},{key:"renderArrayHiddenInput",value:function(){var e=this.props,t=e.checked,n=e.name;return t.map(function(e){var t="".concat(n,"[]");return f.a.createElement("input",{key:e,name:t,type:"hidden",value:e})})}},{key:"renderJoinedHiddenInput",value:function(){var e=this.props,t=e.checked,n=e.name,r=t.join(",");return f.a.createElement("input",{name:n,type:"hidden",value:r})}},{key:"render",value:function(){var e=this.props,t=e.disabled,n=e.nodes,r=e.nativeCheckboxes,a=this.renderTreeNodes(n),i=o()({"react-checkbox-tree":!0,"rct-disabled":t,"rct-native-display":r});return f.a.createElement("div",{className:i},this.renderExpandAll(),this.renderHiddenInput(),a)}}])&&Q(n.prototype,r),a&&Q(n,a),t}();te(ne,"propTypes",{nodes:s.a.arrayOf(K).isRequired,checked:$,disabled:s.a.bool,expandDisabled:s.a.bool,expandOnClick:s.a.bool,expanded:$,icons:L,id:s.a.string,lang:z,name:s.a.string,nameAsArray:s.a.bool,nativeCheckboxes:s.a.bool,noCascade:s.a.bool,onlyLeafCheckboxes:s.a.bool,optimisticToggle:s.a.bool,showExpandAll:s.a.bool,showNodeIcon:s.a.bool,showNodeTitle:s.a.bool,onCheck:s.a.func,onClick:s.a.func,onExpand:s.a.func}),te(ne,"defaultProps",{checked:[],disabled:!1,expandDisabled:!1,expandOnClick:!1,expanded:[],icons:{check:f.a.createElement("span",{className:"rct-icon rct-icon-check"}),uncheck:f.a.createElement("span",{className:"rct-icon rct-icon-uncheck"}),halfCheck:f.a.createElement("span",{className:"rct-icon rct-icon-half-check"}),expandClose:f.a.createElement("span",{className:"rct-icon rct-icon-expand-close"}),expandOpen:f.a.createElement("span",{className:"rct-icon rct-icon-expand-open"}),expandAll:f.a.createElement("span",{className:"rct-icon rct-icon-expand-all"}),collapseAll:f.a.createElement("span",{className:"rct-icon rct-icon-collapse-all"}),parentClose:f.a.createElement("span",{className:"rct-icon rct-icon-parent-close"}),parentOpen:f.a.createElement("span",{className:"rct-icon rct-icon-parent-open"}),leaf:f.a.createElement("span",{className:"rct-icon rct-icon-leaf"})},id:null,lang:{collapseAll:"Collapse all",expandAll:"Expand all",toggle:"Toggle"},name:void 0,nameAsArray:!1,nativeCheckboxes:!1,noCascade:!1,onlyLeafCheckboxes:!1,optimisticToggle:!0,showExpandAll:!1,showNodeIcon:!0,showNodeTitle:!1,onCheck:function(){},onClick:null,onExpand:function(){}});t.default=ne}])});

/***/ }),
/* 660 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),
/* 661 */
/***/ (function(module, exports, __nested_webpack_require_3503062__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3503062__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3503062__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3503062__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3503062__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3503062__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_3503062__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3503062__(1);

var _react2 = _interopRequireDefault(_react);

var _configs = __nested_webpack_require_3503062__(11);

var _utils = __nested_webpack_require_3503062__(10);

__nested_webpack_require_3503062__(662);

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

// Utils
var PlotTypeChooser = function (_React$Component) {
  (0, _inherits3['default'])(PlotTypeChooser, _React$Component);

  function PlotTypeChooser(props) {
    (0, _classCallCheck3['default'])(this, PlotTypeChooser);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (PlotTypeChooser.__proto__ || (0, _getPrototypeOf2['default'])(PlotTypeChooser)).call(this, props));

    _this.DATATYPE_TO_TRACK_TYPE = (0, _configs.DATATYPE_TO_TRACK_TYPE)(_this.props.orientation);
    _this.AVAILABLE_TRACK_TYPES = (0, _configs.AVAILABLE_TRACK_TYPES)(_this.props.datatypes, _this.props.orientation);

    _this.state = {
      selectedPlotType: _this.AVAILABLE_TRACK_TYPES[0]
    };
    return _this;
  }

  // eslint-disable-next-line camelcase


  (0, _createClass3['default'])(PlotTypeChooser, [{
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(newProps) {
        this.AVAILABLE_TRACK_TYPES = (0, _configs.AVAILABLE_TRACK_TYPES)(newProps.datatypes, this.props.orientation);

        if (!this.AVAILABLE_TRACK_TYPES) {
          return;
        }

        if (!newProps.allTracksSameDatatype) {
          return;
        }

        if (this.AVAILABLE_TRACK_TYPES.length > 0) {
          if (!this.AVAILABLE_TRACK_TYPES.includes(this.state.selectedPlotType)) {
            var defaultTrackType = (0, _utils.getDefaultTrackForDatatype)(newProps.datatypes[0][0], this.props.position, this.AVAILABLE_TRACK_TYPES);
            this.handlePlotTypeSelected(defaultTrackType);
          }
        } else {
          // no available track types
          // this could be because the datatype is unknown
          // or because there's multiple different datatypes
          // that don't have common track types
        }
      }

      return UNSAFE_componentWillReceiveProps;
    }()
  }, {
    key: 'handlePlotTypeSelected',
    value: function () {
      function handlePlotTypeSelected(key) {
        this.setState({
          selectedPlotType: key
        });

        this.props.onPlotTypeSelected(key.type);
      }

      return handlePlotTypeSelected;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var AVAILABLE_TRACK_TYPES_LIST = 'No plot types available for track';
        var trackTypeToInfo = {};

        _configs.TRACKS_INFO.forEach(function (ti) {
          trackTypeToInfo[ti.type] = ti;
        });

        if (this.AVAILABLE_TRACK_TYPES) {
          AVAILABLE_TRACK_TYPES_LIST = this.AVAILABLE_TRACK_TYPES.sort(function (a, b) {
            return a.type < b.type;
          }).map(function (x) {
            var thumbnail = trackTypeToInfo[x.type].thumbnail;
            var plotTypeClass = _this2.state.selectedPlotType.type === x.type ? 'plot-type-item plot-type-selected' : 'plot-type-item';
            var imgTag = trackTypeToInfo[x.type].thumbnail ? _react2['default'].createElement('div', {
              className: 'track-thumbnail'
              // eslint-disable-next-line react/no-danger
              , dangerouslySetInnerHTML: { __html: thumbnail.outerHTML }
            }) : _react2['default'].createElement(
              'div',
              { className: 'track-thumbnail' },
              _react2['default'].createElement('svg', { height: 20, width: 30 })
            );
            return _react2['default'].createElement(
              'li',
              {
                key: x.type,
                className: plotTypeClass,
                onClick: function () {
                  function onClick(e) {
                    _this2.setState({ selectedPlotType: x });
                    _this2.props.onPlotTypeSelected(x.type);
                  }

                  return onClick;
                }(),
                style: { listStyle: 'none', paddingLeft: 5, paddingBottom: 0 }
              },
              imgTag,
              _react2['default'].createElement(
                'span',
                { style: { verticalAlign: 'middle' } },
                x.type
              )
            );
          });
        }

        return _react2['default'].createElement(
          'div',
          null,
          AVAILABLE_TRACK_TYPES_LIST.length > 0 && this.props.allTracksSameDatatype && _react2['default'].createElement(
            'div',
            { className: 'plot-type-container' },
            AVAILABLE_TRACK_TYPES_LIST
          ),
          !this.props.allTracksSameDatatype && _react2['default'].createElement(
            'div',
            { className: 'plot-type-container-empty' },
            'Datasets with multiple datatypes chosen. They will be added with their default track types.'
          )
        );
      }

      return render;
    }()
  }]);
  return PlotTypeChooser;
}(_react2['default'].Component);

// Styles


// Configs


PlotTypeChooser.propTypes = {
  allTracksSameDatatype: _propTypes2['default'].bool,
  datatypes: _propTypes2['default'].array,
  orientation: _propTypes2['default'].string,
  onPlotTypeSelected: _propTypes2['default'].func,
  position: _propTypes2['default'].string
};

exports['default'] = PlotTypeChooser;

/***/ }),
/* 662 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),
/* 663 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"collapse-toggle-icon":"AddTrackDialog-module_collapse-toggle-icon-1Of5_","collapsed":"AddTrackDialog-module_collapsed-1ifB1","modal-title":"AddTrackDialog-module_modal-title-1Atka","modal-container":"AddTrackDialog-module_modal-container-14d_4","modal":"AddTrackDialog-module_modal-bZqLI","modal-backdrop":"AddTrackDialog-module_modal-backdrop-ZrVQg","modal-dialog":"AddTrackDialog-module_modal-dialog-3bKDk"};

/***/ }),
/* 664 */
/***/ (function(module, exports, __nested_webpack_require_3510021__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3510021__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3510021__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3510021__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3510021__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_3510021__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_3510021__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3510021__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_3510021__(1);

var _react2 = _interopRequireDefault(_react);

var _mixwith = __nested_webpack_require_3510021__(81);

var _ContextMenuContainer = __nested_webpack_require_3510021__(96);

var _ContextMenuContainer2 = _interopRequireDefault(_ContextMenuContainer);

var _ContextMenuItem = __nested_webpack_require_3510021__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _SeriesListSubmenuMixin = __nested_webpack_require_3510021__(390);

var _SeriesListSubmenuMixin2 = _interopRequireDefault(_SeriesListSubmenuMixin);

var _SeriesListItems = __nested_webpack_require_3510021__(183);

var _configs = __nested_webpack_require_3510021__(11);

__nested_webpack_require_3510021__(68);

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

var _styleModuleImportMap = {
  '../styles/ContextMenu.module.scss': {
    'context-menu': 'ContextMenu-module_context-menu-2OwvL',
    'context-menu-dark': 'ContextMenu-module_context-menu-dark-2PO31',
    'context-menu-icon': 'ContextMenu-module_context-menu-icon-I4kiw',
    'context-menu-item': 'ContextMenu-module_context-menu-item-1HeVv',
    'context-menu-hr': 'ContextMenu-module_context-menu-hr-3yapb',
    'play-icon': 'ContextMenu-module_play-icon-R4pIO',
    'context-menu-span': 'ContextMenu-module_context-menu-span-8EUfZ',
    'context-menu-thumbnail': 'ContextMenu-module_context-menu-thumbnail-2vHLD',
    'context-menu-thumbnail-inline': 'ContextMenu-module_context-menu-thumbnail-inline-1iOcg'
  }
};

// Styles

var ConfigTrackMenu = function (_mix$with) {
  (0, _inherits3['default'])(ConfigTrackMenu, _mix$with);

  function ConfigTrackMenu(props) {
    (0, _classCallCheck3['default'])(this, ConfigTrackMenu);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ConfigTrackMenu.__proto__ || (0, _getPrototypeOf2['default'])(ConfigTrackMenu)).call(this, props));
    /**
     * A window that is opened when a user clicks on the track configuration icon.
     */


    _this.seriesRefs = {};
    _this.seriesListMenu = null;
    return _this;
  }

  (0, _createClass3['default'])(ConfigTrackMenu, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        (0, _get3['default'])(ConfigTrackMenu.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ConfigTrackMenu.prototype), 'componentDidMount', this).call(this);
      }

      return componentDidMount;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var styleNames = 'context-menu';
        if (this.props.theme === _configs.THEME_DARK) styleNames += ' context-menu-dark';

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this2.div = c;
              }

              return ref;
            }(),
            'data-menu-type': 'ConfigTrackMenu',
            style: {
              left: this.state.left,
              top: this.state.top
            },
            className: (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
          },
          (0, _SeriesListItems.getSeriesItems)(this.props.tracks, this.handleItemMouseEnter.bind(this), this.handleMouseLeave.bind(this), null),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              contextMenu: this,
              onClick: function () {
                function onClick() {
                  return _this2.props.onLockValueScale(_this2.props.tracks[0].uid);
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Lock Value Scale With'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              contextMenu: this,
              onClick: function () {
                function onClick() {
                  return _this2.props.onUnlockValueScale(_this2.props.tracks[0].uid);
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Unlock Value Scale'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              contextMenu: this,
              onClick: function () {
                function onClick() {
                  return _this2.props.onAddSeries(_this2.props.tracks[0].uid);
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Add Series'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  return _this2.props.onCloseTrack(_this2.props.tracks[0].uid);
                }

                return onClick;
              }()
            },
            'Close Track'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  _this2.props.onReplaceTrack(_this2.props.tracks[0].uid, _this2.props.trackOrientation);
                }

                return onClick;
              }()
            },
            'Replace Track'
          ),
          this.getSubmenu()
        );
      }

      return render;
    }()
  }]);
  return ConfigTrackMenu;
}((0, _mixwith.mix)(_ContextMenuContainer2['default'])['with'](_SeriesListSubmenuMixin2['default']));

exports['default'] = ConfigTrackMenu;

/***/ }),
/* 665 */
/***/ (function(module, exports, __nested_webpack_require_3517353__) {

"use strict";


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

var _values = __nested_webpack_require_3517353__(37);

var _values2 = _interopRequireDefault(_values);

var _keys = __nested_webpack_require_3517353__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getIterator2 = __nested_webpack_require_3517353__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _getPrototypeOf = __nested_webpack_require_3517353__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3517353__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3517353__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3517353__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3517353__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3517353__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_3517353__(1);

var _react2 = _interopRequireDefault(_react);

var _ContextMenuContainer2 = __nested_webpack_require_3517353__(96);

var _ContextMenuContainer3 = _interopRequireDefault(_ContextMenuContainer2);

var _ContextMenuItem = __nested_webpack_require_3517353__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _NestedContextMenu = __nested_webpack_require_3517353__(391);

var _NestedContextMenu2 = _interopRequireDefault(_NestedContextMenu);

var _configs = __nested_webpack_require_3517353__(11);

__nested_webpack_require_3517353__(68);

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

// Configs
var _styleModuleImportMap = {
  '../styles/ContextMenu.module.scss': {
    'context-menu': 'ContextMenu-module_context-menu-2OwvL',
    'context-menu-dark': 'ContextMenu-module_context-menu-dark-2PO31',
    'context-menu-icon': 'ContextMenu-module_context-menu-icon-I4kiw',
    'context-menu-item': 'ContextMenu-module_context-menu-item-1HeVv',
    'context-menu-hr': 'ContextMenu-module_context-menu-hr-3yapb',
    'play-icon': 'ContextMenu-module_play-icon-R4pIO',
    'context-menu-span': 'ContextMenu-module_context-menu-span-8EUfZ',
    'context-menu-thumbnail': 'ContextMenu-module_context-menu-thumbnail-2vHLD',
    'context-menu-thumbnail-inline': 'ContextMenu-module_context-menu-thumbnail-inline-1iOcg'
  }
};

// Styles

var SeriesListMenu = function (_ContextMenuContainer) {
  (0, _inherits3['default'])(SeriesListMenu, _ContextMenuContainer);

  function SeriesListMenu() {
    (0, _classCallCheck3['default'])(this, SeriesListMenu);
    return (0, _possibleConstructorReturn3['default'])(this, (SeriesListMenu.__proto__ || (0, _getPrototypeOf2['default'])(SeriesListMenu)).apply(this, arguments));
  }

  (0, _createClass3['default'])(SeriesListMenu, [{
    key: 'getConfigureSeriesMenu',
    value: function () {
      function getConfigureSeriesMenu(position, bbox, track) {
        var _this2 = this;

        var menuItems = {};

        // plugin tracks can offer their own options
        // if they clash with the default higlass options
        // they will override them
        var pluginOptionsInfo = window.higlassTracksByType && window.higlassTracksByType[track.type] && window.higlassTracksByType[track.type].config && window.higlassTracksByType[track.type].config.optionsInfo;

        if (pluginOptionsInfo) {
          var _iteratorNormalCompletion = true;
          var _didIteratorError = false;
          var _iteratorError = undefined;

          try {
            for (var _iterator = (0, _getIterator3['default'])((0, _keys2['default'])(pluginOptionsInfo)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
              var key = _step.value;

              _configs.OPTIONS_INFO[key] = pluginOptionsInfo[key];
            }
          } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion && _iterator['return']) {
                _iterator['return']();
              }
            } finally {
              if (_didIteratorError) {
                throw _iteratorError;
              }
            }
          }
        }

        if (!_configs.TRACKS_INFO_BY_TYPE[track.type] || !_configs.TRACKS_INFO_BY_TYPE[track.type].availableOptions) {
          return null;
        }

        var _loop = function () {
          function _loop(optionType) {
            if (optionType in _configs.OPTIONS_INFO) {
              menuItems[optionType] = { name: _configs.OPTIONS_INFO[optionType].name };

              // can we dynamically generate some options?
              // should be used if the options depend on tileset info or other current state
              if (_configs.OPTIONS_INFO[optionType].generateOptions) {
                var generatedOptions = _configs.OPTIONS_INFO[optionType].generateOptions(track);

                if (!menuItems[optionType].children) {
                  menuItems[optionType].children = {};
                }

                var _loop2 = function () {
                  function _loop2(generatedOption) {
                    var optionSelectorSettings = {
                      name: generatedOption.name,
                      value: generatedOption.value,
                      handler: function () {
                        function handler() {
                          track.options[optionType] = generatedOption.value;
                          _this2.props.onTrackOptionsChanged(track.uid, track.options);
                          _this2.props.closeMenu();
                        }

                        return handler;
                      }()
                    };

                    menuItems[optionType].children[generatedOption.value] = optionSelectorSettings;
                  }

                  return _loop2;
                }();

                var _iteratorNormalCompletion3 = true;
                var _didIteratorError3 = false;
                var _iteratorError3 = undefined;

                try {
                  for (var _iterator3 = (0, _getIterator3['default'])(generatedOptions), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                    var generatedOption = _step3.value;

                    _loop2(generatedOption);
                  }
                } catch (err) {
                  _didIteratorError3 = true;
                  _iteratorError3 = err;
                } finally {
                  try {
                    if (!_iteratorNormalCompletion3 && _iterator3['return']) {
                      _iterator3['return']();
                    }
                  } finally {
                    if (_didIteratorError3) {
                      throw _iteratorError3;
                    }
                  }
                }
              }

              if (_configs.OPTIONS_INFO[optionType].inlineOptions) {
                var _loop3 = function () {
                  function _loop3(inlineOptionKey) {
                    var inlineOption = _configs.OPTIONS_INFO[optionType].inlineOptions[inlineOptionKey];

                    // check if there's already available options (e.g.
                    // "Top right") for this option type (e.g. "Label
                    // position")
                    if (!menuItems[optionType].children) {
                      menuItems[optionType].children = {};
                    }

                    var optionSelectorSettings = {
                      name: inlineOption.name,
                      value: inlineOption.value
                      // missing handler to be filled in below
                    };

                    // is there a custom component available for picking this
                    // option type value (e.g. 'custom' color scale)
                    if (inlineOption.componentPickers && inlineOption.componentPickers[track.type]) {
                      optionSelectorSettings.handler = function () {
                        _this2.props.onConfigureTrack(track, inlineOption.componentPickers[track.type]);
                        _this2.props.closeMenu();
                      };
                    } else {
                      // the menu option defines a potential value for this option
                      // type (e.g. "top right")
                      optionSelectorSettings.handler = function () {
                        track.options[optionType] = inlineOption.value;
                        _this2.props.onTrackOptionsChanged(track.uid, track.options);
                        _this2.props.closeMenu();
                      };
                    }

                    menuItems[optionType].children[inlineOptionKey] = optionSelectorSettings;
                  }

                  return _loop3;
                }();

                // we can simply select this option from the menu
                for (var inlineOptionKey in _configs.OPTIONS_INFO[optionType].inlineOptions) {
                  _loop3(inlineOptionKey);
                }
              } else if (_configs.OPTIONS_INFO[optionType].componentPickers && _configs.OPTIONS_INFO[optionType].componentPickers[track.type]) {
                // there's an option picker registered
                menuItems[optionType].handler = function () {
                  _this2.props.onConfigureTrack(track, _configs.OPTIONS_INFO[optionType].componentPickers[track.type]);
                  _this2.props.closeMenu();
                };
              }
            }
          }

          return _loop;
        }();

        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = (0, _getIterator3['default'])(_configs.TRACKS_INFO_BY_TYPE[track.type].availableOptions), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var optionType = _step2.value;

            _loop(optionType);
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2['return']) {
              _iterator2['return']();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        return _react2['default'].createElement(_NestedContextMenu2['default'], {
          key: 'config-series-menu',
          closeMenu: this.props.closeMenu,
          menuItems: menuItems,
          orientation: this.state.orientation,
          parentBbox: bbox,
          position: position,
          theme: this.props.theme
        });
      }

      return getConfigureSeriesMenu;
    }()

    /**
     * Return a list of track types that can be used
     * with the data for this track
     *
     * @param {Object} position The position where to draw ths menu (e.g. {left: 42, top: 88})
     *
     * @param (Object) bbox
     *  The bounding box of the parent menu, used to determine whether
     *  to draw the child menu on the left or the right
     *
     * @param (Object) track The track definition for this series (as in the viewconf)
     */

  }, {
    key: 'getTrackTypeItems',
    value: function () {
      function getTrackTypeItems(position, bbox, track) {
        var _this3 = this;

        // get the datatype of the current track
        //

        // if we've loaded external track types, list them here
        if (window.higlassTracksByType) {
          // Extend `TRACKS_INFO_BY_TYPE` with the configs of plugin tracks.
          (0, _keys2['default'])(window.higlassTracksByType).forEach(function (pluginTrackType) {
            _configs.TRACKS_INFO_BY_TYPE[pluginTrackType] = window.higlassTracksByType[pluginTrackType].config;
          });
        }

        var datatype = track.datatype;


        var orientation = null;
        // make sure that this is a valid track type before trying to
        // look up other tracks that can substitute for it
        if (track.type in _configs.TRACKS_INFO_BY_TYPE) {
          if (!datatype) {
            datatype = _configs.TRACKS_INFO_BY_TYPE[track.type].datatype[0];
          }
          orientation = _configs.TRACKS_INFO_BY_TYPE[track.type].orientation;
        }

        // see which other tracks can display a similar datatype
        var availableTrackTypes = (0, _values2['default'])(_configs.TRACKS_INFO_BY_TYPE).filter(function (x) {
          return x.datatype;
        }).filter(function (x) {
          return x.orientation;
        }).filter(function (x) {
          return x.datatype.includes(datatype);
        }).filter(function (x) {
          return x.orientation === orientation;
        }).map(function (x) {
          return x.type;
        });

        var menuItems = {};

        var _loop4 = function () {
          function _loop4(i) {
            menuItems[availableTrackTypes[i]] = {
              value: availableTrackTypes[i],
              name: availableTrackTypes[i],
              handler: function () {
                function handler() {
                  _this3.props.onChangeTrackType(track.uid, availableTrackTypes[i]);
                }

                return handler;
              }()
            };
          }

          return _loop4;
        }();

        for (var i = 0; i < availableTrackTypes.length; i++) {
          _loop4(i);
        }

        return _react2['default'].createElement(_NestedContextMenu2['default'], {
          key: 'track-type-items',
          closeMenu: this.props.closeMenu,
          menuItems: menuItems,
          orientation: this.state.orientation,
          parentBbox: bbox,
          position: position,
          theme: this.props.theme
        });
      }

      return getTrackTypeItems;
    }()
  }, {
    key: 'getSubmenu',
    value: function () {
      function getSubmenu() {
        if (this.state.submenuShown) {
          // the bounding box of the element which initiated the subMenu
          // necessary so that we can position the submenu next to the initiating
          // element
          var bbox = this.state.submenuSourceBbox;
          var position = this.state.orientation === 'left' ? {
            left: this.state.left,
            top: bbox.top
          } : {
            left: this.state.left + bbox.width + 7,
            top: bbox.top
          };

          // When a submenu is requested, the onMouseEnter handler of the
          // item that requested it provides a structure containing the option
          // picked as well as some data associated with it
          // e.g. {"option": "configure-series", data: track}
          var subMenuData = this.state.submenuShown;
          var track = subMenuData.value;

          if (subMenuData.option === 'track-type') {
            return this.getTrackTypeItems(position, bbox, track);
          }
          return this.getConfigureSeriesMenu(position, bbox, track);
        }

        return _react2['default'].createElement('div', null);
      }

      return getSubmenu;
    }()
  }, {
    key: 'getDivideByMenuItem',
    value: function () {
      function getDivideByMenuItem() {
        var _this4 = this;

        if (this.props.series.data && this.props.series.data.type === 'divided') {
          var newData = {
            tilesetUid: this.props.series.data.children[0].tilesetUid,
            server: this.props.series.data.children[0].server
          };

          // this track is already being divided
          return _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  return _this4.props.onChangeTrackData(_this4.props.series.uid, newData);
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this4.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }(),
              className: 'ContextMenu-module_context-menu-item-1HeVv'
            },
            _react2['default'].createElement(
              'span',
              { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
              'Remove divisor'
            )
          );
        }

        return _react2['default'].createElement(
          _ContextMenuItem2['default'],
          {
            onClick: function () {
              function onClick() {
                return _this4.props.onAddDivisor(_this4.props.series);
              }

              return onClick;
            }(),
            onMouseEnter: function () {
              function onMouseEnter(e) {
                return _this4.handleOtherMouseEnter(e);
              }

              return onMouseEnter;
            }(),
            className: 'ContextMenu-module_context-menu-item-1HeVv'
          },
          _react2['default'].createElement(
            'span',
            { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
            'Divide by'
          )
        );
      }

      return getDivideByMenuItem;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {}

      return componentWillUnmount;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this5 = this;

        var exportDataMenuItem = null;

        if (_configs.TRACKS_INFO_BY_TYPE[this.props.series.type] && _configs.TRACKS_INFO_BY_TYPE[this.props.series.type].exportable) {
          exportDataMenuItem = _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  return _this5.props.onExportData(_this5.props.hostTrack.uid, _this5.props.track.uid);
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this5.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }(),
              className: 'ContextMenu-module_context-menu-item-1HeVv'
            },
            _react2['default'].createElement(
              'span',
              { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
              'Export Data'
            )
          );
        }

        // if a track can't be replaced, this.props.onAddSeries
        // will be null so we don't need to display the menu item
        var replaceSeriesItem = this.props.onAddSeries ? _react2['default'].createElement(
          _ContextMenuItem2['default'],
          {
            onClick: function () {
              function onClick() {
                _this5.props.onCloseTrack(_this5.props.series.uid);
                _this5.props.onAddSeries(_this5.props.hostTrack.uid);
              }

              return onClick;
            }(),
            onMouseEnter: function () {
              function onMouseEnter(e) {
                return _this5.handleOtherMouseEnter(e);
              }

              return onMouseEnter;
            }(),
            className: 'ContextMenu-module_context-menu-item-1HeVv'
          },
          _react2['default'].createElement(
            'span',
            { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
            'Replace Series'
          )
        ) : null;

        var styleNames = 'context-menu';
        if (this.props.theme === _configs.THEME_DARK) styleNames += ' context-menu-dark';

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this5.div = c;
              }

              return ref;
            }(),
            'data-menu-type': 'SeriesListMenu',
            onMouseLeave: this.props.handleMouseLeave,
            style: {
              left: this.state.left,
              top: this.state.top
            },
            className: (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
          },
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {}

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this5.handleItemMouseEnter(e, {
                    option: 'configure-series',
                    value: _this5.props.track
                  });
                }

                return onMouseEnter;
              }(),
              onMouseLeave: function () {
                function onMouseLeave(e) {
                  return _this5.handleMouseLeave(e);
                }

                return onMouseLeave;
              }()
            },
            'Configure Series',
            _react2['default'].createElement(
              'svg',
              { className: 'ContextMenu-module_play-icon-R4pIO' },
              _react2['default'].createElement('use', { xlinkHref: '#play' })
            )
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {}

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this5.handleItemMouseEnter(e, {
                    option: 'track-type',
                    value: _this5.props.track
                  });
                }

                return onMouseEnter;
              }(),
              onMouseLeave: function () {
                function onMouseLeave(e) {
                  return _this5.handleMouseLeave(e);
                }

                return onMouseLeave;
              }(),
              className: 'ContextMenu-module_context-menu-item-1HeVv'
            },
            _react2['default'].createElement(
              'span',
              { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
              'Track Type',
              _react2['default'].createElement(
                'svg',
                { className: 'ContextMenu-module_play-icon-R4pIO' },
                _react2['default'].createElement('use', { xlinkHref: '#play' })
              )
            )
          ),
          exportDataMenuItem,
          this.getDivideByMenuItem(),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: this.props.onCloseTrack,
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this5.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }(),
              className: 'ContextMenu-module_context-menu-item-1HeVv'
            },
            _react2['default'].createElement(
              'span',
              { className: 'ContextMenu-module_context-menu-span-8EUfZ' },
              'Close Series'
            )
          ),
          replaceSeriesItem,
          this.getSubmenu()
        );
      }

      return render;
    }()
  }]);
  return SeriesListMenu;
}(_ContextMenuContainer3['default']);

exports['default'] = SeriesListMenu;

/***/ }),
/* 666 */
/***/ (function(module, exports, __nested_webpack_require_3541160__) {

"use strict";


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

var _propTypes = __nested_webpack_require_3541160__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3541160__(1);

var _react2 = _interopRequireDefault(_react);

var _ContextMenuItem = __nested_webpack_require_3541160__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _SeriesListItems = __nested_webpack_require_3541160__(183);

__nested_webpack_require_3541160__(68);

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

var CloseTrackMenu = function CloseTrackMenu(props) {
  return _react2['default'].createElement(
    'div',
    null,
    (0, _SeriesListItems.getSeriesItems)(props.tracks, null, null, props.onCloseTrack),
    _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
    _react2['default'].createElement(
      _ContextMenuItem2['default'],
      { onClick: function () {
          function onClick() {
            return props.onCloseTrack(props.tracks[0].uid);
          }

          return onClick;
        }() },
      'Close all series'
    )
  );
};

// Styles


CloseTrackMenu.propTypes = {
  onCloseTrack: _propTypes2['default'].func.isRequired,
  tracks: _propTypes2['default'].array.isRequired
};

exports['default'] = CloseTrackMenu;

/***/ }),
/* 667 */
/***/ (function(module, exports, __nested_webpack_require_3542580__) {

"use strict";


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

var _react = __nested_webpack_require_3542580__(1);

var _react2 = _interopRequireDefault(_react);

var _reactSortableHoc = __nested_webpack_require_3542580__(125);

var _HorizontalTrack = __nested_webpack_require_3542580__(394);

var _HorizontalTrack2 = _interopRequireDefault(_HorizontalTrack);

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

var HorizontalItem = (0, _reactSortableHoc.SortableElement)(function (props) {
  return _react2['default'].createElement(_HorizontalTrack2['default'], {
    className: props.className,
    editable: props.editable,
    handleConfigTrack: props.handleConfigTrack,
    handleResizeTrack: props.handleResizeTrack,
    height: props.height,
    item: props.item,
    onAddSeries: props.onAddSeries,
    onCloseTrack: props.onCloseTrack,
    onCloseTrackMenuOpened: props.onCloseTrackMenuOpened,
    onConfigTrackMenuOpened: props.onConfigTrackMenuOpened,
    resizeHandles: props.resizeHandles,
    uid: props.uid,
    width: props.width
  });
});

exports['default'] = HorizontalItem;

/***/ }),
/* 668 */
/***/ (function(module, exports, __nested_webpack_require_3543774__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_3543774__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _extends2 = __nested_webpack_require_3543774__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _getPrototypeOf = __nested_webpack_require_3543774__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3543774__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3543774__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3543774__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3543774__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3543774__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _d3Drag = __nested_webpack_require_3543774__(84);

var _d3Selection = __nested_webpack_require_3543774__(0);

var _propTypes = __nested_webpack_require_3543774__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3543774__(1);

var _react2 = _interopRequireDefault(_react);

var _withTheme = __nested_webpack_require_3543774__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _configs = __nested_webpack_require_3543774__(11);

__nested_webpack_require_3543774__(669);

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

var _styleModuleImportMap = {
  '../styles/DraggableDiv.module.scss': {
    'top-right-handle': 'DraggableDiv-module_top-right-handle-oUk0R',
    'bottom-right-handle': 'DraggableDiv-module_bottom-right-handle-o7UYG',
    'top-left-handle': 'DraggableDiv-module_top-left-handle-R5Zui',
    'bottom-left-handle': 'DraggableDiv-module_bottom-left-handle-FO7d4',
    'top-draggable-handle': 'DraggableDiv-module_top-draggable-handle-3W5bP',
    'bottom-draggable-handle': 'DraggableDiv-module_bottom-draggable-handle-3olLp',
    'left-draggable-handle': 'DraggableDiv-module_left-draggable-handle-2gpow',
    'right-draggable-handle': 'DraggableDiv-module_right-draggable-handle-2Sriq',
    'draggable-div': 'DraggableDiv-module_draggable-div-2eWml',
    'top-draggable-handle-grabber': 'DraggableDiv-module_top-draggable-handle-grabber-2mVDE',
    'bottom-draggable-handle-grabber': 'DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k',
    'left-draggable-handle-grabber': 'DraggableDiv-module_left-draggable-handle-grabber-1Pqhc',
    'right-draggable-handle-grabber': 'DraggableDiv-module_right-draggable-handle-grabber-1mtC0'
  }
};

var DraggableDiv = function (_React$Component) {
  (0, _inherits3['default'])(DraggableDiv, _React$Component);

  function DraggableDiv(props) {
    (0, _classCallCheck3['default'])(this, DraggableDiv);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (DraggableDiv.__proto__ || (0, _getPrototypeOf2['default'])(DraggableDiv)).call(this, props));

    _this.dragTopRight = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragTopRightFunc.bind(_this));
    _this.dragTopLeft = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragTopLeftFunc.bind(_this));
    _this.dragBottomRight = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragBottomRightFunc.bind(_this));
    _this.dragBottomLeft = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragBottomLeftFunc.bind(_this));

    _this.dragBottom = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragBottomFunc.bind(_this));
    _this.dragTop = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragTopFunc.bind(_this));
    _this.dragLeft = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragLeftFunc.bind(_this));
    _this.dragRight = (0, _d3Drag.drag)().on('start', _this.dragStart.bind(_this)).on('drag', _this.dragRightFunc.bind(_this));

    _this.minWidth = 10;
    _this.minHeight = 10;
    _this.bottomHandleWidth = 20;

    _this.state = {
      uid: _this.props.uid,
      width: _this.props.width,
      height: _this.props.height,
      top: _this.props.top,
      left: _this.props.left
    };

    _this.domBody = (0, _d3Selection.select)('body').node();
    return _this;
  }

  /* -------------------------- Life Cycle Methods -------------------------- */

  (0, _createClass3['default'])(DraggableDiv, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        (0, _d3Selection.select)(this.bottomHandle).call(this.dragBottom);
        (0, _d3Selection.select)(this.topHandle).call(this.dragTop);

        (0, _d3Selection.select)(this.leftHandle).call(this.dragLeft);
        (0, _d3Selection.select)(this.rightHandle).call(this.dragRight);
      }

      return componentDidMount;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(newProps) {
        if ('width' in newProps) {
          this.setState({ width: newProps.width });
        }

        if ('height' in newProps) {
          this.setState({ height: newProps.height });
        }
      }

      return UNSAFE_componentWillReceiveProps;
    }()

    /* ---------------------------- Custom Methods ---------------------------- */

  }, {
    key: 'dragBottomFunc',
    value: function () {
      function dragBottomFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newHeight = this.dragStartHeight + (ms[1] - this.dragStartMousePos[1]);
        newHeight = newHeight > this.minHeight ? newHeight : this.minHeight;

        this.setState({ height: newHeight });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragBottomFunc;
    }()
  }, {
    key: 'dragLeftFunc',
    value: function () {
      function dragLeftFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newWidth = this.dragStartWidth - (ms[0] - this.dragStartMousePos[0]);
        newWidth = newWidth > this.minWidth ? newWidth : this.minWidth;

        var newLeft = this.dragStartLeft + ms[0] - this.dragStartMousePos[0];
        newLeft = newWidth > this.minWidth ? newLeft : this.dragStartLeft + this.dragStartWidth - this.minWidth;

        this.setState({
          left: newLeft,
          width: newWidth
        });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragLeftFunc;
    }()
  }, {
    key: 'dragTopFunc',
    value: function () {
      function dragTopFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newHeight = this.dragStartHeight - (ms[1] - this.dragStartMousePos[1]);
        newHeight = newHeight > this.minHeight ? newHeight : this.minHeight;

        var newTop = this.dragStartTop + ms[1] - this.dragStartMousePos[1];
        newTop = newHeight > this.minHeight ? newTop : this.dragStartTop + this.dragStartHeight - this.minHeight;

        this.setState({
          top: newTop,
          height: newHeight
        });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragTopFunc;
    }()
  }, {
    key: 'dragRightFunc',
    value: function () {
      function dragRightFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newWidth = this.dragStartWidth + (ms[0] - this.dragStartMousePos[0]);
        newWidth = newWidth > this.minWidth ? newWidth : this.minWidth;

        this.setState({
          width: newWidth
        });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragRightFunc;
    }()
  }, {
    key: 'dragBottomLeftFunc',
    value: function () {
      function dragBottomLeftFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newHeight = this.dragStartHeight + (ms[1] - this.dragStartMousePos[1]);
        newHeight = newHeight > this.minHeight ? newHeight : this.minHeight;

        var newWidth = this.dragStartWidth - (ms[0] - this.dragStartMousePos[0]);
        newWidth = newWidth > this.minWidth ? newWidth : this.minWidth;

        var newLeft = this.dragStartLeft + ms[0] - this.dragStartMousePos[0];
        newLeft = newWidth > this.minWidth ? newLeft : this.dragStartLeft + this.dragStartWidth - this.minWidth;

        this.setState({
          left: newLeft,
          width: newWidth,
          height: newHeight
        });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragBottomLeftFunc;
    }()
  }, {
    key: 'dragBottomRightFunc',
    value: function () {
      function dragBottomRightFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newWidth = this.dragStartWidth + (ms[0] - this.dragStartMousePos[0]);
        newWidth = newWidth > this.minWidth ? newWidth : this.minWidth;

        var newHeight = this.dragStartHeight + (ms[1] - this.dragStartMousePos[1]);
        newHeight = newHeight > this.minHeight ? newHeight : this.minHeight;

        this.setState({
          width: newWidth,
          height: newHeight
        });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragBottomRightFunc;
    }()
  }, {
    key: 'dragTopRightFunc',
    value: function () {
      function dragTopRightFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newHeight = this.dragStartHeight - (ms[1] - this.dragStartMousePos[1]);
        newHeight = newHeight > this.minHeight ? newHeight : this.minHeight;

        var newTop = this.dragStartTop + ms[1] - this.dragStartMousePos[1];
        newTop = newHeight > this.minHeight ? newTop : this.dragStartTop + this.dragStartHeight - this.minHeight;

        var newWidth = this.dragStartWidth + (ms[0] - this.dragStartMousePos[0]);
        newWidth = newWidth > this.minWidth ? newWidth : this.minWidth;

        this.setState({
          top: newTop,
          width: newWidth,
          height: newHeight
        });

        _d3Selection.event.sourceEvent.stopPropagation();
        this.sizeChanged();
      }

      return dragTopRightFunc;
    }()
  }, {
    key: 'dragTopLeftFunc',
    value: function () {
      function dragTopLeftFunc() {
        var ms = (0, _d3Selection.mouse)(this.domBody);

        var newWidth = this.dragStartWidth - (ms[0] - this.dragStartMousePos[0]);
        newWidth = newWidth > this.minWidth ? newWidth : this.minWidth;

        var newLeft = this.dragStartLeft + ms[0] - this.dragStartMousePos[0];
        newLeft = newWidth > this.minWidth ? newLeft : this.dragStartLeft + this.dragStartWidth - this.minWidth;

        var newHeight = this.dragStartHeight - (ms[1] - this.dragStartMousePos[1]);
        newHeight = newHeight > this.minHeight ? newHeight : this.minHeight;

        var newTop = this.dragStartTop + ms[1] - this.dragStartMousePos[1];
        newTop = newHeight > this.minHeight ? newTop : this.dragStartTop + this.dragStartHeight - this.minHeight;

        this.setState({
          top: newTop,
          left: newLeft,
          width: newWidth,
          height: newHeight
        });

        _d3Selection.event.sourceEvent.stopPropagation();

        this.sizeChanged();
      }

      return dragTopLeftFunc;
    }()
  }, {
    key: 'dragStart',
    value: function () {
      function dragStart() {
        this.dragStartMousePos = (0, _d3Selection.mouse)(this.domBody);

        this.dragStartWidth = this.state.width;
        this.dragStartHeight = this.state.height;

        this.dragStartTop = this.state.top;
        this.dragStartLeft = this.state.left;

        _d3Selection.event.sourceEvent.stopPropagation();
      }

      return dragStart;
    }()
  }, {
    key: 'sizeChanged',
    value: function () {
      function sizeChanged() {
        if (this.props.sizeChanged) {
          this.props.sizeChanged(this.state);
        }
      }

      return sizeChanged;
    }()
  }, {
    key: 'rotateClicked',
    value: function () {
      function rotateClicked() {
        this.props.trackRotated(this.state.uid);
      }

      return rotateClicked;
    }()
  }, {
    key: 'closeClicked',
    value: function () {
      function closeClicked() {
        this.props.trackClosed(this.state.uid);
      }

      return closeClicked;
    }()

    /* ------------------------------ Rendering ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var dragColor = this.props.theme === _configs.THEME_DARK ? 'white' : 'black';

        var divStyle = {
          top: this.state.top,
          left: this.state.left,
          width: this.state.width,
          height: this.state.height,
          opacity: this.props.opacity
        };

        var resizeWidth = 24;
        var resizeHeight = 24;

        var horizStyle = {
          left: this.state.width / 2 - resizeWidth / 2,
          width: resizeWidth
        };

        var vertStyle = {
          top: this.state.height / 2 - resizeHeight / 2,
          height: resizeHeight
        };

        var styles = {
          bottom: (0, _extends3['default'])({}, horizStyle, { bottom: 1 }),
          top: (0, _extends3['default'])({}, horizStyle, { top: 1 }),
          left: (0, _extends3['default'])({}, vertStyle, { left: 1 }),
          right: (0, _extends3['default'])({}, vertStyle, { right: 1 })
        };

        var resizeHandles = [].concat((0, _toConsumableArray3['default'])(this.props.resizeHandles)).map(function (x) {
          return _react2['default'].createElement(
            'div',
            {
              key: x,
              ref: function () {
                function ref(c) {
                  _this2[String(x) + 'Handle'] = c;
                }

                return ref;
              }(),
              style: styles[x],

              title: 'Resize track',
              className: (0, _getClassName3['default'])(String(x) + '-draggable-handle', _styleModuleImportMap)
            },
            _react2['default'].createElement('div', {
              style: { borderColor: dragColor },
              className: (0, _getClassName3['default'])(String(x) + '-draggable-handle-grabber', _styleModuleImportMap)
            })
          );
        });

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this2.divContainer = c;
              }

              return ref;
            }(),
            className: (this.props.className ? this.props.className + ' ' : '') + 'DraggableDiv-module_draggable-div-2eWml',
            style: divStyle
          },
          resizeHandles
        );
      }

      return render;
    }()
  }]);
  return DraggableDiv;
}(_react2['default'].Component);

DraggableDiv.propTypes = {
  className: _propTypes2['default'].string,
  height: _propTypes2['default'].number,
  left: _propTypes2['default'].number,
  opacity: _propTypes2['default'].number,
  resizeHandles: _propTypes2['default'].object,
  sizeChanged: _propTypes2['default'].func,
  top: _propTypes2['default'].number,
  trackClosed: _propTypes2['default'].func,
  trackRotated: _propTypes2['default'].func,
  uid: _propTypes2['default'].string,
  width: _propTypes2['default'].number,
  theme: _propTypes2['default'].symbol
};

exports['default'] = (0, _withTheme2['default'])(DraggableDiv);

/***/ }),
/* 669 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"top-right-handle":"DraggableDiv-module_top-right-handle-oUk0R","bottom-right-handle":"DraggableDiv-module_bottom-right-handle-o7UYG","top-left-handle":"DraggableDiv-module_top-left-handle-R5Zui","bottom-left-handle":"DraggableDiv-module_bottom-left-handle-FO7d4","top-draggable-handle":"DraggableDiv-module_top-draggable-handle-3W5bP","bottom-draggable-handle":"DraggableDiv-module_bottom-draggable-handle-3olLp","left-draggable-handle":"DraggableDiv-module_left-draggable-handle-2gpow","right-draggable-handle":"DraggableDiv-module_right-draggable-handle-2Sriq","draggable-div":"DraggableDiv-module_draggable-div-2eWml","top-draggable-handle-grabber":"DraggableDiv-module_top-draggable-handle-grabber-2mVDE","bottom-draggable-handle-grabber":"DraggableDiv-module_bottom-draggable-handle-grabber-GN1_k","left-draggable-handle-grabber":"DraggableDiv-module_left-draggable-handle-grabber-1Pqhc","right-draggable-handle-grabber":"DraggableDiv-module_right-draggable-handle-grabber-1mtC0"};

/***/ }),
/* 670 */
/***/ (function(module, exports, __nested_webpack_require_3560740__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3560740__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3560740__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3560740__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3560740__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3560740__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_3560740__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3560740__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_3560740__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _reactSortableHoc = __nested_webpack_require_3560740__(125);

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

var TrackArea = function (_React$Component) {
  (0, _inherits3['default'])(TrackArea, _React$Component);

  function TrackArea(props) {
    (0, _classCallCheck3['default'])(this, TrackArea);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (TrackArea.__proto__ || (0, _getPrototypeOf2['default'])(TrackArea)).call(this, props));

    _this.state = {
      controlsVisible: false
    };
    return _this;
  }

  (0, _createClass3['default'])(TrackArea, [{
    key: 'shouldComponentUpdate',
    value: function () {
      function shouldComponentUpdate() {
        return !this.resizing;
      }

      return shouldComponentUpdate;
    }()
  }, {
    key: 'handleMouseEnter',
    value: function () {
      function handleMouseEnter() {
        this.setState({
          controlsVisible: true
        });
      }

      return handleMouseEnter;
    }()
  }, {
    key: 'handleMouseLeave',
    value: function () {
      function handleMouseLeave() {
        this.setState({
          controlsVisible: false
        });
      }

      return handleMouseLeave;
    }()
  }, {
    key: 'handleMouseMove',
    value: function () {
      function handleMouseMove() {
        this.setState({
          controlsVisible: true
        });
      }

      return handleMouseMove;
    }()
  }, {
    key: 'getControls',
    value: function () {
      function getControls() {
        var _this2 = this;

        var Handle = null;

        if (this.moveable) {
          Handle = (0, _reactSortableHoc.SortableHandle)(function () {
            return _react2['default'].createElement(
              'svg',
              {
                className: 'no-zoom',
                height: '10px',
                onClick: function () {
                  function onClick() {}

                  return onClick;
                }(),
                style: _this2.getMoveImgStyle(),
                width: '10px'
              },
              _react2['default'].createElement('use', { xlinkHref: '#move' })
            );
          });
        } else {
          Handle = (0, _reactSortableHoc.SortableHandle)(function () {
            return _react2['default'].createElement('div', null);
          });
        }

        return _react2['default'].createElement(
          'div',
          {
            style: {
              position: 'absolute',
              backgroundColor: 'rgba(255,255,255,0.7)',
              right: '3px',
              top: '3px',
              pointerEvents: 'none',
              paddingLeft: '5px',
              paddingRight: '5px',
              borderRadius: '5px',
              border: '1px solid #dddddd'
            }
          },
          _react2['default'].createElement(Handle, null),
          _react2['default'].createElement(
            'svg',
            {
              ref: function () {
                function ref(c) {
                  _this2.imgConfig = c;
                }

                return ref;
              }(),
              className: 'no-zoom',
              height: '10px',
              onClick: function () {
                function onClick() {
                  var imgDom = _reactDom2['default'].findDOMNode(_this2.imgConfig);
                  var bbox = imgDom.getBoundingClientRect();
                  _this2.props.onConfigTrackMenuOpened(_this2.props.uid, bbox);
                }

                return onClick;
              }(),
              style: this.getSettingsImgStyle(),
              width: '10px'
            },
            _react2['default'].createElement('use', { xlinkHref: '#cog' })
          ),
          _react2['default'].createElement(
            'svg',
            {
              ref: function () {
                function ref(c) {
                  _this2.imgAdd = c;
                }

                return ref;
              }(),
              className: 'no-zoom',
              height: '10px',
              onClick: function () {
                function onClick() {
                  return _this2.props.onAddSeries(_this2.props.uid);
                }

                return onClick;
              }(),
              style: this.getAddImgStyle(),
              width: '10px'
            },
            _react2['default'].createElement('use', { xlinkHref: '#plus' })
          ),
          _react2['default'].createElement(
            'svg',
            {
              ref: function () {
                function ref(c) {
                  _this2.imgClose = c;
                }

                return ref;
              }(),
              className: 'no-zoom',
              height: '10px',
              onClick: function () {
                function onClick() {
                  var imgDom = _reactDom2['default'].findDOMNode(_this2.imgClose);
                  var bbox = imgDom.getBoundingClientRect();
                  _this2.props.onCloseTrackMenuOpened(_this2.props.uid, bbox);
                }

                return onClick;
              }(),
              style: this.getCloseImgStyle(),
              width: '10px'
            },
            _react2['default'].createElement('use', { xlinkHref: '#cross' })
          )
        );
      }

      return getControls;
    }()
  }]);
  return TrackArea;
}(_react2['default'].Component);

TrackArea.propTypes = {
  configMenuOpen: _propTypes2['default'].bool,
  onConfigTrackMenuOpened: _propTypes2['default'].func,
  onCloseTrackMenuOpened: _propTypes2['default'].func,
  onAddSeries: _propTypes2['default'].func,
  uid: _propTypes2['default'].string
};

exports['default'] = TrackArea;

/***/ }),
/* 671 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"horizontal-tiled-plot":"HorizontalTiledPlot-module_horizontal-tiled-plot-3EK65"};

/***/ }),
/* 672 */
/***/ (function(module, exports, __nested_webpack_require_3567688__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3567688__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3567688__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3567688__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3567688__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3567688__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3567688__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_3567688__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3567688__(1);

var _react2 = _interopRequireDefault(_react);

var _d3Brush = __nested_webpack_require_3567688__(83);

var _d3Selection = __nested_webpack_require_3567688__(0);

var _slugid = __nested_webpack_require_3567688__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _ListWrapper = __nested_webpack_require_3567688__(393);

var _ListWrapper2 = _interopRequireDefault(_ListWrapper);

var _VerticalItem = __nested_webpack_require_3567688__(673);

var _VerticalItem2 = _interopRequireDefault(_VerticalItem);

var _SortableList = __nested_webpack_require_3567688__(395);

var _SortableList2 = _interopRequireDefault(_SortableList);

var _utils = __nested_webpack_require_3567688__(10);

var _configs = __nested_webpack_require_3567688__(11);

var _VerticalTiledPlotModule = __nested_webpack_require_3567688__(674);

var _VerticalTiledPlotModule2 = _interopRequireDefault(_VerticalTiledPlotModule);

var _TiledPlotModule = __nested_webpack_require_3567688__(176);

var _TiledPlotModule2 = _interopRequireDefault(_TiledPlotModule);

var _TrackModule = __nested_webpack_require_3567688__(175);

var _TrackModule2 = _interopRequireDefault(_TrackModule);

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

// eslint-disable-line no-unused-vars

// eslint-disable-line no-unused-vars


// Configs
var _styleModuleImportMap = {
  'styles': {
    'vertical-tiled-plot': 'VerticalTiledPlot-module_vertical-tiled-plot-R3sb7'
  },
  'stylesPlot': {
    'tiled-plot': 'TiledPlot-module_tiled-plot-uFHiB',
    'horizontalList': 'TiledPlot-module_horizontalList-1c1P8',
    'list': 'TiledPlot-module_list-24zgV',
    'stylizedList': 'TiledPlot-module_stylizedList-Mt4JL',
    'stylizedItem': 'TiledPlot-module_stylizedItem-2bQBK',
    'stylizedHelper': 'TiledPlot-module_stylizedHelper-3IVEu',
    'horizontalItem': 'TiledPlot-module_horizontalItem-2-ZjU',
    'resizable-track': 'TiledPlot-module_resizable-track-2oLT9',
    'domain': 'TiledPlot-module_domain-qYw6K'
  },
  'stylesTrack': {
    'track-range-selection': 'Track-module_track-range-selection-1yrDf',
    'track-range-selection-active': 'Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-active-primary': 'Track-module_track-range-selection-active-primary-29M73 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-active-secondary': 'Track-module_track-range-selection-active-secondary-1s0t5 Track-module_track-range-selection-active-1oljJ Track-module_track-range-selection-1yrDf',
    'track-range-selection-group-inactive': 'Track-module_track-range-selection-group-inactive-YNRM4',
    'track-range-selection-group-brush-selection': 'Track-module_track-range-selection-group-brush-selection-2VYDl'
  }
}; // eslint-disable-line no-unused-vars


// Styles


// Utils

var VerticalTiledPlot = function (_React$Component) {
  (0, _inherits3['default'])(VerticalTiledPlot, _React$Component);

  function VerticalTiledPlot(props) {
    (0, _classCallCheck3['default'])(this, VerticalTiledPlot);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (VerticalTiledPlot.__proto__ || (0, _getPrototypeOf2['default'])(VerticalTiledPlot)).call(this, props));

    _this.brushBehavior = (0, _d3Brush.brushY)(true).on('start', _this.brushStarted.bind(_this)).on('brush', _this.brushed.bind(_this)).on('end', _this.brushedEnded.bind(_this));
    return _this;
  }

  /* -------------------------- Life Cycle Methods -------------------------- */

  (0, _createClass3['default'])(VerticalTiledPlot, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        if (this.props.isRangeSelectionActive) {
          this.addBrush();
        }
      }

      return componentDidMount;
    }()
  }, {
    key: 'shouldComponentUpdate',
    value: function () {
      function shouldComponentUpdate(nextProps, nextState) {
        if (this.rangeSelectionTriggered) {
          this.rangeSelectionTriggered = false;
          if (this.rangeSelectionTriggeredEnd && this.props.rangeSelection !== nextProps.rangeSelection) {
            this.moveBrush(nextProps.rangeSelection[0] ? nextProps.rangeSelection[0] : null, true);
          }
          this.rangeSelectionTriggeredEnd = false;
          return this.state !== nextState;
        }
        if (this.props.rangeSelection !== nextProps.rangeSelection) {
          var accessor = this.props.is1dRangeSelection ? 0 : 1;

          this.moveBrush(nextProps.rangeSelection[accessor] ? nextProps.rangeSelection[accessor] : null, nextProps.rangeSelectionEnd);
          return this.state !== nextState;
        }
        return true;
      }

      return shouldComponentUpdate;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate() {
        if (this.props.isRangeSelectionActive) {
          this.addBrush();
        } else {
          this.removeBrush();
        }
      }

      return componentDidUpdate;
    }()

    /* --------------------------- Getter / Setter ---------------------------- */

  }, {
    key: 'addBrush',


    /* ---------------------------- Custom Methods ---------------------------- */

    value: function () {
      function addBrush() {
        if (!this.brushEl || this.brushElAddedBefore === this.brushEl) {
          return;
        }

        if (this.brushElAddedBefore) {
          // Remove event listener on old element to avoid memory leaks
          this.brushElAddedBefore.on('.brush', null);
        }

        this.brushEl.call(this.brushBehavior);
        this.brushElAddedBefore = this.brushEl;

        (0, _utils.resetD3BrushStyle)(this.brushEl, _TrackModule2['default']['track-range-selection-group-brush-selection']);
      }

      return addBrush;
    }()
  }, {
    key: 'brushed',
    value: function () {
      function brushed() {
        // Need to reassign variable to check after reset
        var rangeSelectionMoved = this.rangeSelectionMoved;
        this.rangeSelectionMoved = false;

        if (!this.sourceEvent || !this.props.onRangeSelection || rangeSelectionMoved) return;

        this.rangeSelectionTriggered = true;
        this.props.onRangeSelection(_d3Selection.event.selection);
      }

      return brushed;
    }()
  }, {
    key: 'brushStarted',
    value: function () {
      function brushStarted() {
        if (!this.sourceEvent || !_d3Selection.event.selection) return;

        this.props.onRangeSelectionStart();
      }

      return brushStarted;
    }()
  }, {
    key: 'brushedEnded',
    value: function () {
      function brushedEnded() {
        if (!this.props.is1dRangeSelection) return;

        var rangeSelectionMovedEnd = this.rangeSelectionMovedEnd;
        this.rangeSelectionMovedEnd = false;

        // Brush end event with a selection
        if (_d3Selection.event.selection && _d3Selection.event.sourceEvent && this.props.onRangeSelection && !rangeSelectionMovedEnd) {
          this.rangeSelectionTriggered = true;
          this.rangeSelectionTriggeredEnd = true;
          this.props.onRangeSelectionEnd(_d3Selection.event.selection);
        }

        if (!_d3Selection.event.selection) {
          this.rangeSelectionTriggered = true;
          this.props.onRangeSelectionReset();
        }
      }

      return brushedEnded;
    }()
  }, {
    key: 'moveBrush',
    value: function () {
      function moveBrush(rangeSelection) {
        var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        if (!this.brushEl) {
          return;
        }

        var relRange = rangeSelection ? [this.props.scale(rangeSelection[0]), this.props.scale(rangeSelection[1])] : null;

        this.rangeSelectionMoved = true;
        this.rangeSelectionMovedEnd = true;
        if (animate) {
          this.brushEl.transition().call(this.brushBehavior.move, relRange);
        } else {
          this.brushEl.call(this.brushBehavior.move, relRange);
        }
      }

      return moveBrush;
    }()
  }, {
    key: 'removeBrush',
    value: function () {
      function removeBrush() {
        if (this.brushElAddedBefore) {
          // Reset brush selection
          this.brushElAddedBefore.call(this.brushBehavior.move, null);

          // Remove brush behavior
          this.brushElAddedBefore.on('.brush', null);
          this.brushElAddedBefore = undefined;

          this.props.onRangeSelectionReset();
        }
      }

      return removeBrush;
    }()

    /* ------------------------------ Rendering ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var width = this.props.tracks.map(function (x) {
          return x.width;
        }).reduce(_utils.sum, 0);

        var isBrushable = this.props.tracks.map(function (track) {
          return (0, _configs.IS_TRACK_RANGE_SELECTABLE)(track);
        }).reduce(_utils.or, false);

        var rangeSelectorClass = this.props.isRangeSelectionActive ? 'stylesTrack.track-range-selection-active' : 'stylesTrack.track-range-selection';

        return _react2['default'].createElement(
          'div',
          { className: 'VerticalTiledPlot-module_vertical-tiled-plot-R3sb7' },
          isBrushable && _react2['default'].createElement('svg', {
            ref: function () {
              function ref(el) {
                _this2.brushEl = (0, _d3Selection.select)(el);
              }

              return ref;
            }(),
            style: {
              height: this.props.height,
              width: width
            },

            xmlns: 'http://www.w3.org/2000/svg',
            className: (0, _getClassName3['default'])(rangeSelectorClass, _styleModuleImportMap)
          }),
          _react2['default'].createElement(_ListWrapper2['default'], {
            axis: 'x',
            className: String(_TiledPlotModule2['default'].list) + ' ' + String(_TiledPlotModule2['default'].stylizedList) + ' ' + String(_TiledPlotModule2['default'].horizontalList),
            component: _SortableList2['default'],
            editable: this.props.editable,
            handleConfigTrack: this.props.handleConfigTrack,
            handleResizeTrack: this.props.handleResizeTrack,
            height: this.props.height,
            helperClass: _TiledPlotModule2['default'].stylizedHelper,
            itemClass: String(_TiledPlotModule2['default'].stylizedItem) + ' ' + String(_TiledPlotModule2['default'].horizontalItem),
            itemControlAlignLeft: this.props.tracksControlAlignLeft,
            itemReactClass: _VerticalItem2['default'],
            items: this.props.tracks.map(function (d) {
              return {
                configMenuVisible: d.uid === _this2.props.configTrackMenuId,
                uid: d.uid || _slugid2['default'].nice(),
                height: _this2.props.height,
                width: d.width,
                value: d.value
              };
            }),
            onAddSeries: this.props.onAddSeries,
            onCloseTrack: this.props.onCloseTrack,
            onCloseTrackMenuOpened: this.props.onCloseTrackMenuOpened,
            onConfigTrackMenuOpened: this.props.onConfigTrackMenuOpened,
            onSortEnd: this.props.handleSortEnd,
            referenceAncestor: this.props.referenceAncestor,
            resizeHandles: this.props.resizeHandles,
            useDragHandle: true,
            width: width
          })
        );
      }

      return render;
    }()
  }, {
    key: 'sourceEvent',
    get: function () {
      function get() {
        return _d3Selection.event && _d3Selection.event.sourceEvent;
      }

      return get;
    }()
  }]);
  return VerticalTiledPlot;
}(_react2['default'].Component);

VerticalTiledPlot.propTypes = {
  configTrackMenuId: _propTypes2['default'].string,
  editable: _propTypes2['default'].bool,
  handleConfigTrack: _propTypes2['default'].func,
  handleResizeTrack: _propTypes2['default'].func,
  handleSortEnd: _propTypes2['default'].func,
  is1dRangeSelection: _propTypes2['default'].bool,
  isRangeSelectionActive: _propTypes2['default'].bool,
  height: _propTypes2['default'].number,
  onAddSeries: _propTypes2['default'].func,
  onCloseTrack: _propTypes2['default'].func,
  onCloseTrackMenuOpened: _propTypes2['default'].func,
  onConfigTrackMenuOpened: _propTypes2['default'].func,
  onRangeSelection: _propTypes2['default'].func,
  onRangeSelectionEnd: _propTypes2['default'].func,
  onRangeSelectionReset: _propTypes2['default'].func,
  onRangeSelectionStart: _propTypes2['default'].func,
  rangeSelection: _propTypes2['default'].array,
  rangeSelectionEnd: _propTypes2['default'].bool,
  referenceAncestor: _propTypes2['default'].func,
  resizeHandles: _propTypes2['default'].object,
  scale: _propTypes2['default'].func,
  tracks: _propTypes2['default'].array,
  tracksControlAlignLeft: _propTypes2['default'].bool
};

exports['default'] = VerticalTiledPlot;

/***/ }),
/* 673 */
/***/ (function(module, exports, __nested_webpack_require_3581570__) {

"use strict";


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

var _react = __nested_webpack_require_3581570__(1);

var _react2 = _interopRequireDefault(_react);

var _reactSortableHoc = __nested_webpack_require_3581570__(125);

var _VerticalTrack = __nested_webpack_require_3581570__(396);

var _VerticalTrack2 = _interopRequireDefault(_VerticalTrack);

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

var VerticalItem = (0, _reactSortableHoc.SortableElement)(function (props) {
  return _react2['default'].createElement(_VerticalTrack2['default'], {
    className: props.className,
    controlAlignLeft: props.controlAlignLeft,
    editable: props.editable,
    handleConfigTrack: props.handleConfigTrack,
    handleResizeTrack: props.handleResizeTrack,
    height: props.height,
    item: props.item,
    onAddSeries: props.onAddSeries,
    onCloseTrack: props.onCloseTrack,
    onCloseTrackMenuOpened: props.onCloseTrackMenuOpened,
    onConfigTrackMenuOpened: props.onConfigTrackMenuOpened,
    resizeHandles: props.resizeHandles,
    uid: props.uid,
    width: props.width
  });
});

exports['default'] = VerticalItem;

/***/ }),
/* 674 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"vertical-tiled-plot":"VerticalTiledPlot-module_vertical-tiled-plot-R3sb7"};

/***/ }),
/* 675 */
/***/ (function(module, exports, __nested_webpack_require_3583011__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3583011__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3583011__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3583011__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3583011__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3583011__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3583011__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_3583011__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3583011__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _mixwith = __nested_webpack_require_3583011__(81);

var _utils = __nested_webpack_require_3583011__(10);

var _SeriesListItems = __nested_webpack_require_3583011__(183);

var _ContextMenuItem = __nested_webpack_require_3583011__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _ContextMenuContainer = __nested_webpack_require_3583011__(96);

var _ContextMenuContainer2 = _interopRequireDefault(_ContextMenuContainer);

var _SeriesListSubmenuMixin = __nested_webpack_require_3583011__(390);

var _SeriesListSubmenuMixin2 = _interopRequireDefault(_SeriesListSubmenuMixin);

var _configs = __nested_webpack_require_3583011__(11);

__nested_webpack_require_3583011__(68);

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

var _styleModuleImportMap = {
  '../styles/ContextMenu.module.scss': {
    'context-menu': 'ContextMenu-module_context-menu-2OwvL',
    'context-menu-dark': 'ContextMenu-module_context-menu-dark-2PO31',
    'context-menu-icon': 'ContextMenu-module_context-menu-icon-I4kiw',
    'context-menu-item': 'ContextMenu-module_context-menu-item-1HeVv',
    'context-menu-hr': 'ContextMenu-module_context-menu-hr-3yapb',
    'play-icon': 'ContextMenu-module_play-icon-R4pIO',
    'context-menu-span': 'ContextMenu-module_context-menu-span-8EUfZ',
    'context-menu-thumbnail': 'ContextMenu-module_context-menu-thumbnail-2vHLD',
    'context-menu-thumbnail-inline': 'ContextMenu-module_context-menu-thumbnail-inline-1iOcg'
  }
};

// Styles

var ViewContextMenu = function (_mix$with) {
  (0, _inherits3['default'])(ViewContextMenu, _mix$with);

  function ViewContextMenu() {
    (0, _classCallCheck3['default'])(this, ViewContextMenu);
    return (0, _possibleConstructorReturn3['default'])(this, (ViewContextMenu.__proto__ || (0, _getPrototypeOf2['default'])(ViewContextMenu)).apply(this, arguments));
  }

  (0, _createClass3['default'])(ViewContextMenu, [{
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var seriesItems = (0, _SeriesListItems.getSeriesItems)(this.props.tracks, this.handleItemMouseEnter.bind(this), this.handleMouseLeave.bind(this));

        var customItemsWrapped = this.props.customItems ? _react2['default'].Children.map(this.props.customItems, function (child) {
          return _react2['default'].cloneElement(child, {
            onMouseEnter: function () {
              function onMouseEnter(e) {
                _this2.handleOtherMouseEnter(e);
              }

              return onMouseEnter;
            }()
          });
        }) : null;

        var styleNames = 'context-menu';
        if (this.props.theme === _configs.THEME_DARK) styleNames += ' context-menu-dark';

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this2.div = c;
              }

              return ref;
            }(),
            'data-menu-type': 'ViewContextMenu',
            style: {
              left: this.state.left,
              top: this.state.top
            },
            className: (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
          },
          customItemsWrapped,
          customItemsWrapped && _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          seriesItems,
          seriesItems && _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  return _this2.props.onAddTrack({
                    type: 'horizontal-rule',
                    y: _this2.props.coords[1],
                    position: 'whole'
                  });
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Add Horizontal Rule'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  return _this2.props.onAddTrack({
                    type: 'vertical-rule',
                    x: _this2.props.coords[0],
                    position: 'whole'
                  });
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Add Vertical Rule'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick() {
                  return _this2.props.onAddTrack({
                    type: 'cross-rule',
                    x: _this2.props.coords[0],
                    y: _this2.props.coords[1],
                    position: 'whole'
                  });
                }

                return onClick;
              }(),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Add Cross Rule'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          this.hasMatrixTrack(this.props.tracks) && _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: this.handleAddHorizontalSection.bind(this),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Add Horizontal Cross Section'
          ),
          this.hasMatrixTrack(this.props.tracks) && _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: this.handleAddVerticalSection.bind(this),
              onMouseEnter: function () {
                function onMouseEnter(e) {
                  return _this2.handleOtherMouseEnter(e);
                }

                return onMouseEnter;
              }()
            },
            'Add Vertical Cross Section'
          ),
          this.getSubmenu()
        );
      }

      return render;
    }()
  }, {
    key: 'hasMatrixTrack',
    value: function () {
      function hasMatrixTrack(tracks) {
        var trackList = (0, _utils.expandCombinedTracks)(this.props.tracks);
        return trackList.filter(function (track) {
          return track.type === 'heatmap';
        }).length > 0;
      }

      return hasMatrixTrack;
    }()
  }, {
    key: 'handleAddHorizontalSection',
    value: function () {
      function handleAddHorizontalSection() {
        var trackList = (0, _utils.expandCombinedTracks)(this.props.tracks);
        var matrixTrack = trackList.filter(function (track) {
          return track.type === 'heatmap';
        })[0];

        this.props.onAddTrack({
          type: 'horizontal-rule',
          y: this.props.coords[1],
          position: 'whole'
        });
        this.props.onAddTrack({
          data: {
            type: 'horizontal-section',
            server: matrixTrack.server,
            tilesetUid: matrixTrack.tilesetUid,
            slicePos: this.props.coords[1]
          },
          options: {
            valueScaling: 'log'
          },
          type: 'horizontal-bar',
          height: 30,
          position: 'top'
        });
      }

      return handleAddHorizontalSection;
    }()
  }, {
    key: 'handleAddVerticalSection',
    value: function () {
      function handleAddVerticalSection() {
        var trackList = (0, _utils.expandCombinedTracks)(this.props.tracks);
        var matrixTrack = trackList.filter(function (track) {
          return track.type === 'heatmap';
        })[0];

        this.props.onAddTrack({
          type: 'vertical-rule',
          x: this.props.coords[0],
          position: 'whole'
        });
        this.props.onAddTrack({
          data: {
            type: 'vertical-section',
            server: matrixTrack.server,
            tilesetUid: matrixTrack.tilesetUid,
            slicePos: this.props.coords[0]
          },
          options: {
            valueScaling: 'log'
          },
          type: 'vertical-bar',
          height: 30,
          position: 'left'
        });
      }

      return handleAddVerticalSection;
    }()
  }]);
  return ViewContextMenu;
}((0, _mixwith.mix)(_ContextMenuContainer2['default'])['with'](_SeriesListSubmenuMixin2['default']));

ViewContextMenu.propTypes = {
  // the data coordinates where this context menu was initiated
  coords: _propTypes2['default'].array,
  customItems: _propTypes2['default'].array
};

exports['default'] = ViewContextMenu;

/***/ }),
/* 676 */
/***/ (function(module, exports, __nested_webpack_require_3593366__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_3593366__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _promise = __nested_webpack_require_3593366__(62);

var _promise2 = _interopRequireDefault(_promise);

var _isNan = __nested_webpack_require_3593366__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _toConsumableArray2 = __nested_webpack_require_3593366__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _set = __nested_webpack_require_3593366__(38);

var _set2 = _interopRequireDefault(_set);

var _getPrototypeOf = __nested_webpack_require_3593366__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3593366__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3593366__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3593366__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3593366__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3593366__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _d3Selection = __nested_webpack_require_3593366__(0);

var _react = __nested_webpack_require_3593366__(1);

var _react2 = _interopRequireDefault(_react);

var _slugid = __nested_webpack_require_3593366__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _propTypes = __nested_webpack_require_3593366__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Autocomplete = __nested_webpack_require_3593366__(677);

var _Autocomplete2 = _interopRequireDefault(_Autocomplete);

var _ChromosomeInfo = __nested_webpack_require_3593366__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _SearchField = __nested_webpack_require_3593366__(140);

var _SearchField2 = _interopRequireDefault(_SearchField);

var _PopupMenu = __nested_webpack_require_3593366__(264);

var _PopupMenu2 = _interopRequireDefault(_PopupMenu);

var _services = __nested_webpack_require_3593366__(24);

var _withPubSub = __nested_webpack_require_3593366__(69);

var _withPubSub2 = _interopRequireDefault(_withPubSub);

var _utils = __nested_webpack_require_3593366__(10);

var _withTheme = __nested_webpack_require_3593366__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _icons = __nested_webpack_require_3593366__(266);

var _configs = __nested_webpack_require_3593366__(11);

var _GenomePositionSearchBoxModule = __nested_webpack_require_3593366__(681);

var _GenomePositionSearchBoxModule2 = _interopRequireDefault(_GenomePositionSearchBoxModule);

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

// eslint-disable-line no-unused-vars

// Configs


// HOCS
var _styleModuleImportMap = {
  'styles': {
    'genome-position-search': 'GenomePositionSearchBox-module_genome-position-search-SYccr',
    'genome-position-search-focus': 'GenomePositionSearchBox-module_genome-position-search-focus-23by2',
    'genome-position-search-bar': 'GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU',
    'genome-position-search-dark': 'GenomePositionSearchBox-module_genome-position-search-dark-EML2e',
    'genome-position-search-bar-button': 'GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ',
    'genome-position-search-bar-button-focus': 'GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk',
    'genome-position-search-bar-icon': 'GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk',
    'genome-position-search-bar-icon-focus': 'GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z',
    'genome-position-search-bar-suggestions': 'GenomePositionSearchBox-module_genome-position-search-bar-suggestions-SrIoU',
    'btn': 'GenomePositionSearchBox-module_btn-2bTUd',
    'btn-sm': 'GenomePositionSearchBox-module_btn-sm-2Ltms',
    'btn-default': 'GenomePositionSearchBox-module_btn-default-2pap4'
  }
};

// Styles


// Utils


// Services

var GenomePositionSearchBox = function (_React$Component) {
  (0, _inherits3['default'])(GenomePositionSearchBox, _React$Component);

  function GenomePositionSearchBox(props) {
    (0, _classCallCheck3['default'])(this, GenomePositionSearchBox);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (GenomePositionSearchBox.__proto__ || (0, _getPrototypeOf2['default'])(GenomePositionSearchBox)).call(this, props));

    _this.mounted = false;
    _this.uid = _slugid2['default'].nice();
    _this.chromInfo = null;
    _this.searchField = null;
    _this.autocompleteMenu = null;

    _this.xScale = null;
    _this.yScale = null;
    // this.props.zoomDispatch.on('zoom.' + this.uid, this.zoomed.bind(this))

    /*
    this.xOrigScale = scaleLinear().domain(this.props.xDomain)
              .range(this.props.xRange);
    this.yOrigScale = scaleLinear().domain(this.props.yDomain)
              .range(this.props.yRange);
     this.zoomedXScale = this.xOrigScale.copy();
    this.zoomedYScale = this.yOrigScale.copy();
    */

    _this.prevParts = [];

    _this.props.registerViewportChangedListener(_this.scalesChanged.bind(_this));

    _this.menuPosition = { left: 0, top: 0 };

    // the position text is maintained both here and in
    // in state.value so that it can be quickly updated in
    // response to zoom events
    _this.positionText = 'chr4:190,998,876-191,000,255';

    _this.state = {
      genes: [],
      isFocused: false,
      autocompleteServer: _this.props.autocompleteServer,
      autocompleteId: _this.props.autocompleteId,
      availableAssemblies: [],
      selectedAssembly: null
    };

    _this.styles = {
      item: {
        padding: '2px 6px',
        cursor: 'default'
      },

      highlightedItem: {
        color: 'white',
        background: 'hsl(200, 50%, 50%)',
        padding: '2px 6px',
        cursor: 'default'
      },

      menu: {
        border: 'solid 1px #ccc'
      }
    };

    _this.availableAutocompletes = {};

    if (_this.props.autocompleteId) {
      _this.availableAutocompletes[_this.props.chromInfoId] = new _set2['default']([{
        server: _this.props.autocompleteServer,
        acId: _this.props.autocompleteId
      }]);
    }

    _this.availableChromSizes = {};

    /*
    if (this.props.chromInfoServer && this.props.chromInfoId) {
      // if we've been passed a server and chromInfo ID we trust that it exists
      // and use that
      this.availableChromSizes[this.props.chromInfoId] =
        new Set([{server: this.props.chromInfoServer, uuid: this.props.chromInfoId} ]);
      this.fetchChromInfo(this.props.chromInfoId);
    }
    */
    return _this;
  }

  (0, _createClass3['default'])(GenomePositionSearchBox, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        var _this2 = this;

        this.mounted = true;
        // we want to catch keypresses so we can get that enter
        (0, _d3Selection.select)(this.autocompleteMenu.inputEl).on('keypress', this.autocompleteKeyPress.bind(this));

        this.findAvailableAutocompleteSources();
        this.findAvailableChromSizes();

        if (this.props.chromInfoPath) {
          this.searchPosition = true;

          (0, _ChromosomeInfo2['default'])(this.props.chromInfoPath, function (chromInfo) {
            if (!chromInfo) {
              _this2.searchPosition = null;
              return;
            }

            _this2.chromInfo = chromInfo;
            _this2.searchField = new _SearchField2['default'](_this2.chromInfo);

            _this2.setPositionText();
          });
        }

        this.setPositionText();
      }

      return componentDidMount;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        this.mounted = false;
        this.props.removeViewportChangedListener();
      }

      return componentWillUnmount;
    }()
  }, {
    key: 'onAutocompleteChange',
    value: function () {
      function onAutocompleteChange(evt, value) {
        var _this3 = this;

        this.positionText = value;
        this.setState({
          value: value,
          loading: true
        });

        this.changedPart = null;
        var spaceParts = value.split(/ /);
        var partIndex = 0;
        var newParts = [];
        var changedAtStartOfWord = false;

        for (var j = 0; j < spaceParts.length; j++) {
          var parts = spaceParts[j].split(/-/);

          for (var i = 0; i < parts.length; i++) {
            partIndex += 1;
            newParts.push(parts[i]);

            if (i === 0) changedAtStartOfWord = true;else changedAtStartOfWord = false;

            if (i === this.prevParts.length) {
              // new part added
              this.changedPart = partIndex - 1;
              break;
            }

            if (parts[i] !== this.prevParts[i]) {
              this.changedPart = partIndex - 1;
              break;
            }
          }
        }

        this.prevParts = newParts;

        // no autocomplete repository is provided, so we don't try to autcomplete anything
        if (!(this.state.autocompleteServer && this.state.autocompleteId)) {
          return;
        }

        if (this.changedPart !== null) {
          // if something has changed in the input text
          this.setState({
            loading: true
          });
          // send out a request for the autcomplete suggestions
          var url = String(this.state.autocompleteServer) + '/suggest/';
          url += '?d=' + String(this.state.autocompleteId) + '&ac=' + String(newParts[this.changedPart].toLowerCase());
          _services.tileProxy.json(url, function (error, data) {
            if (error) {
              _this3.setState({
                loading: false,
                genes: []
              });
            } else if (_this3.changedPart > 0 && !changedAtStartOfWord) {
              // send out another request for genes with dashes in them
              // but we need to distinguish things that have a dash in front
              // from things that just have a space in front

              var url1 = String(_this3.state.autocompleteServer) + '/suggest/' + ('?d=' + String(_this3.state.autocompleteId)) + ('&ac=' + String(newParts[_this3.changedPart - 1].toLowerCase())) + ('-' + String(newParts[_this3.changedPart].toLowerCase()));
              _services.tileProxy.json(url1, function (error1, data1) {
                if (error1) {
                  _this3.setState({
                    loading: false,
                    genes: data
                  });
                } else {
                  _this3.setState({
                    loading: false,
                    genes: data1.concat(data)
                  });
                }
              }, _this3.props.pubSub);
            } else {
              // we've received a list of autocomplete suggestions
              _this3.setState({ loading: false, genes: data });
            }
          }, this.props.pubSub);
        }
      }

      return onAutocompleteChange;
    }()
  }, {
    key: 'setAvailableAssemblies',
    value: function () {
      function setAvailableAssemblies() {
        var chromsizeKeys = new _set2['default']((0, _utils.dictKeys)(this.availableChromSizes));

        var commonKeys = new _set2['default']([].concat((0, _toConsumableArray3['default'])(chromsizeKeys)));

        if (this.gpsbForm) {
          // only set the state if this comonent is mounted
          this.setState({
            availableAssemblies: [].concat((0, _toConsumableArray3['default'])(commonKeys))
          });
        }
      }

      return setAvailableAssemblies;
    }()
  }, {
    key: 'setSelectedAssembly',
    value: function () {
      function setSelectedAssembly(assemblyName) {
        // component is probably about to be unmounted
        if (!this.mounted) return;

        if (!this.availableChromSizes[assemblyName]) return;
        // we don't know of any available chromosome sizes so just ignore
        // this function call (usually called from the constructor)

        // use the first available server that we have on record for this chromInfoId
        var serverAndChromInfoToUse = [].concat((0, _toConsumableArray3['default'])(this.availableChromSizes[assemblyName]))[0];

        this.setState({
          autocompleteServer: serverAndChromInfoToUse.server
        });

        var server = serverAndChromInfoToUse.server;

        // we need to set a an autocompleteId that matches the chromInfo
        // that was received, but if none has been retrieved yet...

        if (this.availableAutocompletes[assemblyName]) {
          var newAcId = [].concat((0, _toConsumableArray3['default'])(this.availableAutocompletes[assemblyName]))[0].acId;
          this.props.onSelectedAssemblyChanged(assemblyName, newAcId, server);

          if (this.gpsbForm) {
            this.setState({
              autocompleteId: newAcId
            });
          }
        } else {
          this.props.onSelectedAssemblyChanged(assemblyName, null, server);

          if (this.gpsbForm) {
            this.setState({
              autocompleteId: null
            });
          }
        }

        this.fetchChromInfo(serverAndChromInfoToUse.uuid, serverAndChromInfoToUse.server);
      }

      return setSelectedAssembly;
    }()
  }, {
    key: 'setPositionText',
    value: function () {
      function setPositionText() {
        if (!this.mounted) {
          return;
        }
        if (!this.searchField) {
          return;
        }

        var positionString = this.searchField.scalesToPositionText(this.xScale, this.yScale, this.props.twoD);

        // ReactDOM.findDOMNode( this.refs.searchFieldText).value = positionString;
        // used for autocomplete
        this.prevParts = positionString.split(/[ -]/);

        if (this.gpsbForm) {
          this.positionText = positionString;

          // this.origPositionText is used to reset the text if somebody clicks submit
          // on an empty field
          this.origPositionText = positionString;

          this.autocompleteMenu.inputEl.value = positionString;
          // this.setState({ value: positionString });
        }
      }

      return setPositionText;
    }()
  }, {
    key: 'scalesChanged',
    value: function () {
      function scalesChanged(xScale, yScale) {
        this.xScale = xScale;
        this.yScale = yScale;

        // make sure that this component is loaded first
        this.setPositionText();
      }

      return scalesChanged;
    }()
  }, {
    key: 'findAvailableChromSizes',
    value: function () {
      function findAvailableChromSizes() {
        var _this4 = this;

        if (!this.props.trackSourceServers) {
          // if we don't know where to look for track source servers then
          // just give up
          return;
        }

        this.props.trackSourceServers.forEach(function (sourceServer) {
          _services.tileProxy.json(String(sourceServer) + '/available-chrom-sizes/', function (error, data) {
            if (error) {
              console.error(error);
            } else {
              data.results.forEach(function (x) {
                if (!(x.coordSystem in _this4.availableChromSizes)) {
                  _this4.availableChromSizes[x.coordSystem] = new _set2['default']();
                }

                _this4.availableChromSizes[x.coordSystem].add({
                  server: sourceServer,
                  uuid: x.uuid
                });
                _this4.setAvailableAssemblies();
              });

              // we haven't set an assembly yet so set it now
              // props.chromInfoId will be set to the suggested assembly (e.g. "hg19")
              // this will be mapped to an available chromSize (with its own unique uuid)
              if (!_this4.searchField) {
                // only fetch chromsizes if there isn't a specified chromInfoServer
                _this4.fetchChromInfo(_this4.props.chromInfoId in _this4.availableChromSizes ? [].concat((0, _toConsumableArray3['default'])(_this4.availableChromSizes[_this4.props.chromInfoId]))[0].uuid : _this4.props.chromInfoId, _this4.props.chromInfoId in _this4.availableChromSizes ? [].concat((0, _toConsumableArray3['default'])(_this4.availableChromSizes[_this4.props.chromInfoId]))[0].server : _this4.props.chromInfoServer);
              }
            }
          }, _this4.props.pubSub);
        });
      }

      return findAvailableChromSizes;
    }()
  }, {
    key: 'findAvailableAutocompleteSources',
    value: function () {
      function findAvailableAutocompleteSources() {
        var _this5 = this;

        if (!this.props.trackSourceServers) {
          // if there's no available track source servers
          // we can't search for autocomplete sources
          return;
        }

        this.props.trackSourceServers.forEach(function (sourceServer) {
          _services.tileProxy.json(String(sourceServer) + '/tilesets/?limit=100&dt=gene-annotation', function (error, data) {
            if (error) {
              console.error(error);
            } else {
              data.results.forEach(function (x) {
                if (!(x.coordSystem in _this5.availableAutocompletes)) {
                  _this5.availableAutocompletes[x.coordSystem] = new _set2['default']();
                }

                _this5.availableAutocompletes[x.coordSystem].add({
                  server: sourceServer,
                  acId: x.uuid
                });
                _this5.setAvailableAssemblies();
              });

              if (!_this5.state.autocompleteId) {
                // We don't have an autocomplete source yet, so set the one matching the current
                // assembly
                if (_this5.gpsbForm) {
                  // only set the state if this component is mounted
                  if (_this5.availableAutocompletes[_this5.props.chromInfoId]) {
                    _this5.setState({
                      autocompleteId: [].concat((0, _toConsumableArray3['default'])(_this5.availableAutocompletes[_this5.props.chromInfoId]))[0].acId
                    });
                  }
                }
              }
            }
          }, _this5.props.pubSub);
        });
      }

      return findAvailableAutocompleteSources;
    }()

    /**
     * The user has selected an assembly to use for the coordinate search box.
     * Once the appropriate ChromInfo file is fetched, it is stored locally
     *
     * @param {string} chromInfoId The name of the chromosome info set to use
     */

  }, {
    key: 'fetchChromInfo',
    value: function () {
      function fetchChromInfo(chromInfoId, server) {
        var _this6 = this;

        (0, _ChromosomeInfo2['default'])(String(server) + '/chrom-sizes/?id=' + String(chromInfoId), function (newChromInfo) {
          if (!newChromInfo) {
            return;
          }

          _services.tileProxy.json(String(server) + '/tileset_info/?d=' + String(chromInfoId), function (error2, tilesetInfo) {
            if (error2) {
              return;
            }

            if (_this6.gpsbForm) {
              // only set the state if this component is mounted
              _this6.setState({
                selectedAssembly: tilesetInfo[chromInfoId].coordSystem
              });
            }
          }, _this6.props.pubSub);

          _this6.chromInfo = newChromInfo;
          _this6.searchField = new _SearchField2['default'](_this6.chromInfo);

          _this6.setPositionText();
        }, this.props.pubSub);
      }

      return fetchChromInfo;
    }()
  }, {
    key: 'autocompleteKeyPress',
    value: function () {
      function autocompleteKeyPress() {
        var ENTER_KEY_CODE = 13;

        if (_d3Selection.event.keyCode === ENTER_KEY_CODE) {
          this.buttonClick();
        }
      }

      return autocompleteKeyPress;
    }()
  }, {
    key: 'genePositionToSearchBarText',
    value: function () {
      function genePositionToSearchBarText(genePosition) {}

      return genePositionToSearchBarText;
    }()
  }, {
    key: 'replaceGenesWithLoadedPositions',
    value: function () {
      function replaceGenesWithLoadedPositions(genePositions) {
        // iterate over all non-position oriented words and try
        // to replace them with the positions loaded from the suggestions
        // database
        var origSearchText = this.positionText;
        var spaceParts = origSearchText.split(' ');
        var foundGeneSymbol = false;

        for (var i = 0; i < spaceParts.length; i++) {
          var dashParts = spaceParts[i].split('-');

          // check if this "word" is a gene symbol which can be replaced

          // iterate over chunks, checking what the maximum replaceable
          // unit is
          var j = 0;
          var k = 0;
          var spacePart = '';

          while (j < dashParts.length) {
            k = dashParts.length;

            while (k > j) {
              var dashChunk = dashParts.slice(j, k).join('-');

              if (genePositions[dashChunk.toLowerCase()]) {
                var genePosition = genePositions[dashChunk.toLowerCase()];
                var extension = Math.floor((genePosition.txEnd - genePosition.txStart) / 4);

                if (j === 0 && k < dashParts.length) {
                  // there's more parts so this is the first part
                  spacePart = String(genePosition.chr) + ':' + (genePosition.txStart - extension);
                } else if (j === 0 && k === dashParts.length) {
                  // there's only one part so this is a position
                  spacePart = String(genePosition.chr) + ':' + (genePosition.txStart - extension) + '-' + String(genePosition.txEnd + extension);
                } else {
                  spacePart += '- ' + String(genePosition.chr) + ':' + String(genePosition.txEnd + extension);
                  // it's the last part of a range
                }
                foundGeneSymbol = true; // we found a gene symbol
                break;
              } else if (k === j + 1) {
                if (spacePart.length) {
                  spacePart += '-';
                }

                spacePart += dashChunk;
              }

              k -= 1;
            }

            j = k + 1;
          }

          spaceParts[i] = spacePart;
        }

        var newValue = spaceParts.join(' ');
        this.prevParts = newValue.split(/[ -]/);

        this.positionText = newValue;
        this.setState({
          value: newValue
        });
        // return the original keyword that a user searched if we found a gene symbol from it
        return foundGeneSymbol ? origSearchText : null;
      }

      return replaceGenesWithLoadedPositions;
    }()
  }, {
    key: 'replaceGenesWithPositions',
    value: function () {
      function replaceGenesWithPositions(finished) {
        var _this7 = this;

        // replace any gene names in the input with their corresponding positions
        var valueParts = this.positionText.split(/[ -]/);
        var requests = [];

        for (var i = 0; i < valueParts.length; i++) {
          if (valueParts[i].length === 0) {
            continue;
          }

          var retPos = this.searchField.parsePosition(valueParts[i])[2];

          if (retPos === null || (0, _isNan2['default'])(+retPos)) {
            // not a chromsome position, let's see if it's a gene name
            var url = String(this.state.autocompleteServer) + '/suggest/?d=' + String(this.state.autocompleteId) + '&ac=' + String(valueParts[i].toLowerCase());
            requests.push(_services.tileProxy.json(url, _utils.toVoid, this.props.pubSub));
          }
        }

        _promise2['default'].all(requests).then(function (files) {
          if (files) {
            var genePositions = {};

            // extract the position of the top match from the list of files
            for (var _i = 0; _i < files.length; _i++) {
              if (!files[_i][0]) {
                continue;
              }

              for (var j = 0; j < files[_i].length; j++) {
                genePositions[files[_i][j].geneName.toLowerCase()] = files[_i][j];
              }
            }

            var geneSymbol = _this7.replaceGenesWithLoadedPositions(genePositions);

            finished(geneSymbol);
          }
        })['catch'](function (error) {
          return console.error(error);
        });
      }

      return replaceGenesWithPositions;
    }()
  }, {
    key: 'buttonClick',
    value: function () {
      function buttonClick() {
        var _this8 = this;

        this.setState({ genes: [] }); // no menu should be open

        this.replaceGenesWithPositions(function (geneSymbol) {
          var searchFieldValue = _this8.positionText;

          if (_this8.searchField !== null) {
            var rangePair = _this8.searchField.searchPosition(searchFieldValue);
            var range1 = rangePair[0];
            var range2 = rangePair[1];

            if (!range1) {
              _this8.setPositionText(_this8.origPositionText);
              return;
            }

            if (range1 && ((0, _isNan2['default'])(+range1[0]) || (0, _isNan2['default'])(+range1[1])) || range2 && ((0, _isNan2['default'])(+range2[0]) || (0, _isNan2['default'])(+range2[1]))) {
              return;
            }

            if (!range2) {
              range2 = range1;
            }

            var newXScale = _this8.xScale.copy().domain(range1);
            var newYScale = _this8.yScale.copy().domain(range2);

            var _scalesCenterAndK = (0, _utils.scalesCenterAndK)(newXScale, newYScale),
                _scalesCenterAndK2 = (0, _slicedToArray3['default'])(_scalesCenterAndK, 3),
                centerX = _scalesCenterAndK2[0],
                centerY = _scalesCenterAndK2[1],
                k = _scalesCenterAndK2[2];

            if (geneSymbol) {
              // call the callback function of the `onGeneSearch` api if a user searched for a gene symbol
              _this8.props.onGeneSearch({
                geneSymbol: geneSymbol,
                range: range1,
                centerX: centerX,
                centerY: centerY
              });
            }

            _this8.props.setCenters(centerX, centerY, k, _configs.ZOOM_TRANSITION_DURATION);
          }
        });
      }

      return buttonClick;
    }()
  }, {
    key: 'searchFieldSubmit',
    value: function () {
      function searchFieldSubmit() {
        this.buttonClick();
      }

      return searchFieldSubmit;
    }()
  }, {
    key: 'pathJoin',
    value: function () {
      function pathJoin(parts, sep) {
        var separator = sep || '/';
        var replace = new RegExp(String(separator) + '{1,}', 'g');
        return parts.join(separator).replace(replace, separator);
      }

      return pathJoin;
    }()
  }, {
    key: 'geneSelected',
    value: function () {
      function geneSelected(value, objct) {
        var parts = this.positionText.split(' ');
        var partCount = this.changedPart;

        // change the part that was selected
        for (var i = 0; i < parts.length; i++) {
          var dashParts = parts[i].split('-');
          var geneParts = objct.geneName.split('-');

          if (partCount > dashParts.length - 1) {
            partCount -= dashParts.length;
          } else {
            dashParts[partCount] = objct.geneName;

            if (geneParts.length === 2 && partCount > 0 && dashParts[partCount - 1].toLowerCase() === geneParts[0].toLowerCase()) {
              // the gene to be added contains a dash and is
              // meant to replace a part of the previous gene
              // e.g. SOX2-O should be replaced with SOX2-OT

              var newDashParts = dashParts.slice(0, partCount - 1);
              newDashParts.push(geneParts.join('-'));

              if (partCount < dashParts.length - 1) {
                newDashParts.push(dashParts.slice(partCount + 1));
              }

              parts[i] = newDashParts.join('-');
            } else {
              parts[i] = dashParts.join('-');
            }

            break;
          }
        }

        /*
        let new_dash_parts = dash_parts.slice(0, dash_parts.length-1);
        new_dash_parts = new_dash_parts.concat(objct.geneName).join('-');
         let new_parts = parts.splice(0, parts.length-1);
        new_parts = new_parts.concat(new_dash_parts).join(' ');
        */

        this.prevParts = parts.join(' ').split(/[ -]/);

        this.positionText = parts.join(' ');
        this.setState({ value: parts.join(' '), genes: [] });
      }

      return geneSelected;
    }()
  }, {
    key: 'handleMenuVisibilityChange',
    value: function () {
      function handleMenuVisibilityChange(isOpen, inputEl) {
        var box = inputEl.getBoundingClientRect();

        this.menuPosition = {
          left: box.left,
          top: box.top + box.height
        };

        this.setState({
          menuOpened: isOpen
        });
      }

      return handleMenuVisibilityChange;
    }()
  }, {
    key: 'handleRenderMenu',
    value: function () {
      function handleRenderMenu(items) {
        return _react2['default'].createElement(
          _PopupMenu2['default'],
          null,
          _react2['default'].createElement(
            'div',
            {
              style: {
                left: this.menuPosition.left,
                top: this.menuPosition.top
              },
              className: 'GenomePositionSearchBox-module_genome-position-search-bar-suggestions-SrIoU'
            },
            items
          )
        );
      }

      return handleRenderMenu;
    }()
  }, {
    key: 'handleAssemblySelect',
    value: function () {
      function handleAssemblySelect(evt) {
        this.setSelectedAssembly(evt);

        this.setState({
          selectedAssembly: evt
        });
      }

      return handleAssemblySelect;
    }()
  }, {
    key: 'focusHandler',
    value: function () {
      function focusHandler(isFocused) {
        this.setState({
          isFocused: isFocused
        });
      }

      return focusHandler;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this9 = this;

        var assemblyMenuItems = this.state.availableAssemblies.map(function (x) {
          return _react2['default'].createElement(
            'option',
            { key: x, value: x },
            x
          );
        });

        var className = this.state.isFocused ? 'styles.genome-position-search-focus' : 'styles.genome-position-search';

        if (this.props.theme === _configs.THEME_DARK) {
          className += ' styles.genome-position-search-dark';
        }

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this9.gpsbForm = c;
              }

              return ref;
            }(),
            className: (0, _getClassName3['default'])(className, _styleModuleImportMap)
          },
          !this.props.hideAvailableAssemblies && _react2['default'].createElement(
            'select',
            {
              ref: function () {
                function ref(c) {
                  _this9.assemblyPickButton = c;
                }

                return ref;
              }(),
              className: _GenomePositionSearchBoxModule2['default']['genome-position-search-bar-button'],
              id: this.uid,
              onSelect: this.handleAssemblySelect.bind(this),
              title: this.state.selectedAssembly ? this.state.selectedAssembly : '(none)'
            },
            assemblyMenuItems
          ),
          _react2['default'].createElement(_Autocomplete2['default'], {
            ref: function () {
              function ref(c) {
                _this9.autocompleteMenu = c;
              }

              return ref;
            }(),
            getItemValue: function () {
              function getItemValue(item) {
                return item.geneName;
              }

              return getItemValue;
            }(),
            inputProps: {
              className: _GenomePositionSearchBoxModule2['default']['genome-position-search-bar'],
              title: 'Current location: enter a symbol or location to change the position of the current view'
            },
            items: this.state.genes,
            menuStyle: {
              position: 'absolute',
              left: this.menuPosition.left,
              top: this.menuPosition.top,
              border: '1px solid black'
            },
            onChange: this.onAutocompleteChange.bind(this),
            onFocus: this.focusHandler.bind(this),
            onMenuVisibilityChange: this.handleMenuVisibilityChange.bind(this),
            onSelect: function () {
              function onSelect(value, objct) {
                return _this9.geneSelected(value, objct);
              }

              return onSelect;
            }(),
            onSubmit: this.searchFieldSubmit.bind(this),
            renderItem: function () {
              function renderItem(item, isHighlighted) {
                return _react2['default'].createElement(
                  'div',
                  {
                    key: item.refseqid,
                    id: item.refseqid,
                    style: isHighlighted ? _this9.styles.highlightedItem : _this9.styles.item
                  },
                  item.geneName
                );
              }

              return renderItem;
            }(),
            renderMenu: this.handleRenderMenu.bind(this),
            value: this.positionText,
            wrapperStyle: { width: '100%' }
          }),
          _react2['default'].createElement(_icons.SearchIcon, {
            onClick: this.buttonClick.bind(this),
            theStyle: 'multitrack-header-icon'
          })
        );
      }

      return render;
    }()
  }]);
  return GenomePositionSearchBox;
}(_react2['default'].Component);

GenomePositionSearchBox.propTypes = {
  autocompleteId: _propTypes2['default'].string,
  autocompleteServer: _propTypes2['default'].string,
  chromInfoId: _propTypes2['default'].string,
  chromInfoServer: _propTypes2['default'].string,
  hideAvailableAssemblies: _propTypes2['default'].bool,
  isFocused: _propTypes2['default'].bool,
  pubSub: _propTypes2['default'].func,
  onFocus: _propTypes2['default'].func,
  onGeneSearch: _propTypes2['default'].func,
  onSelectedAssemblyChanged: _propTypes2['default'].func,
  registerViewportChangedListener: _propTypes2['default'].func,
  removeViewportChangedListener: _propTypes2['default'].func,
  setCenters: _propTypes2['default'].func,
  theme: _propTypes2['default'].symbol.isRequired,
  trackSourceServers: _propTypes2['default'].array,
  twoD: _propTypes2['default'].bool
};

exports['default'] = (0, _withPubSub2['default'])((0, _withTheme2['default'])(GenomePositionSearchBox));

/***/ }),
/* 677 */
/***/ (function(module, exports, __nested_webpack_require_3628500__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

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

var _stringify = __nested_webpack_require_3628500__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _extends2 = __nested_webpack_require_3628500__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _getPrototypeOf = __nested_webpack_require_3628500__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3628500__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3628500__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3628500__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3628500__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_3628500__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_3628500__(42);

var _domScrollIntoView = __nested_webpack_require_3628500__(678);

var _domScrollIntoView2 = _interopRequireDefault(_domScrollIntoView);

var _propTypes = __nested_webpack_require_3628500__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _debugStates = [];

var Autocomplete = function (_React$Component) {
  (0, _inherits3['default'])(Autocomplete, _React$Component);

  function Autocomplete(props) {
    (0, _classCallCheck3['default'])(this, Autocomplete);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (Autocomplete.__proto__ || (0, _getPrototypeOf2['default'])(Autocomplete)).call(this, props));

    _this.state = {
      highlightedIndex: null,
      menuTop: 0,
      menuLeft: 0,
      menuWidth: 0,
      isOpen: false
    };

    _this.keyDownHandlers = {
      ArrowDown: function () {
        function ArrowDown(event) {
          event.preventDefault();
          var itemsLength = this.getFilteredItems().length;
          if (!itemsLength) return;
          var highlightedIndex = this.state.highlightedIndex;

          var index = highlightedIndex === null || highlightedIndex === itemsLength - 1 ? 0 : highlightedIndex + 1;
          this._performAutoCompleteOnKeyUp = true;
          this.setState({
            highlightedIndex: index,
            isOpen: true
          });
        }

        return ArrowDown;
      }(),
      ArrowUp: function () {
        function ArrowUp(event) {
          event.preventDefault();
          var itemsLength = this.getFilteredItems().length;
          if (!itemsLength) return;
          var highlightedIndex = this.state.highlightedIndex;

          var index = highlightedIndex === 0 || highlightedIndex === null ? itemsLength - 1 : highlightedIndex - 1;
          this._performAutoCompleteOnKeyUp = true;
          this.setState({
            highlightedIndex: index,
            isOpen: true
          });
        }

        return ArrowUp;
      }(),
      Enter: function () {
        function Enter(event) {
          var _this2 = this;

          if (this.state.isOpen === false) {
            // menu is closed so there is no selection to accept -> do nothing
          } else if (this.state.highlightedIndex === null) {
            // input has focus but no menu item is selected + enter is hit
            // -> close the menu, highlight whatever's in input
            this.setState({
              isOpen: false
            }, function () {
              _this2.inputEl.select();
            });
          } else {
            // text entered + menu item has been highlighted + enter is hit
            // -> update value to that of selected menu item, close the menu
            event.preventDefault();
            var item = this.getFilteredItems()[this.state.highlightedIndex];
            var value = this.props.getItemValue(item);
            this.setState({
              isOpen: false,
              highlightedIndex: null
            }, function () {
              // this.refs.input.focus() // TODO: file issue
              _this2.inputEl.setSelectionRange(value.length, value.length);
              _this2.props.onSelect(value, item);
            });
          }
        }

        return Enter;
      }(),
      Escape: function () {
        function Escape() {
          this.setState({
            highlightedIndex: null,
            isOpen: false
          });
        }

        return Escape;
      }()
    };
    return _this;
  }

  (0, _createClass3['default'])(Autocomplete, [{
    key: 'getInitialState',
    value: function () {
      function getInitialState() {
        return {
          isOpen: false,
          highlightedIndex: null
        };
      }

      return getInitialState;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillMount',
    value: function () {
      function UNSAFE_componentWillMount() {
        this._ignoreBlur = false;
        this._performAutoCompleteOnUpdate = false;
        this._performAutoCompleteOnKeyUp = false;
      }

      return UNSAFE_componentWillMount;
    }()

    // eslint-disable-next-line camelcase

  }, {
    key: 'UNSAFE_componentWillReceiveProps',
    value: function () {
      function UNSAFE_componentWillReceiveProps(nextProps) {
        this._performAutoCompleteOnUpdate = true;
        // If `items` has changed we want to reset `highlightedIndex`
        // since it probably no longer refers to a relevant item
        if (this.props.items !== nextProps.items ||
        // The entries in `items` may have been changed even though the
        // object reference remains the same, double check by seeing
        // if `highlightedIndex` points to an existing item
        this.state.highlightedIndex >= nextProps.items.length) {
          this.setState({ highlightedIndex: null });
        }
      }

      return UNSAFE_componentWillReceiveProps;
    }()
  }, {
    key: 'componentDidUpdate',
    value: function () {
      function componentDidUpdate(prevProps, prevState) {
        if (this.state.isOpen === true && prevState.isOpen === false) {
          this.setMenuPositions();
        }

        if (this.state.isOpen && this._performAutoCompleteOnUpdate) {
          this._performAutoCompleteOnUpdate = false;
          this.maybeAutoCompleteText();
        }

        this.maybeScrollItemIntoView();
        if (prevState.isOpen !== this.state.isOpen) {
          this.props.onMenuVisibilityChange(this.state.isOpen, this.inputEl);
        }
      }

      return componentDidUpdate;
    }()
  }, {
    key: 'maybeScrollItemIntoView',
    value: function () {
      function maybeScrollItemIntoView() {
        if (this.state.isOpen === true && this.state.highlightedIndex !== null) {
          // eslint-disable-next-line react/no-string-refs
          var itemNode = this.refs['item-' + String(this.state.highlightedIndex)];
          // eslint-disable-next-line react/no-string-refs
          var menuNode = this.refs.menu;
          if (itemNode) {
            (0, _domScrollIntoView2['default'])((0, _reactDom.findDOMNode)(itemNode), (0, _reactDom.findDOMNode)(menuNode), {
              onlyScrollIfNeeded: true
            });
          }
        }
      }

      return maybeScrollItemIntoView;
    }()
  }, {
    key: 'handleKeyDown',
    value: function () {
      function handleKeyDown(event) {
        if (this.keyDownHandlers[event.key]) {
          this.keyDownHandlers[event.key].call(this, event);
        } else {
          this.setState({
            highlightedIndex: null,
            isOpen: true
          });
        }
      }

      return handleKeyDown;
    }()
  }, {
    key: 'handleChange',
    value: function () {
      function handleChange(event) {
        this._performAutoCompleteOnKeyUp = true;
        this.props.onChange(event, event.target.value);
      }

      return handleChange;
    }()
  }, {
    key: 'handleKeyUp',
    value: function () {
      function handleKeyUp() {
        if (this._performAutoCompleteOnKeyUp) {
          this._performAutoCompleteOnKeyUp = false;
          this.maybeAutoCompleteText();
        }
      }

      return handleKeyUp;
    }()
  }, {
    key: 'getFilteredItems',
    value: function () {
      function getFilteredItems() {
        var _this3 = this;

        var items = this.props.items;

        if (this.props.shouldItemRender) {
          items = items.filter(function (item) {
            return _this3.props.shouldItemRender(item, _this3.props.value);
          });
        }

        if (this.props.sortItems) {
          items.sort(function (a, b) {
            return _this3.props.sortItems(a, b, _this3.props.value);
          });
        }

        return items;
      }

      return getFilteredItems;
    }()
  }, {
    key: 'maybeAutoCompleteText',
    value: function () {
      function maybeAutoCompleteText() {
        if (!this.props.autoHighlight || this.props.value === '') {
          return;
        }
        var highlightedIndex = this.state.highlightedIndex;

        var items = this.getFilteredItems();
        if (items.length === 0) {
          return;
        }
        var matchedItem = highlightedIndex !== null ? items[highlightedIndex] : items[0];
        var itemValue = this.props.getItemValue(matchedItem);
        var itemValueDoesMatch = itemValue.toLowerCase().indexOf(this.props.value.toLowerCase()) === 0;
        if (itemValueDoesMatch && highlightedIndex === null) {
          this.setState({ highlightedIndex: 0 });
        }
      }

      return maybeAutoCompleteText;
    }()
  }, {
    key: 'setMenuPositions',
    value: function () {
      function setMenuPositions() {
        var node = this.inputEl;
        var rect = node.getBoundingClientRect();
        var computedStyle = global.window.getComputedStyle(node);
        var marginBottom = parseInt(computedStyle.marginBottom, 10) || 0;
        var marginLeft = parseInt(computedStyle.marginLeft, 10) || 0;
        var marginRight = parseInt(computedStyle.marginRight, 10) || 0;
        this.setState({
          menuTop: rect.bottom + marginBottom,
          menuLeft: rect.left + marginLeft,
          menuWidth: rect.width + marginLeft + marginRight
        });
      }

      return setMenuPositions;
    }()
  }, {
    key: 'highlightItemFromMouse',
    value: function () {
      function highlightItemFromMouse(index) {
        this.setState({ highlightedIndex: index });
      }

      return highlightItemFromMouse;
    }()
  }, {
    key: 'selectItemFromMouse',
    value: function () {
      function selectItemFromMouse(item) {
        var _this4 = this;

        var value = this.props.getItemValue(item);
        this.setState({
          isOpen: false,
          highlightedIndex: null
        }, function () {
          _this4.props.onSelect(value, item);
          _this4.inputEl.focus();
        });
      }

      return selectItemFromMouse;
    }()
  }, {
    key: 'setIgnoreBlur',
    value: function () {
      function setIgnoreBlur(ignore) {
        this._ignoreBlur = ignore;
      }

      return setIgnoreBlur;
    }()
  }, {
    key: 'renderMenu',
    value: function () {
      function renderMenu() {
        var _this5 = this;

        var items = this.getFilteredItems().map(function (item, index) {
          var element = _this5.props.renderItem(item, _this5.state.highlightedIndex === index, { cursor: 'default' });
          return _react2['default'].cloneElement(element, {
            onMouseDown: function () {
              function onMouseDown() {
                return _this5.setIgnoreBlur(true);
              }

              return onMouseDown;
            }(),
            // Ignore blur to prevent menu from de-rendering before we can process click
            onMouseEnter: function () {
              function onMouseEnter() {
                return _this5.highlightItemFromMouse(index);
              }

              return onMouseEnter;
            }(),
            onClick: function () {
              function onClick() {
                return _this5.selectItemFromMouse(item);
              }

              return onClick;
            }(),
            ref: 'item-' + String(index)
          });
        });
        var style = {
          left: this.state.menuLeft,
          top: this.state.menuTop,
          minWidth: this.state.menuWidth
        };
        if (!items.length) return null;
        var menu = this.props.renderMenu(items, this.props.value, style);
        return _react2['default'].cloneElement(menu, { ref: 'menu' });
      }

      return renderMenu;
    }()
  }, {
    key: 'handleInputBlur',
    value: function () {
      function handleInputBlur() {
        if (this.props.onFocus) {
          this.props.onFocus();
        }
        if (this._ignoreBlur) {
          return;
        }
        this.setState({
          isOpen: false,
          highlightedIndex: null
        });
      }

      return handleInputBlur;
    }()
  }, {
    key: 'handleInputFocus',
    value: function () {
      function handleInputFocus() {
        if (this.props.onFocus) {
          this.props.onFocus(true);
        }
        if (this._ignoreBlur) {
          this.setIgnoreBlur(false);
          return;
        }
        // We don't want `selectItemFromMouse` to trigger when
        // the user clicks into the input to focus it, so set this
        // flag to cancel out the logic in `handleInputClick`.
        // The event order is:  MouseDown -> Focus -> MouseUp -> Click
        this._ignoreClick = true;
        this.setState({ isOpen: true });
      }

      return handleInputFocus;
    }()
  }, {
    key: 'isInputFocused',
    value: function () {
      function isInputFocused() {
        return this.inputEl.ownerDocument && this.inputEl === this.inputEl.ownerDocument.activeElement;
      }

      return isInputFocused;
    }()
  }, {
    key: 'handleInputClick',
    value: function () {
      function handleInputClick() {
        // Input will not be focused if it's disabled
        if (this.isInputFocused() && this.state.isOpen === false) {
          this.setState({ isOpen: true });
        } else if (this.state.highlightedIndex !== null && !this._ignoreClick) {
          this.selectItemFromMouse(this.getFilteredItems()[this.state.highlightedIndex]);
        }
        this._ignoreClick = false;
      }

      return handleInputClick;
    }()
  }, {
    key: 'composeEventHandlers',
    value: function () {
      function composeEventHandlers(internal, external) {
        return external ? function (e) {
          internal(e);
          external(e);
        } : internal;
      }

      return composeEventHandlers;
    }()

    /* ------------------------------ Rendering ------------------------------- */

  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this6 = this;

        if (this.props.debug) {
          // you don't like it, you love it
          _debugStates.push({
            id: _debugStates.length,
            state: this.state
          });
        }

        var inputProps = this.props.inputProps;

        return _react2['default'].createElement(
          'div',
          (0, _extends3['default'])({ style: (0, _extends3['default'])({}, this.props.wrapperStyle) }, this.props.wrapperProps),
          _react2['default'].createElement('input', (0, _extends3['default'])({}, inputProps, {
            ref: function () {
              function ref(el) {
                _this6.inputEl = el;
              }

              return ref;
            }(),
            'aria-autocomplete': 'list',
            autoComplete: 'off',
            onBlur: this.composeEventHandlers(this.handleInputBlur.bind(this), inputProps.onBlur && inputProps.onBlur.bind(this)),
            onChange: this.handleChange.bind(this),
            onClick: this.composeEventHandlers(this.handleInputClick.bind(this), inputProps.onClick && inputProps.onClick.bind(this)),
            onFocus: this.composeEventHandlers(this.handleInputFocus.bind(this), inputProps.onFocus && inputProps.onFocus.bind(this)),
            onKeyDown: this.composeEventHandlers(this.handleKeyDown.bind(this), inputProps.onKeyDown && inputProps.onKeyDown.bind(this)),
            onKeyUp: this.composeEventHandlers(this.handleKeyUp.bind(this), inputProps.onKeyUp && inputProps.onKeyUp.bind(this)),
            role: 'combobox',
            value: this.props.value
          })),
          ('open' in this.props ? this.props.open : this.state.isOpen) && this.renderMenu(),
          this.props.debug && _react2['default'].createElement(
            'pre',
            { style: { marginLeft: 300 } },
            (0, _stringify2['default'])(_debugStates.slice(_debugStates.length - 5, _debugStates.length), null, 2)
          )
        );
      }

      return render;
    }()
  }]);
  return Autocomplete;
}(_react2['default'].Component);

Autocomplete.defaultProps = {
  value: '',
  wrapperProps: {},
  wrapperStyle: {
    display: 'inline-block'
  },
  inputProps: {},
  onChange: function () {
    function onChange() {}

    return onChange;
  }(),
  onSelect: function () {
    function onSelect() {}

    return onSelect;
  }(),
  renderMenu: function () {
    function renderMenu(items, value, style) {
      return (
        /* eslint-disable react/no-this-in-sfc */
        _react2['default'].createElement(
          'div',
          { style: (0, _extends3['default'])({}, style, this.menuStyle) },
          items
        )
        /* eslint-enable react/no-this-in-sfc */

      );
    }

    return renderMenu;
  }(),
  shouldItemRender: function () {
    function shouldItemRender() {
      return true;
    }

    return shouldItemRender;
  }(),

  menuStyle: {
    borderRadius: '3px',
    boxShadow: '0 2px 12px rgba(0, 0, 0, 0.1)',
    background: 'rgba(255, 255, 255, 0.9)',
    padding: '2px 0',
    fontSize: '90%',
    position: 'fixed',
    overflow: 'auto',
    maxHeight: '50%' // TODO: don't cheat, let it flow to the bottom
  },
  autoHighlight: true,
  onMenuVisibilityChange: function () {
    function onMenuVisibilityChange() {}

    return onMenuVisibilityChange;
  }()
};

Autocomplete.propTypes = {
  autoHighlight: _propTypes2['default'].bool,
  debug: _propTypes2['default'].bool,
  getItemValue: _propTypes2['default'].func.isRequired,
  inputProps: _propTypes2['default'].object,
  items: _propTypes2['default'].array,
  menuStyle: _propTypes2['default'].object,
  onChange: _propTypes2['default'].func,
  onFocus: _propTypes2['default'].func,
  onMenuVisibilityChange: _propTypes2['default'].func,
  onSelect: _propTypes2['default'].func,
  open: _propTypes2['default'].bool,
  renderItem: _propTypes2['default'].func.isRequired,
  renderMenu: _propTypes2['default'].func,
  shouldItemRender: _propTypes2['default'].func,
  sortItems: _propTypes2['default'].func,
  value: _propTypes2['default'].any,
  wrapperProps: _propTypes2['default'].object,
  wrapperStyle: _propTypes2['default'].object
};

exports['default'] = Autocomplete;
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_3628500__(27)))

/***/ }),
/* 678 */
/***/ (function(module, exports, __nested_webpack_require_3647754__) {

"use strict";


module.exports = __nested_webpack_require_3647754__(679);

/***/ }),
/* 679 */
/***/ (function(module, exports, __nested_webpack_require_3647891__) {

"use strict";


var util = __nested_webpack_require_3647891__(680);

function scrollIntoView(elem, container, config) {
  config = config || {};
  // document 归一化到 window
  if (container.nodeType === 9) {
    container = util.getWindow(container);
  }

  var allowHorizontalScroll = config.allowHorizontalScroll;
  var onlyScrollIfNeeded = config.onlyScrollIfNeeded;
  var alignWithTop = config.alignWithTop;
  var alignWithLeft = config.alignWithLeft;
  var offsetTop = config.offsetTop || 0;
  var offsetLeft = config.offsetLeft || 0;
  var offsetBottom = config.offsetBottom || 0;
  var offsetRight = config.offsetRight || 0;

  allowHorizontalScroll = allowHorizontalScroll === undefined ? true : allowHorizontalScroll;

  var isWin = util.isWindow(container);
  var elemOffset = util.offset(elem);
  var eh = util.outerHeight(elem);
  var ew = util.outerWidth(elem);
  var containerOffset = undefined;
  var ch = undefined;
  var cw = undefined;
  var containerScroll = undefined;
  var diffTop = undefined;
  var diffBottom = undefined;
  var win = undefined;
  var winScroll = undefined;
  var ww = undefined;
  var wh = undefined;

  if (isWin) {
    win = container;
    wh = util.height(win);
    ww = util.width(win);
    winScroll = {
      left: util.scrollLeft(win),
      top: util.scrollTop(win)
    };
    // elem 相对 container 可视视窗的距离
    diffTop = {
      left: elemOffset.left - winScroll.left - offsetLeft,
      top: elemOffset.top - winScroll.top - offsetTop
    };
    diffBottom = {
      left: elemOffset.left + ew - (winScroll.left + ww) + offsetRight,
      top: elemOffset.top + eh - (winScroll.top + wh) + offsetBottom
    };
    containerScroll = winScroll;
  } else {
    containerOffset = util.offset(container);
    ch = container.clientHeight;
    cw = container.clientWidth;
    containerScroll = {
      left: container.scrollLeft,
      top: container.scrollTop
    };
    // elem 相对 container 可视视窗的距离
    // 注意边框, offset 是边框到根节点
    diffTop = {
      left: elemOffset.left - (containerOffset.left + (parseFloat(util.css(container, 'borderLeftWidth')) || 0)) - offsetLeft,
      top: elemOffset.top - (containerOffset.top + (parseFloat(util.css(container, 'borderTopWidth')) || 0)) - offsetTop
    };
    diffBottom = {
      left: elemOffset.left + ew - (containerOffset.left + cw + (parseFloat(util.css(container, 'borderRightWidth')) || 0)) + offsetRight,
      top: elemOffset.top + eh - (containerOffset.top + ch + (parseFloat(util.css(container, 'borderBottomWidth')) || 0)) + offsetBottom
    };
  }

  if (diffTop.top < 0 || diffBottom.top > 0) {
    // 强制向上
    if (alignWithTop === true) {
      util.scrollTop(container, containerScroll.top + diffTop.top);
    } else if (alignWithTop === false) {
      util.scrollTop(container, containerScroll.top + diffBottom.top);
    } else {
      // 自动调整
      if (diffTop.top < 0) {
        util.scrollTop(container, containerScroll.top + diffTop.top);
      } else {
        util.scrollTop(container, containerScroll.top + diffBottom.top);
      }
    }
  } else {
    if (!onlyScrollIfNeeded) {
      alignWithTop = alignWithTop === undefined ? true : !!alignWithTop;
      if (alignWithTop) {
        util.scrollTop(container, containerScroll.top + diffTop.top);
      } else {
        util.scrollTop(container, containerScroll.top + diffBottom.top);
      }
    }
  }

  if (allowHorizontalScroll) {
    if (diffTop.left < 0 || diffBottom.left > 0) {
      // 强制向上
      if (alignWithLeft === true) {
        util.scrollLeft(container, containerScroll.left + diffTop.left);
      } else if (alignWithLeft === false) {
        util.scrollLeft(container, containerScroll.left + diffBottom.left);
      } else {
        // 自动调整
        if (diffTop.left < 0) {
          util.scrollLeft(container, containerScroll.left + diffTop.left);
        } else {
          util.scrollLeft(container, containerScroll.left + diffBottom.left);
        }
      }
    } else {
      if (!onlyScrollIfNeeded) {
        alignWithLeft = alignWithLeft === undefined ? true : !!alignWithLeft;
        if (alignWithLeft) {
          util.scrollLeft(container, containerScroll.left + diffTop.left);
        } else {
          util.scrollLeft(container, containerScroll.left + diffBottom.left);
        }
      }
    }
  }
}

module.exports = scrollIntoView;

/***/ }),
/* 680 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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

var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source;

function getClientPosition(elem) {
  var box = undefined;
  var x = undefined;
  var y = undefined;
  var doc = elem.ownerDocument;
  var body = doc.body;
  var docElem = doc && doc.documentElement;
  // 根据 GBS 最新数据，A-Grade Browsers 都已支持 getBoundingClientRect 方法，不用再考虑传统的实现方式
  box = elem.getBoundingClientRect();

  // 注：jQuery 还考虑减去 docElem.clientLeft/clientTop
  // 但测试发现，这样反而会导致当 html 和 body 有边距/边框样式时，获取的值不正确
  // 此外，ie6 会忽略 html 的 margin 值，幸运地是没有谁会去设置 html 的 margin

  x = box.left;
  y = box.top;

  // In IE, most of the time, 2 extra pixels are added to the top and left
  // due to the implicit 2-pixel inset border.  In IE6/7 quirks mode and
  // IE6 standards mode, this border can be overridden by setting the
  // document element's border to zero -- thus, we cannot rely on the
  // offset always being 2 pixels.

  // In quirks mode, the offset can be determined by querying the body's
  // clientLeft/clientTop, but in standards mode, it is found by querying
  // the document element's clientLeft/clientTop.  Since we already called
  // getClientBoundingRect we have already forced a reflow, so it is not
  // too expensive just to query them all.

  // ie 下应该减去窗口的边框吧，毕竟默认 absolute 都是相对窗口定位的
  // 窗口边框标准是设 documentElement ,quirks 时设置 body
  // 最好禁止在 body 和 html 上边框 ，但 ie < 9 html 默认有 2px ，减去
  // 但是非 ie 不可能设置窗口边框，body html 也不是窗口 ,ie 可以通过 html,body 设置
  // 标准 ie 下 docElem.clientTop 就是 border-top
  // ie7 html 即窗口边框改变不了。永远为 2
  // 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框，即使设了 border-top 也为 0

  x -= docElem.clientLeft || body.clientLeft || 0;
  y -= docElem.clientTop || body.clientTop || 0;

  return {
    left: x,
    top: y
  };
}

function getScroll(w, top) {
  var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
  var method = 'scroll' + (top ? 'Top' : 'Left');
  if (typeof ret !== 'number') {
    var d = w.document;
    // ie6,7,8 standard mode
    ret = d.documentElement[method];
    if (typeof ret !== 'number') {
      // quirks mode
      ret = d.body[method];
    }
  }
  return ret;
}

function getScrollLeft(w) {
  return getScroll(w);
}

function getScrollTop(w) {
  return getScroll(w, true);
}

function getOffset(el) {
  var pos = getClientPosition(el);
  var doc = el.ownerDocument;
  var w = doc.defaultView || doc.parentWindow;
  pos.left += getScrollLeft(w);
  pos.top += getScrollTop(w);
  return pos;
}
function _getComputedStyle(elem, name, computedStyle_) {
  var val = '';
  var d = elem.ownerDocument;
  var computedStyle = computedStyle_ || d.defaultView.getComputedStyle(elem, null);

  // https://github.com/kissyteam/kissy/issues/61
  if (computedStyle) {
    val = computedStyle.getPropertyValue(name) || computedStyle[name];
  }

  return val;
}

var _RE_NUM_NO_PX = new RegExp('^(' + RE_NUM + ')(?!px)[a-z%]+$', 'i');
var RE_POS = /^(top|right|bottom|left)$/;
var CURRENT_STYLE = 'currentStyle';
var RUNTIME_STYLE = 'runtimeStyle';
var LEFT = 'left';
var PX = 'px';

function _getComputedStyleIE(elem, name) {
  // currentStyle maybe null
  // http://msdn.microsoft.com/en-us/library/ms535231.aspx
  var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name];

  // 当 width/height 设置为百分比时，通过 pixelLeft 方式转换的 width/height 值
  // 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19
  // 在 ie 下不对，需要直接用 offset 方式
  // borderWidth 等值也有问题，但考虑到 borderWidth 设为百分比的概率很小，这里就不考虑了

  // From the awesome hack by Dean Edwards
  // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
  // If we're not dealing with a regular pixel number
  // but a number that has a weird ending, we need to convert it to pixels
  // exclude left right for relativity
  if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) {
    // Remember the original values
    var style = elem.style;
    var left = style[LEFT];
    var rsLeft = elem[RUNTIME_STYLE][LEFT];

    // prevent flashing of content
    elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT];

    // Put in the new values to get a computed value out
    style[LEFT] = name === 'fontSize' ? '1em' : ret || 0;
    ret = style.pixelLeft + PX;

    // Revert the changed values
    style[LEFT] = left;

    elem[RUNTIME_STYLE][LEFT] = rsLeft;
  }
  return ret === '' ? 'auto' : ret;
}

var getComputedStyleX = undefined;
if (typeof window !== 'undefined') {
  getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE;
}

function each(arr, fn) {
  for (var i = 0; i < arr.length; i++) {
    fn(arr[i]);
  }
}

function isBorderBoxFn(elem) {
  return getComputedStyleX(elem, 'boxSizing') === 'border-box';
}

var BOX_MODELS = ['margin', 'border', 'padding'];
var CONTENT_INDEX = -1;
var PADDING_INDEX = 2;
var BORDER_INDEX = 1;
var MARGIN_INDEX = 0;

function swap(elem, options, callback) {
  var old = {};
  var style = elem.style;
  var name = undefined;

  // Remember the old values, and insert the new ones
  for (name in options) {
    if (options.hasOwnProperty(name)) {
      old[name] = style[name];
      style[name] = options[name];
    }
  }

  callback.call(elem);

  // Revert the old values
  for (name in options) {
    if (options.hasOwnProperty(name)) {
      style[name] = old[name];
    }
  }
}

function getPBMWidth(elem, props, which) {
  var value = 0;
  var prop = undefined;
  var j = undefined;
  var i = undefined;
  for (j = 0; j < props.length; j++) {
    prop = props[j];
    if (prop) {
      for (i = 0; i < which.length; i++) {
        var cssProp = undefined;
        if (prop === 'border') {
          cssProp = prop + which[i] + 'Width';
        } else {
          cssProp = prop + which[i];
        }
        value += parseFloat(getComputedStyleX(elem, cssProp)) || 0;
      }
    }
  }
  return value;
}

/**
 * A crude way of determining if an object is a window
 * @member util
 */
function isWindow(obj) {
  // must use == for ie8
  /* eslint eqeqeq:0 */
  return obj != null && obj == obj.window;
}

var domUtils = {};

each(['Width', 'Height'], function (name) {
  domUtils['doc' + name] = function (refWin) {
    var d = refWin.document;
    return Math.max(
    // firefox chrome documentElement.scrollHeight< body.scrollHeight
    // ie standard mode : documentElement.scrollHeight> body.scrollHeight
    d.documentElement['scroll' + name],
    // quirks : documentElement.scrollHeight 最大等于可视窗口多一点？
    d.body['scroll' + name], domUtils['viewport' + name](d));
  };

  domUtils['viewport' + name] = function (win) {
    // pc browser includes scrollbar in window.innerWidth
    var prop = 'client' + name;
    var doc = win.document;
    var body = doc.body;
    var documentElement = doc.documentElement;
    var documentElementProp = documentElement[prop];
    // 标准模式取 documentElement
    // backcompat 取 body
    return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp;
  };
});

/*
 得到元素的大小信息
 @param elem
 @param name
 @param {String} [extra]  'padding' : (css width) + padding
 'border' : (css width) + padding + border
 'margin' : (css width) + padding + border + margin
 */
function getWH(elem, name, extra) {
  if (isWindow(elem)) {
    return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem);
  } else if (elem.nodeType === 9) {
    return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem);
  }
  var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];
  var borderBoxValue = name === 'width' ? elem.offsetWidth : elem.offsetHeight;
  var computedStyle = getComputedStyleX(elem);
  var isBorderBox = isBorderBoxFn(elem, computedStyle);
  var cssBoxValue = 0;
  if (borderBoxValue == null || borderBoxValue <= 0) {
    borderBoxValue = undefined;
    // Fall back to computed then un computed css if necessary
    cssBoxValue = getComputedStyleX(elem, name);
    if (cssBoxValue == null || Number(cssBoxValue) < 0) {
      cssBoxValue = elem.style[name] || 0;
    }
    // Normalize '', auto, and prepare for extra
    cssBoxValue = parseFloat(cssBoxValue) || 0;
  }
  if (extra === undefined) {
    extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX;
  }
  var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox;
  var val = borderBoxValue || cssBoxValue;
  if (extra === CONTENT_INDEX) {
    if (borderBoxValueOrIsBorderBox) {
      return val - getPBMWidth(elem, ['border', 'padding'], which, computedStyle);
    }
    return cssBoxValue;
  }
  if (borderBoxValueOrIsBorderBox) {
    var padding = extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which, computedStyle) : getPBMWidth(elem, ['margin'], which, computedStyle);
    return val + (extra === BORDER_INDEX ? 0 : padding);
  }
  return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which, computedStyle);
}

var cssShow = {
  position: 'absolute',
  visibility: 'hidden',
  display: 'block'
};

// fix #119 : https://github.com/kissyteam/kissy/issues/119
function getWHIgnoreDisplay(elem) {
  var val = undefined;
  var args = arguments;
  // in case elem is window
  // elem.offsetWidth === undefined
  if (elem.offsetWidth !== 0) {
    val = getWH.apply(undefined, args);
  } else {
    swap(elem, cssShow, function () {
      val = getWH.apply(undefined, args);
    });
  }
  return val;
}

function css(el, name, v) {
  var value = v;
  if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
    for (var i in name) {
      if (name.hasOwnProperty(i)) {
        css(el, i, name[i]);
      }
    }
    return undefined;
  }
  if (typeof value !== 'undefined') {
    if (typeof value === 'number') {
      value += 'px';
    }
    el.style[name] = value;
    return undefined;
  }
  return getComputedStyleX(el, name);
}

each(['width', 'height'], function (name) {
  var first = name.charAt(0).toUpperCase() + name.slice(1);
  domUtils['outer' + first] = function (el, includeMargin) {
    return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX);
  };
  var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom'];

  domUtils[name] = function (elem, val) {
    if (val !== undefined) {
      if (elem) {
        var computedStyle = getComputedStyleX(elem);
        var isBorderBox = isBorderBoxFn(elem);
        if (isBorderBox) {
          val += getPBMWidth(elem, ['padding', 'border'], which, computedStyle);
        }
        return css(elem, name, val);
      }
      return undefined;
    }
    return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX);
  };
});

// 设置 elem 相对 elem.ownerDocument 的坐标
function setOffset(elem, offset) {
  // set position first, in-case top/left are set even on static elem
  if (css(elem, 'position') === 'static') {
    elem.style.position = 'relative';
  }

  var old = getOffset(elem);
  var ret = {};
  var current = undefined;
  var key = undefined;

  for (key in offset) {
    if (offset.hasOwnProperty(key)) {
      current = parseFloat(css(elem, key)) || 0;
      ret[key] = current + offset[key] - old[key];
    }
  }
  css(elem, ret);
}

module.exports = _extends({
  getWindow: function getWindow(node) {
    var doc = node.ownerDocument || node;
    return doc.defaultView || doc.parentWindow;
  },
  offset: function offset(el, value) {
    if (typeof value !== 'undefined') {
      setOffset(el, value);
    } else {
      return getOffset(el);
    }
  },

  isWindow: isWindow,
  each: each,
  css: css,
  clone: function clone(obj) {
    var ret = {};
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        ret[i] = obj[i];
      }
    }
    var overflow = obj.overflow;
    if (overflow) {
      for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
          ret.overflow[i] = obj.overflow[i];
        }
      }
    }
    return ret;
  },
  scrollLeft: function scrollLeft(w, v) {
    if (isWindow(w)) {
      if (v === undefined) {
        return getScrollLeft(w);
      }
      window.scrollTo(v, getScrollTop(w));
    } else {
      if (v === undefined) {
        return w.scrollLeft;
      }
      w.scrollLeft = v;
    }
  },
  scrollTop: function scrollTop(w, v) {
    if (isWindow(w)) {
      if (v === undefined) {
        return getScrollTop(w);
      }
      window.scrollTo(getScrollLeft(w), v);
    } else {
      if (v === undefined) {
        return w.scrollTop;
      }
      w.scrollTop = v;
    }
  },

  viewportWidth: 0,
  viewportHeight: 0
}, domUtils);

/***/ }),
/* 681 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"genome-position-search":"GenomePositionSearchBox-module_genome-position-search-SYccr","genome-position-search-focus":"GenomePositionSearchBox-module_genome-position-search-focus-23by2","genome-position-search-bar":"GenomePositionSearchBox-module_genome-position-search-bar-1_0ZU","genome-position-search-dark":"GenomePositionSearchBox-module_genome-position-search-dark-EML2e","genome-position-search-bar-button":"GenomePositionSearchBox-module_genome-position-search-bar-button-33SWJ","genome-position-search-bar-button-focus":"GenomePositionSearchBox-module_genome-position-search-bar-button-focus-1IhAk","genome-position-search-bar-icon":"GenomePositionSearchBox-module_genome-position-search-bar-icon-14AEk","genome-position-search-bar-icon-focus":"GenomePositionSearchBox-module_genome-position-search-bar-icon-focus-1Ay7Z","genome-position-search-bar-suggestions":"GenomePositionSearchBox-module_genome-position-search-bar-suggestions-SrIoU","btn":"GenomePositionSearchBox-module_btn-2bTUd","btn-sm":"GenomePositionSearchBox-module_btn-sm-2Ltms","btn-default":"GenomePositionSearchBox-module_btn-default-2pap4"};

/***/ }),
/* 682 */
/***/ (function(module, exports, __nested_webpack_require_3666551__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3666551__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3666551__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3666551__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3666551__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3666551__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = __nested_webpack_require_3666551__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3666551__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _Button = __nested_webpack_require_3666551__(170);

var _Button2 = _interopRequireDefault(_Button);

var _Dialog = __nested_webpack_require_3666551__(169);

var _Dialog2 = _interopRequireDefault(_Dialog);

__nested_webpack_require_3666551__(683);

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

var ExportLinkDialog = function (_React$Component) {
  (0, _inherits3['default'])(ExportLinkDialog, _React$Component);

  function ExportLinkDialog() {
    (0, _classCallCheck3['default'])(this, ExportLinkDialog);
    return (0, _possibleConstructorReturn3['default'])(this, (ExportLinkDialog.__proto__ || (0, _getPrototypeOf2['default'])(ExportLinkDialog)).apply(this, arguments));
  }

  (0, _createClass3['default'])(ExportLinkDialog, [{
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        return _react2['default'].createElement(
          _Dialog2['default'],
          {
            okayOnly: true,
            okayTitle: 'Done',
            onOkay: this.props.onDone,
            title: 'Share view link'
          },
          _react2['default'].createElement(
            'div',
            { className: 'ExportLinkDialog-module_export-link-dialog-wrapper-ldYlL' },
            _react2['default'].createElement('input', {
              ref: function () {
                function ref(element) {
                  if (!element) return;
                  _this2.input = element;
                  element.focus();
                  element.select();
                }

                return ref;
              }(),
              onClick: function () {
                function onClick(event) {
                  event.target.select();
                }

                return onClick;
              }(),
              placeholder: 'Generating the link...',
              readOnly: true,
              value: this.props.url
            }),
            _react2['default'].createElement(
              _Button2['default'],
              {
                onClick: function () {
                  function onClick(event) {
                    _this2.input.select();
                    document.execCommand('copy');
                  }

                  return onClick;
                }()
              },
              'Copy'
            )
          )
        );
      }

      return render;
    }()
  }]);
  return ExportLinkDialog;
}(_react2['default'].Component);

ExportLinkDialog.defaultProps = {
  onDone: function () {
    function onDone() {}

    return onDone;
  }(),
  url: ''
};

ExportLinkDialog.propTypes = {
  onDone: _propTypes2['default'].func,
  url: _propTypes2['default'].string
};

exports['default'] = ExportLinkDialog;

/***/ }),
/* 683 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"export-link-dialog-wrapper":"ExportLinkDialog-module_export-link-dialog-wrapper-ldYlL"};

/***/ }),
/* 684 */
/***/ (function(module, exports, __nested_webpack_require_3670404__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_3670404__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3670404__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3670404__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3670404__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3670404__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3670404__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_3670404__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3670404__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _PopupMenu = __nested_webpack_require_3670404__(264);

var _PopupMenu2 = _interopRequireDefault(_PopupMenu);

var _ContextMenuContainer = __nested_webpack_require_3670404__(96);

var _ContextMenuContainer2 = _interopRequireDefault(_ContextMenuContainer);

var _ConfigViewMenu = __nested_webpack_require_3670404__(685);

var _ConfigViewMenu2 = _interopRequireDefault(_ConfigViewMenu);

var _AddTrackPositionMenu = __nested_webpack_require_3670404__(686);

var _AddTrackPositionMenu2 = _interopRequireDefault(_AddTrackPositionMenu);

var _withTheme = __nested_webpack_require_3670404__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _configs = __nested_webpack_require_3670404__(11);

__nested_webpack_require_3670404__(267);

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

// Configs
var _styleModuleImportMap = {
  '../styles/ViewHeader.module.scss': {
    'multitrack-header': 'ViewHeader-module_multitrack-header-3XnZx',
    'multitrack-header-focus': 'ViewHeader-module_multitrack-header-focus-3akkN',
    'multitrack-header-squeazed': 'ViewHeader-module_multitrack-header-squeazed-GHIVd',
    'multitrack-header-dark': 'ViewHeader-module_multitrack-header-dark-97tZt',
    'multitrack-header-id': 'ViewHeader-module_multitrack-header-id-3YURk',
    'multitrack-header-left': 'ViewHeader-module_multitrack-header-left-Qj9Sm',
    'multitrack-header-grabber': 'ViewHeader-module_multitrack-header-grabber-3jrIz',
    'multitrack-header-grabber-squeazed': 'ViewHeader-module_multitrack-header-grabber-squeazed-dU45Z',
    'multitrack-header-search': 'ViewHeader-module_multitrack-header-search-1X_3_',
    'multitrack-header-nav-list': 'ViewHeader-module_multitrack-header-nav-list-2nvcu',
    'multitrack-header-icon': 'ViewHeader-module_multitrack-header-icon-16QKZ',
    'multitrack-header-icon-squeazed': 'ViewHeader-module_multitrack-header-icon-squeazed-25lkF',
    'mouse-tool-selection': 'ViewHeader-module_mouse-tool-selection-1pg2m'
  }
};

// Styles


// HOCS

var ViewHeader = function (_React$Component) {
  (0, _inherits3['default'])(ViewHeader, _React$Component);

  function ViewHeader(props) {
    (0, _classCallCheck3['default'])(this, ViewHeader);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ViewHeader.__proto__ || (0, _getPrototypeOf2['default'])(ViewHeader)).call(this, props));

    _this.configImg = null;
    _this.plusImg = null;

    _this.state = {
      addTrackPositionMenuUid: null,
      addTrackPositionMenuPosition: null,
      configMenuUid: null,
      configMenuPosition: null,
      isFocused: false,
      width: -1
    };

    _this.handleTrackPositionChosenBound = _this.handleTrackPositionChosen.bind(_this);
    return _this;
  }

  (0, _createClass3['default'])(ViewHeader, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        // eslint-disable-next-line react/no-did-mount-set-state
        this.setState({ width: this.el.clientWidth });
      }

      return componentDidMount;
    }()
  }, {
    key: 'checkWidth',
    value: function () {
      function checkWidth() {
        var width = this.el.clientWidth;

        if (width !== this.state.width) this.setState({ width: width });
      }

      return checkWidth;
    }()

    /**
     * The user clicked on the `cog` of the menu so we need to open
     * it.
     */

  }, {
    key: 'handleConfigMenuOpened',
    value: function () {
      function handleConfigMenuOpened(uid) {
        this.setState({
          configMenuUid: uid,
          configMenuPosition: this.configImg.getBoundingClientRect()
        });
      }

      return handleConfigMenuOpened;
    }()

    /**
     * The user has clicked on the 'plus' sign at the top of a TiledPlot
     * so we need to open the Track Position Chooser dialog
     */

  }, {
    key: 'handleAddTrackPositionMenuOpened',
    value: function () {
      function handleAddTrackPositionMenuOpened(uid) {
        this.setState({
          addTrackPositionMenuUid: uid,
          addTrackPositionMenuPosition: this.plusImg.getBoundingClientRect()
        });
      }

      return handleAddTrackPositionMenuOpened;
    }()

    /**
     * The user has chosen a position for the new track. The actual
     * track selection will be handled by TiledPlot
     *
     * We just need to close the menu here.
     */

  }, {
    key: 'handleTrackPositionChosen',
    value: function () {
      function handleTrackPositionChosen(position) {
        this.props.onTrackPositionChosen(position);

        this.setState({
          addTrackPositionMenuUid: null,
          addTrackPositionMenuPosition: null
        });
      }

      return handleTrackPositionChosen;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this2 = this;

        var configMenu = null;
        var addTrackPositionMenu = null;

        if (this.state.addTrackPositionMenuPosition) {
          addTrackPositionMenu = _react2['default'].createElement(
            _PopupMenu2['default'],
            {
              onMenuClosed: function () {
                function onMenuClosed() {
                  _this2.setState({
                    addTrackPositionMenuUid: null,
                    addTrackPositionMenuPosition: null
                  });
                }

                return onMenuClosed;
              }()
            },
            _react2['default'].createElement(
              _ContextMenuContainer2['default'],
              {
                orientation: 'left',
                position: this.state.addTrackPositionMenuPosition,
                theme: this.props.theme
              },
              _react2['default'].createElement(_AddTrackPositionMenu2['default'], {
                onTrackPositionChosen: this.handleTrackPositionChosenBound
              })
            )
          );
        }

        if (this.state.configMenuUid) {
          configMenu = _react2['default'].createElement(
            _PopupMenu2['default'],
            { onMenuClosed: function () {
                function onMenuClosed() {
                  return _this2.setState({ configMenuUid: null });
                }

                return onMenuClosed;
              }() },
            _react2['default'].createElement(_ConfigViewMenu2['default'], {
              onClearView: function () {
                function onClearView() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onClearView();
                }

                return onClearView;
              }(),
              onEditViewConfig: function () {
                function onEditViewConfig() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onEditViewConfig(_this2.state.configMenuUid);
                }

                return onEditViewConfig;
              }(),
              onExportPNG: function () {
                function onExportPNG() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onExportPNG();
                }

                return onExportPNG;
              }(),
              onExportSVG: function () {
                function onExportSVG() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onExportSVG();
                }

                return onExportSVG;
              }(),
              onExportViewAsJSON: function () {
                function onExportViewAsJSON() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onExportViewsAsJSON();
                }

                return onExportViewAsJSON;
              }(),
              onExportViewAsLink: function () {
                function onExportViewAsLink() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onExportViewsAsLink();
                }

                return onExportViewAsLink;
              }(),
              onLockLocation: function () {
                function onLockLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onLockLocation(_this2.state.configMenuUid);
                }

                return onLockLocation;
              }(),
              onLockZoom: function () {
                function onLockZoom() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onLockZoom(_this2.state.configMenuUid);
                }

                return onLockZoom;
              }(),
              onLockZoomAndLocation: function () {
                function onLockZoomAndLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onLockZoomAndLocation(_this2.state.configMenuUid);
                }

                return onLockZoomAndLocation;
              }(),
              onOptionsChanged: function () {
                function onOptionsChanged(newOptions) {
                  _this2.props.onViewOptionsChanged(newOptions);
                  _this2.setState({ configMenuUid: null }); // hide the menu
                }

                return onOptionsChanged;
              }(),
              onProjectViewport: function () {
                function onProjectViewport() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onProjectViewport(_this2.state.configMenuUid);
                }

                return onProjectViewport;
              }(),
              onTakeAndLockZoomAndLocation: function () {
                function onTakeAndLockZoomAndLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onTakeAndLockZoomAndLocation(_this2.state.configMenuUid);
                }

                return onTakeAndLockZoomAndLocation;
              }(),
              onTogglePositionSearchBox: function () {
                function onTogglePositionSearchBox() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onTogglePositionSearchBox(_this2.state.configMenuUid);
                }

                return onTogglePositionSearchBox;
              }(),
              onUnlockLocation: function () {
                function onUnlockLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onUnlockLocation(_this2.state.configMenuUid);
                }

                return onUnlockLocation;
              }(),
              onUnlockZoom: function () {
                function onUnlockZoom() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onUnlockZoom(_this2.state.configMenuUid);
                }

                return onUnlockZoom;
              }(),
              onUnlockZoomAndLocation: function () {
                function onUnlockZoomAndLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onUnlockZoomAndLocation(_this2.state.configMenuUid);
                }

                return onUnlockZoomAndLocation;
              }(),
              onYankLocation: function () {
                function onYankLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onYankLocation(_this2.state.configMenuUid);
                }

                return onYankLocation;
              }(),
              onYankZoom: function () {
                function onYankZoom() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onYankZoom(_this2.state.configMenuUid);
                }

                return onYankZoom;
              }(),
              onYankZoomAndLocation: function () {
                function onYankZoomAndLocation() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onYankZoomAndLocation(_this2.state.configMenuUid);
                }

                return onYankZoomAndLocation;
              }(),
              onZoomToData: function () {
                function onZoomToData() {
                  _this2.setState({ configMenuUid: null }); // hide the menu
                  _this2.props.onZoomToData(_this2.state.configMenuUid);
                }

                return onZoomToData;
              }(),
              orientation: 'left',
              position: this.state.configMenuPosition,
              theme: this.props.theme
            })
          );
        }

        var GenomePositionSearchBox = this.props.getGenomePositionSearchBox(this.state.isFocused, function (focus) {
          _this2.setState({
            isFocused: focus
          });
        });

        var className = this.state.isFocused ? 'multitrack-header-focus' : 'multitrack-header';

        var classNameIcon = this.state.width <= _configs.VIEW_HEADER_MED_WIDTH_SEARCH_BAR ? 'multitrack-header-icon-squeazed' : 'multitrack-header-icon';

        if (this.props.theme === _configs.THEME_DARK) {
          className += ' multitrack-header-dark';
        }

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this2.el = c;
              }

              return ref;
            }(),
            className: (0, _getClassName3['default'])(className, _styleModuleImportMap)
          },
          _react2['default'].createElement(
            'div',
            { className: 'ViewHeader-module_multitrack-header-left-Qj9Sm' },
            this.props.mouseTool === _configs.MOUSE_TOOL_SELECT && _react2['default'].createElement(
              'svg',
              {
                title: 'Selection tool active',
                className: (0, _getClassName3['default'])('mouse-tool-selection ' + classNameIcon, _styleModuleImportMap)
              },
              _react2['default'].createElement('use', { xlinkHref: '#select' })
            ),
            _react2['default'].createElement(
              'div',
              {
                className: 'ViewHeader-module_multitrack-header-grabber-3jrIz',
                title: 'Drag to move the view'
              },
              _react2['default'].createElement('div', null),
              _react2['default'].createElement('div', null),
              _react2['default'].createElement('div', null)
            ),
            this.state.width > _configs.VIEW_HEADER_MIN_WIDTH_SEARCH_BAR && _react2['default'].createElement(
              'div',
              { className: 'ViewHeader-module_multitrack-header-search-1X_3_' },
              this.props.isGenomePositionSearchBoxVisible && GenomePositionSearchBox
            )
          ),
          _react2['default'].createElement(
            'nav',
            { className: 'ViewHeader-module_multitrack-header-nav-list-2nvcu' },
            _react2['default'].createElement(
              'svg',
              { onClick: this.props.onAddView, className: (0, _getClassName3['default'])(classNameIcon, _styleModuleImportMap)
              },
              _react2['default'].createElement(
                'title',
                null,
                'Add new view (clone this view)'
              ),
              _react2['default'].createElement('use', { xlinkHref: '#copy' })
            ),
            _react2['default'].createElement(
              'svg',
              {
                ref: function () {
                  function ref(c) {
                    _this2.configImg = c;
                  }

                  return ref;
                }(),
                onClick: function () {
                  function onClick() {
                    return _this2.handleConfigMenuOpened(_this2.props.viewUid);
                  }

                  return onClick;
                }(),
                className: (0, _getClassName3['default'])(classNameIcon, _styleModuleImportMap)
              },
              _react2['default'].createElement(
                'title',
                null,
                'Configure this view'
              ),
              _react2['default'].createElement('use', { xlinkHref: '#cog' })
            ),
            _react2['default'].createElement(
              'svg',
              {
                ref: function () {
                  function ref(c) {
                    _this2.plusImg = c;
                  }

                  return ref;
                }(),
                onClick: function () {
                  function onClick() {
                    return _this2.handleAddTrackPositionMenuOpened(_this2.props.viewUid);
                  }

                  return onClick;
                }(),
                className: (0, _getClassName3['default'])(classNameIcon, _styleModuleImportMap)
              },
              _react2['default'].createElement(
                'title',
                null,
                'Add Track'
              ),
              _react2['default'].createElement('use', { xlinkHref: '#plus' })
            ),
            _react2['default'].createElement(
              'svg',
              { onClick: this.props.onCloseView, className: (0, _getClassName3['default'])(classNameIcon, _styleModuleImportMap)
              },
              _react2['default'].createElement(
                'title',
                null,
                'Close View'
              ),
              _react2['default'].createElement('use', { xlinkHref: '#cross' })
            )
          ),
          configMenu,
          addTrackPositionMenu
        );
      }

      return render;
    }()
  }]);
  return ViewHeader;
}(_react2['default'].Component);

ViewHeader.defaultProps = {
  isGenomePositionSearchBoxVisible: false
};

ViewHeader.propTypes = {
  getGenomePositionSearchBox: _propTypes2['default'].func.isRequired,
  isGenomePositionSearchBoxVisible: _propTypes2['default'].bool,
  mouseTool: _propTypes2['default'].string.isRequired,
  onAddView: _propTypes2['default'].func.isRequired,
  onClearView: _propTypes2['default'].func.isRequired,
  onCloseView: _propTypes2['default'].func.isRequired,
  onEditViewConfig: _propTypes2['default'].func.isRequired,
  onExportSVG: _propTypes2['default'].func.isRequired,
  onExportPNG: _propTypes2['default'].func.isRequired,
  onExportViewsAsJSON: _propTypes2['default'].func.isRequired,
  onExportViewsAsLink: _propTypes2['default'].func.isRequired,
  onLockLocation: _propTypes2['default'].func.isRequired,
  onLockZoom: _propTypes2['default'].func.isRequired,
  onLockZoomAndLocation: _propTypes2['default'].func.isRequired,
  onProjectViewport: _propTypes2['default'].func.isRequired,
  onTakeAndLockZoomAndLocation: _propTypes2['default'].func.isRequired,
  onTogglePositionSearchBox: _propTypes2['default'].func.isRequired,
  onTrackPositionChosen: _propTypes2['default'].func.isRequired,
  onUnlockLocation: _propTypes2['default'].func.isRequired,
  onUnlockZoom: _propTypes2['default'].func.isRequired,
  onUnlockZoomAndLocation: _propTypes2['default'].func.isRequired,
  onViewOptionsChanged: _propTypes2['default'].func.isRequired,
  onYankLocation: _propTypes2['default'].func.isRequired,
  onYankZoom: _propTypes2['default'].func.isRequired,
  onYankZoomAndLocation: _propTypes2['default'].func.isRequired,
  onZoomToData: _propTypes2['default'].func.isRequired,
  theme: _propTypes2['default'].symbol.isRequired,
  viewUid: _propTypes2['default'].string.isRequired
};

exports['default'] = (0, _withTheme2['default'])(ViewHeader);

/***/ }),
/* 685 */
/***/ (function(module, exports, __nested_webpack_require_3691250__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_3691250__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _keys = __nested_webpack_require_3691250__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getPrototypeOf = __nested_webpack_require_3691250__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3691250__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3691250__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3691250__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3691250__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3691250__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _react = __nested_webpack_require_3691250__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_3691250__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _ContextMenuContainer2 = __nested_webpack_require_3691250__(96);

var _ContextMenuContainer3 = _interopRequireDefault(_ContextMenuContainer2);

var _ContextMenuItem = __nested_webpack_require_3691250__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _NestedContextMenu = __nested_webpack_require_3691250__(391);

var _NestedContextMenu2 = _interopRequireDefault(_NestedContextMenu);

__nested_webpack_require_3691250__(68);

var _configs = __nested_webpack_require_3691250__(11);

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

// Styles
var _styleModuleImportMap = {
  '../styles/ContextMenu.module.scss': {
    'context-menu': 'ContextMenu-module_context-menu-2OwvL',
    'context-menu-dark': 'ContextMenu-module_context-menu-dark-2PO31',
    'context-menu-icon': 'ContextMenu-module_context-menu-icon-I4kiw',
    'context-menu-item': 'ContextMenu-module_context-menu-item-1HeVv',
    'context-menu-hr': 'ContextMenu-module_context-menu-hr-3yapb',
    'play-icon': 'ContextMenu-module_play-icon-R4pIO',
    'context-menu-span': 'ContextMenu-module_context-menu-span-8EUfZ',
    'context-menu-thumbnail': 'ContextMenu-module_context-menu-thumbnail-2vHLD',
    'context-menu-thumbnail-inline': 'ContextMenu-module_context-menu-thumbnail-inline-1iOcg'
  }
};

var ConfigViewMenu = function (_ContextMenuContainer) {
  (0, _inherits3['default'])(ConfigViewMenu, _ContextMenuContainer);

  function ConfigViewMenu(props) {
    (0, _classCallCheck3['default'])(this, ConfigViewMenu);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ConfigViewMenu.__proto__ || (0, _getPrototypeOf2['default'])(ConfigViewMenu)).call(this, props));

    _this.state = {
      submenuShown: false
    };
    return _this;
  }

  (0, _createClass3['default'])(ConfigViewMenu, [{
    key: 'getConfigureViewMenu',
    value: function () {
      function getConfigureViewMenu(position, bbox) {
        var _this2 = this;

        var availableOptions = ['backgroundColor'];
        var menuItems = {};
        var newOptions = {};

        var _loop = function () {
          function _loop(optionType) {
            if (optionType in (0, _keys2['default'])(_configs.OPTIONS_INFO)) {
              menuItems[optionType] = { name: _configs.OPTIONS_INFO[optionType].name };

              if (_configs.OPTIONS_INFO[optionType].inlineOptions) {
                var _loop2 = function () {
                  function _loop2(inlineOptionKey) {
                    var inlineOption = _configs.OPTIONS_INFO[optionType].inlineOptions[inlineOptionKey];

                    // check if there's already available options (e.g.
                    // "Top right") for this option type (e.g. "Label
                    // position")
                    if (!menuItems[optionType].children) {
                      menuItems[optionType].children = {};
                    }

                    var optionSelectorSettings = {
                      name: inlineOption.name,
                      value: inlineOption.value
                      // missing handler to be filled in below
                    };

                    // the menu option defines a potential value for this option
                    // type (e.g. "top right")
                    optionSelectorSettings.handler = function () {
                      newOptions[optionType] = inlineOption.value;
                      _this2.props.onOptionsChanged(newOptions);
                    };

                    menuItems[optionType].children[inlineOptionKey] = optionSelectorSettings;
                  }

                  return _loop2;
                }();

                // we can simply select this option from the menu
                for (var inlineOptionKey in _configs.OPTIONS_INFO[optionType].inlineOptions) {
                  _loop2(inlineOptionKey);
                }
              }
            }
          }

          return _loop;
        }();

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = (0, _getIterator3['default'])(availableOptions), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var optionType = _step.value;

            _loop(optionType);
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator['return']) {
              _iterator['return']();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        return _react2['default'].createElement(_NestedContextMenu2['default'], {
          key: 'config-series-menu',
          closeMenu: this.props.closeMenu,
          menuItems: menuItems,
          orientation: this.state.orientation,
          parentBbox: bbox,
          position: position,
          theme: this.props.theme
        });
      }

      return getConfigureViewMenu;
    }()
  }, {
    key: 'getSubmenu',
    value: function () {
      function getSubmenu() {
        if (this.state.submenuShown) {
          // the bounding box of the element which initiated the subMenu
          // necessary so that we can position the submenu next to the initiating
          // element
          var bbox = this.state.submenuSourceBbox;
          var position = this.state.orientation === 'left' ? {
            left: this.state.left,
            top: bbox.top
          } : {
            left: this.state.left + bbox.width + 7,
            top: bbox.top
          };

          var subMenuData = this.state.submenuShown;
          if (subMenuData.option === 'options') {
            return this.getConfigureViewMenu(position, bbox);
          }

          return _react2['default'].createElement('div', null);
        }

        return _react2['default'].createElement('div', null);
      }

      return getSubmenu;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this3 = this;

        var styleNames = 'context-menu';
        if (this.props.theme === _configs.THEME_DARK) styleNames += ' context-menu-dark';

        return _react2['default'].createElement(
          'div',
          {
            ref: function () {
              function ref(c) {
                _this3.div = c;
              }

              return ref;
            }(),
            'data-menu-type': 'ConfigViewMenu',
            style: {
              left: this.state.left,
              top: this.state.top
            },
            className: (0, _getClassName3['default'])(styleNames, _styleModuleImportMap)
          },
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            {
              onClick: function () {
                function onClick(e) {
                  return _this3.props.onTogglePositionSearchBox(e);
                }

                return onClick;
              }()
            },
            'Toggle position search box'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onZoomToData(e);
                }

                return onClick;
              }() },
            'Zoom to data extent'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onClearView(e);
                }

                return onClick;
              }() },
            'Clear View'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onYankZoom(e);
                }

                return onClick;
              }() },
            'Take zoom from'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onYankLocation(e);
                }

                return onClick;
              }() },
            'Take location from'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onYankZoomAndLocation(e);
                }

                return onClick;
              }() },
            'Take zoom and location from'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: this.props.onLockZoom },
            'Lock zoom with'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: this.props.onLockLocation },
            'Lock location with'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: this.props.onLockZoomAndLocation },
            'Lock zoom and location with'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: this.props.onTakeAndLockZoomAndLocation },
            'Take and lock zoom and location with'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onUnlockZoom(e);
                }

                return onClick;
              }() },
            'Unlock zoom'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onUnlockLocation(e);
                }

                return onClick;
              }() },
            'Unlock location'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onUnlockZoomAndLocation(e);
                }

                return onClick;
              }() },
            'Unlock zoom and location'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onProjectViewport(e);
                }

                return onClick;
              }() },
            'Show this viewport on'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick(e) {
                  return _this3.props.onEditViewConfig(e);
                }

                return onClick;
              }() },
            'Edit view config'
          ),
          _react2['default'].createElement('hr', { className: 'ContextMenu-module_context-menu-hr-3yapb' }),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick() {
                  return _this3.props.onExportSVG();
                }

                return onClick;
              }() },
            'Export views as SVG'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick() {
                  return _this3.props.onExportPNG();
                }

                return onClick;
              }() },
            'Export views as PNG'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick() {
                  return _this3.props.onExportViewAsJSON();
                }

                return onClick;
              }() },
            'Export views as JSON'
          ),
          _react2['default'].createElement(
            _ContextMenuItem2['default'],
            { onClick: function () {
                function onClick() {
                  return _this3.props.onExportViewAsLink();
                }

                return onClick;
              }() },
            'Export views as Link'
          ),
          this.getSubmenu()
        );
      }

      return render;
    }()
  }]);
  return ConfigViewMenu;
}(_ContextMenuContainer3['default']);

ConfigViewMenu.propTypes = {
  onEditViewConfig: _propTypes2['default'].func.isRequired,
  onExportSVG: _propTypes2['default'].func,
  onExportPNG: _propTypes2['default'].func,
  onExportViewAsJSON: _propTypes2['default'].func,
  onExportViewAsLink: _propTypes2['default'].func,
  onLockLocation: _propTypes2['default'].func,
  onLockZoom: _propTypes2['default'].func,
  onLockZoomAndLocation: _propTypes2['default'].func,
  onProjectViewport: _propTypes2['default'].func,
  onTakeAndLockZoomAndLocation: _propTypes2['default'].func,
  onTogglePositionSearchBox: _propTypes2['default'].func,
  onUnlockLocation: _propTypes2['default'].func,
  onUnlockZoom: _propTypes2['default'].func,
  onUnlockZoomAndLocation: _propTypes2['default'].func,
  onYankLocation: _propTypes2['default'].func,
  onYankZoom: _propTypes2['default'].func,
  onYankZoomAndLocation: _propTypes2['default'].func,
  onZoomToData: _propTypes2['default'].func,
  theme: _propTypes2['default'].symbol
};

exports['default'] = ConfigViewMenu;

/***/ }),
/* 686 */
/***/ (function(module, exports, __nested_webpack_require_3707140__) {

"use strict";


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

var _getClassName2 = __nested_webpack_require_3707140__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_3707140__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3707140__(1);

var _react2 = _interopRequireDefault(_react);

var _withTheme = __nested_webpack_require_3707140__(78);

var _withTheme2 = _interopRequireDefault(_withTheme);

var _configs = __nested_webpack_require_3707140__(11);

__nested_webpack_require_3707140__(687);

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

var _styleModuleImportMap = {
  '../styles/AddTrackPositionMenu.module.scss': {
    'add-track-position-table': 'AddTrackPositionMenu-module_add-track-position-table-RHODc',
    'add-track-position-table-dark': 'AddTrackPositionMenu-module_add-track-position-table-dark-_B9fu',
    'add-track-position-other': 'AddTrackPositionMenu-module_add-track-position-other-lIGbb',
    'add-track-position-top-center': 'AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e',
    'add-track-position-middle-left': 'AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN',
    'add-track-position-middle-right': 'AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn',
    'add-track-position-middle-middle': 'AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd',
    'add-track-position-bottom-middle': 'AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE',
    'add-track-position-span': 'AddTrackPositionMenu-module_add-track-position-span-2hbwE'
  }
};


function AddTrackPositionMenu(props) {
  var tableStyleNames = 'add-track-position-table';
  if (props.theme === _configs.THEME_DARK) tableStyleNames += ' add-track-position-table-dark';
  return _react2['default'].createElement(
    'div',
    null,
    _react2['default'].createElement(
      'div',
      { className: 'AddTrackPositionMenu-module_add-track-position-span-2hbwE' },
      'Add Track...'
    ),
    _react2['default'].createElement(
      'table',
      {
        className: (0, _getClassName3['default'])(tableStyleNames, _styleModuleImportMap)
      },
      _react2['default'].createElement(
        'tbody',
        null,
        _react2['default'].createElement(
          'tr',
          { style: { height: '30px' } },
          _react2['default'].createElement('td', { className: 'AddTrackPositionMenu-module_add-track-position-other-lIGbb' }),
          _react2['default'].createElement(
            'td',
            {
              onClick: function () {
                function onClick() {
                  return props.onTrackPositionChosen('top');
                }

                return onClick;
              }(),
              className: 'AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e'
            },
            'top'
          ),
          _react2['default'].createElement('td', { className: 'AddTrackPositionMenu-module_add-track-position-other-lIGbb' })
        ),
        _react2['default'].createElement(
          'tr',
          { style: { height: '80px' } },
          _react2['default'].createElement(
            'td',
            {
              onClick: function () {
                function onClick() {
                  return props.onTrackPositionChosen('left');
                }

                return onClick;
              }(),
              className: 'AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN'
            },
            'left'
          ),
          _react2['default'].createElement(
            'td',
            {
              onClick: function () {
                function onClick() {
                  return props.onTrackPositionChosen('center');
                }

                return onClick;
              }(),
              className: 'AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd'
            },
            'center'
          ),
          _react2['default'].createElement(
            'td',
            {
              onClick: function () {
                function onClick() {
                  return props.onTrackPositionChosen('right');
                }

                return onClick;
              }(),
              className: 'AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn'
            },
            'right'
          )
        ),
        _react2['default'].createElement(
          'tr',
          { style: { height: '30px' } },
          _react2['default'].createElement('td', { className: 'AddTrackPositionMenu-module_add-track-position-other-lIGbb' }),
          _react2['default'].createElement(
            'td',
            {
              onClick: function () {
                function onClick() {
                  return props.onTrackPositionChosen('bottom');
                }

                return onClick;
              }(),
              className: 'AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE'
            },
            'bottom'
          ),
          _react2['default'].createElement('td', { className: 'AddTrackPositionMenu-module_add-track-position-other-lIGbb' })
        )
      )
    )
  );
}

AddTrackPositionMenu.propTypes = {
  onTrackPositionChosen: _propTypes2['default'].func.isRequired,
  theme: _propTypes2['default'].symbol.isRequired
};

exports['default'] = (0, _withTheme2['default'])(AddTrackPositionMenu);

/***/ }),
/* 687 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"add-track-position-table":"AddTrackPositionMenu-module_add-track-position-table-RHODc","add-track-position-table-dark":"AddTrackPositionMenu-module_add-track-position-table-dark-_B9fu","add-track-position-other":"AddTrackPositionMenu-module_add-track-position-other-lIGbb","add-track-position-top-center":"AddTrackPositionMenu-module_add-track-position-top-center-2Dw4e","add-track-position-middle-left":"AddTrackPositionMenu-module_add-track-position-middle-left-2ycaN","add-track-position-middle-right":"AddTrackPositionMenu-module_add-track-position-middle-right-Qqjnn","add-track-position-middle-middle":"AddTrackPositionMenu-module_add-track-position-middle-middle-2YFZd","add-track-position-bottom-middle":"AddTrackPositionMenu-module_add-track-position-bottom-middle-3ityE","add-track-position-span":"AddTrackPositionMenu-module_add-track-position-span-2hbwE"};

/***/ }),
/* 688 */
/***/ (function(module, exports, __nested_webpack_require_3713714__) {

"use strict";


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

var _stringify = __nested_webpack_require_3713714__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _regenerator = __nested_webpack_require_3713714__(246);

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = __nested_webpack_require_3713714__(247);

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _getPrototypeOf = __nested_webpack_require_3713714__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_3713714__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_3713714__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_3713714__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_3713714__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _getClassName2 = __nested_webpack_require_3713714__(29);

var _getClassName3 = _interopRequireDefault(_getClassName2);

var _propTypes = __nested_webpack_require_3713714__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_3713714__(1);

var _react2 = _interopRequireDefault(_react);

var _reactSimpleCodeEditor = __nested_webpack_require_3713714__(689);

var _reactSimpleCodeEditor2 = _interopRequireDefault(_reactSimpleCodeEditor);

var _prismCore = __nested_webpack_require_3713714__(690);

__nested_webpack_require_3713714__(691);

var _ajv = __nested_webpack_require_3713714__(397);

var _ajv2 = _interopRequireDefault(_ajv);

var _schema = __nested_webpack_require_3713714__(271);

var _schema2 = _interopRequireDefault(_schema);

var _Button = __nested_webpack_require_3713714__(170);

var _Button2 = _interopRequireDefault(_Button);

var _Dialog = __nested_webpack_require_3713714__(169);

var _Dialog2 = _interopRequireDefault(_Dialog);

var _withModal = __nested_webpack_require_3713714__(132);

var _withModal2 = _interopRequireDefault(_withModal);

var _withPubSub = __nested_webpack_require_3713714__(69);

var _withPubSub2 = _interopRequireDefault(_withPubSub);

var _utils = __nested_webpack_require_3713714__(10);

__nested_webpack_require_3713714__(724);

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

var _styleModuleImportMap = {
  '../styles/ViewConfigEditor.module.scss': {
    'view-config-editor-header': 'ViewConfigEditor-module_view-config-editor-header-2nTtX',
    'view-config-editor': 'ViewConfigEditor-module_view-config-editor-2HAFN',
    'view-config-log': 'ViewConfigEditor-module_view-config-log-1mYmL',
    'view-config-log-header': 'ViewConfigEditor-module_view-config-log-header-3EbEM',
    'view-config-log-msg': 'ViewConfigEditor-module_view-config-log-msg-2-CJZ',
    'title': 'ViewConfigEditor-module_title-3nLH_',
    'Warning': 'ViewConfigEditor-module_Warning-_sgiB',
    'Success': 'ViewConfigEditor-module_Success-nclFo',
    'Error': 'ViewConfigEditor-module_Error-3enaC'
  }
};

var ViewConfigEditor = function (_React$Component) {
  (0, _inherits3['default'])(ViewConfigEditor, _React$Component);

  function ViewConfigEditor(props) {
    (0, _classCallCheck3['default'])(this, ViewConfigEditor);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ViewConfigEditor.__proto__ || (0, _getPrototypeOf2['default'])(ViewConfigEditor)).call(this, props));

    _this.state = {
      code: props.viewConfig,
      hide: false,
      showLog: false,
      logMsgs: _this.getLogMsgs(props.viewConfig)
    };

    _this.handleChangeBound = _this.handleChange.bind(_this);
    _this.handleKeyDownBound = _this.handleKeyDown.bind(_this);
    _this.handleKeyUpBound = _this.handleKeyUp.bind(_this);
    _this.handleSubmitBound = _this.handleSubmit.bind(_this);
    _this.hideBound = _this.hide.bind(_this);
    _this.showBound = _this.show.bind(_this);
    _this.toggleLogBound = _this.toggleLog.bind(_this);

    _this.pubSubs = [];

    _this.pubSubs.push(_this.props.pubSub.subscribe('keydown', _this.handleKeyDownBound));
    _this.pubSubs.push(_this.props.pubSub.subscribe('keyup', _this.handleKeyUpBound));
    return _this;
  }

  (0, _createClass3['default'])(ViewConfigEditor, [{
    key: 'componentDidMount',
    value: function () {
      var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function () {
        function _callee() {
          return _regenerator2['default'].wrap(function () {
            function _callee$(_context) {
              while (1) {
                switch (_context.prev = _context.next) {
                  case 0:
                    if (!this.editor) {
                      _context.next = 6;
                      break;
                    }

                    this.editor._input.focus();
                    this.editor._input.setSelectionRange(0, 0);
                    _context.next = 5;
                    return (0, _utils.timeout)(0);

                  case 5:
                    this.editorWrap.scrollTop = 0;

                  case 6:
                  case 'end':
                    return _context.stop();
                }
              }
            }

            return _callee$;
          }(), _callee, this);
        }

        return _callee;
      }()));

      function componentDidMount() {
        return _ref.apply(this, arguments);
      }

      return componentDidMount;
    }()
  }, {
    key: 'componentWillUnmount',
    value: function () {
      function componentWillUnmount() {
        var _this2 = this;

        this.pubSubs.forEach(function (subscription) {
          return _this2.props.pubSub.unsubscribe(subscription);
        });
        this.pubSubs = [];
      }

      return componentWillUnmount;
    }()
  }, {
    key: 'handleChange',
    value: function () {
      function handleChange(code) {
        var logMsgs = this.getLogMsgs(code);
        this.setState({ code: code, logMsgs: logMsgs });
      }

      return handleChange;
    }()
  }, {
    key: 'handleKeyDown',
    value: function () {
      function handleKeyDown(event) {
        if (event.key === 's' && (event.ctrlKey || event.metaKey)) {
          event.preventDefault();
          this.props.onChange(this.state.code);
        }
        if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
          event.preventDefault();
          this.props.onChange(this.state.code);
          this.props.modal.close();
        }
      }

      return handleKeyDown;
    }()
  }, {
    key: 'handleKeyUp',
    value: function () {
      function handleKeyUp(event) {
        this.setState({ hide: false });

        if (event.key === 'Escape') {
          event.preventDefault();
          this.props.modal.close();
          this.props.onCancel();
        }
      }

      return handleKeyUp;
    }()
  }, {
    key: 'handleSubmit',
    value: function () {
      function handleSubmit(event) {
        if (event) event.preventDefault();

        this.props.onSave(this.state.code);
      }

      return handleSubmit;
    }()
  }, {
    key: 'getLogMsgs',
    value: function () {
      function getLogMsgs(code) {
        var logMsgs = [];
        var viewConfig = void 0;
        try {
          viewConfig = JSON.parse(code);
        } catch (e) {
          console.warn(e);
          logMsgs.push({ type: 'Error', msg: e.toString() });
          return logMsgs;
        }
        var validate = new _ajv2['default']().compile(_schema2['default']);
        var valid = validate(viewConfig);
        if (!valid) {
          console.warn('Invalid viewconf');
          logMsgs.push({ type: 'Warning', msg: 'Invalid viewconf' });
        }
        if (validate.errors) {
          console.warn((0, _stringify2['default'])(validate.errors, null, 2));
          validate.errors.forEach(function (e) {
            logMsgs.push({ type: 'Warning', msg: (0, _stringify2['default'])(e, null, 2) });
          });
        }
        if (logMsgs.length === 0) {
          logMsgs.push({ type: 'Success', msg: 'No error or warnings' });
        }
        return logMsgs;
      }

      return getLogMsgs;
    }()
  }, {
    key: 'hide',
    value: function () {
      function hide() {
        this.setState({ hide: true });
      }

      return hide;
    }()
  }, {
    key: 'show',
    value: function () {
      function show() {
        this.setState({ hide: false });
      }

      return show;
    }()
  }, {
    key: 'hideLog',
    value: function () {
      function hideLog() {
        this.setState({ showLog: false });
      }

      return hideLog;
    }()
  }, {
    key: 'showLog',
    value: function () {
      function showLog() {
        this.setState({ showLog: true });
      }

      return showLog;
    }()
  }, {
    key: 'toggleLog',
    value: function () {
      function toggleLog() {
        if (this.state.showLog) {
          this.hideLog();
        } else {
          this.showLog();
        }
      }

      return toggleLog;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var _this3 = this;

        var logMessages = this.state.logMsgs.map(function (d, i) {
          var key = String(i) + '-' + String(d.msg);
          return _react2['default'].createElement(
            'tr',
            { key: key },
            _react2['default'].createElement(
              'td',
              {
                className: (0, _getClassName3['default'])('title ' + String(d.type), _styleModuleImportMap)
              },
              '[' + String(i) + '] ' + String(d.type)
            ),
            _react2['default'].createElement(
              'td',
              null,
              _react2['default'].createElement(
                'pre',
                null,
                d.msg
              )
            )
          );
        });

        return _react2['default'].createElement(
          _Dialog2['default'],
          {
            cancelShortcut: 'ESC',
            cancelTitle: 'Discard Changes',
            hide: this.state.hide,
            maxHeight: true,
            okayShortcut: '\u2318+Enter',
            okayTitle: 'Save and Close',
            onCancel: this.props.onCancel,
            onOkay: this.handleSubmitBound,
            title: 'Edit View Config'
          },
          _react2['default'].createElement(
            'header',
            { className: 'ViewConfigEditor-module_view-config-editor-header-2nTtX' },
            _react2['default'].createElement(
              _Button2['default'],
              {
                onBlur: this.showBound,
                onMouseDown: this.hideBound,
                onMouseOut: this.showBound,
                onMouseUp: this.showBound
              },
              'Hide While Mousedown'
            ),
            _react2['default'].createElement(
              _Button2['default'],
              {
                onClick: function () {
                  function onClick() {
                    _this3.props.onChange(_this3.state.code);
                  }

                  return onClick;
                }(),
                shortcut: '\u2318+S'
              },
              'Save'
            )
          ),
          _react2['default'].createElement(
            'div',
            {
              ref: function () {
                function ref(c) {
                  _this3.editorWrap = c;
                }

                return ref;
              }(),
              className: 'ViewConfigEditor-module_view-config-editor-2HAFN'
            },
            _react2['default'].createElement(_reactSimpleCodeEditor2['default'], {
              ref: function () {
                function ref(c) {
                  _this3.editor = c;
                }

                return ref;
              }(),
              highlight: function () {
                function highlight(code) {
                  return (0, _prismCore.highlight)(code, _prismCore.languages.json);
                }

                return highlight;
              }(),
              onValueChange: this.handleChangeBound,
              padding: 10,
              style: {
                fontFamily: '"Fira code", "Fira Mono", monospace',
                fontSize: 'inherit'
              },
              value: this.state.code
            })
          ),
          _react2['default'].createElement(
            'div',
            {
              style: {
                height: this.state.showLog ? '50%' : '30px'
              },
              className: 'ViewConfigEditor-module_view-config-log-1mYmL'
            },
            _react2['default'].createElement(
              'div',
              {
                onClick: function () {
                  function onClick() {
                    return _this3.toggleLogBound();
                  }

                  return onClick;
                }(),
                className: 'ViewConfigEditor-module_view-config-log-header-3EbEM'
              },
              'Log Messages (' + String(this.state.logMsgs.filter(function (d) {
                return d.type !== 'Success';
              }).length) + ')'
            ),
            _react2['default'].createElement(
              'div',
              {
                style: {
                  padding: this.state.showLog ? '10px' : 0
                },
                className: 'ViewConfigEditor-module_view-config-log-msg-2-CJZ'
              },
              _react2['default'].createElement(
                'table',
                null,
                _react2['default'].createElement(
                  'tbody',
                  null,
                  logMessages
                )
              )
            )
          )
        );
      }

      return render;
    }()
  }]);
  return ViewConfigEditor;
}(_react2['default'].Component);

ViewConfigEditor.propTypes = {
  modal: _propTypes2['default'].object.isRequired,
  onCancel: _propTypes2['default'].func.isRequired,
  onChange: _propTypes2['default'].func.isRequired,
  onSave: _propTypes2['default'].func.isRequired,
  pubSub: _propTypes2['default'].object.isRequired,
  viewConfig: _propTypes2['default'].object.isRequired
};

exports['default'] = (0, _withPubSub2['default'])((0, _withModal2['default'])(ViewConfigEditor));

/***/ }),
/* 689 */
/***/ (function(module, exports, __nested_webpack_require_3727975__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_3727975__(1);

var React = _interopRequireWildcard(_react);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* global global */

var KEYCODE_ENTER = 13;
var KEYCODE_TAB = 9;
var KEYCODE_BACKSPACE = 8;
var KEYCODE_Y = 89;
var KEYCODE_Z = 90;
var KEYCODE_M = 77;
var KEYCODE_PARENS = 57;
var KEYCODE_BRACKETS = 219;
var KEYCODE_QUOTE = 222;
var KEYCODE_BACK_QUOTE = 192;

var HISTORY_LIMIT = 100;
var HISTORY_TIME_GAP = 3000;

var isWindows = 'navigator' in global && /Win/i.test(navigator.platform);
var isMacLike = 'navigator' in global && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);

var className = 'npm__react-simple-code-editor__textarea';

var cssText = /* CSS */'\n/**\n * Reset the text fill color so that placeholder is visible\n */\n.' + className + ':empty {\n  -webkit-text-fill-color: inherit !important;\n}\n\n/**\n * Hack to apply on some CSS on IE10 and IE11\n */\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n  /**\n    * IE doesn\'t support \'-webkit-text-fill-color\'\n    * So we use \'color: transparent\' to make the text transparent on IE\n    * Unlike other browsers, it doesn\'t affect caret color in IE\n    */\n  .' + className + ' {\n    color: transparent !important;\n  }\n\n  .' + className + '::selection {\n    background-color: #accef7 !important;\n    color: transparent !important;\n  }\n}\n';

var Editor = function (_React$Component) {
  _inherits(Editor, _React$Component);

  function Editor() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Editor);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Editor.__proto__ || Object.getPrototypeOf(Editor)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      capture: true
    }, _this._recordCurrentState = function () {
      var input = _this._input;

      if (!input) return;

      // Save current state of the input
      var value = input.value,
          selectionStart = input.selectionStart,
          selectionEnd = input.selectionEnd;


      _this._recordChange({
        value: value,
        selectionStart: selectionStart,
        selectionEnd: selectionEnd
      });
    }, _this._getLines = function (text, position) {
      return text.substring(0, position).split('\n');
    }, _this._recordChange = function (record) {
      var overwrite = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var _this$_history = _this._history,
          stack = _this$_history.stack,
          offset = _this$_history.offset;


      if (stack.length && offset > -1) {
        // When something updates, drop the redo operations
        _this._history.stack = stack.slice(0, offset + 1);

        // Limit the number of operations to 100
        var count = _this._history.stack.length;

        if (count > HISTORY_LIMIT) {
          var extras = count - HISTORY_LIMIT;

          _this._history.stack = stack.slice(extras, count);
          _this._history.offset = Math.max(_this._history.offset - extras, 0);
        }
      }

      var timestamp = Date.now();

      if (overwrite) {
        var last = _this._history.stack[_this._history.offset];

        if (last && timestamp - last.timestamp < HISTORY_TIME_GAP) {
          // A previous entry exists and was in short interval

          // Match the last word in the line
          var re = /[^a-z0-9]([a-z0-9]+)$/i;

          // Get the previous line
          var previous = _this._getLines(last.value, last.selectionStart).pop().match(re);

          // Get the current line
          var current = _this._getLines(record.value, record.selectionStart).pop().match(re);

          if (previous && current && current[1].startsWith(previous[1])) {
            // The last word of the previous line and current line match
            // Overwrite previous entry so that undo will remove whole word
            _this._history.stack[_this._history.offset] = _extends({}, record, { timestamp: timestamp });

            return;
          }
        }
      }

      // Add the new operation to the stack
      _this._history.stack.push(_extends({}, record, { timestamp: timestamp }));
      _this._history.offset++;
    }, _this._updateInput = function (record) {
      var input = _this._input;

      if (!input) return;

      // Update values and selection state
      input.value = record.value;
      input.selectionStart = record.selectionStart;
      input.selectionEnd = record.selectionEnd;

      _this.props.onValueChange(record.value);
    }, _this._applyEdits = function (record) {
      // Save last selection state
      var input = _this._input;
      var last = _this._history.stack[_this._history.offset];

      if (last && input) {
        _this._history.stack[_this._history.offset] = _extends({}, last, {
          selectionStart: input.selectionStart,
          selectionEnd: input.selectionEnd
        });
      }

      // Save the changes
      _this._recordChange(record);
      _this._updateInput(record);
    }, _this._undoEdit = function () {
      var _this$_history2 = _this._history,
          stack = _this$_history2.stack,
          offset = _this$_history2.offset;

      // Get the previous edit

      var record = stack[offset - 1];

      if (record) {
        // Apply the changes and update the offset
        _this._updateInput(record);
        _this._history.offset = Math.max(offset - 1, 0);
      }
    }, _this._redoEdit = function () {
      var _this$_history3 = _this._history,
          stack = _this$_history3.stack,
          offset = _this$_history3.offset;

      // Get the next edit

      var record = stack[offset + 1];

      if (record) {
        // Apply the changes and update the offset
        _this._updateInput(record);
        _this._history.offset = Math.min(offset + 1, stack.length - 1);
      }
    }, _this._handleKeyDown = function (e) {
      var _this$props = _this.props,
          tabSize = _this$props.tabSize,
          insertSpaces = _this$props.insertSpaces,
          ignoreTabKey = _this$props.ignoreTabKey,
          onKeyDown = _this$props.onKeyDown;


      if (onKeyDown) {
        onKeyDown(e);

        if (e.defaultPrevented) {
          return;
        }
      }

      var _e$target = e.target,
          value = _e$target.value,
          selectionStart = _e$target.selectionStart,
          selectionEnd = _e$target.selectionEnd;


      var tabCharacter = (insertSpaces ? ' ' : '\t').repeat(tabSize);

      if (e.keyCode === KEYCODE_TAB && !ignoreTabKey && _this.state.capture) {
        // Prevent focus change
        e.preventDefault();

        if (e.shiftKey) {
          // Unindent selected lines
          var linesBeforeCaret = _this._getLines(value, selectionStart);
          var startLine = linesBeforeCaret.length - 1;
          var endLine = _this._getLines(value, selectionEnd).length - 1;
          var nextValue = value.split('\n').map(function (line, i) {
            if (i >= startLine && i <= endLine && line.startsWith(tabCharacter)) {
              return line.substring(tabCharacter.length);
            }

            return line;
          }).join('\n');

          if (value !== nextValue) {
            var startLineText = linesBeforeCaret[startLine];

            _this._applyEdits({
              value: nextValue,
              // Move the start cursor if first line in selection was modified
              // It was modified only if it started with a tab
              selectionStart: startLineText.startsWith(tabCharacter) ? selectionStart - tabCharacter.length : selectionStart,
              // Move the end cursor by total number of characters removed
              selectionEnd: selectionEnd - (value.length - nextValue.length)
            });
          }
        } else if (selectionStart !== selectionEnd) {
          // Indent selected lines
          var _linesBeforeCaret = _this._getLines(value, selectionStart);
          var _startLine = _linesBeforeCaret.length - 1;
          var _endLine = _this._getLines(value, selectionEnd).length - 1;
          var _startLineText = _linesBeforeCaret[_startLine];

          _this._applyEdits({
            value: value.split('\n').map(function (line, i) {
              if (i >= _startLine && i <= _endLine) {
                return tabCharacter + line;
              }

              return line;
            }).join('\n'),
            // Move the start cursor by number of characters added in first line of selection
            // Don't move it if it there was no text before cursor
            selectionStart: /\S/.test(_startLineText) ? selectionStart + tabCharacter.length : selectionStart,
            // Move the end cursor by total number of characters added
            selectionEnd: selectionEnd + tabCharacter.length * (_endLine - _startLine + 1)
          });
        } else {
          var updatedSelection = selectionStart + tabCharacter.length;

          _this._applyEdits({
            // Insert tab character at caret
            value: value.substring(0, selectionStart) + tabCharacter + value.substring(selectionEnd),
            // Update caret position
            selectionStart: updatedSelection,
            selectionEnd: updatedSelection
          });
        }
      } else if (e.keyCode === KEYCODE_BACKSPACE) {
        var hasSelection = selectionStart !== selectionEnd;
        var textBeforeCaret = value.substring(0, selectionStart);

        if (textBeforeCaret.endsWith(tabCharacter) && !hasSelection) {
          // Prevent default delete behaviour
          e.preventDefault();

          var _updatedSelection = selectionStart - tabCharacter.length;

          _this._applyEdits({
            // Remove tab character at caret
            value: value.substring(0, selectionStart - tabCharacter.length) + value.substring(selectionEnd),
            // Update caret position
            selectionStart: _updatedSelection,
            selectionEnd: _updatedSelection
          });
        }
      } else if (e.keyCode === KEYCODE_ENTER) {
        // Ignore selections
        if (selectionStart === selectionEnd) {
          // Get the current line
          var line = _this._getLines(value, selectionStart).pop();
          var matches = line.match(/^\s+/);

          if (matches && matches[0]) {
            e.preventDefault();

            // Preserve indentation on inserting a new line
            var indent = '\n' + matches[0];
            var _updatedSelection2 = selectionStart + indent.length;

            _this._applyEdits({
              // Insert indentation character at caret
              value: value.substring(0, selectionStart) + indent + value.substring(selectionEnd),
              // Update caret position
              selectionStart: _updatedSelection2,
              selectionEnd: _updatedSelection2
            });
          }
        }
      } else if (e.keyCode === KEYCODE_PARENS || e.keyCode === KEYCODE_BRACKETS || e.keyCode === KEYCODE_QUOTE || e.keyCode === KEYCODE_BACK_QUOTE) {
        var chars = void 0;

        if (e.keyCode === KEYCODE_PARENS && e.shiftKey) {
          chars = ['(', ')'];
        } else if (e.keyCode === KEYCODE_BRACKETS) {
          if (e.shiftKey) {
            chars = ['{', '}'];
          } else {
            chars = ['[', ']'];
          }
        } else if (e.keyCode === KEYCODE_QUOTE) {
          if (e.shiftKey) {
            chars = ['"', '"'];
          } else {
            chars = ["'", "'"];
          }
        } else if (e.keyCode === KEYCODE_BACK_QUOTE && !e.shiftKey) {
          chars = ['`', '`'];
        }

        // If text is selected, wrap them in the characters
        if (selectionStart !== selectionEnd && chars) {
          e.preventDefault();

          _this._applyEdits({
            value: value.substring(0, selectionStart) + chars[0] + value.substring(selectionStart, selectionEnd) + chars[1] + value.substring(selectionEnd),
            // Update caret position
            selectionStart: selectionStart,
            selectionEnd: selectionEnd + 2
          });
        }
      } else if ((isMacLike ? // Trigger undo with ⌘+Z on Mac
      e.metaKey && e.keyCode === KEYCODE_Z : // Trigger undo with Ctrl+Z on other platforms
      e.ctrlKey && e.keyCode === KEYCODE_Z) && !e.shiftKey && !e.altKey) {
        e.preventDefault();

        _this._undoEdit();
      } else if ((isMacLike ? // Trigger redo with ⌘+Shift+Z on Mac
      e.metaKey && e.keyCode === KEYCODE_Z && e.shiftKey : isWindows ? // Trigger redo with Ctrl+Y on Windows
      e.ctrlKey && e.keyCode === KEYCODE_Y : // Trigger redo with Ctrl+Shift+Z on other platforms
      e.ctrlKey && e.keyCode === KEYCODE_Z && e.shiftKey) && !e.altKey) {
        e.preventDefault();

        _this._redoEdit();
      } else if (e.keyCode === KEYCODE_M && e.ctrlKey && (isMacLike ? e.shiftKey : true)) {
        e.preventDefault();

        // Toggle capturing tab key so users can focus away
        _this.setState(function (state) {
          return {
            capture: !state.capture
          };
        });
      }
    }, _this._handleChange = function (e) {
      var _e$target2 = e.target,
          value = _e$target2.value,
          selectionStart = _e$target2.selectionStart,
          selectionEnd = _e$target2.selectionEnd;


      _this._recordChange({
        value: value,
        selectionStart: selectionStart,
        selectionEnd: selectionEnd
      }, true);

      _this.props.onValueChange(value);
    }, _this._history = {
      stack: [],
      offset: -1
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Editor, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this._recordCurrentState();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          value = _props.value,
          style = _props.style,
          padding = _props.padding,
          highlight = _props.highlight,
          textareaId = _props.textareaId,
          autoFocus = _props.autoFocus,
          disabled = _props.disabled,
          form = _props.form,
          maxLength = _props.maxLength,
          minLength = _props.minLength,
          name = _props.name,
          placeholder = _props.placeholder,
          readOnly = _props.readOnly,
          required = _props.required,
          onClick = _props.onClick,
          onFocus = _props.onFocus,
          onBlur = _props.onBlur,
          onKeyUp = _props.onKeyUp,
          onKeyDown = _props.onKeyDown,
          onValueChange = _props.onValueChange,
          tabSize = _props.tabSize,
          insertSpaces = _props.insertSpaces,
          ignoreTabKey = _props.ignoreTabKey,
          rest = _objectWithoutProperties(_props, ['value', 'style', 'padding', 'highlight', 'textareaId', 'autoFocus', 'disabled', 'form', 'maxLength', 'minLength', 'name', 'placeholder', 'readOnly', 'required', 'onClick', 'onFocus', 'onBlur', 'onKeyUp', 'onKeyDown', 'onValueChange', 'tabSize', 'insertSpaces', 'ignoreTabKey']);

      var contentStyle = {
        paddingTop: padding,
        paddingRight: padding,
        paddingBottom: padding,
        paddingLeft: padding
      };

      var highlighted = highlight(value);

      return React.createElement(
        'div',
        _extends({}, rest, { style: _extends({}, styles.container, style) }),
        React.createElement('textarea', {
          ref: function ref(c) {
            return _this2._input = c;
          },
          style: _extends({}, styles.editor, styles.textarea, contentStyle),
          className: className,
          id: textareaId,
          value: value,
          onChange: this._handleChange,
          onKeyDown: this._handleKeyDown,
          onClick: onClick,
          onKeyUp: onKeyUp,
          onFocus: onFocus,
          onBlur: onBlur,
          disabled: disabled,
          form: form,
          maxLength: maxLength,
          minLength: minLength,
          name: name,
          placeholder: placeholder,
          readOnly: readOnly,
          required: required,
          autoFocus: autoFocus,
          autoCapitalize: 'off',
          autoComplete: 'off',
          autoCorrect: 'off',
          spellCheck: false,
          'data-gramm': false
        }),
        React.createElement('pre', _extends({
          'aria-hidden': 'true',
          style: _extends({}, styles.editor, styles.highlight, contentStyle)
        }, typeof highlighted === 'string' ? { dangerouslySetInnerHTML: { __html: highlighted + '<br />' } } : { children: highlighted })),
        React.createElement('style', { type: 'text/css', dangerouslySetInnerHTML: { __html: cssText } })
      );
    }
  }, {
    key: 'session',
    get: function get() {
      return {
        history: this._history
      };
    },
    set: function set(session) {
      this._history = session.history;
    }
  }]);

  return Editor;
}(React.Component);

Editor.defaultProps = {
  tabSize: 2,
  insertSpaces: true,
  ignoreTabKey: false,
  padding: 0
};
exports.default = Editor;


var styles = {
  container: {
    position: 'relative',
    textAlign: 'left',
    boxSizing: 'border-box',
    padding: 0,
    overflow: 'hidden'
  },
  textarea: {
    position: 'absolute',
    top: 0,
    left: 0,
    height: '100%',
    width: '100%',
    resize: 'none',
    color: 'inherit',
    overflow: 'hidden',
    MozOsxFontSmoothing: 'grayscale',
    WebkitFontSmoothing: 'antialiased',
    WebkitTextFillColor: 'transparent'
  },
  highlight: {
    position: 'relative',
    pointerEvents: 'none'
  },
  editor: {
    margin: 0,
    border: 0,
    background: 'none',
    boxSizing: 'inherit',
    display: 'inherit',
    fontFamily: 'inherit',
    fontSize: 'inherit',
    fontStyle: 'inherit',
    fontVariantLigatures: 'inherit',
    fontWeight: 'inherit',
    letterSpacing: 'inherit',
    lineHeight: 'inherit',
    tabSize: 'inherit',
    textIndent: 'inherit',
    textRendering: 'inherit',
    textTransform: 'inherit',
    whiteSpace: 'pre-wrap',
    wordBreak: 'keep-all',
    overflowWrap: 'break-word'
  }
};
//# sourceMappingURL=index.js.map
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_3727975__(27)))

/***/ }),
/* 690 */
/***/ (function(module, exports, __nested_webpack_require_3748715__) {

/* WEBPACK VAR INJECTION */(function(global) {var _self = (typeof window !== 'undefined')
	? window   // if in browser
	: (
		(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
		? self // if in worker
		: {}   // if in node js
	);

/**
 * Prism: Lightweight, robust, elegant syntax highlighting
 * MIT license http://www.opensource.org/licenses/mit-license.php/
 * @author Lea Verou http://lea.verou.me
 */

var Prism = (function (_self){

// Private helper vars
var lang = /\blang(?:uage)?-([\w-]+)\b/i;
var uniqueId = 0;

var _ = {
	manual: _self.Prism && _self.Prism.manual,
	disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
	util: {
		encode: function (tokens) {
			if (tokens instanceof Token) {
				return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
			} else if (Array.isArray(tokens)) {
				return tokens.map(_.util.encode);
			} else {
				return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
			}
		},

		type: function (o) {
			return Object.prototype.toString.call(o).slice(8, -1);
		},

		objId: function (obj) {
			if (!obj['__id']) {
				Object.defineProperty(obj, '__id', { value: ++uniqueId });
			}
			return obj['__id'];
		},

		// Deep clone a language definition (e.g. to extend it)
		clone: function deepClone(o, visited) {
			var clone, id, type = _.util.type(o);
			visited = visited || {};

			switch (type) {
				case 'Object':
					id = _.util.objId(o);
					if (visited[id]) {
						return visited[id];
					}
					clone = {};
					visited[id] = clone;

					for (var key in o) {
						if (o.hasOwnProperty(key)) {
							clone[key] = deepClone(o[key], visited);
						}
					}

					return clone;

				case 'Array':
					id = _.util.objId(o);
					if (visited[id]) {
						return visited[id];
					}
					clone = [];
					visited[id] = clone;

					o.forEach(function (v, i) {
						clone[i] = deepClone(v, visited);
					});

					return clone;

				default:
					return o;
			}
		}
	},

	languages: {
		extend: function (id, redef) {
			var lang = _.util.clone(_.languages[id]);

			for (var key in redef) {
				lang[key] = redef[key];
			}

			return lang;
		},

		/**
		 * Insert a token before another token in a language literal
		 * As this needs to recreate the object (we cannot actually insert before keys in object literals),
		 * we cannot just provide an object, we need an object and a key.
		 * @param inside The key (or language id) of the parent
		 * @param before The key to insert before.
		 * @param insert Object with the key/value pairs to insert
		 * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
		 */
		insertBefore: function (inside, before, insert, root) {
			root = root || _.languages;
			var grammar = root[inside];
			var ret = {};

			for (var token in grammar) {
				if (grammar.hasOwnProperty(token)) {

					if (token == before) {
						for (var newToken in insert) {
							if (insert.hasOwnProperty(newToken)) {
								ret[newToken] = insert[newToken];
							}
						}
					}

					// Do not insert token which also occur in insert. See #1525
					if (!insert.hasOwnProperty(token)) {
						ret[token] = grammar[token];
					}
				}
			}

			var old = root[inside];
			root[inside] = ret;

			// Update references in other language definitions
			_.languages.DFS(_.languages, function(key, value) {
				if (value === old && key != inside) {
					this[key] = ret;
				}
			});

			return ret;
		},

		// Traverse a language definition with Depth First Search
		DFS: function DFS(o, callback, type, visited) {
			visited = visited || {};

			var objId = _.util.objId;

			for (var i in o) {
				if (o.hasOwnProperty(i)) {
					callback.call(o, i, o[i], type || i);

					var property = o[i],
					    propertyType = _.util.type(property);

					if (propertyType === 'Object' && !visited[objId(property)]) {
						visited[objId(property)] = true;
						DFS(property, callback, null, visited);
					}
					else if (propertyType === 'Array' && !visited[objId(property)]) {
						visited[objId(property)] = true;
						DFS(property, callback, i, visited);
					}
				}
			}
		}
	},
	plugins: {},

	highlightAll: function(async, callback) {
		_.highlightAllUnder(document, async, callback);
	},

	highlightAllUnder: function(container, async, callback) {
		var env = {
			callback: callback,
			selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
		};

		_.hooks.run("before-highlightall", env);

		var elements = env.elements || container.querySelectorAll(env.selector);

		for (var i=0, element; element = elements[i++];) {
			_.highlightElement(element, async === true, env.callback);
		}
	},

	highlightElement: function(element, async, callback) {
		// Find language
		var language, grammar, parent = element;

		while (parent && !lang.test(parent.className)) {
			parent = parent.parentNode;
		}

		if (parent) {
			language = (parent.className.match(lang) || [,''])[1].toLowerCase();
			grammar = _.languages[language];
		}

		// Set language on the element, if not present
		element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;

		if (element.parentNode) {
			// Set language on the parent, for styling
			parent = element.parentNode;

			if (/pre/i.test(parent.nodeName)) {
				parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
			}
		}

		var code = element.textContent;

		var env = {
			element: element,
			language: language,
			grammar: grammar,
			code: code
		};

		var insertHighlightedCode = function (highlightedCode) {
			env.highlightedCode = highlightedCode;

			_.hooks.run('before-insert', env);

			env.element.innerHTML = env.highlightedCode;

			_.hooks.run('after-highlight', env);
			_.hooks.run('complete', env);
			callback && callback.call(env.element);
		}

		_.hooks.run('before-sanity-check', env);

		if (!env.code) {
			_.hooks.run('complete', env);
			return;
		}

		_.hooks.run('before-highlight', env);

		if (!env.grammar) {
			insertHighlightedCode(_.util.encode(env.code));
			return;
		}

		if (async && _self.Worker) {
			var worker = new Worker(_.filename);

			worker.onmessage = function(evt) {
				insertHighlightedCode(evt.data);
			};

			worker.postMessage(JSON.stringify({
				language: env.language,
				code: env.code,
				immediateClose: true
			}));
		}
		else {
			insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
		}
	},

	highlight: function (text, grammar, language) {
		var env = {
			code: text,
			grammar: grammar,
			language: language
		};
		_.hooks.run('before-tokenize', env);
		env.tokens = _.tokenize(env.code, env.grammar);
		_.hooks.run('after-tokenize', env);
		return Token.stringify(_.util.encode(env.tokens), env.language);
	},

	matchGrammar: function (text, strarr, grammar, index, startPos, oneshot, target) {
		for (var token in grammar) {
			if(!grammar.hasOwnProperty(token) || !grammar[token]) {
				continue;
			}

			if (token == target) {
				return;
			}

			var patterns = grammar[token];
			patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns];

			for (var j = 0; j < patterns.length; ++j) {
				var pattern = patterns[j],
					inside = pattern.inside,
					lookbehind = !!pattern.lookbehind,
					greedy = !!pattern.greedy,
					lookbehindLength = 0,
					alias = pattern.alias;

				if (greedy && !pattern.pattern.global) {
					// Without the global flag, lastIndex won't work
					var flags = pattern.pattern.toString().match(/[imuy]*$/)[0];
					pattern.pattern = RegExp(pattern.pattern.source, flags + "g");
				}

				pattern = pattern.pattern || pattern;

				// Don’t cache length as it changes during the loop
				for (var i = index, pos = startPos; i < strarr.length; pos += strarr[i].length, ++i) {

					var str = strarr[i];

					if (strarr.length > text.length) {
						// Something went terribly wrong, ABORT, ABORT!
						return;
					}

					if (str instanceof Token) {
						continue;
					}

					if (greedy && i != strarr.length - 1) {
						pattern.lastIndex = pos;
						var match = pattern.exec(text);
						if (!match) {
							break;
						}

						var from = match.index + (lookbehind ? match[1].length : 0),
						    to = match.index + match[0].length,
						    k = i,
						    p = pos;

						for (var len = strarr.length; k < len && (p < to || (!strarr[k].type && !strarr[k - 1].greedy)); ++k) {
							p += strarr[k].length;
							// Move the index i to the element in strarr that is closest to from
							if (from >= p) {
								++i;
								pos = p;
							}
						}

						// If strarr[i] is a Token, then the match starts inside another Token, which is invalid
						if (strarr[i] instanceof Token) {
							continue;
						}

						// Number of tokens to delete and replace with the new match
						delNum = k - i;
						str = text.slice(pos, p);
						match.index -= pos;
					} else {
						pattern.lastIndex = 0;

						var match = pattern.exec(str),
							delNum = 1;
					}

					if (!match) {
						if (oneshot) {
							break;
						}

						continue;
					}

					if(lookbehind) {
						lookbehindLength = match[1] ? match[1].length : 0;
					}

					var from = match.index + lookbehindLength,
					    match = match[0].slice(lookbehindLength),
					    to = from + match.length,
					    before = str.slice(0, from),
					    after = str.slice(to);

					var args = [i, delNum];

					if (before) {
						++i;
						pos += before.length;
						args.push(before);
					}

					var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias, match, greedy);

					args.push(wrapped);

					if (after) {
						args.push(after);
					}

					Array.prototype.splice.apply(strarr, args);

					if (delNum != 1)
						_.matchGrammar(text, strarr, grammar, i, pos, true, token);

					if (oneshot)
						break;
				}
			}
		}
	},

	tokenize: function(text, grammar) {
		var strarr = [text];

		var rest = grammar.rest;

		if (rest) {
			for (var token in rest) {
				grammar[token] = rest[token];
			}

			delete grammar.rest;
		}

		_.matchGrammar(text, strarr, grammar, 0, 0, false);

		return strarr;
	},

	hooks: {
		all: {},

		add: function (name, callback) {
			var hooks = _.hooks.all;

			hooks[name] = hooks[name] || [];

			hooks[name].push(callback);
		},

		run: function (name, env) {
			var callbacks = _.hooks.all[name];

			if (!callbacks || !callbacks.length) {
				return;
			}

			for (var i=0, callback; callback = callbacks[i++];) {
				callback(env);
			}
		}
	},

	Token: Token
};

_self.Prism = _;

function Token(type, content, alias, matchedStr, greedy) {
	this.type = type;
	this.content = content;
	this.alias = alias;
	// Copy of the full string this token was created from
	this.length = (matchedStr || "").length|0;
	this.greedy = !!greedy;
}

Token.stringify = function(o, language, parent) {
	if (typeof o == 'string') {
		return o;
	}

	if (Array.isArray(o)) {
		return o.map(function(element) {
			return Token.stringify(element, language, o);
		}).join('');
	}

	var env = {
		type: o.type,
		content: Token.stringify(o.content, language, parent),
		tag: 'span',
		classes: ['token', o.type],
		attributes: {},
		language: language,
		parent: parent
	};

	if (o.alias) {
		var aliases = Array.isArray(o.alias) ? o.alias : [o.alias];
		Array.prototype.push.apply(env.classes, aliases);
	}

	_.hooks.run('wrap', env);

	var attributes = Object.keys(env.attributes).map(function(name) {
		return name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
	}).join(' ');

	return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '</' + env.tag + '>';

};

if (!_self.document) {
	if (!_self.addEventListener) {
		// in Node.js
		return _;
	}

	if (!_.disableWorkerMessageHandler) {
		// In worker
		_self.addEventListener('message', function (evt) {
			var message = JSON.parse(evt.data),
				lang = message.language,
				code = message.code,
				immediateClose = message.immediateClose;

			_self.postMessage(_.highlight(code, _.languages[lang], lang));
			if (immediateClose) {
				_self.close();
			}
		}, false);
	}

	return _;
}

//Get current script and highlight
var script = document.currentScript || [].slice.call(document.getElementsByTagName("script")).pop();

if (script) {
	_.filename = script.src;

	if (!_.manual && !script.hasAttribute('data-manual')) {
		if(document.readyState !== "loading") {
			if (window.requestAnimationFrame) {
				window.requestAnimationFrame(_.highlightAll);
			} else {
				window.setTimeout(_.highlightAll, 16);
			}
		}
		else {
			document.addEventListener('DOMContentLoaded', _.highlightAll);
		}
	}
}

return _;

})(_self);

if (  true && module.exports) {
	module.exports = Prism;
}

// hack for components to work correctly in node.js
if (typeof global !== 'undefined') {
	global.Prism = Prism;
}

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_3748715__(27)))

/***/ }),
/* 691 */
/***/ (function(module, exports) {

Prism.languages.json = {
	'comment': /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
	'property': {
		pattern: /"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
		greedy: true
	},
	'string': {
		pattern: /"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
		greedy: true
	},
	'number': /-?\d+\.?\d*(e[+-]?\d+)?/i,
	'punctuation': /[{}[\],]/,
	'operator': /:/,
	'boolean': /\b(?:true|false)\b/,
	'null': {
		pattern: /\bnull\b/,
		alias: 'keyword'
	}
};


/***/ }),
/* 692 */
/***/ (function(module, exports, __nested_webpack_require_3762370__) {

"use strict";


var resolve = __nested_webpack_require_3762370__(268)
  , util = __nested_webpack_require_3762370__(117)
  , errorClasses = __nested_webpack_require_3762370__(270)
  , stableStringify = __nested_webpack_require_3762370__(399);

var validateGenerator = __nested_webpack_require_3762370__(400);

/**
 * Functions below are used inside compiled validations function
 */

var ucs2length = util.ucs2length;
var equal = __nested_webpack_require_3762370__(269);

// this error is thrown by async schemas to return validation errors via exception
var ValidationError = errorClasses.Validation;

module.exports = compile;


/**
 * Compiles schema to validation function
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Object} root object with information about the root schema for this schema
 * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
 * @param  {String} baseId base ID for IDs in the schema
 * @return {Function} validation function
 */
function compile(schema, root, localRefs, baseId) {
  /* jshint validthis: true, evil: true */
  /* eslint no-shadow: 0 */
  var self = this
    , opts = this._opts
    , refVal = [ undefined ]
    , refs = {}
    , patterns = []
    , patternsHash = {}
    , defaults = []
    , defaultsHash = {}
    , customRules = [];

  root = root || { schema: schema, refVal: refVal, refs: refs };

  var c = checkCompiling.call(this, schema, root, baseId);
  var compilation = this._compilations[c.index];
  if (c.compiling) return (compilation.callValidate = callValidate);

  var formats = this._formats;
  var RULES = this.RULES;

  try {
    var v = localCompile(schema, root, localRefs, baseId);
    compilation.validate = v;
    var cv = compilation.callValidate;
    if (cv) {
      cv.schema = v.schema;
      cv.errors = null;
      cv.refs = v.refs;
      cv.refVal = v.refVal;
      cv.root = v.root;
      cv.$async = v.$async;
      if (opts.sourceCode) cv.source = v.source;
    }
    return v;
  } finally {
    endCompiling.call(this, schema, root, baseId);
  }

  /* @this   {*} - custom context, see passContext option */
  function callValidate() {
    /* jshint validthis: true */
    var validate = compilation.validate;
    var result = validate.apply(this, arguments);
    callValidate.errors = validate.errors;
    return result;
  }

  function localCompile(_schema, _root, localRefs, baseId) {
    var isRoot = !_root || (_root && _root.schema == _schema);
    if (_root.schema != root.schema)
      return compile.call(self, _schema, _root, localRefs, baseId);

    var $async = _schema.$async === true;

    var sourceCode = validateGenerator({
      isTop: true,
      schema: _schema,
      isRoot: isRoot,
      baseId: baseId,
      root: _root,
      schemaPath: '',
      errSchemaPath: '#',
      errorPath: '""',
      MissingRefError: errorClasses.MissingRef,
      RULES: RULES,
      validate: validateGenerator,
      util: util,
      resolve: resolve,
      resolveRef: resolveRef,
      usePattern: usePattern,
      useDefault: useDefault,
      useCustomRule: useCustomRule,
      opts: opts,
      formats: formats,
      logger: self.logger,
      self: self
    });

    sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
                   + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
                   + sourceCode;

    if (opts.processCode) sourceCode = opts.processCode(sourceCode);
    // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
    var validate;
    try {
      var makeValidate = new Function(
        'self',
        'RULES',
        'formats',
        'root',
        'refVal',
        'defaults',
        'customRules',
        'equal',
        'ucs2length',
        'ValidationError',
        sourceCode
      );

      validate = makeValidate(
        self,
        RULES,
        formats,
        root,
        refVal,
        defaults,
        customRules,
        equal,
        ucs2length,
        ValidationError
      );

      refVal[0] = validate;
    } catch(e) {
      self.logger.error('Error compiling schema, function code:', sourceCode);
      throw e;
    }

    validate.schema = _schema;
    validate.errors = null;
    validate.refs = refs;
    validate.refVal = refVal;
    validate.root = isRoot ? validate : _root;
    if ($async) validate.$async = true;
    if (opts.sourceCode === true) {
      validate.source = {
        code: sourceCode,
        patterns: patterns,
        defaults: defaults
      };
    }

    return validate;
  }

  function resolveRef(baseId, ref, isRoot) {
    ref = resolve.url(baseId, ref);
    var refIndex = refs[ref];
    var _refVal, refCode;
    if (refIndex !== undefined) {
      _refVal = refVal[refIndex];
      refCode = 'refVal[' + refIndex + ']';
      return resolvedRef(_refVal, refCode);
    }
    if (!isRoot && root.refs) {
      var rootRefId = root.refs[ref];
      if (rootRefId !== undefined) {
        _refVal = root.refVal[rootRefId];
        refCode = addLocalRef(ref, _refVal);
        return resolvedRef(_refVal, refCode);
      }
    }

    refCode = addLocalRef(ref);
    var v = resolve.call(self, localCompile, root, ref);
    if (v === undefined) {
      var localSchema = localRefs && localRefs[ref];
      if (localSchema) {
        v = resolve.inlineRef(localSchema, opts.inlineRefs)
            ? localSchema
            : compile.call(self, localSchema, root, localRefs, baseId);
      }
    }

    if (v === undefined) {
      removeLocalRef(ref);
    } else {
      replaceLocalRef(ref, v);
      return resolvedRef(v, refCode);
    }
  }

  function addLocalRef(ref, v) {
    var refId = refVal.length;
    refVal[refId] = v;
    refs[ref] = refId;
    return 'refVal' + refId;
  }

  function removeLocalRef(ref) {
    delete refs[ref];
  }

  function replaceLocalRef(ref, v) {
    var refId = refs[ref];
    refVal[refId] = v;
  }

  function resolvedRef(refVal, code) {
    return typeof refVal == 'object' || typeof refVal == 'boolean'
            ? { code: code, schema: refVal, inline: true }
            : { code: code, $async: refVal && !!refVal.$async };
  }

  function usePattern(regexStr) {
    var index = patternsHash[regexStr];
    if (index === undefined) {
      index = patternsHash[regexStr] = patterns.length;
      patterns[index] = regexStr;
    }
    return 'pattern' + index;
  }

  function useDefault(value) {
    switch (typeof value) {
      case 'boolean':
      case 'number':
        return '' + value;
      case 'string':
        return util.toQuotedString(value);
      case 'object':
        if (value === null) return 'null';
        var valueStr = stableStringify(value);
        var index = defaultsHash[valueStr];
        if (index === undefined) {
          index = defaultsHash[valueStr] = defaults.length;
          defaults[index] = value;
        }
        return 'default' + index;
    }
  }

  function useCustomRule(rule, schema, parentSchema, it) {
    if (self._opts.validateSchema !== false) {
      var deps = rule.definition.dependencies;
      if (deps && !deps.every(function(keyword) {
        return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
      }))
        throw new Error('parent schema must have all required keywords: ' + deps.join(','));

      var validateSchema = rule.definition.validateSchema;
      if (validateSchema) {
        var valid = validateSchema(schema);
        if (!valid) {
          var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
          if (self._opts.validateSchema == 'log') self.logger.error(message);
          else throw new Error(message);
        }
      }
    }

    var compile = rule.definition.compile
      , inline = rule.definition.inline
      , macro = rule.definition.macro;

    var validate;
    if (compile) {
      validate = compile.call(self, schema, parentSchema, it);
    } else if (macro) {
      validate = macro.call(self, schema, parentSchema, it);
      if (opts.validateSchema !== false) self.validateSchema(validate, true);
    } else if (inline) {
      validate = inline.call(self, it, rule.keyword, schema, parentSchema);
    } else {
      validate = rule.definition.validate;
      if (!validate) return;
    }

    if (validate === undefined)
      throw new Error('custom keyword "' + rule.keyword + '"failed to compile');

    var index = customRules.length;
    customRules[index] = validate;

    return {
      code: 'customRule' + index,
      validate: validate
    };
  }
}


/**
 * Checks if the schema is currently compiled
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
 */
function checkCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var index = compIndex.call(this, schema, root, baseId);
  if (index >= 0) return { index: index, compiling: true };
  index = this._compilations.length;
  this._compilations[index] = {
    schema: schema,
    root: root,
    baseId: baseId
  };
  return { index: index, compiling: false };
}


/**
 * Removes the schema from the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 */
function endCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var i = compIndex.call(this, schema, root, baseId);
  if (i >= 0) this._compilations.splice(i, 1);
}


/**
 * Index of schema compilation in the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Integer} compilation index
 */
function compIndex(schema, root, baseId) {
  /* jshint validthis: true */
  for (var i=0; i<this._compilations.length; i++) {
    var c = this._compilations[i];
    if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  }
  return -1;
}


function patternCode(i, patterns) {
  return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
}


function defaultCode(i) {
  return 'var default' + i + ' = defaults[' + i + '];';
}


function refValCode(i, refVal) {
  return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
}


function customRuleCode(i) {
  return 'var customRule' + i + ' = customRules[' + i + '];';
}


function vars(arr, statement) {
  if (!arr.length) return '';
  var code = '';
  for (var i=0; i<arr.length; i++)
    code += statement(i, arr);
  return code;
}


/***/ }),
/* 693 */
/***/ (function(module, exports, __webpack_require__) {

/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
(function (global, factory) {
	  true ? factory(exports) :
	0;
}(this, (function (exports) { 'use strict';

function merge() {
    for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
        sets[_key] = arguments[_key];
    }

    if (sets.length > 1) {
        sets[0] = sets[0].slice(0, -1);
        var xl = sets.length - 1;
        for (var x = 1; x < xl; ++x) {
            sets[x] = sets[x].slice(1, -1);
        }
        sets[xl] = sets[xl].slice(1);
        return sets.join('');
    } else {
        return sets[0];
    }
}
function subexp(str) {
    return "(?:" + str + ")";
}
function typeOf(o) {
    return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
}
function toUpperCase(str) {
    return str.toUpperCase();
}
function toArray(obj) {
    return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
}
function assign(target, source) {
    var obj = target;
    if (source) {
        for (var key in source) {
            obj[key] = source[key];
        }
    }
    return obj;
}

function buildExps(isIRI) {
    var ALPHA$$ = "[A-Za-z]",
        CR$ = "[\\x0D]",
        DIGIT$$ = "[0-9]",
        DQUOTE$$ = "[\\x22]",
        HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
        //case-insensitive
    LF$$ = "[\\x0A]",
        SP$$ = "[\\x20]",
        PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
        //expanded
    GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
        SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
        RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
        UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
        //subset, excludes bidi control characters
    IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
        //subset
    UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
        SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
        USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
        DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
        DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$),
        //relaxed parsing rules
    IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
        H16$ = subexp(HEXDIG$$ + "{1,4}"),
        LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
        IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
        //                           6( h16 ":" ) ls32
    IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
        //                      "::" 5( h16 ":" ) ls32
    IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
        //[               h16 ] "::" 4( h16 ":" ) ls32
    IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
        //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
    IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
        //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
    IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
        //[ *3( h16 ":" ) h16 ] "::"    h16 ":"   ls32
    IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
        //[ *4( h16 ":" ) h16 ] "::"              ls32
    IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
        //[ *5( h16 ":" ) h16 ] "::"              h16
    IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
        //[ *6( h16 ":" ) h16 ] "::"
    IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
        ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
        //RFC 6874
    IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
        //RFC 6874
    IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
        //RFC 6874, with relaxed parsing rules
    IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
        IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
        //RFC 6874
    REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
        HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
        PORT$ = subexp(DIGIT$$ + "*"),
        AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
        PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
        SEGMENT$ = subexp(PCHAR$ + "*"),
        SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
        SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
        PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
        PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
        //simplified
    PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
        //simplified
    PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
        //simplified
    PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
        PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
        QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
        FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
        HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
        URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
        RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
        RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
        URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
        ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
        GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
        RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
        ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
        SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
        AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
    return {
        NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
        NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
        NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
        ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        UNRESERVED: new RegExp(UNRESERVED$$, "g"),
        OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
        PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
        IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
        IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
    };
}
var URI_PROTOCOL = buildExps(false);

var IRI_PROTOCOL = buildExps(true);

var slicedToArray = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();













var toConsumableArray = function (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);
  }
};

/** Highest positive signed 32-bit float value */

var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1

/** Bootstring parameters */
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'

/** Regular expressions */
var regexPunycode = /^xn--/;
var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators

/** Error messages */
var errors = {
	'overflow': 'Overflow: input needs wider integers to process',
	'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
	'invalid-input': 'Invalid input'
};

/** Convenience shortcuts */
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;

/*--------------------------------------------------------------------------*/

/**
 * A generic error utility function.
 * @private
 * @param {String} type The error type.
 * @returns {Error} Throws a `RangeError` with the applicable error message.
 */
function error$1(type) {
	throw new RangeError(errors[type]);
}

/**
 * A generic `Array#map` utility function.
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} callback The function that gets called for every array
 * item.
 * @returns {Array} A new array of values returned by the callback function.
 */
function map(array, fn) {
	var result = [];
	var length = array.length;
	while (length--) {
		result[length] = fn(array[length]);
	}
	return result;
}

/**
 * A simple `Array#map`-like wrapper to work with domain name strings or email
 * addresses.
 * @private
 * @param {String} domain The domain name or email address.
 * @param {Function} callback The function that gets called for every
 * character.
 * @returns {Array} A new string of characters returned by the callback
 * function.
 */
function mapDomain(string, fn) {
	var parts = string.split('@');
	var result = '';
	if (parts.length > 1) {
		// In email addresses, only the domain name should be punycoded. Leave
		// the local part (i.e. everything up to `@`) intact.
		result = parts[0] + '@';
		string = parts[1];
	}
	// Avoid `split(regex)` for IE8 compatibility. See #17.
	string = string.replace(regexSeparators, '\x2E');
	var labels = string.split('.');
	var encoded = map(labels, fn).join('.');
	return result + encoded;
}

/**
 * Creates an array containing the numeric code points of each Unicode
 * character in the string. While JavaScript uses UCS-2 internally,
 * this function will convert a pair of surrogate halves (each of which
 * UCS-2 exposes as separate characters) into a single code point,
 * matching UTF-16.
 * @see `punycode.ucs2.encode`
 * @see <https://mathiasbynens.be/notes/javascript-encoding>
 * @memberOf punycode.ucs2
 * @name decode
 * @param {String} string The Unicode input string (UCS-2).
 * @returns {Array} The new array of code points.
 */
function ucs2decode(string) {
	var output = [];
	var counter = 0;
	var length = string.length;
	while (counter < length) {
		var value = string.charCodeAt(counter++);
		if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
			// It's a high surrogate, and there is a next character.
			var extra = string.charCodeAt(counter++);
			if ((extra & 0xFC00) == 0xDC00) {
				// Low surrogate.
				output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
			} else {
				// It's an unmatched surrogate; only append this code unit, in case the
				// next code unit is the high surrogate of a surrogate pair.
				output.push(value);
				counter--;
			}
		} else {
			output.push(value);
		}
	}
	return output;
}

/**
 * Creates a string based on an array of numeric code points.
 * @see `punycode.ucs2.decode`
 * @memberOf punycode.ucs2
 * @name encode
 * @param {Array} codePoints The array of numeric code points.
 * @returns {String} The new Unicode string (UCS-2).
 */
var ucs2encode = function ucs2encode(array) {
	return String.fromCodePoint.apply(String, toConsumableArray(array));
};

/**
 * Converts a basic code point into a digit/integer.
 * @see `digitToBasic()`
 * @private
 * @param {Number} codePoint The basic numeric code point value.
 * @returns {Number} The numeric value of a basic code point (for use in
 * representing integers) in the range `0` to `base - 1`, or `base` if
 * the code point does not represent a value.
 */
var basicToDigit = function basicToDigit(codePoint) {
	if (codePoint - 0x30 < 0x0A) {
		return codePoint - 0x16;
	}
	if (codePoint - 0x41 < 0x1A) {
		return codePoint - 0x41;
	}
	if (codePoint - 0x61 < 0x1A) {
		return codePoint - 0x61;
	}
	return base;
};

/**
 * Converts a digit/integer into a basic code point.
 * @see `basicToDigit()`
 * @private
 * @param {Number} digit The numeric value of a basic code point.
 * @returns {Number} The basic code point whose value (when used for
 * representing integers) is `digit`, which needs to be in the range
 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 * used; else, the lowercase form is used. The behavior is undefined
 * if `flag` is non-zero and `digit` has no uppercase form.
 */
var digitToBasic = function digitToBasic(digit, flag) {
	//  0..25 map to ASCII a..z or A..Z
	// 26..35 map to ASCII 0..9
	return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};

/**
 * Bias adaptation function as per section 3.4 of RFC 3492.
 * https://tools.ietf.org/html/rfc3492#section-3.4
 * @private
 */
var adapt = function adapt(delta, numPoints, firstTime) {
	var k = 0;
	delta = firstTime ? floor(delta / damp) : delta >> 1;
	delta += floor(delta / numPoints);
	for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
		delta = floor(delta / baseMinusTMin);
	}
	return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};

/**
 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 * symbols.
 * @memberOf punycode
 * @param {String} input The Punycode string of ASCII-only symbols.
 * @returns {String} The resulting string of Unicode symbols.
 */
var decode = function decode(input) {
	// Don't use UCS-2.
	var output = [];
	var inputLength = input.length;
	var i = 0;
	var n = initialN;
	var bias = initialBias;

	// Handle the basic code points: let `basic` be the number of input code
	// points before the last delimiter, or `0` if there is none, then copy
	// the first basic code points to the output.

	var basic = input.lastIndexOf(delimiter);
	if (basic < 0) {
		basic = 0;
	}

	for (var j = 0; j < basic; ++j) {
		// if it's not a basic code point
		if (input.charCodeAt(j) >= 0x80) {
			error$1('not-basic');
		}
		output.push(input.charCodeAt(j));
	}

	// Main decoding loop: start just after the last delimiter if any basic code
	// points were copied; start at the beginning otherwise.

	for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{

		// `index` is the index of the next character to be consumed.
		// Decode a generalized variable-length integer into `delta`,
		// which gets added to `i`. The overflow checking is easier
		// if we increase `i` as we go, then subtract off its starting
		// value at the end to obtain `delta`.
		var oldi = i;
		for (var w = 1, k = base;; /* no condition */k += base) {

			if (index >= inputLength) {
				error$1('invalid-input');
			}

			var digit = basicToDigit(input.charCodeAt(index++));

			if (digit >= base || digit > floor((maxInt - i) / w)) {
				error$1('overflow');
			}

			i += digit * w;
			var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;

			if (digit < t) {
				break;
			}

			var baseMinusT = base - t;
			if (w > floor(maxInt / baseMinusT)) {
				error$1('overflow');
			}

			w *= baseMinusT;
		}

		var out = output.length + 1;
		bias = adapt(i - oldi, out, oldi == 0);

		// `i` was supposed to wrap around from `out` to `0`,
		// incrementing `n` each time, so we'll fix that now:
		if (floor(i / out) > maxInt - n) {
			error$1('overflow');
		}

		n += floor(i / out);
		i %= out;

		// Insert `n` at position `i` of the output.
		output.splice(i++, 0, n);
	}

	return String.fromCodePoint.apply(String, output);
};

/**
 * Converts a string of Unicode symbols (e.g. a domain name label) to a
 * Punycode string of ASCII-only symbols.
 * @memberOf punycode
 * @param {String} input The string of Unicode symbols.
 * @returns {String} The resulting Punycode string of ASCII-only symbols.
 */
var encode = function encode(input) {
	var output = [];

	// Convert the input in UCS-2 to an array of Unicode code points.
	input = ucs2decode(input);

	// Cache the length.
	var inputLength = input.length;

	// Initialize the state.
	var n = initialN;
	var delta = 0;
	var bias = initialBias;

	// Handle the basic code points.
	var _iteratorNormalCompletion = true;
	var _didIteratorError = false;
	var _iteratorError = undefined;

	try {
		for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
			var _currentValue2 = _step.value;

			if (_currentValue2 < 0x80) {
				output.push(stringFromCharCode(_currentValue2));
			}
		}
	} catch (err) {
		_didIteratorError = true;
		_iteratorError = err;
	} finally {
		try {
			if (!_iteratorNormalCompletion && _iterator.return) {
				_iterator.return();
			}
		} finally {
			if (_didIteratorError) {
				throw _iteratorError;
			}
		}
	}

	var basicLength = output.length;
	var handledCPCount = basicLength;

	// `handledCPCount` is the number of code points that have been handled;
	// `basicLength` is the number of basic code points.

	// Finish the basic string with a delimiter unless it's empty.
	if (basicLength) {
		output.push(delimiter);
	}

	// Main encoding loop:
	while (handledCPCount < inputLength) {

		// All non-basic code points < n have been handled already. Find the next
		// larger one:
		var m = maxInt;
		var _iteratorNormalCompletion2 = true;
		var _didIteratorError2 = false;
		var _iteratorError2 = undefined;

		try {
			for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
				var currentValue = _step2.value;

				if (currentValue >= n && currentValue < m) {
					m = currentValue;
				}
			}

			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
			// but guard against overflow.
		} catch (err) {
			_didIteratorError2 = true;
			_iteratorError2 = err;
		} finally {
			try {
				if (!_iteratorNormalCompletion2 && _iterator2.return) {
					_iterator2.return();
				}
			} finally {
				if (_didIteratorError2) {
					throw _iteratorError2;
				}
			}
		}

		var handledCPCountPlusOne = handledCPCount + 1;
		if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
			error$1('overflow');
		}

		delta += (m - n) * handledCPCountPlusOne;
		n = m;

		var _iteratorNormalCompletion3 = true;
		var _didIteratorError3 = false;
		var _iteratorError3 = undefined;

		try {
			for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
				var _currentValue = _step3.value;

				if (_currentValue < n && ++delta > maxInt) {
					error$1('overflow');
				}
				if (_currentValue == n) {
					// Represent delta as a generalized variable-length integer.
					var q = delta;
					for (var k = base;; /* no condition */k += base) {
						var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
						if (q < t) {
							break;
						}
						var qMinusT = q - t;
						var baseMinusT = base - t;
						output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
						q = floor(qMinusT / baseMinusT);
					}

					output.push(stringFromCharCode(digitToBasic(q, 0)));
					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
					delta = 0;
					++handledCPCount;
				}
			}
		} catch (err) {
			_didIteratorError3 = true;
			_iteratorError3 = err;
		} finally {
			try {
				if (!_iteratorNormalCompletion3 && _iterator3.return) {
					_iterator3.return();
				}
			} finally {
				if (_didIteratorError3) {
					throw _iteratorError3;
				}
			}
		}

		++delta;
		++n;
	}
	return output.join('');
};

/**
 * Converts a Punycode string representing a domain name or an email address
 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 * it doesn't matter if you call it on a string that has already been
 * converted to Unicode.
 * @memberOf punycode
 * @param {String} input The Punycoded domain name or email address to
 * convert to Unicode.
 * @returns {String} The Unicode representation of the given Punycode
 * string.
 */
var toUnicode = function toUnicode(input) {
	return mapDomain(input, function (string) {
		return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
	});
};

/**
 * Converts a Unicode string representing a domain name or an email address to
 * Punycode. Only the non-ASCII parts of the domain name will be converted,
 * i.e. it doesn't matter if you call it with a domain that's already in
 * ASCII.
 * @memberOf punycode
 * @param {String} input The domain name or email address to convert, as a
 * Unicode string.
 * @returns {String} The Punycode representation of the given domain name or
 * email address.
 */
var toASCII = function toASCII(input) {
	return mapDomain(input, function (string) {
		return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
	});
};

/*--------------------------------------------------------------------------*/

/** Define the public API */
var punycode = {
	/**
  * A string representing the current Punycode.js version number.
  * @memberOf punycode
  * @type String
  */
	'version': '2.1.0',
	/**
  * An object of methods to convert from JavaScript's internal character
  * representation (UCS-2) to Unicode code points, and back.
  * @see <https://mathiasbynens.be/notes/javascript-encoding>
  * @memberOf punycode
  * @type Object
  */
	'ucs2': {
		'decode': ucs2decode,
		'encode': ucs2encode
	},
	'decode': decode,
	'encode': encode,
	'toASCII': toASCII,
	'toUnicode': toUnicode
};

/**
 * URI.js
 *
 * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/uri-js
 */
/**
 * Copyright 2011 Gary Court. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Gary Court.
 */
var SCHEMES = {};
function pctEncChar(chr) {
    var c = chr.charCodeAt(0);
    var e = void 0;
    if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
    return e;
}
function pctDecChars(str) {
    var newStr = "";
    var i = 0;
    var il = str.length;
    while (i < il) {
        var c = parseInt(str.substr(i + 1, 2), 16);
        if (c < 128) {
            newStr += String.fromCharCode(c);
            i += 3;
        } else if (c >= 194 && c < 224) {
            if (il - i >= 6) {
                var c2 = parseInt(str.substr(i + 4, 2), 16);
                newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
            } else {
                newStr += str.substr(i, 6);
            }
            i += 6;
        } else if (c >= 224) {
            if (il - i >= 9) {
                var _c = parseInt(str.substr(i + 4, 2), 16);
                var c3 = parseInt(str.substr(i + 7, 2), 16);
                newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
            } else {
                newStr += str.substr(i, 9);
            }
            i += 9;
        } else {
            newStr += str.substr(i, 3);
            i += 3;
        }
    }
    return newStr;
}
function _normalizeComponentEncoding(components, protocol) {
    function decodeUnreserved(str) {
        var decStr = pctDecChars(str);
        return !decStr.match(protocol.UNRESERVED) ? str : decStr;
    }
    if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
    if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    return components;
}

function _stripLeadingZeros(str) {
    return str.replace(/^0*(.*)/, "$1") || "0";
}
function _normalizeIPv4(host, protocol) {
    var matches = host.match(protocol.IPV4ADDRESS) || [];

    var _matches = slicedToArray(matches, 2),
        address = _matches[1];

    if (address) {
        return address.split(".").map(_stripLeadingZeros).join(".");
    } else {
        return host;
    }
}
function _normalizeIPv6(host, protocol) {
    var matches = host.match(protocol.IPV6ADDRESS) || [];

    var _matches2 = slicedToArray(matches, 3),
        address = _matches2[1],
        zone = _matches2[2];

    if (address) {
        var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
            _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
            last = _address$toLowerCase$2[0],
            first = _address$toLowerCase$2[1];

        var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
        var lastFields = last.split(":").map(_stripLeadingZeros);
        var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
        var fieldCount = isLastFieldIPv4Address ? 7 : 8;
        var lastFieldsStart = lastFields.length - fieldCount;
        var fields = Array(fieldCount);
        for (var x = 0; x < fieldCount; ++x) {
            fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
        }
        if (isLastFieldIPv4Address) {
            fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
        }
        var allZeroFields = fields.reduce(function (acc, field, index) {
            if (!field || field === "0") {
                var lastLongest = acc[acc.length - 1];
                if (lastLongest && lastLongest.index + lastLongest.length === index) {
                    lastLongest.length++;
                } else {
                    acc.push({ index: index, length: 1 });
                }
            }
            return acc;
        }, []);
        var longestZeroFields = allZeroFields.sort(function (a, b) {
            return b.length - a.length;
        })[0];
        var newHost = void 0;
        if (longestZeroFields && longestZeroFields.length > 1) {
            var newFirst = fields.slice(0, longestZeroFields.index);
            var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
            newHost = newFirst.join(":") + "::" + newLast.join(":");
        } else {
            newHost = fields.join(":");
        }
        if (zone) {
            newHost += "%" + zone;
        }
        return newHost;
    } else {
        return host;
    }
}
var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
function parse(uriString) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var components = {};
    var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
    if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
    var matches = uriString.match(URI_PARSE);
    if (matches) {
        if (NO_MATCH_IS_UNDEFINED) {
            //store each component
            components.scheme = matches[1];
            components.userinfo = matches[3];
            components.host = matches[4];
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = matches[7];
            components.fragment = matches[8];
            //fix port number
            if (isNaN(components.port)) {
                components.port = matches[5];
            }
        } else {
            //IE FIX for improper RegExp matching
            //store each component
            components.scheme = matches[1] || undefined;
            components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
            components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
            components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined;
            //fix port number
            if (isNaN(components.port)) {
                components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
            }
        }
        if (components.host) {
            //normalize IP hosts
            components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
        }
        //determine reference type
        if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
            components.reference = "same-document";
        } else if (components.scheme === undefined) {
            components.reference = "relative";
        } else if (components.fragment === undefined) {
            components.reference = "absolute";
        } else {
            components.reference = "uri";
        }
        //check for reference errors
        if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
            components.error = components.error || "URI is not a " + options.reference + " reference.";
        }
        //find scheme handler
        var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
        //check if scheme can't handle IRIs
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
            //if host component is a domain name
            if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
                //convert Unicode IDN -> ASCII IDN
                try {
                    components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
                } catch (e) {
                    components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
                }
            }
            //convert IRI -> URI
            _normalizeComponentEncoding(components, URI_PROTOCOL);
        } else {
            //normalize encodings
            _normalizeComponentEncoding(components, protocol);
        }
        //perform scheme specific parsing
        if (schemeHandler && schemeHandler.parse) {
            schemeHandler.parse(components, options);
        }
    } else {
        components.error = components.error || "URI can not be parsed.";
    }
    return components;
}

function _recomposeAuthority(components, options) {
    var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
    var uriTokens = [];
    if (components.userinfo !== undefined) {
        uriTokens.push(components.userinfo);
        uriTokens.push("@");
    }
    if (components.host !== undefined) {
        //normalize IP hosts, add brackets and escape zone separator for IPv6
        uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
            return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
        }));
    }
    if (typeof components.port === "number") {
        uriTokens.push(":");
        uriTokens.push(components.port.toString(10));
    }
    return uriTokens.length ? uriTokens.join("") : undefined;
}

var RDS1 = /^\.\.?\//;
var RDS2 = /^\/\.(\/|$)/;
var RDS3 = /^\/\.\.(\/|$)/;
var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
function removeDotSegments(input) {
    var output = [];
    while (input.length) {
        if (input.match(RDS1)) {
            input = input.replace(RDS1, "");
        } else if (input.match(RDS2)) {
            input = input.replace(RDS2, "/");
        } else if (input.match(RDS3)) {
            input = input.replace(RDS3, "/");
            output.pop();
        } else if (input === "." || input === "..") {
            input = "";
        } else {
            var im = input.match(RDS5);
            if (im) {
                var s = im[0];
                input = input.slice(s.length);
                output.push(s);
            } else {
                throw new Error("Unexpected dot segment condition");
            }
        }
    }
    return output.join("");
}

function serialize(components) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
    var uriTokens = [];
    //find scheme handler
    var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
    //perform scheme specific serialization
    if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
    if (components.host) {
        //if host component is an IPv6 address
        if (protocol.IPV6ADDRESS.test(components.host)) {}
        //TODO: normalize IPv6 address as per RFC 5952

        //if host component is a domain name
        else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
                //convert IDN via punycode
                try {
                    components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
                } catch (e) {
                    components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
                }
            }
    }
    //normalize encoding
    _normalizeComponentEncoding(components, protocol);
    if (options.reference !== "suffix" && components.scheme) {
        uriTokens.push(components.scheme);
        uriTokens.push(":");
    }
    var authority = _recomposeAuthority(components, options);
    if (authority !== undefined) {
        if (options.reference !== "suffix") {
            uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (components.path && components.path.charAt(0) !== "/") {
            uriTokens.push("/");
        }
    }
    if (components.path !== undefined) {
        var s = components.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
            s = removeDotSegments(s);
        }
        if (authority === undefined) {
            s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
        }
        uriTokens.push(s);
    }
    if (components.query !== undefined) {
        uriTokens.push("?");
        uriTokens.push(components.query);
    }
    if (components.fragment !== undefined) {
        uriTokens.push("#");
        uriTokens.push(components.fragment);
    }
    return uriTokens.join(""); //merge tokens into a string
}

function resolveComponents(base, relative) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    var skipNormalization = arguments[3];

    var target = {};
    if (!skipNormalization) {
        base = parse(serialize(base, options), options); //normalize base components
        relative = parse(serialize(relative, options), options); //normalize relative components
    }
    options = options || {};
    if (!options.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        //target.authority = relative.authority;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
    } else {
        if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
            //target.authority = relative.authority;
            target.userinfo = relative.userinfo;
            target.host = relative.host;
            target.port = relative.port;
            target.path = removeDotSegments(relative.path || "");
            target.query = relative.query;
        } else {
            if (!relative.path) {
                target.path = base.path;
                if (relative.query !== undefined) {
                    target.query = relative.query;
                } else {
                    target.query = base.query;
                }
            } else {
                if (relative.path.charAt(0) === "/") {
                    target.path = removeDotSegments(relative.path);
                } else {
                    if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
                        target.path = "/" + relative.path;
                    } else if (!base.path) {
                        target.path = relative.path;
                    } else {
                        target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
                    }
                    target.path = removeDotSegments(target.path);
                }
                target.query = relative.query;
            }
            //target.authority = base.authority;
            target.userinfo = base.userinfo;
            target.host = base.host;
            target.port = base.port;
        }
        target.scheme = base.scheme;
    }
    target.fragment = relative.fragment;
    return target;
}

function resolve(baseURI, relativeURI, options) {
    var schemelessOptions = assign({ scheme: 'null' }, options);
    return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
}

function normalize(uri, options) {
    if (typeof uri === "string") {
        uri = serialize(parse(uri, options), options);
    } else if (typeOf(uri) === "object") {
        uri = parse(serialize(uri, options), options);
    }
    return uri;
}

function equal(uriA, uriB, options) {
    if (typeof uriA === "string") {
        uriA = serialize(parse(uriA, options), options);
    } else if (typeOf(uriA) === "object") {
        uriA = serialize(uriA, options);
    }
    if (typeof uriB === "string") {
        uriB = serialize(parse(uriB, options), options);
    } else if (typeOf(uriB) === "object") {
        uriB = serialize(uriB, options);
    }
    return uriA === uriB;
}

function escapeComponent(str, options) {
    return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
}

function unescapeComponent(str, options) {
    return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
}

var handler = {
    scheme: "http",
    domainHost: true,
    parse: function parse(components, options) {
        //report missing host
        if (!components.host) {
            components.error = components.error || "HTTP URIs must have a host.";
        }
        return components;
    },
    serialize: function serialize(components, options) {
        //normalize the default port
        if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") {
            components.port = undefined;
        }
        //normalize the empty path
        if (!components.path) {
            components.path = "/";
        }
        //NOTE: We do not parse query strings for HTTP URIs
        //as WWW Form Url Encoded query strings are part of the HTML4+ spec,
        //and not the HTTP spec.
        return components;
    }
};

var handler$1 = {
    scheme: "https",
    domainHost: handler.domainHost,
    parse: handler.parse,
    serialize: handler.serialize
};

var O = {};
var isIRI = true;
//RFC 3986
var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]";  //(%d1-8 / %d11-12 / %d14-31 / %d127)
//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$);  //%d33 / %d35-91 / %d93-126 / obs-qtext
//const VCHAR$$ = "[\\x21-\\x7E]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$));  //%d0 / CR / LF / obs-qtext
//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
var UNRESERVED = new RegExp(UNRESERVED$$, "g");
var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
var NOT_HFVALUE = NOT_HFNAME;
function decodeUnreserved(str) {
    var decStr = pctDecChars(str);
    return !decStr.match(UNRESERVED) ? str : decStr;
}
var handler$2 = {
    scheme: "mailto",
    parse: function parse$$1(components, options) {
        var mailtoComponents = components;
        var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
        mailtoComponents.path = undefined;
        if (mailtoComponents.query) {
            var unknownHeaders = false;
            var headers = {};
            var hfields = mailtoComponents.query.split("&");
            for (var x = 0, xl = hfields.length; x < xl; ++x) {
                var hfield = hfields[x].split("=");
                switch (hfield[0]) {
                    case "to":
                        var toAddrs = hfield[1].split(",");
                        for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
                            to.push(toAddrs[_x]);
                        }
                        break;
                    case "subject":
                        mailtoComponents.subject = unescapeComponent(hfield[1], options);
                        break;
                    case "body":
                        mailtoComponents.body = unescapeComponent(hfield[1], options);
                        break;
                    default:
                        unknownHeaders = true;
                        headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
                        break;
                }
            }
            if (unknownHeaders) mailtoComponents.headers = headers;
        }
        mailtoComponents.query = undefined;
        for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
            var addr = to[_x2].split("@");
            addr[0] = unescapeComponent(addr[0]);
            if (!options.unicodeSupport) {
                //convert Unicode IDN -> ASCII IDN
                try {
                    addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
                } catch (e) {
                    mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
                }
            } else {
                addr[1] = unescapeComponent(addr[1], options).toLowerCase();
            }
            to[_x2] = addr.join("@");
        }
        return mailtoComponents;
    },
    serialize: function serialize$$1(mailtoComponents, options) {
        var components = mailtoComponents;
        var to = toArray(mailtoComponents.to);
        if (to) {
            for (var x = 0, xl = to.length; x < xl; ++x) {
                var toAddr = String(to[x]);
                var atIdx = toAddr.lastIndexOf("@");
                var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
                var domain = toAddr.slice(atIdx + 1);
                //convert IDN via punycode
                try {
                    domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
                } catch (e) {
                    components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
                }
                to[x] = localPart + "@" + domain;
            }
            components.path = to.join(",");
        }
        var headers = mailtoComponents.headers = mailtoComponents.headers || {};
        if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
        if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
        var fields = [];
        for (var name in headers) {
            if (headers[name] !== O[name]) {
                fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
            }
        }
        if (fields.length) {
            components.query = fields.join("&");
        }
        return components;
    }
};

var URN_PARSE = /^([^\:]+)\:(.*)/;
//RFC 2141
var handler$3 = {
    scheme: "urn",
    parse: function parse$$1(components, options) {
        var matches = components.path && components.path.match(URN_PARSE);
        var urnComponents = components;
        if (matches) {
            var scheme = options.scheme || urnComponents.scheme || "urn";
            var nid = matches[1].toLowerCase();
            var nss = matches[2];
            var urnScheme = scheme + ":" + (options.nid || nid);
            var schemeHandler = SCHEMES[urnScheme];
            urnComponents.nid = nid;
            urnComponents.nss = nss;
            urnComponents.path = undefined;
            if (schemeHandler) {
                urnComponents = schemeHandler.parse(urnComponents, options);
            }
        } else {
            urnComponents.error = urnComponents.error || "URN can not be parsed.";
        }
        return urnComponents;
    },
    serialize: function serialize$$1(urnComponents, options) {
        var scheme = options.scheme || urnComponents.scheme || "urn";
        var nid = urnComponents.nid;
        var urnScheme = scheme + ":" + (options.nid || nid);
        var schemeHandler = SCHEMES[urnScheme];
        if (schemeHandler) {
            urnComponents = schemeHandler.serialize(urnComponents, options);
        }
        var uriComponents = urnComponents;
        var nss = urnComponents.nss;
        uriComponents.path = (nid || options.nid) + ":" + nss;
        return uriComponents;
    }
};

var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
//RFC 4122
var handler$4 = {
    scheme: "urn:uuid",
    parse: function parse(urnComponents, options) {
        var uuidComponents = urnComponents;
        uuidComponents.uuid = uuidComponents.nss;
        uuidComponents.nss = undefined;
        if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
            uuidComponents.error = uuidComponents.error || "UUID is not valid.";
        }
        return uuidComponents;
    },
    serialize: function serialize(uuidComponents, options) {
        var urnComponents = uuidComponents;
        //normalize UUID
        urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
        return urnComponents;
    }
};

SCHEMES[handler.scheme] = handler;
SCHEMES[handler$1.scheme] = handler$1;
SCHEMES[handler$2.scheme] = handler$2;
SCHEMES[handler$3.scheme] = handler$3;
SCHEMES[handler$4.scheme] = handler$4;

exports.SCHEMES = SCHEMES;
exports.pctEncChar = pctEncChar;
exports.pctDecChars = pctDecChars;
exports.parse = parse;
exports.removeDotSegments = removeDotSegments;
exports.serialize = serialize;
exports.resolveComponents = resolveComponents;
exports.resolve = resolve;
exports.normalize = normalize;
exports.equal = equal;
exports.escapeComponent = escapeComponent;
exports.unescapeComponent = unescapeComponent;

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

})));
//# sourceMappingURL=uri.all.js.map


/***/ }),
/* 694 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
  var length = 0
    , len = str.length
    , pos = 0
    , value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos);
      if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
    }
  }
  return length;
};


/***/ }),
/* 695 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


/***/ }),
/* 696 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";



var Cache = module.exports = function Cache() {
  this._cache = {};
};


Cache.prototype.put = function Cache_put(key, value) {
  this._cache[key] = value;
};


Cache.prototype.get = function Cache_get(key) {
  return this._cache[key];
};


Cache.prototype.del = function Cache_del(key) {
  delete this._cache[key];
};


Cache.prototype.clear = function Cache_clear() {
  this._cache = {};
};


/***/ }),
/* 697 */
/***/ (function(module, exports, __nested_webpack_require_3831837__) {

"use strict";


var util = __nested_webpack_require_3831837__(117);

var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
// uri-template: https://tools.ietf.org/html/rfc6570
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;


module.exports = formats;

function formats(mode) {
  mode = mode == 'full' ? 'full' : 'fast';
  return util.copy(formats[mode]);
}


formats.fast = {
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
  date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
  'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
  // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
  'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
  'uri-template': URITEMPLATE,
  url: URL,
  // email (sources from jsen validator):
  // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
  email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  hostname: HOSTNAME,
  // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  // uuid: http://tools.ietf.org/html/rfc4122
  uuid: UUID,
  // JSON-pointer: https://tools.ietf.org/html/rfc6901
  // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  'json-pointer': JSON_POINTER,
  'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


formats.full = {
  date: date,
  time: time,
  'date-time': date_time,
  uri: uri,
  'uri-reference': URIREF,
  'uri-template': URITEMPLATE,
  url: URL,
  email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  hostname: hostname,
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  uuid: UUID,
  'json-pointer': JSON_POINTER,
  'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


function isLeapYear(year) {
  // https://tools.ietf.org/html/rfc3339#appendix-C
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}


function date(str) {
  // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  var matches = str.match(DATE);
  if (!matches) return false;

  var year = +matches[1];
  var month = +matches[2];
  var day = +matches[3];

  return month >= 1 && month <= 12 && day >= 1 &&
          day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}


function time(str, full) {
  var matches = str.match(TIME);
  if (!matches) return false;

  var hour = matches[1];
  var minute = matches[2];
  var second = matches[3];
  var timeZone = matches[5];
  return ((hour <= 23 && minute <= 59 && second <= 59) ||
          (hour == 23 && minute == 59 && second == 60)) &&
         (!full || timeZone);
}


var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  var dateTime = str.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}


function hostname(str) {
  // https://tools.ietf.org/html/rfc1034#section-3.5
  // https://tools.ietf.org/html/rfc1123#section-2
  return str.length <= 255 && HOSTNAME.test(str);
}


var NOT_URI_FRAGMENT = /\/|:/;
function uri(str) {
  // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}


var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
  if (Z_ANCHOR.test(str)) return false;
  try {
    new RegExp(str);
    return true;
  } catch(e) {
    return false;
  }
}


/***/ }),
/* 698 */
/***/ (function(module, exports, __nested_webpack_require_3844163__) {

"use strict";


var ruleModules = __nested_webpack_require_3844163__(699)
  , toHash = __nested_webpack_require_3844163__(117).toHash;

module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ { 'maximum': ['exclusiveMaximum'] },
               { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
               { 'properties': ['additionalProperties', 'patternProperties'] } ] },
    { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
  ];

  var ALL = [ 'type', '$comment' ];
  var KEYWORDS = [
    '$schema', '$id', 'id', '$data', '$async', 'title',
    'description', 'default', 'definitions',
    'examples', 'readOnly', 'writeOnly',
    'contentMediaType', 'contentEncoding',
    'additionalItems', 'then', 'else'
  ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);

  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      var implKeywords;
      if (typeof keyword == 'object') {
        var key = Object.keys(keyword)[0];
        implKeywords = keyword[key];
        keyword = key;
        implKeywords.forEach(function (k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword],
        implements: implKeywords
      };
      return rule;
    });

    RULES.all.$comment = {
      keyword: '$comment',
      code: ruleModules.$comment
    };

    if (group.type) RULES.types[group.type] = group;
  });

  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.custom = {};

  return RULES;
};


/***/ }),
/* 699 */
/***/ (function(module, exports, __nested_webpack_require_3846276__) {

"use strict";


//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
  '$ref': __nested_webpack_require_3846276__(700),
  allOf: __nested_webpack_require_3846276__(701),
  anyOf: __nested_webpack_require_3846276__(702),
  '$comment': __nested_webpack_require_3846276__(703),
  const: __nested_webpack_require_3846276__(704),
  contains: __nested_webpack_require_3846276__(705),
  dependencies: __nested_webpack_require_3846276__(706),
  'enum': __nested_webpack_require_3846276__(707),
  format: __nested_webpack_require_3846276__(708),
  'if': __nested_webpack_require_3846276__(709),
  items: __nested_webpack_require_3846276__(710),
  maximum: __nested_webpack_require_3846276__(401),
  minimum: __nested_webpack_require_3846276__(401),
  maxItems: __nested_webpack_require_3846276__(402),
  minItems: __nested_webpack_require_3846276__(402),
  maxLength: __nested_webpack_require_3846276__(403),
  minLength: __nested_webpack_require_3846276__(403),
  maxProperties: __nested_webpack_require_3846276__(404),
  minProperties: __nested_webpack_require_3846276__(404),
  multipleOf: __nested_webpack_require_3846276__(711),
  not: __nested_webpack_require_3846276__(712),
  oneOf: __nested_webpack_require_3846276__(713),
  pattern: __nested_webpack_require_3846276__(714),
  properties: __nested_webpack_require_3846276__(715),
  propertyNames: __nested_webpack_require_3846276__(716),
  required: __nested_webpack_require_3846276__(717),
  uniqueItems: __nested_webpack_require_3846276__(718),
  validate: __nested_webpack_require_3846276__(400)
};


/***/ }),
/* 700 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_ref(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $async, $refCode;
  if ($schema == '#' || $schema == '#/') {
    if (it.isRoot) {
      $async = it.async;
      $refCode = 'validate';
    } else {
      $async = it.root.schema.$async === true;
      $refCode = 'root.refVal[0]';
    }
  } else {
    var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
    if ($refVal === undefined) {
      var $message = it.MissingRefError.message(it.baseId, $schema);
      if (it.opts.missingRefs == 'fail') {
        it.logger.error($message);
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        if ($breakOnError) {
          out += ' if (false) { ';
        }
      } else if (it.opts.missingRefs == 'ignore') {
        it.logger.warn($message);
        if ($breakOnError) {
          out += ' if (true) { ';
        }
      } else {
        throw new it.MissingRefError(it.baseId, $schema, $message);
      }
    } else if ($refVal.inline) {
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = 'valid' + $it.level;
      $it.schema = $refVal.schema;
      $it.schemaPath = '';
      $it.errSchemaPath = $schema;
      var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
      out += ' ' + ($code) + ' ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
      }
    } else {
      $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
      $refCode = $refVal.code;
    }
  }
  if ($refCode) {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    if (it.opts.passContext) {
      out += ' ' + ($refCode) + '.call(this, ';
    } else {
      out += ' ' + ($refCode) + '( ';
    }
    out += ' ' + ($data) + ', (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
    var __callValidate = out;
    out = $$outStack.pop();
    if ($async) {
      if (!it.async) throw new Error('async schema referenced by sync schema');
      if ($breakOnError) {
        out += ' var ' + ($valid) + '; ';
      }
      out += ' try { await ' + (__callValidate) + '; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = true; ';
      }
      out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = false; ';
      }
      out += ' } ';
      if ($breakOnError) {
        out += ' if (' + ($valid) + ') { ';
      }
    } else {
      out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
      if ($breakOnError) {
        out += ' else { ';
      }
    }
  }
  return out;
}


/***/ }),
/* 701 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_allOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $allSchemasEmpty = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $allSchemasEmpty = false;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($breakOnError) {
    if ($allSchemasEmpty) {
      out += ' if (true) { ';
    } else {
      out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
    }
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),
/* 702 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_anyOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $noEmptySchema = $schema.every(function($sch) {
    return it.util.schemaHasRules($sch, it.RULES.all);
  });
  if ($noEmptySchema) {
    var $currentBaseId = $it.baseId;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
        $closingBraces += '}';
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match some schema in anyOf\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
    out = it.util.cleanUpCode(out);
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}


/***/ }),
/* 703 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_comment(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $comment = it.util.toQuotedString($schema);
  if (it.opts.$comment === true) {
    out += ' console.log(' + ($comment) + ');';
  } else if (typeof it.opts.$comment == 'function') {
    out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
  }
  return out;
}


/***/ }),
/* 704 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_const(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!$isData) {
    out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to constant\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 705 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_contains(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId,
    $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all);
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($nonEmptySchema) {
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    out += ' if (' + ($nextValid) + ') break; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
  } else {
    out += ' if (' + ($data) + '.length == 0) {';
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should contain a valid item\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } else { ';
  if ($nonEmptySchema) {
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  }
  if (it.opts.allErrors) {
    out += ' } ';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),
/* 706 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_dependencies(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $schemaDeps = {},
    $propertyDeps = {},
    $ownProperties = it.opts.ownProperties;
  for ($property in $schema) {
    var $sch = $schema[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
  out += 'var ' + ($errs) + ' = errors;';
  var $currentErrorPath = it.errorPath;
  out += 'var missing' + ($lvl) + ';';
  for (var $property in $propertyDeps) {
    $deps = $propertyDeps[$property];
    if ($deps.length) {
      out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      if ($breakOnError) {
        out += ' && ( ';
        var arr1 = $deps;
        if (arr1) {
          var $propertyKey, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $propertyKey = arr1[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ')) {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should have ';
            if ($deps.length == 1) {
              out += 'property ' + (it.util.escapeQuotes($deps[0]));
            } else {
              out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
            }
            out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      } else {
        out += ' ) { ';
        var arr2 = $deps;
        if (arr2) {
          var $propertyKey, i2 = -1,
            l2 = arr2.length - 1;
          while (i2 < l2) {
            $propertyKey = arr2[i2 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'should have ';
                if ($deps.length == 1) {
                  out += 'property ' + (it.util.escapeQuotes($deps[0]));
                } else {
                  out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
                }
                out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
      out += ' }   ';
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
  }
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
  for (var $property in $schemaDeps) {
    var $sch = $schemaDeps[$property];
    if (it.util.schemaHasRules($sch, it.RULES.all)) {
      out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      out += ') { ';
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + it.util.getProperty($property);
      $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  }
  if ($breakOnError) {
    out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),
/* 707 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_enum(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $i = 'i' + $lvl,
    $vSchema = 'schema' + $lvl;
  if (!$isData) {
    out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ';';
  if ($isData) {
    out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  }
  out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  if ($isData) {
    out += '  }  ';
  }
  out += ' if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to one of the allowed values\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 708 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_format(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  if (it.opts.format === false) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
    return out;
  }
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $unknownFormats = it.opts.unknownFormats,
    $allowUnknown = Array.isArray($unknownFormats);
  if ($isData) {
    var $format = 'format' + $lvl,
      $isObject = 'isObject' + $lvl,
      $formatType = 'formatType' + $lvl;
    out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
    if (it.async) {
      out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
    }
    out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' (';
    if ($unknownFormats != 'ignore') {
      out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
      if ($allowUnknown) {
        out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
      }
      out += ') || ';
    }
    out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
    if (it.async) {
      out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
    } else {
      out += ' ' + ($format) + '(' + ($data) + ') ';
    }
    out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
  } else {
    var $format = it.formats[$schema];
    if (!$format) {
      if ($unknownFormats == 'ignore') {
        it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else {
        throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
      }
    }
    var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
    var $formatType = $isObject && $format.type || 'string';
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
    if ($formatType != $ruleType) {
      if ($breakOnError) {
        out += ' if (true) { ';
      }
      return out;
    }
    if ($async) {
      if (!it.async) throw new Error('async format in sync schema');
      var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
      out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
    } else {
      out += ' if (! ';
      var $formatRef = 'formats' + it.util.getProperty($schema);
      if ($isObject) $formatRef += '.validate';
      if (typeof $format == 'function') {
        out += ' ' + ($formatRef) + '(' + ($data) + ') ';
      } else {
        out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
      }
      out += ') { ';
    }
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match format "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 709 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_if(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $thenSch = it.schema['then'],
    $elseSch = it.schema['else'],
    $thenPresent = $thenSch !== undefined && it.util.schemaHasRules($thenSch, it.RULES.all),
    $elsePresent = $elseSch !== undefined && it.util.schemaHasRules($elseSch, it.RULES.all),
    $currentBaseId = $it.baseId;
  if ($thenPresent || $elsePresent) {
    var $ifClause;
    $it.createErrors = false;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    out += '  ' + (it.validate($it)) + ' ';
    $it.baseId = $currentBaseId;
    $it.createErrors = true;
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    if ($thenPresent) {
      out += ' if (' + ($nextValid) + ') {  ';
      $it.schema = it.schema['then'];
      $it.schemaPath = it.schemaPath + '.then';
      $it.errSchemaPath = it.errSchemaPath + '/then';
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
      if ($thenPresent && $elsePresent) {
        $ifClause = 'ifClause' + $lvl;
        out += ' var ' + ($ifClause) + ' = \'then\'; ';
      } else {
        $ifClause = '\'then\'';
      }
      out += ' } ';
      if ($elsePresent) {
        out += ' else { ';
      }
    } else {
      out += ' if (!' + ($nextValid) + ') { ';
    }
    if ($elsePresent) {
      $it.schema = it.schema['else'];
      $it.schemaPath = it.schemaPath + '.else';
      $it.errSchemaPath = it.errSchemaPath + '/else';
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
      if ($thenPresent && $elsePresent) {
        $ifClause = 'ifClause' + $lvl;
        out += ' var ' + ($ifClause) + ' = \'else\'; ';
      } else {
        $ifClause = '\'else\'';
      }
      out += ' } ';
    }
    out += ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' }   ';
    if ($breakOnError) {
      out += ' else { ';
    }
    out = it.util.cleanUpCode(out);
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}


/***/ }),
/* 710 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_items(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId;
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if (Array.isArray($schema)) {
    var $additionalItems = it.schema.additionalItems;
    if ($additionalItems === false) {
      out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += '  if (!' + ($valid) + ') {   ';
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
      out += ' } ';
      $errSchemaPath = $currErrSchemaPath;
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
          var $passData = $data + '[' + $i + ']';
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + '[' + $i + ']';
          $it.errSchemaPath = $errSchemaPath + '/' + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
    if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + '.additionalItems';
      $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
      } else {
        out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
      }
      if ($breakOnError) {
        out += ' if (!' + ($nextValid) + ') break; ';
      }
      out += ' } }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  } else if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    if ($breakOnError) {
      out += ' if (!' + ($nextValid) + ') break; ';
    }
    out += ' }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),
/* 711 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  out += 'var division' + ($lvl) + ';if (';
  if ($isData) {
    out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
  }
  out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
  if (it.opts.multipleOfPrecision) {
    out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
  } else {
    out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
  }
  out += ' ) ';
  if ($isData) {
    out += '  )  ';
  }
  out += ' ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be multiple of ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 712 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_not(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
    out += ' ' + (it.validate($it)) + ' ';
    $it.createErrors = true;
    if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (' + ($nextValid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    out += '  var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if ($breakOnError) {
      out += ' if (false) { ';
    }
  }
  return out;
}


/***/ }),
/* 713 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_oneOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $prevValid = 'prevValid' + $lvl,
    $passingSchemas = 'passingSchemas' + $lvl;
  out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
  var $wasComposite = it.compositeRule;
  it.compositeRule = $it.compositeRule = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if (it.util.schemaHasRules($sch, it.RULES.all)) {
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
      } else {
        out += ' var ' + ($nextValid) + ' = true; ';
      }
      if ($i) {
        out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
        $closingBraces += '}';
      }
      out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
    }
  }
  it.compositeRule = $it.compositeRule = $wasComposite;
  out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match exactly one schema in oneOf\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; return false; ';
    }
  }
  out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}


/***/ }),
/* 714 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_pattern(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
  }
  out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match pattern "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}


/***/ }),
/* 715 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_properties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $key = 'key' + $lvl,
    $idx = 'idx' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $dataProperties = 'dataProperties' + $lvl;
  var $schemaKeys = Object.keys($schema || {}),
    $pProperties = it.schema.patternProperties || {},
    $pPropertyKeys = Object.keys($pProperties),
    $aProperties = it.schema.additionalProperties,
    $someProperties = $schemaKeys.length || $pPropertyKeys.length,
    $noAdditional = $aProperties === false,
    $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
    $removeAdditional = it.opts.removeAdditional,
    $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
    $ownProperties = it.opts.ownProperties,
    $currentBaseId = it.baseId;
  var $required = it.schema.required;
  if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
  out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
  if ($ownProperties) {
    out += ' var ' + ($dataProperties) + ' = undefined;';
  }
  if ($checkAdditional) {
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    if ($someProperties) {
      out += ' var isAdditional' + ($lvl) + ' = !(false ';
      if ($schemaKeys.length) {
        if ($schemaKeys.length > 8) {
          out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
        } else {
          var arr1 = $schemaKeys;
          if (arr1) {
            var $propertyKey, i1 = -1,
              l1 = arr1.length - 1;
            while (i1 < l1) {
              $propertyKey = arr1[i1 += 1];
              out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr2 = $pPropertyKeys;
        if (arr2) {
          var $pProperty, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $pProperty = arr2[$i += 1];
            out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      out += ' ); if (isAdditional' + ($lvl) + ') { ';
    }
    if ($removeAdditional == 'all') {
      out += ' delete ' + ($data) + '[' + ($key) + ']; ';
    } else {
      var $currentErrorPath = it.errorPath;
      var $additionalProperty = '\' + ' + $key + ' + \'';
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
      }
      if ($noAdditional) {
        if ($removeAdditional) {
          out += ' delete ' + ($data) + '[' + ($key) + ']; ';
        } else {
          out += ' ' + ($nextValid) + ' = false; ';
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + '/additionalProperties';
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = ''; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is an invalid additional property';
              } else {
                out += 'should NOT have additional properties';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            /* istanbul ignore if */
            if (it.async) {
              out += ' throw new ValidationError([' + (__err) + ']); ';
            } else {
              out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
          } else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
          }
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            out += ' break; ';
          }
        }
      } else if ($additionalIsSchema) {
        if ($removeAdditional == 'failing') {
          out += ' var ' + ($errs) + ' = errors;  ';
          var $wasComposite = it.compositeRule;
          it.compositeRule = $it.compositeRule = true;
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
          it.compositeRule = $it.compositeRule = $wasComposite;
        } else {
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
        }
      }
      it.errorPath = $currentErrorPath;
    }
    if ($someProperties) {
      out += ' } ';
    }
    out += ' }  ';
    if ($breakOnError) {
      out += ' if (' + ($nextValid) + ') { ';
      $closingBraces += '}';
    }
  }
  var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  if ($schemaKeys.length) {
    var arr3 = $schemaKeys;
    if (arr3) {
      var $propertyKey, i3 = -1,
        l3 = arr3.length - 1;
      while (i3 < l3) {
        $propertyKey = arr3[i3 += 1];
        var $sch = $schema[$propertyKey];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          var $prop = it.util.getProperty($propertyKey),
            $passData = $data + $prop,
            $hasDefault = $useDefaults && $sch.default !== undefined;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + $prop;
          $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
          $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
          $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            $code = it.util.varReplace($code, $nextData, $passData);
            var $useData = $passData;
          } else {
            var $useData = $nextData;
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
          }
          if ($hasDefault) {
            out += ' ' + ($code) + ' ';
          } else {
            if ($requiredHash && $requiredHash[$propertyKey]) {
              out += ' if ( ' + ($useData) + ' === undefined ';
              if ($ownProperties) {
                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
              }
              out += ') { ' + ($nextValid) + ' = false; ';
              var $currentErrorPath = it.errorPath,
                $currErrSchemaPath = $errSchemaPath,
                $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + '/required';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'';
                  if (it.opts._errorDataPathProperty) {
                    out += 'is a required property';
                  } else {
                    out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              $errSchemaPath = $currErrSchemaPath;
              it.errorPath = $currentErrorPath;
              out += ' } else { ';
            } else {
              if ($breakOnError) {
                out += ' if ( ' + ($useData) + ' === undefined ';
                if ($ownProperties) {
                  out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ') { ' + ($nextValid) + ' = true; } else { ';
              } else {
                out += ' if (' + ($useData) + ' !== undefined ';
                if ($ownProperties) {
                  out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ' ) { ';
              }
            }
            out += ' ' + ($code) + ' } ';
          }
        }
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($pPropertyKeys.length) {
    var arr4 = $pPropertyKeys;
    if (arr4) {
      var $pProperty, i4 = -1,
        l4 = arr4.length - 1;
      while (i4 < l4) {
        $pProperty = arr4[i4 += 1];
        var $sch = $pProperties[$pProperty];
        if (it.util.schemaHasRules($sch, it.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
          $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
          if ($ownProperties) {
            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
          } else {
            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
          }
          out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
          out += ' } ';
          if ($breakOnError) {
            out += ' else ' + ($nextValid) + ' = true; ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),
/* 716 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  out += 'var ' + ($errs) + ' = errors;';
  if (it.util.schemaHasRules($schema, it.RULES.all)) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    var $key = 'key' + $lvl,
      $idx = 'idx' + $lvl,
      $i = 'i' + $lvl,
      $invalidName = '\' + ' + $key + ' + \'',
      $dataNxt = $it.dataLevel = it.dataLevel + 1,
      $nextData = 'data' + $dataNxt,
      $dataProperties = 'dataProperties' + $lvl,
      $ownProperties = it.opts.ownProperties,
      $currentBaseId = it.baseId;
    if ($ownProperties) {
      out += ' var ' + ($dataProperties) + ' = undefined; ';
    }
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    out += ' var startErrs' + ($lvl) + ' = errors; ';
    var $passData = $key;
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; }   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    if ($breakOnError) {
      out += ' break; ';
    }
    out += ' } }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  out = it.util.cleanUpCode(out);
  return out;
}


/***/ }),
/* 717 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_required(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $vSchema = 'schema' + $lvl;
  if (!$isData) {
    if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
      var $required = [];
      var arr1 = $schema;
      if (arr1) {
        var $property, i1 = -1,
          l1 = arr1.length - 1;
        while (i1 < l1) {
          $property = arr1[i1 += 1];
          var $propertySch = it.schema.properties[$property];
          if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
            $required[$required.length] = $property;
          }
        }
      }
    } else {
      var $required = $schema;
    }
  }
  if ($isData || $required.length) {
    var $currentErrorPath = it.errorPath,
      $loopRequired = $isData || $required.length >= it.opts.loopRequired,
      $ownProperties = it.opts.ownProperties;
    if ($breakOnError) {
      out += ' var missing' + ($lvl) + '; ';
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        out += ' var ' + ($valid) + ' = true; ';
        if ($isData) {
          out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
        if ($ownProperties) {
          out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += '; if (!' + ($valid) + ') break; } ';
        if ($isData) {
          out += '  }  ';
        }
        out += '  if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      } else {
        out += ' if ( ';
        var arr2 = $required;
        if (arr2) {
          var $propertyKey, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $propertyKey = arr2[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ') {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      }
    } else {
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        if ($isData) {
          out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is a required property';
              } else {
                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
        if ($ownProperties) {
          out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += ') {  var err =   '; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
        if ($isData) {
          out += '  }  ';
        }
      } else {
        var arr3 = $required;
        if (arr3) {
          var $propertyKey, i3 = -1,
            l3 = arr3.length - 1;
          while (i3 < l3) {
            $propertyKey = arr3[i3 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'';
                if (it.opts._errorDataPathProperty) {
                  out += 'is a required property';
                } else {
                  out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                }
                out += '\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
    }
    it.errorPath = $currentErrorPath;
  } else if ($breakOnError) {
    out += ' if (true) {';
  }
  return out;
}


/***/ }),
/* 718 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (($schema || $isData) && it.opts.uniqueItems !== false) {
    if ($isData) {
      out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
    }
    out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
    var $itemType = it.schema.items && it.schema.items.type,
      $typeIsArray = Array.isArray($itemType);
    if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
      out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
    } else {
      out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
      var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
      out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
      if ($typeIsArray) {
        out += ' if (typeof item == \'string\') item = \'"\' + item; ';
      }
      out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
    }
    out += ' } ';
    if ($isData) {
      out += '  }  ';
    }
    out += ' if (!' + ($valid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema:  ';
        if ($isData) {
          out += 'validate.schema' + ($schemaPath);
        } else {
          out += '' + ($schema);
        }
        out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}


/***/ }),
/* 719 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var KEYWORDS = [
  'multipleOf',
  'maximum',
  'exclusiveMaximum',
  'minimum',
  'exclusiveMinimum',
  'maxLength',
  'minLength',
  'pattern',
  'additionalItems',
  'maxItems',
  'minItems',
  'uniqueItems',
  'maxProperties',
  'minProperties',
  'required',
  'additionalProperties',
  'enum',
  'format',
  'const'
];

module.exports = function (metaSchema, keywordsJsonPointers) {
  for (var i=0; i<keywordsJsonPointers.length; i++) {
    metaSchema = JSON.parse(JSON.stringify(metaSchema));
    var segments = keywordsJsonPointers[i].split('/');
    var keywords = metaSchema;
    var j;
    for (j=1; j<segments.length; j++)
      keywords = keywords[segments[j]];

    for (j=0; j<KEYWORDS.length; j++) {
      var key = KEYWORDS[j];
      var schema = keywords[key];
      if (schema) {
        keywords[key] = {
          anyOf: [
            schema,
            { $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
          ]
        };
      }
    }
  }

  return metaSchema;
};


/***/ }),
/* 720 */
/***/ (function(module, exports, __nested_webpack_require_3936631__) {

"use strict";


var MissingRefError = __nested_webpack_require_3936631__(270).MissingRef;

module.exports = compileAsync;


/**
 * Creates validating function for passed schema with asynchronous loading of missing schemas.
 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
 * @this  Ajv
 * @param {Object}   schema schema object
 * @param {Boolean}  meta optional true to compile meta-schema; this parameter can be skipped
 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
 * @return {Promise} promise that resolves with a validating function.
 */
function compileAsync(schema, meta, callback) {
  /* eslint no-shadow: 0 */
  /* global Promise */
  /* jshint validthis: true */
  var self = this;
  if (typeof this._opts.loadSchema != 'function')
    throw new Error('options.loadSchema should be a function');

  if (typeof meta == 'function') {
    callback = meta;
    meta = undefined;
  }

  var p = loadMetaSchemaOf(schema).then(function () {
    var schemaObj = self._addSchema(schema, undefined, meta);
    return schemaObj.validate || _compileAsync(schemaObj);
  });

  if (callback) {
    p.then(
      function(v) { callback(null, v); },
      callback
    );
  }

  return p;


  function loadMetaSchemaOf(sch) {
    var $schema = sch.$schema;
    return $schema && !self.getSchema($schema)
            ? compileAsync.call(self, { $ref: $schema }, true)
            : Promise.resolve();
  }


  function _compileAsync(schemaObj) {
    try { return self._compile(schemaObj); }
    catch(e) {
      if (e instanceof MissingRefError) return loadMissingSchema(e);
      throw e;
    }


    function loadMissingSchema(e) {
      var ref = e.missingSchema;
      if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');

      var schemaPromise = self._loadingSchemas[ref];
      if (!schemaPromise) {
        schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
        schemaPromise.then(removePromise, removePromise);
      }

      return schemaPromise.then(function (sch) {
        if (!added(ref)) {
          return loadMetaSchemaOf(sch).then(function () {
            if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
          });
        }
      }).then(function() {
        return _compileAsync(schemaObj);
      });

      function removePromise() {
        delete self._loadingSchemas[ref];
      }

      function added(ref) {
        return self._refs[ref] || self._schemas[ref];
      }
    }
  }
}


/***/ }),
/* 721 */
/***/ (function(module, exports, __nested_webpack_require_3939353__) {

"use strict";


var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
var customRuleCode = __nested_webpack_require_3939353__(722);
var metaSchema = __nested_webpack_require_3939353__(405);

module.exports = {
  add: addKeyword,
  get: getKeyword,
  remove: removeKeyword,
  validate: validateKeyword
};

var definitionSchema = {
  definitions: {
    simpleTypes: metaSchema.definitions.simpleTypes
  },
  type: 'object',
  dependencies: {
    schema: ['validate'],
    $data: ['validate'],
    statements: ['inline'],
    valid: {not: {required: ['macro']}}
  },
  properties: {
    type: metaSchema.properties.type,
    schema: {type: 'boolean'},
    statements: {type: 'boolean'},
    dependencies: {
      type: 'array',
      items: {type: 'string'}
    },
    metaSchema: {type: 'object'},
    modifying: {type: 'boolean'},
    valid: {type: 'boolean'},
    $data: {type: 'boolean'},
    async: {type: 'boolean'},
    errors: {
      anyOf: [
        {type: 'boolean'},
        {const: 'full'}
      ]
    }
  }
};

/**
 * Define custom keyword
 * @this  Ajv
 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
 * @return {Ajv} this for method chaining
 */
function addKeyword(keyword, definition) {
  /* jshint validthis: true */
  /* eslint no-shadow: 0 */
  var RULES = this.RULES;
  if (RULES.keywords[keyword])
    throw new Error('Keyword ' + keyword + ' is already defined');

  if (!IDENTIFIER.test(keyword))
    throw new Error('Keyword ' + keyword + ' is not a valid identifier');

  if (definition) {
    this.validateKeyword(definition, true);

    var dataType = definition.type;
    if (Array.isArray(dataType)) {
      for (var i=0; i<dataType.length; i++)
        _addRule(keyword, dataType[i], definition);
    } else {
      _addRule(keyword, dataType, definition);
    }

    var metaSchema = definition.metaSchema;
    if (metaSchema) {
      if (definition.$data && this._opts.$data) {
        metaSchema = {
          anyOf: [
            metaSchema,
            { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
          ]
        };
      }
      definition.validateSchema = this.compile(metaSchema, true);
    }
  }

  RULES.keywords[keyword] = RULES.all[keyword] = true;


  function _addRule(keyword, dataType, definition) {
    var ruleGroup;
    for (var i=0; i<RULES.length; i++) {
      var rg = RULES[i];
      if (rg.type == dataType) {
        ruleGroup = rg;
        break;
      }
    }

    if (!ruleGroup) {
      ruleGroup = { type: dataType, rules: [] };
      RULES.push(ruleGroup);
    }

    var rule = {
      keyword: keyword,
      definition: definition,
      custom: true,
      code: customRuleCode,
      implements: definition.implements
    };
    ruleGroup.rules.push(rule);
    RULES.custom[keyword] = rule;
  }

  return this;
}


/**
 * Get keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
 */
function getKeyword(keyword) {
  /* jshint validthis: true */
  var rule = this.RULES.custom[keyword];
  return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}


/**
 * Remove keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Ajv} this for method chaining
 */
function removeKeyword(keyword) {
  /* jshint validthis: true */
  var RULES = this.RULES;
  delete RULES.keywords[keyword];
  delete RULES.all[keyword];
  delete RULES.custom[keyword];
  for (var i=0; i<RULES.length; i++) {
    var rules = RULES[i].rules;
    for (var j=0; j<rules.length; j++) {
      if (rules[j].keyword == keyword) {
        rules.splice(j, 1);
        break;
      }
    }
  }
  return this;
}


/**
 * Validate keyword definition
 * @this  Ajv
 * @param {Object} definition keyword definition object.
 * @param {Boolean} throwError true to throw exception if definition is invalid
 * @return {boolean} validation result
 */
function validateKeyword(definition, throwError) {
  validateKeyword.errors = null;
  var v = this._validateKeyword = this._validateKeyword
                                  || this.compile(definitionSchema, true);

  if (v(definition)) return true;
  validateKeyword.errors = v.errors;
  if (throwError)
    throw new Error('custom keyword definition is invalid: '  + this.errorsText(v.errors));
  else
    return false;
}


/***/ }),
/* 722 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function generate_custom(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $rule = this,
    $definition = 'definition' + $lvl,
    $rDef = $rule.definition,
    $closingBraces = '';
  var $compile, $inline, $macro, $ruleValidate, $validateCode;
  if ($isData && $rDef.$data) {
    $validateCode = 'keywordValidate' + $lvl;
    var $validateSchema = $rDef.validateSchema;
    out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
  } else {
    $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
    if (!$ruleValidate) return;
    $schemaValue = 'validate.schema' + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }
  var $ruleErrs = $validateCode + '.errors',
    $i = 'i' + $lvl,
    $ruleErr = 'ruleErr' + $lvl,
    $asyncKeyword = $rDef.async;
  if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
  if (!($inline || $macro)) {
    out += '' + ($ruleErrs) + ' = null;';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($isData && $rDef.$data) {
    $closingBraces += '}';
    out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
    if ($validateSchema) {
      $closingBraces += '}';
      out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
    }
  }
  if ($inline) {
    if ($rDef.statements) {
      out += ' ' + ($ruleValidate.validate) + ' ';
    } else {
      out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
    }
  } else if ($macro) {
    var $it = it.util.copy(it);
    var $closingBraces = '';
    $it.level++;
    var $nextValid = 'valid' + $it.level;
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = '';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($code);
  } else {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    out += '  ' + ($validateCode) + '.call( ';
    if (it.opts.passContext) {
      out += 'this';
    } else {
      out += 'self';
    }
    if ($compile || $rDef.schema === false) {
      out += ' , ' + ($data) + ' ';
    } else {
      out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
    }
    out += ' , (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
    var def_callRuleValidate = out;
    out = $$outStack.pop();
    if ($rDef.errors === false) {
      out += ' ' + ($valid) + ' = ';
      if ($asyncKeyword) {
        out += 'await ';
      }
      out += '' + (def_callRuleValidate) + '; ';
    } else {
      if ($asyncKeyword) {
        $ruleErrs = 'customErrors' + $lvl;
        out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
      } else {
        out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
      }
    }
  }
  if ($rDef.modifying) {
    out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
  }
  out += '' + ($closingBraces);
  if ($rDef.valid) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  } else {
    out += ' if ( ';
    if ($rDef.valid === undefined) {
      out += ' !';
      if ($macro) {
        out += '' + ($nextValid);
      } else {
        out += '' + ($valid);
      }
    } else {
      out += ' ' + (!$rDef.valid) + ' ';
    }
    out += ') { ';
    $errorKeyword = $rule.keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    var def_customError = out;
    out = $$outStack.pop();
    if ($inline) {
      if ($rDef.errors) {
        if ($rDef.errors != 'full') {
          out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } ';
        }
      } else {
        if ($rDef.errors === false) {
          out += ' ' + (def_customError) + ' ';
        } else {
          out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } } ';
        }
      }
    } else if ($macro) {
      out += '   var err =   '; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError(vErrors); ';
        } else {
          out += ' validate.errors = vErrors; return false; ';
        }
      }
    } else {
      if ($rDef.errors === false) {
        out += ' ' + (def_customError) + ' ';
      } else {
        out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
        if (it.opts.verbose) {
          out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
        }
        out += ' } } else { ' + (def_customError) + ' } ';
      }
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  }
  return out;
}


/***/ }),
/* 723 */
/***/ (function(module) {

module.exports = {"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false};

/***/ }),
/* 724 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"view-config-editor-header":"ViewConfigEditor-module_view-config-editor-header-2nTtX","view-config-editor":"ViewConfigEditor-module_view-config-editor-2HAFN","view-config-log":"ViewConfigEditor-module_view-config-log-1mYmL","view-config-log-header":"ViewConfigEditor-module_view-config-log-header-3EbEM","view-config-log-msg":"ViewConfigEditor-module_view-config-log-msg-2-CJZ","title":"ViewConfigEditor-module_title-3nLH_","Warning":"ViewConfigEditor-module_Warning-_sgiB","Success":"ViewConfigEditor-module_Success-nclFo","Error":"ViewConfigEditor-module_Error-3enaC"};

/***/ }),
/* 725 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports['default'] = createSymbolIcon;
/**
 * Create a path-based symbol icon
 *
 * @method  createSymbolIcon
 * @author  Fritz Lekschas
 * @date    2016-10-09
 * @param   {Object}  el       D3 selected base element to where the symbols
 *   should be appended to.
 * @param   {String}  id       ID of the icon to be created.
 * @param   {Array}   paths    Array of path strings.
 * @param   {String}  viewBox  View box string.
 */
function createSymbolIcon(el, id, paths, viewBox) {
  var symbol = el.append('symbol').attr('id', id).attr('viewBox', viewBox);

  paths.forEach(function (d) {
    return symbol.append('path').attr('d', d).attr('fill', 'currentColor');
  });
}

/***/ }),
/* 726 */
/***/ (function(module, exports, __nested_webpack_require_3955902__) {

"use strict";


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

var _typeof2 = __nested_webpack_require_3955902__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

var _values = __nested_webpack_require_3955902__(37);

var _values2 = _interopRequireDefault(_values);

var _stringify = __nested_webpack_require_3955902__(35);

var _stringify2 = _interopRequireDefault(_stringify);

var _promise = __nested_webpack_require_3955902__(62);

var _promise2 = _interopRequireDefault(_promise);

var _keys = __nested_webpack_require_3955902__(18);

var _keys2 = _interopRequireDefault(_keys);

var _getIterator2 = __nested_webpack_require_3955902__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _defineProperties = __nested_webpack_require_3955902__(727);

var _defineProperties2 = _interopRequireDefault(_defineProperties);

var _reactDom = __nested_webpack_require_3955902__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _pubSubEs = __nested_webpack_require_3955902__(134);

var _pubSubEs2 = _interopRequireDefault(_pubSubEs);

var _ajv = __nested_webpack_require_3955902__(397);

var _ajv2 = _interopRequireDefault(_ajv);

var _schema = __nested_webpack_require_3955902__(271);

var _schema2 = _interopRequireDefault(_schema);

var _services = __nested_webpack_require_3955902__(24);

var _utils = __nested_webpack_require_3955902__(10);

var _configs = __nested_webpack_require_3955902__(11);

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

var forceUpdate = function forceUpdate(self) {
  self.setState(self.state);
};

var createApi = function () {
  function api(context, pubSub) {
    /** @type {import('./HiGlassComponent').default} */
    var self = context;

    var pubSubs = [];

    var apiPubSub = (0, _pubSubEs2['default'])();

    var _destroy = function () {
      function _destroy() {
        pubSubs.forEach(function (subscription) {
          return pubSub.unsubscribe(subscription);
        });
        pubSubs = [];
      }

      return _destroy;
    }();

    // Internal API
    return {
      destroy: _destroy,
      publish: apiPubSub.publish,
      // Stack: mapping of callback names to arrays of callbacks, useful
      // to determine how many callbacks exist for a particular event.
      stack: apiPubSub.stack,
      // Public API
      'public': (0, _defineProperties2['default'])({

        /**
         * Enable or disable broadcasting the mouse position globally
         * @param {boolean} isBroadcastMousePositionGlobally - If `true` the mouse
         *   position will be broadcasted globally.
         */
        setBroadcastMousePositionGlobally: function () {
          function setBroadcastMousePositionGlobally() {
            var isBroadcastMousePositionGlobally = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

            self.setBroadcastMousePositionGlobally(isBroadcastMousePositionGlobally);
          }

          return setBroadcastMousePositionGlobally;
        }(),


        /**
         * Enable or disable showing the global mouse position
         * @param {boolean} isShowGlobalMousePosition - If `true` the global mouse
         *   position will be shown for any track that has
         *   `options.showMousePosition = true`.
         */
        setShowGlobalMousePosition: function () {
          function setShowGlobalMousePosition() {
            var isShowGlobalMousePosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

            self.setShowGlobalMousePosition(isShowGlobalMousePosition);
          }

          return setShowGlobalMousePosition;
        }(),


        /**
         * Convenience function to enable / disable the global mouse position
         * @description This function is equivalent to calling
         *   `setBroadcastMousePositionGlobally()` and
         *   `setShowGlobalMousePosition()`.
         * @param {boolean} isGlobalMousePosition - If `true` the global mouse
         *   position will be shown and broadcasted.
         */
        setGlobalMousePosition: function () {
          function setGlobalMousePosition() {
            var isGlobalMousePosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

            self.setBroadcastMousePositionGlobally(isGlobalMousePosition);
            self.setShowGlobalMousePosition(isGlobalMousePosition);
          }

          return setGlobalMousePosition;
        }(),


        /**
         * Set an auth header to be included with all tile requests.
         *
         * @param {string} newHeader The contensts of the header to be included.
         * Example: ``hgapi.setAuthHeader('JWT xyz')``
         */
        setAuthHeader: function () {
          function setAuthHeader(newHeader) {
            (0, _services.setTileProxyAuthHeader)(newHeader);

            // we need to re-request all the tiles
            self.reload();
          }

          return setAuthHeader;
        }(),


        /**
         * Get the currently set auth header
         */
        getAuthHeader: function () {
          function getAuthHeader() {
            return (0, _services.setTileProxyAuthHeader)();
          }

          return getAuthHeader;
        }(),


        /**
         * Get a reference to the React HiGlassComponent
         *
         * @returns {HiGlassComponent}
         */
        getComponent: function () {
          function getComponent() {
            return self;
          }

          return getComponent;
        }(),


        /**
         * Reload all or specific tiles for viewId/trackId
         *
         * @param {array} target Should be an array of type
         *                       ({ viewId: string, trackId: string } | string).
         *                       If the array is just strings, it's interpreted
         *                       as a list of views whose tracks to reload.
         */
        reload: function () {
          function reload(target) {
            /** @type {{ viewId: string, trackId: string}[]} */
            var tracks = void 0;
            if (!target) {
              tracks = self.iterateOverTracks();
            } else {
              tracks = target.flatMap(function (d) {
                return typeof d === 'string' ? self.iterateOverTracksInView(d) : d;
              });
            }

            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
              for (var _iterator = (0, _getIterator3['default'])(tracks), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var _ref = _step.value;
                var viewId = _ref.viewId,
                    trackId = _ref.trackId;

                var selectedTrack = self.getTrackObject(viewId, trackId);
                // iterate over childTracks if CombinedTrack
                var _iteratorNormalCompletion2 = true;
                var _didIteratorError2 = false;
                var _iteratorError2 = undefined;

                try {
                  for (var _iterator2 = (0, _getIterator3['default'])(selectedTrack.childTracks || [selectedTrack]), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                    var track = _step2.value;

                    // reload tiles for tracks with tiles.
                    if (track.fetchedTiles) {
                      track.removeTiles((0, _keys2['default'])(track.fetchedTiles));
                      track.fetching.clear();
                      track.refreshTiles();
                    }
                    // second argument forces re-render
                    track.rerender(track.options, true);
                  }
                } catch (err) {
                  _didIteratorError2 = true;
                  _iteratorError2 = err;
                } finally {
                  try {
                    if (!_iteratorNormalCompletion2 && _iterator2['return']) {
                      _iterator2['return']();
                    }
                  } finally {
                    if (_didIteratorError2) {
                      throw _iteratorError2;
                    }
                  }
                }
              }
            } catch (err) {
              _didIteratorError = true;
              _iteratorError = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion && _iterator['return']) {
                  _iterator['return']();
                }
              } finally {
                if (_didIteratorError) {
                  throw _iteratorError;
                }
              }
            }
          }

          return reload;
        }(),


        /**
         * Destroy HiGlass instance
         */
        destroy: function () {
          function destroy() {
            _destroy();
            _reactDom2['default'].unmountComponentAtNode(self.topDiv.parentNode);
          }

          return destroy;
        }(),


        /**
         * Force integer range selections.
         *
         * @example
         *
         * hgv.activateTool('select'); // Activate select tool
         * hgv.setRangeSelectionToFloat(); // Allow float range selections
         */
        setRangeSelectionToInt: function () {
          function setRangeSelectionToInt() {
            self.setState({ rangeSelectionToInt: true });
          }

          return setRangeSelectionToInt;
        }(),


        /**
         * Force float range selections.
         *
         * @example
         *
         * hgv.activateTool('select'); // Activate select tool
         * hgv.setRangeSelectionToFloat(); // Allow float range selections
         */
        setRangeSelectionToFloat: function () {
          function setRangeSelectionToFloat() {
            self.setState({ rangeSelectionToInt: false });
          }

          return setRangeSelectionToFloat;
        }(),


        /**
         *
         *  The following enpoint restricts the size of range selection equally for 1D or
         *  2D tracks to a certain length (specified in absolute coordinates).
         *
         * @param {Number} [minSize = 0]  Minimum range selection.
         *   ``undefined`` unsets the value.
         * @param {Number} [maxSize = Infinity] Maximum range selection.
         *   ``undefined`` unsets the value.
         * @example
         *
         * hgv.activateTool('select'); // Activate select tool
         * hgv.setRangeSelection1dSize(5000, 10000); // Force selections to be between 5 and 10 Kb
         */
        setRangeSelection1dSize: function () {
          function setRangeSelection1dSize() {
            var minSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
            var maxSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;

            self.setState({
              rangeSelection1dSize: [minSize, maxSize]
            });
          }

          return setRangeSelection1dSize;
        }(),


        /**
         * Set a new view config to define the layout and data
         * of this component
         *
         * @param {obj} newViewConfig A JSON object that defines
         *    the state of the HiGlassComponent
         * @param {boolean} resolveImmediately If true, the returned promise resolves immediately
         *    even if not all data has loaded. This should be set to true, if the new viewconf does not request new data. Default: false.
         * @example
         *
         * const p = hgv.setViewConfig(newViewConfig);
         * p.then(() => {
         *   // the initial set of tiles has been loaded
         * });
         *
         * @return {Promise} dataLoaded A promise that resolves when
         *   all of the data for this viewconfig is loaded. If `resolveImmediately` is set to true,
         * the promise resolves without waiting for the data to be loaded.
         */
        setViewConfig: function () {
          function setViewConfig(newViewConfig) {
            var _this = this;

            var resolveImmediately = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

            var viewsByUid = self.processViewConfig(newViewConfig);
            var p = new _promise2['default'](function (resolve) {
              _this.requestsInFlight = 0;

              pubSubs.push(pubSub.subscribe('requestSent', function () {
                _this.requestsInFlight += 1;
              }));

              pubSubs.push(pubSub.subscribe('requestReceived', function () {
                _this.requestsInFlight -= 1;

                if (_this.requestsInFlight === 0) {
                  resolve();
                }
              }));

              self.setState({
                viewConfig: newViewConfig,
                views: viewsByUid
              }, function () {
                if (resolveImmediately) {
                  resolve();
                }
              });
            });

            return p;
          }

          return setViewConfig;
        }(),


        /**
         * Retrieve the visible viewconf.
         *
         * @returns (Object) A JSON object describing the visible views
         */
        getViewConfig: function () {
          function getViewConfig() {
            return self.getViewsAsJson();
          }

          return getViewConfig;
        }(),


        /**
         * Validate a viewconf.
         *
         * @returns (Boolean) A JSON object describing the visible views
         */
        validateViewConfig: function () {
          function validateViewConfig(viewConfig) {
            var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
                _ref2$verbose = _ref2.verbose,
                verbose = _ref2$verbose === undefined ? false : _ref2$verbose;

            var validate = new _ajv2['default']().compile(_schema2['default']);
            var valid = validate(viewConfig);
            if (verbose && validate.errors) {
              console.warn((0, _stringify2['default'])(validate.errors, null, 2));
            }
            return valid;
          }

          return validateViewConfig;
        }(),


        /**
         * Get the minimum and maximum visible values for a given track.
         *
         * @param {string} viewId The id of the view containing the track.
         * @param {string} trackId The id of the track to query.
         * @param {bool} [ignoreOffScreenValues=false] If ``true`` only truly visible values
         *  are considered. Otherwise the values of visible tiles are used. Not that
         *  considering only the truly visible
         *  values results in a roughly 10x slowdown (from 0.1 to 1 millisecond).
         * @param {bool} [ignoreFixedScale=false]  If ``true`` potentially fixed scaled values are
         *  ignored. I.e., if the
         *  absolute range is ``[1, 18]`` but you have fixed the output range to
         *  ``[4, 5]`` you would normally retrieve ``[4, 5]``. Having this option set to
         *  ``true`` retrieves the absolute ``[1, 18]`` range.
         * @example
         * const [minVal, maxVal] = hgv.getMinMaxValue('myView', 'myTrack');
         * @returns {Array} The minimum and maximum value
         */
        getMinMaxValue: function () {
          function getMinMaxValue(viewId, trackId) {
            var ignoreOffScreenValues = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
            var ignoreFixedScale = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

            return self.getMinMaxValue(viewId, trackId, ignoreOffScreenValues, ignoreFixedScale);
          }

          return getMinMaxValue;
        }(),


        /**
         * Generate a sharable link to the current view config. The `url` parameter should contain
         * the API endpoint used to export the view link (e.g. 'http://localhost:8989/api/v1/viewconfs').
         * If it is not provided, the value is taken from the `exportViewUrl` value of the viewconf.
         *
         * @param {string}  url  Custom URL that should point to a higlass server's
         *   view config endpoint, i.e.,
         *   `http://my-higlass-server.com/api/v1/viewconfs/`.
         * @returns {Object}  Promise resolving to the link ID and URL.
         * @example
         * hgv.shareViewConfigAsLink('http://localhost:8989/api/v1/viewconfs')
         * .then((sharedViewConfig) => {
         *   const { id, url } = sharedViewConfig;
         *   console.log(`Shared view config (ID: ${id}) is available at ${url}`)
         * })
         * .catch((err) => { console.error('Something did not work. Sorry', err); })
         */
        shareViewConfigAsLink: function () {
          function shareViewConfigAsLink(url) {
            return self.handleExportViewsAsLink(url, true);
          }

          return shareViewConfigAsLink;
        }(),


        /**
         * Show overlays where this track can be positioned. This
         * function will take a track definition and display red,
         * blue or green overlays highlighting where the track can
         * be placed on the view. Blue indicates that a track can
         * be placed in that region, red that it can't and green that
         * the mouse is currently over the given region.
         *
         * @param {obj} track { server, tilesetUid, datatype }
         *
         * @example
         *
         *  let lineTrack = {
         *   "server": "http://higlass.io/api/v1",
         *   "tilesetUid": "WtBJUYawQzS9M2WVIIHnlA",
         *   "datatype": "multivec",
         *   "defaultTracks": ['horizontal-stacked-bar']
         * }
         *
         * window.hgApi.showAvailableTrackPositions(lineTrack);
         */
        showAvailableTrackPositions: function () {
          function showAvailableTrackPositions(track) {
            self.setState({
              draggingHappening: track
            });
          }

          return showAvailableTrackPositions;
        }(),


        /**
         * Hide the overlay showing where a track can be positioned
         */
        hideAvailableTrackPositions: function () {
          function hideAvailableTrackPositions() {
            self.setState({
              draggingHappening: null
            });
          }

          return hideAvailableTrackPositions;
        }(),


        /**
         * Show the track chooser which highlights tracks
         * when the mouse is over them.
         *
         * @param  {Function} callback (toViewUid, toTrackUid) =>: A function
         *                             to be called when a track is chosen.
         * @return {[type]}            [description]
         */
        showTrackChooser: function () {
          function showTrackChooser(callback) {
            self.setState({
              chooseTrackHandler: function () {
                function chooseTrackHandler() {
                  self.setState({
                    chooseTrackHandler: null
                  });

                  callback.apply(undefined, arguments);
                }

                return chooseTrackHandler;
              }()
            });
          }

          return showTrackChooser;
        }(),


        /**
         * Hide the track chooser.
         */
        hideTrackChooser: function () {
          function hideTrackChooser() {
            this.setState({
              chooseTrackHandler: null
            });
          }

          return hideTrackChooser;
        }(),

        /**
         *
         * When comparing different 1D tracks it can be desirable to fix their y or value
         * scale
         *
         * @param {string} [viewId=''] The view identifier. If you only have one view this
         * parameter can be omitted.
         *
         * @param {string} [trackId=null] The track identifier.
         * @param [Number] [minValue=null] Minimum value used for scaling the track.
         * @param [Number] [maxValue=null] Maximum value used for scaling the track.
         *
         * @example
         *
         * hgv.setTrackValueScale(myView, myTrack, 0, 100); // Sets the scaling to [0, 100]
         * hgv.setTrackValueScale(myView, myTrack); // Unsets the fixed scaling, i.e., enables
         * dynamic scaling again.
         */
        setTrackValueScaleLimits: function () {
          function setTrackValueScaleLimits(viewId, trackId, minValue, maxValue) {
            self.setTrackValueScaleLimits(viewId, trackId, minValue, maxValue);
          }

          return setTrackValueScaleLimits;
        }(),


        /**
         * Choose a theme.
         * @deprecated since version 1.6.6. Use `setTheme()` instead.
         */
        setDarkTheme: function () {
          function setDarkTheme(darkTheme) {
            console.warn('`setDarkTheme(true)` is deprecated. Please use `setTheme("dark")`.');
            var theme = darkTheme ? 'dark' : 'light';
            self.setTheme(theme);
          }

          return setDarkTheme;
        }(),


        /**
         * Choose a theme.
         */
        setTheme: function () {
          function setTheme(theme) {
            console.warn('Please note that theming is still in beta!');
            self.setTheme(theme);
          }

          return setTheme;
        }(),


        /**
         * Change the current view port to a certain data location.
         * When ``animateTime`` is greater than 0, animate the transition.
          * If working with genomic data, a chromosome info file will need to be used in
         * order to calculate "data" coordinates from chromosome coordinates. "Data"
         * coordinates are simply the coordinates as if the chromosomes were placed next
         * to each other.
         *
         * @param {string} viewUid The identifier of the view to zoom
         * @param {Number} start1Abs The x start position
         * @param {Number} end1Abs The x end position
         * @param {Number} start2Abs (optional) The y start position. If not specified
         *    start1Abs will be used.
         * @param {Number} end2Abs (optional) The y end position. If not specified
         *    end1Abs will be used
         * @param {Number} animateTime The time to spend zooming to the specified location
         * @example
         *    // Absolute coordinates
         * hgApi.zoomTo('view1', 1000000, 1100000, 2000000, 2100000, 500);
         * // Chromosomal coordinates
         * hglib
         *   // Pass in the URL of your chrom sizes
         *   .ChromosomeInfo('//s3.amazonaws.com/pkerp/data/hg19/chromSizes.tsv')
         *   // Now we can use the chromInfo object to convert
         *   .then((chromInfo) => {
         *     // Go to PTEN
         *     hgApi.zoomTo(
         *       viewConfig.views[0].uid,
         *       chromInfo.chrToAbs(['chr10', 89596071]),
         *       chromInfo.chrToAbs(['chr10', 89758810]),
         *       chromInfo.chrToAbs(['chr10', 89596071]),
         *       chromInfo.chrToAbs(['chr10', 89758810]),
         *       2500  // Animation time
         *     );
         *   });
         *   // Just in case, let us catch errors
         *   .catch(error => console.error('Oh boy...', error))
         * // Using getLocation() for coordinates
         * let firstViewLoc = hgApi.getLocation(oldViewUid);
         * hgApi.zoomTo(
         *  viewUid,
         *  firstViewLoc["xDomain"][0],
         *  firstViewLoc["xDomain"][1],
         *  firstViewLoc["yDomain"][0],
         *  firstViewLoc["yDomain"][1]
         * );
         */
        zoomTo: function () {
          function zoomTo(viewUid, start1Abs, end1Abs, start2Abs, end2Abs) {
            var animateTime = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;

            self.zoomTo(viewUid, start1Abs, end1Abs, start2Abs, end2Abs, animateTime);
          }

          return zoomTo;
        }(),


        /**
         * Change the current view port to a location near the gene of interest.
         * When ``animateTime`` is greater than 0, animate the transition.
         *
         * @param {string} viewUid The identifier of the view to zoom
         * @param {string} geneName The name of gene symbol to search
         * @param {string} padding The padding (base pairs) around a given gene for the navigation
         * @param {Number} animateTime The time to spend zooming to the specified location
         * @example
         * // Zoom to the location near 'MYC'
         * hgApi.zoomToGene('view1', 'MYC', 100, 2000);
         */
        zoomToGene: function () {
          function zoomToGene(viewUid, geneName) {
            var padding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
            var animateTime = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;

            self.zoomToGene(viewUid, geneName, padding, animateTime);
          }

          return zoomToGene;
        }(),


        /**
         * Get the list of genes of top match for a given keyword.
         *
         * @param {string} viewUid The id of the view containing the track.
         * @param {string} keyword The substring of gene name to search.
         * @param {function} callback A function to be called upon gene list search.
         * @example
         * hgv.suggestGene('view1', 'MY', (suggestions) => {
         *    if(suggestions && suggestions.length > 0) {
         *      console.log('Gene suggested', suggestions[0].geneName);
         *      console.log('Chromosome', suggestions[0].chr);
         *      console.log('Start position', suggestions[0].txStart);
         *      console.log('End position', suggestions[0].txEnd);
         *    }
         * });
         */
        suggestGene: function () {
          function suggestGene(viewUid, keyword, callback) {
            return self.suggestGene(viewUid, keyword, callback);
          }

          return suggestGene;
        }(),


        /**
         * Zoom so that the entirety of all the datasets in a view
         * are visible.
         * The passed in ``viewUid`` should refer to a view which is present. If it
         * doesn't, an exception will be thrown. Note that if this function is invoked
         * directly after a HiGlass component is created, the information about the
         * visible tilesets will not have been retrieved from the server and
         * ``zoomToDataExtent`` will not work as expected. To ensure that the
         * visible data has been loaded from the server, use the ``setViewConfig``
         * function and place ``zoomToDataExtent`` in the promise resolution.
         *
         * @param {string} viewUid The view uid of the view to zoom
         * @example
         *
         * const p = hgv.setViewConfig(newViewConfig);
         * p.then(() => {
         *     hgv.zoomToDataExtent('viewUid');
         * });
         */
        zoomToDataExtent: function () {
          function zoomToDataExtent(viewUid) {
            self.handleZoomToData(viewUid);
          }

          return zoomToDataExtent;
        }(),


        /**
         * The endpoint allows you to reset the viewport to the initially defined X and Y
         * domains of your view config.
         *
         * @param {string} viewId The view identifier. If you have only one view you can
         * omit this parameter.
         *
         * @example
         *
         * hgv.resetViewport(); // Resets the first view
         */
        resetViewport: function () {
          function resetViewport(viewId) {
            self.resetViewport(viewId);
          }

          return resetViewport;
        }(),


        /**
         * Some tools needs conflicting mouse events such as mousedown or mousemove. To
         * avoid complicated triggers for certain actions HiGlass supports different mouse
         * tools for different interactions. The default mouse tool enables pan&zoom. The
         * only other mouse tool available right now is ``select``, which lets you brush
         * on to a track to select a range for annotating regions.
         *
         * @param {string} [mouseTool='']  Select a mouse tool to use. Currently there
         * only 'default' and 'select' are available.
         *
         * @example
         *
         * hgv.activateTool('select'); // Select tool is active
         * hgv.activateTool(); // Default pan&zoom tool is active
         */
        activateTool: function () {
          function activateTool(tool) {
            switch (tool) {
              case 'select':
                self.setMouseTool(_configs.MOUSE_TOOL_SELECT);
                break;

              default:
                self.setMouseTool(_configs.MOUSE_TOOL_MOVE);
                break;
            }
          }

          return activateTool;
        }(),


        /**
         * Get a Promise which returns a Blob containing a PNG for the current view.
         * It's possible to get string of the PNG bytes from that:
         *
         * @example
         * hgApi.exportAsPngBlobPromise().then(function(blob) {
         *   var reader = new FileReader();
         *   reader.addEventListener("loadend", function() {
         *     var array = new Uint8Array(reader.result.slice(0,8));
         *     console.log(array);
         *     console.log(new TextDecoder("iso-8859-2").decode(array));
         *   });
         *   reader.readAsArrayBuffer(blob);
         * });
         *
         * @returns {promise}
         */
        exportAsPngBlobPromise: function () {
          function exportAsPngBlobPromise() {
            return self.createPNGBlobPromise();
          }

          return exportAsPngBlobPromise;
        }(),


        /**
         * Get the current view as an SVG. Relies on all the tracks implementing
         * their respective exportAsSVG methods.
         *
         * @returns {string} An SVG string of the current view.
         */
        exportAsSvg: function () {
          function exportAsSvg() {
            return self.createSVGString();
          }

          return exportAsSvg;
        }(),


        /**
         * Export the current view as a Viewconf.
         *
         * @returns {string} A stringified version of the current viewconf
         */
        exportAsViewConfString: function () {
          function exportAsViewConfString() {
            return self.getViewsAsString();
          }

          return exportAsViewConfString;
        }(),


        /**
         * Get the current range selection
         *
         * @return {Array} The current range selection
         */
        getRangeSelection: function () {
          function getRangeSelection() {
            return self.rangeSelection;
          }

          return getRangeSelection;
        }(),


        /**
         * Get the current location for a view.
         *
         * @param {string} [viewId=null] The id of the view to get the location for
         * @returns {obj} A an object containing four arrays representing the domains and ranges of
         *  the x and y scales of the view.
         * @example
         *
         * const {xDomain, yDomain, xRange, yRange} = hgv.getLocation('viewId');
         */
        getLocation: function () {
          function getLocation(viewId) {
            var wurstId = viewId ? self.xScales[viewId] && self.yScales[viewId] && viewId : (0, _values2['default'])(self.tiledPlots)[0] && (0, _values2['default'])(self.tiledPlots)[0].props.uid;

            if (!wurstId) {
              return 'Please provide a valid view UUID sweetheart 😙';
            }

            return {
              xDomain: self.xScales[wurstId].domain(),
              yDomain: self.yScales[wurstId].domain(),
              xRange: self.xScales[wurstId].range(),
              yRange: self.yScales[wurstId].range()
            };
          }

          return getLocation;
        }(),


        /**
         * Return the track's javascript object. This is useful for subscribing to
         * data events (dataChanged)
         *
         * @param {string} viewId The id of the view containing the track
         * @param {string} trackId The id of the track within the view
         * @return {obj} The HiGlass track object for this track
         */
        getTrackObject: function () {
          function getTrackObject(viewId, trackId) {
            var newViewId = viewId;
            var newTrackId = trackId;

            if (!trackId) {
              newViewId = (0, _values2['default'])(self.state.views)[0].uid;
              newTrackId = viewId;
            }

            return (0, _utils.getTrackObjectFromHGC)(self, newViewId, newTrackId);
          }

          return getTrackObject;
        }(),


        /**
         * Set or get an option.
         * @param   {string}  key  The name of the option you want get or set
         * @param   {*}  value  If not `undefined`, `key` will be set to `value`
         * @return  {obj}  When `value` is `undefined` the current value of
         *   `key` will be returned.
         */
        option: function () {
          function option(key, value) {
            if (typeof value === 'undefined') return self.props.options[key];

            switch (key) {
              case 'sizeMode':
                self.props.options[key] = value;
                forceUpdate(self);
                break;

              default:
                console.warn('This option "' + String(key) + '" is either unknown or not settable.');
            }

            return undefined;
          }

          return option;
        }(),


        /**
         * Cancel a subscription.
         *
         * @param {string} event One of the available events
         * @param {function} listener The function to unsubscribe
         * @param {string} viewId The viewId to unsubscribe it from (not strictly necessary)
         * The variables used in the following examples are coming from the examples of ``on()``.
         *
         * @example
         *
         * hgv.off('location', listener, 'viewId1');
         * hgv.off('rangeSelection', rangeListener);
         * hgv.off('viewConfig', viewConfigListener);
         * hgv.off('mouseMoveZoom', mmz);
         * hgv.off('wheel', wheelListener);
         * hgv.off('createSVG');
         * hgv.off('geneSearch', geneSearchListener);
         */
        off: function () {
          function off(event, listenerId, viewId) {
            var callback = (typeof listenerId === 'undefined' ? 'undefined' : (0, _typeof3['default'])(listenerId)) === 'object' ? listenerId.callback : listenerId;

            switch (event) {
              case 'click':
                apiPubSub.unsubscribe('click', callback);
                break;

              case 'cursorLocation':
                apiPubSub.unsubscribe('cursorLocation', callback);
                break;

              case 'location':
                self.offLocationChange(viewId, listenerId);
                break;

              case 'mouseMoveZoom':
                apiPubSub.unsubscribe('mouseMoveZoom', callback);
                break;

              case 'wheel':
                apiPubSub.unsubscribe('wheel', callback);
                break;

              case 'rangeSelection':
                apiPubSub.unsubscribe('rangeSelection', callback);
                break;

              case 'viewConfig':
                self.offViewChange(listenerId);
                break;

              case 'createSVG':
                self.offPostCreateSVG();
                break;

              case 'geneSearch':
                apiPubSub.unsubscribe('geneSearch', callback);
                break;

              default:
                // nothing
                break;
            }
          }

          return off;
        }(),


        /**
         * Subscribe to events
         *
         *
         * HiGlass exposes the following event, which one can subscribe to via this method:
         *
         * - location
         * - rangeSelection
         * - viewConfig
         * - mouseMoveZoom
         *
         * **Event types**
         *
         * ``click``: Returns clicked objects. (Currently only clicks on 1D annotations are captured.)
         *
         * .. code-block:: javascript
         *
         *     {
         *       type: 'annotation',
         *       event: { ... },
         *       payload: [230000000, 561000000]
         *     }
         *
         * ``cursorLocation:`` Returns an object describing the location under the cursor
         *
         * .. code-block:: javascript
         *
         *    {
         *        absX: 100,
         *        absY: 200,
         *        relX: 50,
         *        relY: 150,
         *        relTrackX: 50,
         *        relTrackY: 100,
         *        dataX: 10000,
         *        dataY: 123456,
         *        isFrom2dTrack: false,
         *        isFromVerticalTrack: false,
         *    }
         *
         * ``location:`` Returns an object describing the visible region
         *
         * .. code-block:: javascript
         *
         *    {
         *        xDomain: [1347750580.3773856, 1948723324.787681],
         *        xRange: [0, 346],
         *        yDomain: [1856870481.5391564, 2407472678.0075483],
         *        yRange: [0, 317]
         *    }
         *
         * ``rangeSelection:`` Returns a BED- (1D) or BEDPE (1d) array of the selected data and
         * genomic range (if chrom-sizes are available)
         *
         * .. code-block:: javascript
         *
         *  // Global output
         *  {
         *    dataRange: [...]
         *    genomicRange: [...]
         *  }
         *
         *  // 1D data range
         *  [[1218210862, 1528541001], null]
         *
         *  // 2D data range
         *  [[1218210862, 1528541001], [1218210862, 1528541001]]
         *
         *  // 1D or BED-like array
         *  [["chr1", 249200621, "chrM", 50000], null]
         *
         *  // 2D or BEDPE-like array
         *  [["chr1", 249200621, "chr2", 50000], ["chr3", 197972430, "chr4", 50000]]
         *
         * ``viewConfig:`` Returns the current view config (as a string).
         *  This event is published upon interactions including:
         *  - Saving in the view config editor modal.
         *  - Panning and zooming in views, which update view object ``initialXDomain`` and ``initialYDomain`` values.
         *  - Brushing in ``viewport-projection-`` tracks containing null ``fromViewUid`` fields, which update track object ``projectionXDomain`` and ``projectionYDomain`` values.
         *
         * ``mouseMoveZoom:`` Returns the location and data at the mouse cursor's
         * screen location.
         *
         * .. code-block:: javascript
         *
         *  {
         *    // Float value of the hovering track
         *    data,
         *    // Absolute x screen position of the cursor in px
         *    absX,
         *    // Absolute y screen position of the cursor in px
         *    absY,
         *    // X screen position of the cursor in px relative to the track extent.
         *    relX,
         *    // Y screen position of the cursor in px relative to the track extent.
         *    relY,
         *    // Data x position of the cursor relative to the track's data.
         *    dataX,
         *    // Data y position of the cursor relative to the track's data.
         *    dataY,
         *    // Track orientation, i.e., '1d-horizontal', '1d-vertical', or '2d'
         *    orientation: '1d-horizontal',
         *
         *    // The following properties are only returned when hovering 2D tracks:
         *    // Raw Float32Array
         *    dataLens,
         *    // Dimension of the lens, e.g., 3 (the lens is squared so `3` corresponds
         *    // to a 3x3 matrix represented by an array of length 9)
         *    dim,
         *    // Function for converting the raw data values to rgb values
         *    toRgb,
         *    // Center position of the data or genomic position (as a BED array)
         *    center,
         *    // Range of the x data or genomic position (as a BEDPE array)
         *    xRange,
         *    // Range of the y data or genomic position (as a BEDPE array)
         *    yRange,
         *    // If `true` `center`, `xRange`, and `yRange` are given in genomic positions
         *    isGenomicCoords
         *  }
         *
         * ``createSVG:`` Set a callback to obtain the current exported SVG DOM node,
         *                and potentially return a manipulated SVG DOM node.
         *
         * @param {string} event One of the events described below
         *
         * @param {function} callback A callback to be called when the event occurs
         *
         * @param {string} viewId The view ID to listen to events
         *
         * @example
         *
         * let locationListenerId;
         * hgv.on(
         *   'location',
         *   location => console.log('Here we are:', location),
         *   'viewId1',
         *   listenerId => locationListenerId = listenerId
         * );
         *
         * const rangeListenerId = hgv.on(
         *   'rangeSelection',
         *   range => console.log('Selected', range)
         * );
         *
         * const viewConfigListenerId = hgv.on(
         *   'viewConfig',
         *   range => console.log('Selected', range)
         * );
         *
         * const mmz = event => console.log('Moved', event);
         * hgv.on('mouseMoveZoom', mmz);
         *
         * const wheelListener = event => console.log('Wheel', event);
         * hgv.on('wheel', wheelListener);
         *
         * hgv.on('createSVG', (svg) => {
         *    const circle = document.createElement('circle');
         *    circle.setAttribute('cx', 100);
         *    circle.setAttribute('cy', 100);
         *    circle.setAttribute('r', 50);
         *    circle.setAttribute('fill', 'green');
         *    svg.appendChild(circle);
         *    return svg;
         * });
         *
         * const geneSearchListener = event => {
         *    console.log('Gene searched', event.geneSymbol);
         *    console.log('Range of the gene', event.range);
         *    console.log('Center of the gene', event.centerX);
         * }
         * hgv.on('geneSearch', geneSearchListener);
         */
        on: function () {
          function on(event, callback, viewId, callbackId) {
            switch (event) {
              case 'click':
                return apiPubSub.subscribe('click', callback);

              case 'cursorLocation':
                return apiPubSub.subscribe('cursorLocation', callback);

              case 'location':
                // returns a set of scales (xScale, yScale) on every zoom event
                return self.onLocationChange(viewId, callback, callbackId);

              case 'mouseMoveZoom':
                return apiPubSub.subscribe('mouseMoveZoom', callback);

              case 'wheel':
                return apiPubSub.subscribe('wheel', callback);

              case 'rangeSelection':
                return apiPubSub.subscribe('rangeSelection', callback);

              case 'viewConfig':
                return self.onViewChange(callback);

              case 'createSVG':
                return self.onPostCreateSVG(callback);

              case 'geneSearch':
                return apiPubSub.subscribe('geneSearch', callback);

              default:
                return undefined;
            }
          }

          return on;
        }()
      }, {
        version: {
          /**
           * HiGlass version
           * @return {string} Version number
           */
          get: function () {
            function get() {
              // Note, `VERSION` is exposed by webpack across the entire app. I.e.,
              // it's globally available within the build but not outside. See
              // `plugins` in `webpack.config.js`
              return "1.11.9";
            }

            return get;
          }(),
          configurable: true,
          enumerable: true
        }
      })
    };
  }

  return api;
}();

exports['default'] = createApi;

/***/ }),
/* 727 */
/***/ (function(module, exports, __nested_webpack_require_4000310__) {

module.exports = { "default": __nested_webpack_require_4000310__(728), __esModule: true };

/***/ }),
/* 728 */
/***/ (function(module, exports, __nested_webpack_require_4000464__) {

__nested_webpack_require_4000464__(729);
var $Object = __nested_webpack_require_4000464__(12).Object;
module.exports = function defineProperties(T, D) {
  return $Object.defineProperties(T, D);
};


/***/ }),
/* 729 */
/***/ (function(module, exports, __nested_webpack_require_4000710__) {

var $export = __nested_webpack_require_4000710__(16);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__nested_webpack_require_4000710__(36), 'Object', { defineProperties: __nested_webpack_require_4000710__(162) });


/***/ }),
/* 730 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin
module.exports = {"higlass":"HiGlass-module_higlass-1NHR2","higlass-dark-theme":"HiGlass-module_higlass-dark-theme-2visd","higlass-container-overflow":"HiGlass-module_higlass-container-overflow-zNXnY","higlass-scroll-container-overflow":"HiGlass-module_higlass-scroll-container-overflow-2FS0w","higlass-scroll-container-scroll":"HiGlass-module_higlass-scroll-container-scroll-2lAU4","higlass-canvas":"HiGlass-module_higlass-canvas-_mP9r","higlass-drawing-surface":"HiGlass-module_higlass-drawing-surface-3aQQo","higlass-svg":"HiGlass-module_higlass-svg-JJZbf","tiled-area":"HiGlass-module_tiled-area-22H1L","track-mouseover-menu":"HiGlass-module_track-mouseover-menu-1AoaP"};

/***/ }),
/* 731 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),
/* 732 */
/***/ (function(module, exports, __nested_webpack_require_4001919__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_4001919__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_4001919__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_4001919__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_4001919__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_4001919__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _propTypes = __nested_webpack_require_4001919__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _d3Color = __nested_webpack_require_4001919__(9);

var _react = __nested_webpack_require_4001919__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4001919__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _reactColor = __nested_webpack_require_4001919__(822);

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

var SketchInlinePicker = function (_React$Component) {
  (0, _inherits3['default'])(SketchInlinePicker, _React$Component);

  function SketchInlinePicker(props) {
    (0, _classCallCheck3['default'])(this, SketchInlinePicker);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (SketchInlinePicker.__proto__ || (0, _getPrototypeOf2['default'])(SketchInlinePicker)).call(this, props));

    var startColor = (0, _d3Color.rgb)(props.color);

    _this.state = {
      displayColorPicker: false,
      color: {
        r: startColor.r,
        g: startColor.g,
        b: startColor.b,
        a: startColor.opacity
      }
    };
    return _this;
  }

  (0, _createClass3['default'])(SketchInlinePicker, [{
    key: 'handleClick',
    value: function () {
      function handleClick() {
        this.setState(function (prevState) {
          return {
            displayColorPicker: !prevState.displayColorPicker
          };
        });
      }

      return handleClick;
    }()
  }, {
    key: 'handleClose',
    value: function () {
      function handleClose() {
        this.setState({ displayColorPicker: false });
      }

      return handleClose;
    }()
  }, {
    key: 'handleChange',
    value: function () {
      function handleChange(color) {
        var rgb = color.rgb;
        var colorString = 'rgba(' + String(rgb.r) + ',' + String(rgb.g) + ',' + String(rgb.b) + ',' + String(rgb.a) + ')';

        this.props.onChange(colorString);
        this.setState({ color: color.rgb });
      }

      return handleChange;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        var styles = (0, _reactcss2['default'])({
          'default': {
            color: {
              width: '32px',
              height: '14px',
              borderRadius: '2px',
              background: 'rgba(' + String(this.state.color.r) + ', ' + String(this.state.color.g) + ', ' + String(this.state.color.b) + ', ' + String(this.state.color.a) + ')'
            },
            swatch: {
              padding: '5px',
              background: '#fff',
              cursor: 'pointer',
              borderRadius: '1px'
            },
            popover: {
              position: 'absolute',
              zIndex: '2'
            },
            cover: {
              position: 'fixed',
              top: '0px',
              right: '0px',
              bottom: '0px',
              left: '0px'
            }
          }
        });

        return _react2['default'].createElement(
          'div',
          null,
          _react2['default'].createElement(
            'div',
            { onClick: this.handleClick.bind(this), style: styles.swatch },
            _react2['default'].createElement('div', { style: styles.color })
          ),
          this.state.displayColorPicker ? _react2['default'].createElement(
            'div',
            { style: styles.popover },
            _react2['default'].createElement('div', { onClick: this.handleClose.bind(this), style: styles.cover }),
            _react2['default'].createElement(_reactColor.SketchPicker, {
              color: this.state.color,
              onChange: this.handleChange.bind(this)
            })
          ) : null
        );
      }

      return render;
    }()
  }]);
  return SketchInlinePicker;
}(_react2['default'].Component);

SketchInlinePicker.propTypes = {
  color: _propTypes2['default'].string,
  onChange: _propTypes2['default'].func
};

exports['default'] = SketchInlinePicker;

/***/ }),
/* 733 */
/***/ (function(module, exports, __nested_webpack_require_4006636__) {

"use strict";


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

var _isString2 = __nested_webpack_require_4006636__(734);

var _isString3 = _interopRequireDefault(_isString2);

var _forOwn2 = __nested_webpack_require_4006636__(272);

var _forOwn3 = _interopRequireDefault(_forOwn2);

var _isPlainObject2 = __nested_webpack_require_4006636__(412);

var _isPlainObject3 = _interopRequireDefault(_isPlainObject2);

var _map2 = __nested_webpack_require_4006636__(70);

var _map3 = _interopRequireDefault(_map2);

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

var flattenNames = exports.flattenNames = function flattenNames() {
  var things = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

  var names = [];

  (0, _map3.default)(things, function (thing) {
    if (Array.isArray(thing)) {
      flattenNames(thing).map(function (name) {
        return names.push(name);
      });
    } else if ((0, _isPlainObject3.default)(thing)) {
      (0, _forOwn3.default)(thing, function (value, key) {
        value === true && names.push(key);
        names.push(key + '-' + value);
      });
    } else if ((0, _isString3.default)(thing)) {
      names.push(thing);
    }
  });

  return names;
};

exports.default = flattenNames;

/***/ }),
/* 734 */
/***/ (function(module, exports, __nested_webpack_require_4008002__) {

var baseGetTag = __nested_webpack_require_4008002__(97),
    isArray = __nested_webpack_require_4008002__(31),
    isObjectLike = __nested_webpack_require_4008002__(56);

/** `Object#toString` result references. */
var stringTag = '[object String]';

/**
 * Checks if `value` is classified as a `String` primitive or object.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
 * @example
 *
 * _.isString('abc');
 * // => true
 *
 * _.isString(1);
 * // => false
 */
function isString(value) {
  return typeof value == 'string' ||
    (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}

module.exports = isString;


/***/ }),
/* 735 */
/***/ (function(module, exports, __nested_webpack_require_4008804__) {

var Symbol = __nested_webpack_require_4008804__(118);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;

/**
 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
 *
 * @private
 * @param {*} value The value to query.
 * @returns {string} Returns the raw `toStringTag`.
 */
function getRawTag(value) {
  var isOwn = hasOwnProperty.call(value, symToStringTag),
      tag = value[symToStringTag];

  try {
    value[symToStringTag] = undefined;
    var unmasked = true;
  } catch (e) {}

  var result = nativeObjectToString.call(value);
  if (unmasked) {
    if (isOwn) {
      value[symToStringTag] = tag;
    } else {
      delete value[symToStringTag];
    }
  }
  return result;
}

module.exports = getRawTag;


/***/ }),
/* 736 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var nativeObjectToString = objectProto.toString;

/**
 * Converts `value` to a string using `Object.prototype.toString`.
 *
 * @private
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 */
function objectToString(value) {
  return nativeObjectToString.call(value);
}

module.exports = objectToString;


/***/ }),
/* 737 */
/***/ (function(module, exports) {

/**
 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
 *
 * @private
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseFor(fromRight) {
  return function(object, iteratee, keysFunc) {
    var index = -1,
        iterable = Object(object),
        props = keysFunc(object),
        length = props.length;

    while (length--) {
      var key = props[fromRight ? length : ++index];
      if (iteratee(iterable[key], key, iterable) === false) {
        break;
      }
    }
    return object;
  };
}

module.exports = createBaseFor;


/***/ }),
/* 738 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.times` without support for iteratee shorthands
 * or max array length checks.
 *
 * @private
 * @param {number} n The number of times to invoke `iteratee`.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the array of results.
 */
function baseTimes(n, iteratee) {
  var index = -1,
      result = Array(n);

  while (++index < n) {
    result[index] = iteratee(index);
  }
  return result;
}

module.exports = baseTimes;


/***/ }),
/* 739 */
/***/ (function(module, exports, __nested_webpack_require_4011917__) {

var baseGetTag = __nested_webpack_require_4011917__(97),
    isObjectLike = __nested_webpack_require_4011917__(56);

/** `Object#toString` result references. */
var argsTag = '[object Arguments]';

/**
 * The base implementation of `_.isArguments`.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 */
function baseIsArguments(value) {
  return isObjectLike(value) && baseGetTag(value) == argsTag;
}

module.exports = baseIsArguments;


/***/ }),
/* 740 */
/***/ (function(module, exports) {

/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

module.exports = stubFalse;


/***/ }),
/* 741 */
/***/ (function(module, exports, __nested_webpack_require_4012819__) {

var baseGetTag = __nested_webpack_require_4012819__(97),
    isLength = __nested_webpack_require_4012819__(274),
    isObjectLike = __nested_webpack_require_4012819__(56);

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    weakMapTag = '[object WeakMap]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;

/**
 * The base implementation of `_.isTypedArray` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
 */
function baseIsTypedArray(value) {
  return isObjectLike(value) &&
    isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}

module.exports = baseIsTypedArray;


/***/ }),
/* 742 */
/***/ (function(module, exports, __nested_webpack_require_4015120__) {

var isPrototype = __nested_webpack_require_4015120__(186),
    nativeKeys = __nested_webpack_require_4015120__(743);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeys(object) {
  if (!isPrototype(object)) {
    return nativeKeys(object);
  }
  var result = [];
  for (var key in Object(object)) {
    if (hasOwnProperty.call(object, key) && key != 'constructor') {
      result.push(key);
    }
  }
  return result;
}

module.exports = baseKeys;


/***/ }),
/* 743 */
/***/ (function(module, exports, __nested_webpack_require_4015974__) {

var overArg = __nested_webpack_require_4015974__(410);

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);

module.exports = nativeKeys;


/***/ }),
/* 744 */
/***/ (function(module, exports, __nested_webpack_require_4016260__) {

var baseIsMatch = __nested_webpack_require_4016260__(745),
    getMatchData = __nested_webpack_require_4016260__(784),
    matchesStrictComparable = __nested_webpack_require_4016260__(424);

/**
 * The base implementation of `_.matches` which doesn't clone `source`.
 *
 * @private
 * @param {Object} source The object of property values to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatches(source) {
  var matchData = getMatchData(source);
  if (matchData.length == 1 && matchData[0][2]) {
    return matchesStrictComparable(matchData[0][0], matchData[0][1]);
  }
  return function(object) {
    return object === source || baseIsMatch(object, source, matchData);
  };
}

module.exports = baseMatches;


/***/ }),
/* 745 */
/***/ (function(module, exports, __nested_webpack_require_4017033__) {

var Stack = __nested_webpack_require_4017033__(187),
    baseIsEqual = __nested_webpack_require_4017033__(415);

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.isMatch` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The object to inspect.
 * @param {Object} source The object of property values to match.
 * @param {Array} matchData The property names, values, and compare flags to match.
 * @param {Function} [customizer] The function to customize comparisons.
 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
 */
function baseIsMatch(object, source, matchData, customizer) {
  var index = matchData.length,
      length = index,
      noCustomizer = !customizer;

  if (object == null) {
    return !length;
  }
  object = Object(object);
  while (index--) {
    var data = matchData[index];
    if ((noCustomizer && data[2])
          ? data[1] !== object[data[0]]
          : !(data[0] in object)
        ) {
      return false;
    }
  }
  while (++index < length) {
    data = matchData[index];
    var key = data[0],
        objValue = object[key],
        srcValue = data[1];

    if (noCustomizer && data[2]) {
      if (objValue === undefined && !(key in object)) {
        return false;
      }
    } else {
      var stack = new Stack;
      if (customizer) {
        var result = customizer(objValue, srcValue, key, object, source, stack);
      }
      if (!(result === undefined
            ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
            : result
          )) {
        return false;
      }
    }
  }
  return true;
}

module.exports = baseIsMatch;


/***/ }),
/* 746 */
/***/ (function(module, exports) {

/**
 * Removes all key-value entries from the list cache.
 *
 * @private
 * @name clear
 * @memberOf ListCache
 */
function listCacheClear() {
  this.__data__ = [];
  this.size = 0;
}

module.exports = listCacheClear;


/***/ }),
/* 747 */
/***/ (function(module, exports, __nested_webpack_require_4019157__) {

var assocIndexOf = __nested_webpack_require_4019157__(189);

/** Used for built-in method references. */
var arrayProto = Array.prototype;

/** Built-in value references. */
var splice = arrayProto.splice;

/**
 * Removes `key` and its value from the list cache.
 *
 * @private
 * @name delete
 * @memberOf ListCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function listCacheDelete(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    return false;
  }
  var lastIndex = data.length - 1;
  if (index == lastIndex) {
    data.pop();
  } else {
    splice.call(data, index, 1);
  }
  --this.size;
  return true;
}

module.exports = listCacheDelete;


/***/ }),
/* 748 */
/***/ (function(module, exports, __nested_webpack_require_4020009__) {

var assocIndexOf = __nested_webpack_require_4020009__(189);

/**
 * Gets the list cache value for `key`.
 *
 * @private
 * @name get
 * @memberOf ListCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function listCacheGet(key) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  return index < 0 ? undefined : data[index][1];
}

module.exports = listCacheGet;


/***/ }),
/* 749 */
/***/ (function(module, exports, __nested_webpack_require_4020506__) {

var assocIndexOf = __nested_webpack_require_4020506__(189);

/**
 * Checks if a list cache value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf ListCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function listCacheHas(key) {
  return assocIndexOf(this.__data__, key) > -1;
}

module.exports = listCacheHas;


/***/ }),
/* 750 */
/***/ (function(module, exports, __nested_webpack_require_4020986__) {

var assocIndexOf = __nested_webpack_require_4020986__(189);

/**
 * Sets the list cache `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf ListCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the list cache instance.
 */
function listCacheSet(key, value) {
  var data = this.__data__,
      index = assocIndexOf(data, key);

  if (index < 0) {
    ++this.size;
    data.push([key, value]);
  } else {
    data[index][1] = value;
  }
  return this;
}

module.exports = listCacheSet;


/***/ }),
/* 751 */
/***/ (function(module, exports, __nested_webpack_require_4021616__) {

var ListCache = __nested_webpack_require_4021616__(188);

/**
 * Removes all key-value entries from the stack.
 *
 * @private
 * @name clear
 * @memberOf Stack
 */
function stackClear() {
  this.__data__ = new ListCache;
  this.size = 0;
}

module.exports = stackClear;


/***/ }),
/* 752 */
/***/ (function(module, exports) {

/**
 * Removes `key` and its value from the stack.
 *
 * @private
 * @name delete
 * @memberOf Stack
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function stackDelete(key) {
  var data = this.__data__,
      result = data['delete'](key);

  this.size = data.size;
  return result;
}

module.exports = stackDelete;


/***/ }),
/* 753 */
/***/ (function(module, exports) {

/**
 * Gets the stack value for `key`.
 *
 * @private
 * @name get
 * @memberOf Stack
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function stackGet(key) {
  return this.__data__.get(key);
}

module.exports = stackGet;


/***/ }),
/* 754 */
/***/ (function(module, exports) {

/**
 * Checks if a stack value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Stack
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function stackHas(key) {
  return this.__data__.has(key);
}

module.exports = stackHas;


/***/ }),
/* 755 */
/***/ (function(module, exports, __nested_webpack_require_4023123__) {

var ListCache = __nested_webpack_require_4023123__(188),
    Map = __nested_webpack_require_4023123__(279),
    MapCache = __nested_webpack_require_4023123__(280);

/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;

/**
 * Sets the stack `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Stack
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the stack cache instance.
 */
function stackSet(key, value) {
  var data = this.__data__;
  if (data instanceof ListCache) {
    var pairs = data.__data__;
    if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
      pairs.push([key, value]);
      this.size = ++data.size;
      return this;
    }
    data = this.__data__ = new MapCache(pairs);
  }
  data.set(key, value);
  this.size = data.size;
  return this;
}

module.exports = stackSet;


/***/ }),
/* 756 */
/***/ (function(module, exports, __nested_webpack_require_4024065__) {

var isFunction = __nested_webpack_require_4024065__(277),
    isMasked = __nested_webpack_require_4024065__(757),
    isObject = __nested_webpack_require_4024065__(45),
    toSource = __nested_webpack_require_4024065__(414);

/**
 * Used to match `RegExp`
 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
 */
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;

/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;

/** Used for built-in method references. */
var funcProto = Function.prototype,
    objectProto = Object.prototype;

/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
  funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);

/**
 * The base implementation of `_.isNative` without bad shim checks.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a native function,
 *  else `false`.
 */
function baseIsNative(value) {
  if (!isObject(value) || isMasked(value)) {
    return false;
  }
  var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  return pattern.test(toSource(value));
}

module.exports = baseIsNative;


/***/ }),
/* 757 */
/***/ (function(module, exports, __nested_webpack_require_4025568__) {

var coreJsData = __nested_webpack_require_4025568__(758);

/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
  var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  return uid ? ('Symbol(src)_1.' + uid) : '';
}());

/**
 * Checks if `func` has its source masked.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
 */
function isMasked(func) {
  return !!maskSrcKey && (maskSrcKey in func);
}

module.exports = isMasked;


/***/ }),
/* 758 */
/***/ (function(module, exports, __nested_webpack_require_4026211__) {

var root = __nested_webpack_require_4026211__(41);

/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];

module.exports = coreJsData;


/***/ }),
/* 759 */
/***/ (function(module, exports) {

/**
 * Gets the value at `key` of `object`.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {string} key The key of the property to get.
 * @returns {*} Returns the property value.
 */
function getValue(object, key) {
  return object == null ? undefined : object[key];
}

module.exports = getValue;


/***/ }),
/* 760 */
/***/ (function(module, exports, __nested_webpack_require_4026835__) {

var Hash = __nested_webpack_require_4026835__(761),
    ListCache = __nested_webpack_require_4026835__(188),
    Map = __nested_webpack_require_4026835__(279);

/**
 * Removes all key-value entries from the map.
 *
 * @private
 * @name clear
 * @memberOf MapCache
 */
function mapCacheClear() {
  this.size = 0;
  this.__data__ = {
    'hash': new Hash,
    'map': new (Map || ListCache),
    'string': new Hash
  };
}

module.exports = mapCacheClear;


/***/ }),
/* 761 */
/***/ (function(module, exports, __nested_webpack_require_4027321__) {

var hashClear = __nested_webpack_require_4027321__(762),
    hashDelete = __nested_webpack_require_4027321__(763),
    hashGet = __nested_webpack_require_4027321__(764),
    hashHas = __nested_webpack_require_4027321__(765),
    hashSet = __nested_webpack_require_4027321__(766);

/**
 * Creates a hash object.
 *
 * @private
 * @constructor
 * @param {Array} [entries] The key-value pairs to cache.
 */
function Hash(entries) {
  var index = -1,
      length = entries == null ? 0 : entries.length;

  this.clear();
  while (++index < length) {
    var entry = entries[index];
    this.set(entry[0], entry[1]);
  }
}

// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;

module.exports = Hash;


/***/ }),
/* 762 */
/***/ (function(module, exports, __nested_webpack_require_4028157__) {

var nativeCreate = __nested_webpack_require_4028157__(190);

/**
 * Removes all key-value entries from the hash.
 *
 * @private
 * @name clear
 * @memberOf Hash
 */
function hashClear() {
  this.__data__ = nativeCreate ? nativeCreate(null) : {};
  this.size = 0;
}

module.exports = hashClear;


/***/ }),
/* 763 */
/***/ (function(module, exports) {

/**
 * Removes `key` and its value from the hash.
 *
 * @private
 * @name delete
 * @memberOf Hash
 * @param {Object} hash The hash to modify.
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function hashDelete(key) {
  var result = this.has(key) && delete this.__data__[key];
  this.size -= result ? 1 : 0;
  return result;
}

module.exports = hashDelete;


/***/ }),
/* 764 */
/***/ (function(module, exports, __nested_webpack_require_4029018__) {

var nativeCreate = __nested_webpack_require_4029018__(190);

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Gets the hash value for `key`.
 *
 * @private
 * @name get
 * @memberOf Hash
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function hashGet(key) {
  var data = this.__data__;
  if (nativeCreate) {
    var result = data[key];
    return result === HASH_UNDEFINED ? undefined : result;
  }
  return hasOwnProperty.call(data, key) ? data[key] : undefined;
}

module.exports = hashGet;


/***/ }),
/* 765 */
/***/ (function(module, exports, __nested_webpack_require_4029867__) {

var nativeCreate = __nested_webpack_require_4029867__(190);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Checks if a hash value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf Hash
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function hashHas(key) {
  var data = this.__data__;
  return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}

module.exports = hashHas;


/***/ }),
/* 766 */
/***/ (function(module, exports, __nested_webpack_require_4030570__) {

var nativeCreate = __nested_webpack_require_4030570__(190);

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Sets the hash `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf Hash
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the hash instance.
 */
function hashSet(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  return this;
}

module.exports = hashSet;


/***/ }),
/* 767 */
/***/ (function(module, exports, __nested_webpack_require_4031245__) {

var getMapData = __nested_webpack_require_4031245__(191);

/**
 * Removes `key` and its value from the map.
 *
 * @private
 * @name delete
 * @memberOf MapCache
 * @param {string} key The key of the value to remove.
 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
 */
function mapCacheDelete(key) {
  var result = getMapData(this, key)['delete'](key);
  this.size -= result ? 1 : 0;
  return result;
}

module.exports = mapCacheDelete;


/***/ }),
/* 768 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is suitable for use as unique object key.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
 */
function isKeyable(value) {
  var type = typeof value;
  return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
    ? (value !== '__proto__')
    : (value === null);
}

module.exports = isKeyable;


/***/ }),
/* 769 */
/***/ (function(module, exports, __nested_webpack_require_4032262__) {

var getMapData = __nested_webpack_require_4032262__(191);

/**
 * Gets the map value for `key`.
 *
 * @private
 * @name get
 * @memberOf MapCache
 * @param {string} key The key of the value to get.
 * @returns {*} Returns the entry value.
 */
function mapCacheGet(key) {
  return getMapData(this, key).get(key);
}

module.exports = mapCacheGet;


/***/ }),
/* 770 */
/***/ (function(module, exports, __nested_webpack_require_4032671__) {

var getMapData = __nested_webpack_require_4032671__(191);

/**
 * Checks if a map value for `key` exists.
 *
 * @private
 * @name has
 * @memberOf MapCache
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function mapCacheHas(key) {
  return getMapData(this, key).has(key);
}

module.exports = mapCacheHas;


/***/ }),
/* 771 */
/***/ (function(module, exports, __nested_webpack_require_4033132__) {

var getMapData = __nested_webpack_require_4033132__(191);

/**
 * Sets the map `key` to `value`.
 *
 * @private
 * @name set
 * @memberOf MapCache
 * @param {string} key The key of the value to set.
 * @param {*} value The value to set.
 * @returns {Object} Returns the map cache instance.
 */
function mapCacheSet(key, value) {
  var data = getMapData(this, key),
      size = data.size;

  data.set(key, value);
  this.size += data.size == size ? 0 : 1;
  return this;
}

module.exports = mapCacheSet;


/***/ }),
/* 772 */
/***/ (function(module, exports, __nested_webpack_require_4033700__) {

var Stack = __nested_webpack_require_4033700__(187),
    equalArrays = __nested_webpack_require_4033700__(416),
    equalByTag = __nested_webpack_require_4033700__(777),
    equalObjects = __nested_webpack_require_4033700__(780),
    getTag = __nested_webpack_require_4033700__(192),
    isArray = __nested_webpack_require_4033700__(31),
    isBuffer = __nested_webpack_require_4033700__(185),
    isTypedArray = __nested_webpack_require_4033700__(273);

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    objectTag = '[object Object]';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqual` for arrays and objects which performs
 * deep comparisons and tracks traversed objects enabling objects with circular
 * references to be compared.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
  var objIsArr = isArray(object),
      othIsArr = isArray(other),
      objTag = objIsArr ? arrayTag : getTag(object),
      othTag = othIsArr ? arrayTag : getTag(other);

  objTag = objTag == argsTag ? objectTag : objTag;
  othTag = othTag == argsTag ? objectTag : othTag;

  var objIsObj = objTag == objectTag,
      othIsObj = othTag == objectTag,
      isSameTag = objTag == othTag;

  if (isSameTag && isBuffer(object)) {
    if (!isBuffer(other)) {
      return false;
    }
    objIsArr = true;
    objIsObj = false;
  }
  if (isSameTag && !objIsObj) {
    stack || (stack = new Stack);
    return (objIsArr || isTypedArray(object))
      ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
      : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
  }
  if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
    var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
        othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');

    if (objIsWrapped || othIsWrapped) {
      var objUnwrapped = objIsWrapped ? object.value() : object,
          othUnwrapped = othIsWrapped ? other.value() : other;

      stack || (stack = new Stack);
      return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
    }
  }
  if (!isSameTag) {
    return false;
  }
  stack || (stack = new Stack);
  return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}

module.exports = baseIsEqualDeep;


/***/ }),
/* 773 */
/***/ (function(module, exports, __nested_webpack_require_4036800__) {

var MapCache = __nested_webpack_require_4036800__(280),
    setCacheAdd = __nested_webpack_require_4036800__(774),
    setCacheHas = __nested_webpack_require_4036800__(775);

/**
 *
 * Creates an array cache object to store unique values.
 *
 * @private
 * @constructor
 * @param {Array} [values] The values to cache.
 */
function SetCache(values) {
  var index = -1,
      length = values == null ? 0 : values.length;

  this.__data__ = new MapCache;
  while (++index < length) {
    this.add(values[index]);
  }
}

// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;

module.exports = SetCache;


/***/ }),
/* 774 */
/***/ (function(module, exports) {

/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';

/**
 * Adds `value` to the array cache.
 *
 * @private
 * @name add
 * @memberOf SetCache
 * @alias push
 * @param {*} value The value to cache.
 * @returns {Object} Returns the cache instance.
 */
function setCacheAdd(value) {
  this.__data__.set(value, HASH_UNDEFINED);
  return this;
}

module.exports = setCacheAdd;


/***/ }),
/* 775 */
/***/ (function(module, exports) {

/**
 * Checks if `value` is in the array cache.
 *
 * @private
 * @name has
 * @memberOf SetCache
 * @param {*} value The value to search for.
 * @returns {number} Returns `true` if `value` is found, else `false`.
 */
function setCacheHas(value) {
  return this.__data__.has(value);
}

module.exports = setCacheHas;


/***/ }),
/* 776 */
/***/ (function(module, exports) {

/**
 * Checks if a `cache` value for `key` exists.
 *
 * @private
 * @param {Object} cache The cache to query.
 * @param {string} key The key of the entry to check.
 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
 */
function cacheHas(cache, key) {
  return cache.has(key);
}

module.exports = cacheHas;


/***/ }),
/* 777 */
/***/ (function(module, exports, __nested_webpack_require_4038762__) {

var Symbol = __nested_webpack_require_4038762__(118),
    Uint8Array = __nested_webpack_require_4038762__(418),
    eq = __nested_webpack_require_4038762__(120),
    equalArrays = __nested_webpack_require_4038762__(416),
    mapToArray = __nested_webpack_require_4038762__(778),
    setToArray = __nested_webpack_require_4038762__(779);

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]';

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * A specialized version of `baseIsEqualDeep` for comparing objects of
 * the same `toStringTag`.
 *
 * **Note:** This function only supports comparing values with tags of
 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {string} tag The `toStringTag` of the objects to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
  switch (tag) {
    case dataViewTag:
      if ((object.byteLength != other.byteLength) ||
          (object.byteOffset != other.byteOffset)) {
        return false;
      }
      object = object.buffer;
      other = other.buffer;

    case arrayBufferTag:
      if ((object.byteLength != other.byteLength) ||
          !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
        return false;
      }
      return true;

    case boolTag:
    case dateTag:
    case numberTag:
      // Coerce booleans to `1` or `0` and dates to milliseconds.
      // Invalid dates are coerced to `NaN`.
      return eq(+object, +other);

    case errorTag:
      return object.name == other.name && object.message == other.message;

    case regexpTag:
    case stringTag:
      // Coerce regexes to strings and treat strings, primitives and objects,
      // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
      // for more details.
      return object == (other + '');

    case mapTag:
      var convert = mapToArray;

    case setTag:
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
      convert || (convert = setToArray);

      if (object.size != other.size && !isPartial) {
        return false;
      }
      // Assume cyclic values are equal.
      var stacked = stack.get(object);
      if (stacked) {
        return stacked == other;
      }
      bitmask |= COMPARE_UNORDERED_FLAG;

      // Recursively compare objects (susceptible to call stack limits).
      stack.set(object, other);
      var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
      stack['delete'](object);
      return result;

    case symbolTag:
      if (symbolValueOf) {
        return symbolValueOf.call(object) == symbolValueOf.call(other);
      }
  }
  return false;
}

module.exports = equalByTag;


/***/ }),
/* 778 */
/***/ (function(module, exports) {

/**
 * Converts `map` to its key-value pairs.
 *
 * @private
 * @param {Object} map The map to convert.
 * @returns {Array} Returns the key-value pairs.
 */
function mapToArray(map) {
  var index = -1,
      result = Array(map.size);

  map.forEach(function(value, key) {
    result[++index] = [key, value];
  });
  return result;
}

module.exports = mapToArray;


/***/ }),
/* 779 */
/***/ (function(module, exports) {

/**
 * Converts `set` to an array of its values.
 *
 * @private
 * @param {Object} set The set to convert.
 * @returns {Array} Returns the values.
 */
function setToArray(set) {
  var index = -1,
      result = Array(set.size);

  set.forEach(function(value) {
    result[++index] = value;
  });
  return result;
}

module.exports = setToArray;


/***/ }),
/* 780 */
/***/ (function(module, exports, __nested_webpack_require_4043423__) {

var getAllKeys = __nested_webpack_require_4043423__(419);

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * A specialized version of `baseIsEqualDeep` for objects with support for
 * partial deep comparisons.
 *
 * @private
 * @param {Object} object The object to compare.
 * @param {Object} other The other object to compare.
 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
 * @param {Function} customizer The function to customize comparisons.
 * @param {Function} equalFunc The function to determine equivalents of values.
 * @param {Object} stack Tracks traversed `object` and `other` objects.
 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
 */
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
  var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
      objProps = getAllKeys(object),
      objLength = objProps.length,
      othProps = getAllKeys(other),
      othLength = othProps.length;

  if (objLength != othLength && !isPartial) {
    return false;
  }
  var index = objLength;
  while (index--) {
    var key = objProps[index];
    if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
      return false;
    }
  }
  // Assume cyclic values are equal.
  var stacked = stack.get(object);
  if (stacked && stack.get(other)) {
    return stacked == other;
  }
  var result = true;
  stack.set(object, other);
  stack.set(other, object);

  var skipCtor = isPartial;
  while (++index < objLength) {
    key = objProps[index];
    var objValue = object[key],
        othValue = other[key];

    if (customizer) {
      var compared = isPartial
        ? customizer(othValue, objValue, key, other, object, stack)
        : customizer(objValue, othValue, key, object, other, stack);
    }
    // Recursively compare objects (susceptible to call stack limits).
    if (!(compared === undefined
          ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
          : compared
        )) {
      result = false;
      break;
    }
    skipCtor || (skipCtor = key == 'constructor');
  }
  if (result && !skipCtor) {
    var objCtor = object.constructor,
        othCtor = other.constructor;

    // Non `Object` object instances with different constructors are not equal.
    if (objCtor != othCtor &&
        ('constructor' in object && 'constructor' in other) &&
        !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
          typeof othCtor == 'function' && othCtor instanceof othCtor)) {
      result = false;
    }
  }
  stack['delete'](object);
  stack['delete'](other);
  return result;
}

module.exports = equalObjects;


/***/ }),
/* 781 */
/***/ (function(module, exports, __nested_webpack_require_4046405__) {

var getNative = __nested_webpack_require_4046405__(99),
    root = __nested_webpack_require_4046405__(41);

/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');

module.exports = DataView;


/***/ }),
/* 782 */
/***/ (function(module, exports, __nested_webpack_require_4046699__) {

var getNative = __nested_webpack_require_4046699__(99),
    root = __nested_webpack_require_4046699__(41);

/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');

module.exports = Promise;


/***/ }),
/* 783 */
/***/ (function(module, exports, __nested_webpack_require_4046990__) {

var getNative = __nested_webpack_require_4046990__(99),
    root = __nested_webpack_require_4046990__(41);

/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');

module.exports = Set;


/***/ }),
/* 784 */
/***/ (function(module, exports, __nested_webpack_require_4047269__) {

var isStrictComparable = __nested_webpack_require_4047269__(423),
    keys = __nested_webpack_require_4047269__(119);

/**
 * Gets the property names, values, and compare flags of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the match data of `object`.
 */
function getMatchData(object) {
  var result = keys(object),
      length = result.length;

  while (length--) {
    var key = result[length],
        value = object[key];

    result[length] = [key, value, isStrictComparable(value)];
  }
  return result;
}

module.exports = getMatchData;


/***/ }),
/* 785 */
/***/ (function(module, exports, __nested_webpack_require_4047920__) {

var baseIsEqual = __nested_webpack_require_4047920__(415),
    get = __nested_webpack_require_4047920__(786),
    hasIn = __nested_webpack_require_4047920__(425),
    isKey = __nested_webpack_require_4047920__(285),
    isStrictComparable = __nested_webpack_require_4047920__(423),
    matchesStrictComparable = __nested_webpack_require_4047920__(424),
    toKey = __nested_webpack_require_4047920__(145);

/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
    COMPARE_UNORDERED_FLAG = 2;

/**
 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
 *
 * @private
 * @param {string} path The path of the property to get.
 * @param {*} srcValue The value to match.
 * @returns {Function} Returns the new spec function.
 */
function baseMatchesProperty(path, srcValue) {
  if (isKey(path) && isStrictComparable(srcValue)) {
    return matchesStrictComparable(toKey(path), srcValue);
  }
  return function(object) {
    var objValue = get(object, path);
    return (objValue === undefined && objValue === srcValue)
      ? hasIn(object, path)
      : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
  };
}

module.exports = baseMatchesProperty;


/***/ }),
/* 786 */
/***/ (function(module, exports, __nested_webpack_require_4049130__) {

var baseGet = __nested_webpack_require_4049130__(284);

/**
 * Gets the value at `path` of `object`. If the resolved value is
 * `undefined`, the `defaultValue` is returned in its place.
 *
 * @static
 * @memberOf _
 * @since 3.7.0
 * @category Object
 * @param {Object} object The object to query.
 * @param {Array|string} path The path of the property to get.
 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
 *
 * _.get(object, 'a[0].b.c');
 * // => 3
 *
 * _.get(object, ['a', '0', 'b', 'c']);
 * // => 3
 *
 * _.get(object, 'a.b.c', 'default');
 * // => 'default'
 */
function get(object, path, defaultValue) {
  var result = object == null ? undefined : baseGet(object, path);
  return result === undefined ? defaultValue : result;
}

module.exports = get;


/***/ }),
/* 787 */
/***/ (function(module, exports, __nested_webpack_require_4050096__) {

var memoizeCapped = __nested_webpack_require_4050096__(788);

/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;

/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;

/**
 * Converts `string` to a property path array.
 *
 * @private
 * @param {string} string The string to convert.
 * @returns {Array} Returns the property path array.
 */
var stringToPath = memoizeCapped(function(string) {
  var result = [];
  if (string.charCodeAt(0) === 46 /* . */) {
    result.push('');
  }
  string.replace(rePropName, function(match, number, quote, subString) {
    result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
  });
  return result;
});

module.exports = stringToPath;


/***/ }),
/* 788 */
/***/ (function(module, exports, __nested_webpack_require_4051012__) {

var memoize = __nested_webpack_require_4051012__(789);

/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;

/**
 * A specialized version of `_.memoize` which clears the memoized function's
 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
 *
 * @private
 * @param {Function} func The function to have its output memoized.
 * @returns {Function} Returns the new memoized function.
 */
function memoizeCapped(func) {
  var result = memoize(func, function(key) {
    if (cache.size === MAX_MEMOIZE_SIZE) {
      cache.clear();
    }
    return key;
  });

  var cache = result.cache;
  return result;
}

module.exports = memoizeCapped;


/***/ }),
/* 789 */
/***/ (function(module, exports, __nested_webpack_require_4051728__) {

var MapCache = __nested_webpack_require_4051728__(280);

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that memoizes the result of `func`. If `resolver` is
 * provided, it determines the cache key for storing the result based on the
 * arguments provided to the memoized function. By default, the first argument
 * provided to the memoized function is used as the map cache key. The `func`
 * is invoked with the `this` binding of the memoized function.
 *
 * **Note:** The cache is exposed as the `cache` property on the memoized
 * function. Its creation may be customized by replacing the `_.memoize.Cache`
 * constructor with one whose instances implement the
 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to have its output memoized.
 * @param {Function} [resolver] The function to resolve the cache key.
 * @returns {Function} Returns the new memoized function.
 * @example
 *
 * var object = { 'a': 1, 'b': 2 };
 * var other = { 'c': 3, 'd': 4 };
 *
 * var values = _.memoize(_.values);
 * values(object);
 * // => [1, 2]
 *
 * values(other);
 * // => [3, 4]
 *
 * object.a = 2;
 * values(object);
 * // => [1, 2]
 *
 * // Modify the result cache.
 * values.cache.set(object, ['a', 'b']);
 * values(object);
 * // => ['a', 'b']
 *
 * // Replace `_.memoize.Cache`.
 * _.memoize.Cache = WeakMap;
 */
function memoize(func, resolver) {
  if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var memoized = function() {
    var args = arguments,
        key = resolver ? resolver.apply(this, args) : args[0],
        cache = memoized.cache;

    if (cache.has(key)) {
      return cache.get(key);
    }
    var result = func.apply(this, args);
    memoized.cache = cache.set(key, result) || cache;
    return result;
  };
  memoized.cache = new (memoize.Cache || MapCache);
  return memoized;
}

// Expose `MapCache`.
memoize.Cache = MapCache;

module.exports = memoize;


/***/ }),
/* 790 */
/***/ (function(module, exports, __nested_webpack_require_4054033__) {

var baseToString = __nested_webpack_require_4054033__(791);

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString(value) {
  return value == null ? '' : baseToString(value);
}

module.exports = toString;


/***/ }),
/* 791 */
/***/ (function(module, exports, __nested_webpack_require_4054690__) {

var Symbol = __nested_webpack_require_4054690__(118),
    arrayMap = __nested_webpack_require_4054690__(413),
    isArray = __nested_webpack_require_4054690__(31),
    isSymbol = __nested_webpack_require_4054690__(194);

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return arrayMap(value, baseToString) + '';
  }
  if (isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}

module.exports = baseToString;


/***/ }),
/* 792 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.hasIn` without support for deep paths.
 *
 * @private
 * @param {Object} [object] The object to query.
 * @param {Array|string} key The key to check.
 * @returns {boolean} Returns `true` if `key` exists, else `false`.
 */
function baseHasIn(object, key) {
  return object != null && key in Object(object);
}

module.exports = baseHasIn;


/***/ }),
/* 793 */
/***/ (function(module, exports, __nested_webpack_require_4056367__) {

var castPath = __nested_webpack_require_4056367__(193),
    isArguments = __nested_webpack_require_4056367__(184),
    isArray = __nested_webpack_require_4056367__(31),
    isIndex = __nested_webpack_require_4056367__(142),
    isLength = __nested_webpack_require_4056367__(274),
    toKey = __nested_webpack_require_4056367__(145);

/**
 * Checks if `path` exists on `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @param {Array|string} path The path to check.
 * @param {Function} hasFunc The function to check properties.
 * @returns {boolean} Returns `true` if `path` exists, else `false`.
 */
function hasPath(object, path, hasFunc) {
  path = castPath(path, object);

  var index = -1,
      length = path.length,
      result = false;

  while (++index < length) {
    var key = toKey(path[index]);
    if (!(result = object != null && hasFunc(object, key))) {
      break;
    }
    object = object[key];
  }
  if (result || ++index != length) {
    return result;
  }
  length = object == null ? 0 : object.length;
  return !!length && isLength(length) && isIndex(key, length) &&
    (isArray(object) || isArguments(object));
}

module.exports = hasPath;


/***/ }),
/* 794 */
/***/ (function(module, exports, __nested_webpack_require_4057547__) {

var baseProperty = __nested_webpack_require_4057547__(795),
    basePropertyDeep = __nested_webpack_require_4057547__(796),
    isKey = __nested_webpack_require_4057547__(285),
    toKey = __nested_webpack_require_4057547__(145);

/**
 * Creates a function that returns the value at `path` of a given object.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 * @example
 *
 * var objects = [
 *   { 'a': { 'b': 2 } },
 *   { 'a': { 'b': 1 } }
 * ];
 *
 * _.map(objects, _.property('a.b'));
 * // => [2, 1]
 *
 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
 * // => [1, 2]
 */
function property(path) {
  return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}

module.exports = property;


/***/ }),
/* 795 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.property` without support for deep paths.
 *
 * @private
 * @param {string} key The key of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function baseProperty(key) {
  return function(object) {
    return object == null ? undefined : object[key];
  };
}

module.exports = baseProperty;


/***/ }),
/* 796 */
/***/ (function(module, exports, __nested_webpack_require_4058839__) {

var baseGet = __nested_webpack_require_4058839__(284);

/**
 * A specialized version of `baseProperty` which supports deep paths.
 *
 * @private
 * @param {Array|string} path The path of the property to get.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyDeep(path) {
  return function(object) {
    return baseGet(object, path);
  };
}

module.exports = basePropertyDeep;


/***/ }),
/* 797 */
/***/ (function(module, exports, __nested_webpack_require_4059312__) {

var baseEach = __nested_webpack_require_4059312__(146),
    isArrayLike = __nested_webpack_require_4059312__(98);

/**
 * The base implementation of `_.map` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @returns {Array} Returns the new mapped array.
 */
function baseMap(collection, iteratee) {
  var index = -1,
      result = isArrayLike(collection) ? Array(collection.length) : [];

  baseEach(collection, function(value, key, collection) {
    result[++index] = iteratee(value, key, collection);
  });
  return result;
}

module.exports = baseMap;


/***/ }),
/* 798 */
/***/ (function(module, exports, __nested_webpack_require_4060060__) {

var isArrayLike = __nested_webpack_require_4060060__(98);

/**
 * Creates a `baseEach` or `baseEachRight` function.
 *
 * @private
 * @param {Function} eachFunc The function to iterate over a collection.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {Function} Returns the new base function.
 */
function createBaseEach(eachFunc, fromRight) {
  return function(collection, iteratee) {
    if (collection == null) {
      return collection;
    }
    if (!isArrayLike(collection)) {
      return eachFunc(collection, iteratee);
    }
    var length = collection.length,
        index = fromRight ? length : -1,
        iterable = Object(collection);

    while ((fromRight ? index-- : ++index < length)) {
      if (iteratee(iterable[index], index, iterable) === false) {
        break;
      }
    }
    return collection;
  };
}

module.exports = createBaseEach;


/***/ }),
/* 799 */
/***/ (function(module, exports, __nested_webpack_require_4061024__) {

"use strict";


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

var _forOwn2 = __nested_webpack_require_4061024__(272);

var _forOwn3 = _interopRequireDefault(_forOwn2);

var _cloneDeep2 = __nested_webpack_require_4061024__(800);

var _cloneDeep3 = _interopRequireDefault(_cloneDeep2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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

var mergeClasses = exports.mergeClasses = function mergeClasses(classes) {
  var activeNames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  var styles = classes.default && (0, _cloneDeep3.default)(classes.default) || {};
  activeNames.map(function (name) {
    var toMerge = classes[name];
    if (toMerge) {
      (0, _forOwn3.default)(toMerge, function (value, key) {
        if (!styles[key]) {
          styles[key] = {};
        }

        styles[key] = _extends({}, styles[key], toMerge[key]);
      });
    }

    return name;
  });
  return styles;
};

exports.default = mergeClasses;

/***/ }),
/* 800 */
/***/ (function(module, exports, __nested_webpack_require_4062390__) {

var baseClone = __nested_webpack_require_4062390__(801);

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
    CLONE_SYMBOLS_FLAG = 4;

/**
 * This method is like `_.clone` except that it recursively clones `value`.
 *
 * @static
 * @memberOf _
 * @since 1.0.0
 * @category Lang
 * @param {*} value The value to recursively clone.
 * @returns {*} Returns the deep cloned value.
 * @see _.clone
 * @example
 *
 * var objects = [{ 'a': 1 }, { 'b': 2 }];
 *
 * var deep = _.cloneDeep(objects);
 * console.log(deep[0] === objects[0]);
 * // => false
 */
function cloneDeep(value) {
  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}

module.exports = cloneDeep;


/***/ }),
/* 801 */
/***/ (function(module, exports, __nested_webpack_require_4063149__) {

var Stack = __nested_webpack_require_4063149__(187),
    arrayEach = __nested_webpack_require_4063149__(286),
    assignValue = __nested_webpack_require_4063149__(195),
    baseAssign = __nested_webpack_require_4063149__(802),
    baseAssignIn = __nested_webpack_require_4063149__(803),
    cloneBuffer = __nested_webpack_require_4063149__(427),
    copyArray = __nested_webpack_require_4063149__(196),
    copySymbols = __nested_webpack_require_4063149__(806),
    copySymbolsIn = __nested_webpack_require_4063149__(807),
    getAllKeys = __nested_webpack_require_4063149__(419),
    getAllKeysIn = __nested_webpack_require_4063149__(808),
    getTag = __nested_webpack_require_4063149__(192),
    initCloneArray = __nested_webpack_require_4063149__(809),
    initCloneByTag = __nested_webpack_require_4063149__(810),
    initCloneObject = __nested_webpack_require_4063149__(430),
    isArray = __nested_webpack_require_4063149__(31),
    isBuffer = __nested_webpack_require_4063149__(185),
    isMap = __nested_webpack_require_4063149__(814),
    isObject = __nested_webpack_require_4063149__(45),
    isSet = __nested_webpack_require_4063149__(816),
    keys = __nested_webpack_require_4063149__(119);

/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
    CLONE_FLAT_FLAG = 2,
    CLONE_SYMBOLS_FLAG = 4;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    arrayTag = '[object Array]',
    boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    errorTag = '[object Error]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    objectTag = '[object Object]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]',
    weakMapTag = '[object WeakMap]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';

/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;

/**
 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
 * traversed objects.
 *
 * @private
 * @param {*} value The value to clone.
 * @param {boolean} bitmask The bitmask flags.
 *  1 - Deep clone
 *  2 - Flatten inherited properties
 *  4 - Clone symbols
 * @param {Function} [customizer] The function to customize cloning.
 * @param {string} [key] The key of `value`.
 * @param {Object} [object] The parent object of `value`.
 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
 * @returns {*} Returns the cloned value.
 */
function baseClone(value, bitmask, customizer, key, object, stack) {
  var result,
      isDeep = bitmask & CLONE_DEEP_FLAG,
      isFlat = bitmask & CLONE_FLAT_FLAG,
      isFull = bitmask & CLONE_SYMBOLS_FLAG;

  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== undefined) {
    return result;
  }
  if (!isObject(value)) {
    return value;
  }
  var isArr = isArray(value);
  if (isArr) {
    result = initCloneArray(value);
    if (!isDeep) {
      return copyArray(value, result);
    }
  } else {
    var tag = getTag(value),
        isFunc = tag == funcTag || tag == genTag;

    if (isBuffer(value)) {
      return cloneBuffer(value, isDeep);
    }
    if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
      result = (isFlat || isFunc) ? {} : initCloneObject(value);
      if (!isDeep) {
        return isFlat
          ? copySymbolsIn(value, baseAssignIn(result, value))
          : copySymbols(value, baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = initCloneByTag(value, tag, isDeep);
    }
  }
  // Check for circular references and return its corresponding clone.
  stack || (stack = new Stack);
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);

  if (isSet(value)) {
    value.forEach(function(subValue) {
      result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (isMap(value)) {
    value.forEach(function(subValue, key) {
      result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
    });
  }

  var keysFunc = isFull
    ? (isFlat ? getAllKeysIn : getAllKeys)
    : (isFlat ? keysIn : keys);

  var props = isArr ? undefined : keysFunc(value);
  arrayEach(props || value, function(subValue, key) {
    if (props) {
      key = subValue;
      subValue = value[key];
    }
    // Recursively populate clone (susceptible to call stack limits).
    assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
  });
  return result;
}

module.exports = baseClone;


/***/ }),
/* 802 */
/***/ (function(module, exports, __nested_webpack_require_4068818__) {

var copyObject = __nested_webpack_require_4068818__(100),
    keys = __nested_webpack_require_4068818__(119);

/**
 * The base implementation of `_.assign` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssign(object, source) {
  return object && copyObject(source, keys(source), object);
}

module.exports = baseAssign;


/***/ }),
/* 803 */
/***/ (function(module, exports, __nested_webpack_require_4069374__) {

var copyObject = __nested_webpack_require_4069374__(100),
    keysIn = __nested_webpack_require_4069374__(121);

/**
 * The base implementation of `_.assignIn` without support for multiple sources
 * or `customizer` functions.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @returns {Object} Returns `object`.
 */
function baseAssignIn(object, source) {
  return object && copyObject(source, keysIn(source), object);
}

module.exports = baseAssignIn;


/***/ }),
/* 804 */
/***/ (function(module, exports, __nested_webpack_require_4069940__) {

var isObject = __nested_webpack_require_4069940__(45),
    isPrototype = __nested_webpack_require_4069940__(186),
    nativeKeysIn = __nested_webpack_require_4069940__(805);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function baseKeysIn(object) {
  if (!isObject(object)) {
    return nativeKeysIn(object);
  }
  var isProto = isPrototype(object),
      result = [];

  for (var key in object) {
    if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
      result.push(key);
    }
  }
  return result;
}

module.exports = baseKeysIn;


/***/ }),
/* 805 */
/***/ (function(module, exports) {

/**
 * This function is like
 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
 * except that it includes inherited enumerable properties.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names.
 */
function nativeKeysIn(object) {
  var result = [];
  if (object != null) {
    for (var key in Object(object)) {
      result.push(key);
    }
  }
  return result;
}

module.exports = nativeKeysIn;


/***/ }),
/* 806 */
/***/ (function(module, exports, __nested_webpack_require_4071436__) {

var copyObject = __nested_webpack_require_4071436__(100),
    getSymbols = __nested_webpack_require_4071436__(282);

/**
 * Copies own symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbols(source, object) {
  return copyObject(source, getSymbols(source), object);
}

module.exports = copySymbols;


/***/ }),
/* 807 */
/***/ (function(module, exports, __nested_webpack_require_4071961__) {

var copyObject = __nested_webpack_require_4071961__(100),
    getSymbolsIn = __nested_webpack_require_4071961__(428);

/**
 * Copies own and inherited symbols of `source` to `object`.
 *
 * @private
 * @param {Object} source The object to copy symbols from.
 * @param {Object} [object={}] The object to copy symbols to.
 * @returns {Object} Returns `object`.
 */
function copySymbolsIn(source, object) {
  return copyObject(source, getSymbolsIn(source), object);
}

module.exports = copySymbolsIn;


/***/ }),
/* 808 */
/***/ (function(module, exports, __nested_webpack_require_4072508__) {

var baseGetAllKeys = __nested_webpack_require_4072508__(420),
    getSymbolsIn = __nested_webpack_require_4072508__(428),
    keysIn = __nested_webpack_require_4072508__(121);

/**
 * Creates an array of own and inherited enumerable property names and
 * symbols of `object`.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property names and symbols.
 */
function getAllKeysIn(object) {
  return baseGetAllKeys(object, keysIn, getSymbolsIn);
}

module.exports = getAllKeysIn;


/***/ }),
/* 809 */
/***/ (function(module, exports) {

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Initializes an array clone.
 *
 * @private
 * @param {Array} array The array to clone.
 * @returns {Array} Returns the initialized clone.
 */
function initCloneArray(array) {
  var length = array.length,
      result = new array.constructor(length);

  // Add properties assigned by `RegExp#exec`.
  if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}

module.exports = initCloneArray;


/***/ }),
/* 810 */
/***/ (function(module, exports, __nested_webpack_require_4073824__) {

var cloneArrayBuffer = __nested_webpack_require_4073824__(288),
    cloneDataView = __nested_webpack_require_4073824__(811),
    cloneRegExp = __nested_webpack_require_4073824__(812),
    cloneSymbol = __nested_webpack_require_4073824__(813),
    cloneTypedArray = __nested_webpack_require_4073824__(429);

/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
    dateTag = '[object Date]',
    mapTag = '[object Map]',
    numberTag = '[object Number]',
    regexpTag = '[object RegExp]',
    setTag = '[object Set]',
    stringTag = '[object String]',
    symbolTag = '[object Symbol]';

var arrayBufferTag = '[object ArrayBuffer]',
    dataViewTag = '[object DataView]',
    float32Tag = '[object Float32Array]',
    float64Tag = '[object Float64Array]',
    int8Tag = '[object Int8Array]',
    int16Tag = '[object Int16Array]',
    int32Tag = '[object Int32Array]',
    uint8Tag = '[object Uint8Array]',
    uint8ClampedTag = '[object Uint8ClampedArray]',
    uint16Tag = '[object Uint16Array]',
    uint32Tag = '[object Uint32Array]';

/**
 * Initializes an object clone based on its `toStringTag`.
 *
 * **Note:** This function only supports cloning values with tags of
 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
 *
 * @private
 * @param {Object} object The object to clone.
 * @param {string} tag The `toStringTag` of the object to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneByTag(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case arrayBufferTag:
      return cloneArrayBuffer(object);

    case boolTag:
    case dateTag:
      return new Ctor(+object);

    case dataViewTag:
      return cloneDataView(object, isDeep);

    case float32Tag: case float64Tag:
    case int8Tag: case int16Tag: case int32Tag:
    case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
      return cloneTypedArray(object, isDeep);

    case mapTag:
      return new Ctor;

    case numberTag:
    case stringTag:
      return new Ctor(object);

    case regexpTag:
      return cloneRegExp(object);

    case setTag:
      return new Ctor;

    case symbolTag:
      return cloneSymbol(object);
  }
}

module.exports = initCloneByTag;


/***/ }),
/* 811 */
/***/ (function(module, exports, __nested_webpack_require_4076148__) {

var cloneArrayBuffer = __nested_webpack_require_4076148__(288);

/**
 * Creates a clone of `dataView`.
 *
 * @private
 * @param {Object} dataView The data view to clone.
 * @param {boolean} [isDeep] Specify a deep clone.
 * @returns {Object} Returns the cloned data view.
 */
function cloneDataView(dataView, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}

module.exports = cloneDataView;


/***/ }),
/* 812 */
/***/ (function(module, exports) {

/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;

/**
 * Creates a clone of `regexp`.
 *
 * @private
 * @param {Object} regexp The regexp to clone.
 * @returns {Object} Returns the cloned regexp.
 */
function cloneRegExp(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}

module.exports = cloneRegExp;


/***/ }),
/* 813 */
/***/ (function(module, exports, __nested_webpack_require_4077225__) {

var Symbol = __nested_webpack_require_4077225__(118);

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;

/**
 * Creates a clone of the `symbol` object.
 *
 * @private
 * @param {Object} symbol The symbol object to clone.
 * @returns {Object} Returns the cloned symbol object.
 */
function cloneSymbol(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}

module.exports = cloneSymbol;


/***/ }),
/* 814 */
/***/ (function(module, exports, __nested_webpack_require_4077832__) {

var baseIsMap = __nested_webpack_require_4077832__(815),
    baseUnary = __nested_webpack_require_4077832__(275),
    nodeUtil = __nested_webpack_require_4077832__(276);

/* Node.js helper references. */
var nodeIsMap = nodeUtil && nodeUtil.isMap;

/**
 * Checks if `value` is classified as a `Map` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 * @example
 *
 * _.isMap(new Map);
 * // => true
 *
 * _.isMap(new WeakMap);
 * // => false
 */
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;

module.exports = isMap;


/***/ }),
/* 815 */
/***/ (function(module, exports, __nested_webpack_require_4078528__) {

var getTag = __nested_webpack_require_4078528__(192),
    isObjectLike = __nested_webpack_require_4078528__(56);

/** `Object#toString` result references. */
var mapTag = '[object Map]';

/**
 * The base implementation of `_.isMap` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
 */
function baseIsMap(value) {
  return isObjectLike(value) && getTag(value) == mapTag;
}

module.exports = baseIsMap;


/***/ }),
/* 816 */
/***/ (function(module, exports, __nested_webpack_require_4079087__) {

var baseIsSet = __nested_webpack_require_4079087__(817),
    baseUnary = __nested_webpack_require_4079087__(275),
    nodeUtil = __nested_webpack_require_4079087__(276);

/* Node.js helper references. */
var nodeIsSet = nodeUtil && nodeUtil.isSet;

/**
 * Checks if `value` is classified as a `Set` object.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 * @example
 *
 * _.isSet(new Set);
 * // => true
 *
 * _.isSet(new WeakSet);
 * // => false
 */
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;

module.exports = isSet;


/***/ }),
/* 817 */
/***/ (function(module, exports, __nested_webpack_require_4079783__) {

var getTag = __nested_webpack_require_4079783__(192),
    isObjectLike = __nested_webpack_require_4079783__(56);

/** `Object#toString` result references. */
var setTag = '[object Set]';

/**
 * The base implementation of `_.isSet` without Node.js optimizations.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
 */
function baseIsSet(value) {
  return isObjectLike(value) && getTag(value) == setTag;
}

module.exports = baseIsSet;


/***/ }),
/* 818 */
/***/ (function(module, exports, __nested_webpack_require_4080342__) {

"use strict";


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

var _forOwn2 = __nested_webpack_require_4080342__(272);

var _forOwn3 = _interopRequireDefault(_forOwn2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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

var transforms = {
  borderRadius: function borderRadius(value) {
    return {
      msBorderRadius: value,
      MozBorderRadius: value,
      OBorderRadius: value,
      WebkitBorderRadius: value,
      borderRadius: value
    };
  },
  boxShadow: function boxShadow(value) {
    return {
      msBoxShadow: value,
      MozBoxShadow: value,
      OBoxShadow: value,
      WebkitBoxShadow: value,
      boxShadow: value
    };
  },
  userSelect: function userSelect(value) {
    return {
      WebkitTouchCallout: value,
      KhtmlUserSelect: value,
      MozUserSelect: value,
      msUserSelect: value,
      WebkitUserSelect: value,
      userSelect: value
    };
  },

  flex: function flex(value) {
    return {
      WebkitBoxFlex: value,
      MozBoxFlex: value,
      WebkitFlex: value,
      msFlex: value,
      flex: value
    };
  },
  flexBasis: function flexBasis(value) {
    return {
      WebkitFlexBasis: value,
      flexBasis: value
    };
  },
  justifyContent: function justifyContent(value) {
    return {
      WebkitJustifyContent: value,
      justifyContent: value
    };
  },

  transition: function transition(value) {
    return {
      msTransition: value,
      MozTransition: value,
      OTransition: value,
      WebkitTransition: value,
      transition: value
    };
  },

  transform: function transform(value) {
    return {
      msTransform: value,
      MozTransform: value,
      OTransform: value,
      WebkitTransform: value,
      transform: value
    };
  },
  absolute: function absolute(value) {
    var direction = value && value.split(' ');
    return {
      position: 'absolute',
      top: direction && direction[0],
      right: direction && direction[1],
      bottom: direction && direction[2],
      left: direction && direction[3]
    };
  },
  extend: function extend(name, otherElementStyles) {
    var otherStyle = otherElementStyles[name];
    if (otherStyle) {
      return otherStyle;
    }
    return {
      'extend': name
    };
  }
};

var autoprefix = exports.autoprefix = function autoprefix(elements) {
  var prefixed = {};
  (0, _forOwn3.default)(elements, function (styles, element) {
    var expanded = {};
    (0, _forOwn3.default)(styles, function (value, key) {
      var transform = transforms[key];
      if (transform) {
        expanded = _extends({}, expanded, transform(value));
      } else {
        expanded[key] = value;
      }
    });
    prefixed[element] = expanded;
  });
  return prefixed;
};

exports.default = autoprefix;

/***/ }),
/* 819 */
/***/ (function(module, exports, __nested_webpack_require_4083504__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4083504__(1);

var _react2 = _interopRequireDefault(_react);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var hover = exports.hover = function hover(Component) {
  var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span';

  return function (_React$Component) {
    _inherits(Hover, _React$Component);

    function Hover() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, Hover);

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

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Hover.__proto__ || Object.getPrototypeOf(Hover)).call.apply(_ref, [this].concat(args))), _this), _this.state = { hover: false }, _this.handleMouseOver = function () {
        return _this.setState({ hover: true });
      }, _this.handleMouseOut = function () {
        return _this.setState({ hover: false });
      }, _this.render = function () {
        return _react2.default.createElement(
          Span,
          { onMouseOver: _this.handleMouseOver, onMouseOut: _this.handleMouseOut },
          _react2.default.createElement(Component, _extends({}, _this.props, _this.state))
        );
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    return Hover;
  }(_react2.default.Component);
};

exports.default = hover;

/***/ }),
/* 820 */
/***/ (function(module, exports, __nested_webpack_require_4086318__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4086318__(1);

var _react2 = _interopRequireDefault(_react);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var active = exports.active = function active(Component) {
  var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span';

  return function (_React$Component) {
    _inherits(Active, _React$Component);

    function Active() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, Active);

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

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Active.__proto__ || Object.getPrototypeOf(Active)).call.apply(_ref, [this].concat(args))), _this), _this.state = { active: false }, _this.handleMouseDown = function () {
        return _this.setState({ active: true });
      }, _this.handleMouseUp = function () {
        return _this.setState({ active: false });
      }, _this.render = function () {
        return _react2.default.createElement(
          Span,
          { onMouseDown: _this.handleMouseDown, onMouseUp: _this.handleMouseUp },
          _react2.default.createElement(Component, _extends({}, _this.props, _this.state))
        );
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    return Active;
  }(_react2.default.Component);
};

exports.default = active;

/***/ }),
/* 821 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var loopable = function loopable(i, length) {
  var props = {};
  var setProp = function setProp(name) {
    var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

    props[name] = value;
  };

  i === 0 && setProp('first-child');
  i === length - 1 && setProp('last-child');
  (i === 0 || i % 2 === 0) && setProp('even');
  Math.abs(i % 2) === 1 && setProp('odd');
  setProp('nth-child', i);

  return props;
};

exports.default = loopable;

/***/ }),
/* 822 */
/***/ (function(module, exports, __nested_webpack_require_4089777__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CustomPicker = exports.TwitterPicker = exports.SwatchesPicker = exports.SliderPicker = exports.SketchPicker = exports.PhotoshopPicker = exports.MaterialPicker = exports.HuePicker = exports.GithubPicker = exports.CompactPicker = exports.ChromePicker = exports.default = exports.CirclePicker = exports.BlockPicker = exports.AlphaPicker = undefined;

var _Alpha = __nested_webpack_require_4089777__(823);

Object.defineProperty(exports, 'AlphaPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Alpha).default;
  }
});

var _Block = __nested_webpack_require_4089777__(846);

Object.defineProperty(exports, 'BlockPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Block).default;
  }
});

var _Circle = __nested_webpack_require_4089777__(848);

Object.defineProperty(exports, 'CirclePicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Circle).default;
  }
});

var _Chrome = __nested_webpack_require_4089777__(850);

Object.defineProperty(exports, 'ChromePicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Chrome).default;
  }
});

var _Compact = __nested_webpack_require_4089777__(855);

Object.defineProperty(exports, 'CompactPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Compact).default;
  }
});

var _Github = __nested_webpack_require_4089777__(858);

Object.defineProperty(exports, 'GithubPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Github).default;
  }
});

var _Hue = __nested_webpack_require_4089777__(860);

Object.defineProperty(exports, 'HuePicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Hue).default;
  }
});

var _Material = __nested_webpack_require_4089777__(862);

Object.defineProperty(exports, 'MaterialPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Material).default;
  }
});

var _Photoshop = __nested_webpack_require_4089777__(863);

Object.defineProperty(exports, 'PhotoshopPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Photoshop).default;
  }
});

var _Sketch = __nested_webpack_require_4089777__(869);

Object.defineProperty(exports, 'SketchPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Sketch).default;
  }
});

var _Slider = __nested_webpack_require_4089777__(872);

Object.defineProperty(exports, 'SliderPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Slider).default;
  }
});

var _Swatches = __nested_webpack_require_4089777__(876);

Object.defineProperty(exports, 'SwatchesPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Swatches).default;
  }
});

var _Twitter = __nested_webpack_require_4089777__(880);

Object.defineProperty(exports, 'TwitterPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_Twitter).default;
  }
});

var _ColorWrap = __nested_webpack_require_4089777__(437);

Object.defineProperty(exports, 'CustomPicker', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_ColorWrap).default;
  }
});

var _Chrome2 = _interopRequireDefault(_Chrome);

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

exports.default = _Chrome2.default;

/***/ }),
/* 823 */
/***/ (function(module, exports, __nested_webpack_require_4093222__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4093222__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4093222__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __nested_webpack_require_4093222__(22);

var _AlphaPointer = __nested_webpack_require_4093222__(845);

var _AlphaPointer2 = _interopRequireDefault(_AlphaPointer);

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

var AlphaPicker = exports.AlphaPicker = function AlphaPicker(_ref) {
  var rgb = _ref.rgb,
      hsl = _ref.hsl,
      width = _ref.width,
      height = _ref.height,
      onChange = _ref.onChange,
      direction = _ref.direction,
      style = _ref.style,
      renderers = _ref.renderers,
      pointer = _ref.pointer,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        position: 'relative',
        width: width,
        height: height
      },
      alpha: {
        radius: '2px',
        style: style
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'alpha-picker ' + className },
    _react2.default.createElement(_common.Alpha, _extends({}, styles.alpha, {
      rgb: rgb,
      hsl: hsl,
      pointer: pointer,
      renderers: renderers,
      onChange: onChange,
      direction: direction
    }))
  );
};

AlphaPicker.defaultProps = {
  width: '316px',
  height: '16px',
  direction: 'horizontal',
  pointer: _AlphaPointer2.default
};

exports.default = (0, _common.ColorWrap)(AlphaPicker);

/***/ }),
/* 824 */
/***/ (function(module, exports, __nested_webpack_require_4095308__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4095308__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4095308__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _alpha = __nested_webpack_require_4095308__(825);

var alpha = _interopRequireWildcard(_alpha);

var _Checkboard = __nested_webpack_require_4095308__(289);

var _Checkboard2 = _interopRequireDefault(_Checkboard);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Alpha = exports.Alpha = function (_ref) {
  _inherits(Alpha, _ref);

  function Alpha() {
    var _ref2;

    var _temp, _this, _ret;

    _classCallCheck(this, Alpha);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref2 = Alpha.__proto__ || Object.getPrototypeOf(Alpha)).call.apply(_ref2, [this].concat(args))), _this), _this.handleChange = function (e, skip) {
      var change = alpha.calculateChange(e, skip, _this.props, _this.container);
      change && _this.props.onChange && _this.props.onChange(change, e);
    }, _this.handleMouseDown = function (e) {
      _this.handleChange(e, true);
      window.addEventListener('mousemove', _this.handleChange);
      window.addEventListener('mouseup', _this.handleMouseUp);
    }, _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    }, _this.unbindEventListeners = function () {
      window.removeEventListener('mousemove', _this.handleChange);
      window.removeEventListener('mouseup', _this.handleMouseUp);
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Alpha, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.unbindEventListeners();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var rgb = this.props.rgb;
      var styles = (0, _reactcss2.default)({
        'default': {
          alpha: {
            absolute: '0px 0px 0px 0px',
            borderRadius: this.props.radius
          },
          checkboard: {
            absolute: '0px 0px 0px 0px',
            overflow: 'hidden',
            borderRadius: this.props.radius
          },
          gradient: {
            absolute: '0px 0px 0px 0px',
            background: 'linear-gradient(to right, rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 0) 0%,\n           rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 1) 100%)',
            boxShadow: this.props.shadow,
            borderRadius: this.props.radius
          },
          container: {
            position: 'relative',
            height: '100%',
            margin: '0 3px'
          },
          pointer: {
            position: 'absolute',
            left: rgb.a * 100 + '%'
          },
          slider: {
            width: '4px',
            borderRadius: '1px',
            height: '8px',
            boxShadow: '0 0 2px rgba(0, 0, 0, .6)',
            background: '#fff',
            marginTop: '1px',
            transform: 'translateX(-2px)'
          }
        },
        'vertical': {
          gradient: {
            background: 'linear-gradient(to bottom, rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 0) 0%,\n           rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', 1) 100%)'
          },
          pointer: {
            left: 0,
            top: rgb.a * 100 + '%'
          }
        },
        'overwrite': _extends({}, this.props.style)
      }, {
        vertical: this.props.direction === 'vertical',
        overwrite: true
      });

      return _react2.default.createElement(
        'div',
        { style: styles.alpha },
        _react2.default.createElement(
          'div',
          { style: styles.checkboard },
          _react2.default.createElement(_Checkboard2.default, { renderers: this.props.renderers })
        ),
        _react2.default.createElement('div', { style: styles.gradient }),
        _react2.default.createElement(
          'div',
          {
            style: styles.container,
            ref: function ref(container) {
              return _this2.container = container;
            },
            onMouseDown: this.handleMouseDown,
            onTouchMove: this.handleChange,
            onTouchStart: this.handleChange
          },
          _react2.default.createElement(
            'div',
            { style: styles.pointer },
            this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.slider })
          )
        )
      );
    }
  }]);

  return Alpha;
}(_react.PureComponent || _react.Component);

exports.default = Alpha;

/***/ }),
/* 825 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var calculateChange = exports.calculateChange = function calculateChange(e, skip, props, container) {
  e.preventDefault();
  var containerWidth = container.clientWidth;
  var containerHeight = container.clientHeight;
  var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX;
  var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY;
  var left = x - (container.getBoundingClientRect().left + window.pageXOffset);
  var top = y - (container.getBoundingClientRect().top + window.pageYOffset);

  if (props.direction === 'vertical') {
    var a = void 0;
    if (top < 0) {
      a = 0;
    } else if (top > containerHeight) {
      a = 1;
    } else {
      a = Math.round(top * 100 / containerHeight) / 100;
    }

    if (props.hsl.a !== a) {
      return {
        h: props.hsl.h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: a,
        source: 'rgb'
      };
    }
  } else {
    var _a = void 0;
    if (left < 0) {
      _a = 0;
    } else if (left > containerWidth) {
      _a = 1;
    } else {
      _a = Math.round(left * 100 / containerWidth) / 100;
    }

    if (props.a !== _a) {
      return {
        h: props.hsl.h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: _a,
        source: 'rgb'
      };
    }
  }
  return null;
};

/***/ }),
/* 826 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


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

var render = exports.render = function render(c1, c2, size, serverCanvas) {
  if (typeof document === 'undefined' && !serverCanvas) {
    return null;
  }
  var canvas = serverCanvas ? new serverCanvas() : document.createElement('canvas');
  canvas.width = size * 2;
  canvas.height = size * 2;
  var ctx = canvas.getContext('2d');
  if (!ctx) {
    return null;
  } // If no context can be found, return early.
  ctx.fillStyle = c1;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = c2;
  ctx.fillRect(0, 0, size, size);
  ctx.translate(size, size);
  ctx.fillRect(0, 0, size, size);
  return canvas.toDataURL();
};

var get = exports.get = function get(c1, c2, size, serverCanvas) {
  var key = c1 + '-' + c2 + '-' + size + (serverCanvas ? '-server' : '');
  var checkboard = render(c1, c2, size, serverCanvas);

  if (checkboardCache[key]) {
    return checkboardCache[key];
  }
  checkboardCache[key] = checkboard;
  return checkboard;
};

/***/ }),
/* 827 */
/***/ (function(module, exports, __nested_webpack_require_4104820__) {

"use strict";


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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4104820__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4104820__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var EditableInput = exports.EditableInput = function (_ref) {
  _inherits(EditableInput, _ref);

  function EditableInput(props) {
    _classCallCheck(this, EditableInput);

    var _this = _possibleConstructorReturn(this, (EditableInput.__proto__ || Object.getPrototypeOf(EditableInput)).call(this));

    _this.handleBlur = function () {
      if (_this.state.blurValue) {
        _this.setState({ value: _this.state.blurValue, blurValue: null });
      }
    };

    _this.handleChange = function (e) {
      if (_this.props.label) {
        _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, e.target.value), e);
      } else {
        _this.props.onChange && _this.props.onChange(e.target.value, e);
      }

      _this.setState({ value: e.target.value });
    };

    _this.handleKeyDown = function (e) {
      // In case `e.target.value` is a percentage remove the `%` character
      // and update accordingly with a percentage
      // https://github.com/casesandberg/react-color/issues/383
      var stringValue = String(e.target.value);
      var isPercentage = stringValue.indexOf('%') > -1;
      var number = Number(stringValue.replace(/%/g, ''));
      if (!isNaN(number)) {
        var amount = _this.props.arrowOffset || 1;

        // Up
        if (e.keyCode === 38) {
          if (_this.props.label !== null) {
            _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, number + amount), e);
          } else {
            _this.props.onChange && _this.props.onChange(number + amount, e);
          }

          if (isPercentage) {
            _this.setState({ value: number + amount + '%' });
          } else {
            _this.setState({ value: number + amount });
          }
        }

        // Down
        if (e.keyCode === 40) {
          if (_this.props.label !== null) {
            _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, number - amount), e);
          } else {
            _this.props.onChange && _this.props.onChange(number - amount, e);
          }

          if (isPercentage) {
            _this.setState({ value: number - amount + '%' });
          } else {
            _this.setState({ value: number - amount });
          }
        }
      }
    };

    _this.handleDrag = function (e) {
      if (_this.props.dragLabel) {
        var newValue = Math.round(_this.props.value + e.movementX);
        if (newValue >= 0 && newValue <= _this.props.dragMax) {
          _this.props.onChange && _this.props.onChange(_defineProperty({}, _this.props.label, newValue), e);
        }
      }
    };

    _this.handleMouseDown = function (e) {
      if (_this.props.dragLabel) {
        e.preventDefault();
        _this.handleDrag(e);
        window.addEventListener('mousemove', _this.handleDrag);
        window.addEventListener('mouseup', _this.handleMouseUp);
      }
    };

    _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    };

    _this.unbindEventListeners = function () {
      window.removeEventListener('mousemove', _this.handleDrag);
      window.removeEventListener('mouseup', _this.handleMouseUp);
    };

    _this.state = {
      value: String(props.value).toUpperCase(),
      blurValue: String(props.value).toUpperCase()
    };
    return _this;
  }

  _createClass(EditableInput, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var input = this.input;
      if (nextProps.value !== this.state.value) {
        if (input === document.activeElement) {
          this.setState({ blurValue: String(nextProps.value).toUpperCase() });
        } else {
          this.setState({ value: String(nextProps.value).toUpperCase(), blurValue: !this.state.blurValue && String(nextProps.value).toUpperCase() });
        }
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.unbindEventListeners();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var styles = (0, _reactcss2.default)({
        'default': {
          wrap: {
            position: 'relative'
          }
        },
        'user-override': {
          wrap: this.props.style && this.props.style.wrap ? this.props.style.wrap : {},
          input: this.props.style && this.props.style.input ? this.props.style.input : {},
          label: this.props.style && this.props.style.label ? this.props.style.label : {}
        },
        'dragLabel-true': {
          label: {
            cursor: 'ew-resize'
          }
        }
      }, {
        'user-override': true
      }, this.props);

      return _react2.default.createElement(
        'div',
        { style: styles.wrap },
        _react2.default.createElement('input', {
          style: styles.input,
          ref: function ref(input) {
            return _this2.input = input;
          },
          value: this.state.value,
          onKeyDown: this.handleKeyDown,
          onChange: this.handleChange,
          onBlur: this.handleBlur,
          placeholder: this.props.placeholder,
          spellCheck: 'false'
        }),
        this.props.label && !this.props.hideLabel ? _react2.default.createElement(
          'span',
          { style: styles.label, onMouseDown: this.handleMouseDown },
          this.props.label
        ) : null
      );
    }
  }]);

  return EditableInput;
}(_react.PureComponent || _react.Component);

exports.default = EditableInput;

/***/ }),
/* 828 */
/***/ (function(module, exports, __nested_webpack_require_4112501__) {

"use strict";


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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4112501__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4112501__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _hue = __nested_webpack_require_4112501__(829);

var hue = _interopRequireWildcard(_hue);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Hue = exports.Hue = function (_ref) {
  _inherits(Hue, _ref);

  function Hue() {
    var _ref2;

    var _temp, _this, _ret;

    _classCallCheck(this, Hue);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref2 = Hue.__proto__ || Object.getPrototypeOf(Hue)).call.apply(_ref2, [this].concat(args))), _this), _this.handleChange = function (e, skip) {
      var change = hue.calculateChange(e, skip, _this.props, _this.container);
      change && _this.props.onChange && _this.props.onChange(change, e);
    }, _this.handleMouseDown = function (e) {
      _this.handleChange(e, true);
      window.addEventListener('mousemove', _this.handleChange);
      window.addEventListener('mouseup', _this.handleMouseUp);
    }, _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Hue, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.unbindEventListeners();
    }
  }, {
    key: 'unbindEventListeners',
    value: function unbindEventListeners() {
      window.removeEventListener('mousemove', this.handleChange);
      window.removeEventListener('mouseup', this.handleMouseUp);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props$direction = this.props.direction,
          direction = _props$direction === undefined ? 'horizontal' : _props$direction;


      var styles = (0, _reactcss2.default)({
        'default': {
          hue: {
            absolute: '0px 0px 0px 0px',
            borderRadius: this.props.radius,
            boxShadow: this.props.shadow
          },
          container: {
            padding: '0 2px',
            position: 'relative',
            height: '100%',
            borderRadius: this.props.radius
          },
          pointer: {
            position: 'absolute',
            left: this.props.hsl.h * 100 / 360 + '%'
          },
          slider: {
            marginTop: '1px',
            width: '4px',
            borderRadius: '1px',
            height: '8px',
            boxShadow: '0 0 2px rgba(0, 0, 0, .6)',
            background: '#fff',
            transform: 'translateX(-2px)'
          }
        },
        'vertical': {
          pointer: {
            left: '0px',
            top: -(this.props.hsl.h * 100 / 360) + 100 + '%'
          }
        }
      }, { vertical: direction === 'vertical' });

      return _react2.default.createElement(
        'div',
        { style: styles.hue },
        _react2.default.createElement(
          'div',
          {
            className: 'hue-' + direction,
            style: styles.container,
            ref: function ref(container) {
              return _this2.container = container;
            },
            onMouseDown: this.handleMouseDown,
            onTouchMove: this.handleChange,
            onTouchStart: this.handleChange
          },
          _react2.default.createElement(
            'style',
            null,
            '\n            .hue-horizontal {\n              background: linear-gradient(to right, #f00 0%, #ff0 17%, #0f0\n                33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n              background: -webkit-linear-gradient(to right, #f00 0%, #ff0\n                17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n            }\n\n            .hue-vertical {\n              background: linear-gradient(to top, #f00 0%, #ff0 17%, #0f0 33%,\n                #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n              background: -webkit-linear-gradient(to top, #f00 0%, #ff0 17%,\n                #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%);\n            }\n          '
          ),
          _react2.default.createElement(
            'div',
            { style: styles.pointer },
            this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.slider })
          )
        )
      );
    }
  }]);

  return Hue;
}(_react.PureComponent || _react.Component);

exports.default = Hue;

/***/ }),
/* 829 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var calculateChange = exports.calculateChange = function calculateChange(e, skip, props, container) {
  e.preventDefault();
  var containerWidth = container.clientWidth;
  var containerHeight = container.clientHeight;
  var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX;
  var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY;
  var left = x - (container.getBoundingClientRect().left + window.pageXOffset);
  var top = y - (container.getBoundingClientRect().top + window.pageYOffset);

  if (props.direction === 'vertical') {
    var h = void 0;
    if (top < 0) {
      h = 359;
    } else if (top > containerHeight) {
      h = 0;
    } else {
      var percent = -(top * 100 / containerHeight) + 100;
      h = 360 * percent / 100;
    }

    if (props.hsl.h !== h) {
      return {
        h: h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: props.hsl.a,
        source: 'rgb'
      };
    }
  } else {
    var _h = void 0;
    if (left < 0) {
      _h = 0;
    } else if (left > containerWidth) {
      _h = 359;
    } else {
      var _percent = left * 100 / containerWidth;
      _h = 360 * _percent / 100;
    }

    if (props.hsl.h !== _h) {
      return {
        h: _h,
        s: props.hsl.s,
        l: props.hsl.l,
        a: props.hsl.a,
        source: 'rgb'
      };
    }
  }
  return null;
};

/***/ }),
/* 830 */
/***/ (function(module, exports, __nested_webpack_require_4120561__) {

"use strict";


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

var _react = __nested_webpack_require_4120561__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4120561__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4120561__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4120561__(46);

var _merge2 = _interopRequireDefault(_merge);

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

var Raised = exports.Raised = function Raised(_ref) {
  var zDepth = _ref.zDepth,
      radius = _ref.radius,
      background = _ref.background,
      children = _ref.children,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      wrap: {
        position: 'relative',
        display: 'inline-block'
      },
      content: {
        position: 'relative'
      },
      bg: {
        absolute: '0px 0px 0px 0px',
        boxShadow: '0 ' + zDepth + 'px ' + zDepth * 4 + 'px rgba(0,0,0,.24)',
        borderRadius: radius,
        background: background
      }
    },
    'zDepth-0': {
      bg: {
        boxShadow: 'none'
      }
    },

    'zDepth-1': {
      bg: {
        boxShadow: '0 2px 10px rgba(0,0,0,.12), 0 2px 5px rgba(0,0,0,.16)'
      }
    },
    'zDepth-2': {
      bg: {
        boxShadow: '0 6px 20px rgba(0,0,0,.19), 0 8px 17px rgba(0,0,0,.2)'
      }
    },
    'zDepth-3': {
      bg: {
        boxShadow: '0 17px 50px rgba(0,0,0,.19), 0 12px 15px rgba(0,0,0,.24)'
      }
    },
    'zDepth-4': {
      bg: {
        boxShadow: '0 25px 55px rgba(0,0,0,.21), 0 16px 28px rgba(0,0,0,.22)'
      }
    },
    'zDepth-5': {
      bg: {
        boxShadow: '0 40px 77px rgba(0,0,0,.22), 0 27px 24px rgba(0,0,0,.2)'
      }
    },
    'square': {
      bg: {
        borderRadius: '0'
      }
    },
    'circle': {
      bg: {
        borderRadius: '50%'
      }
    }
  }, passedStyles), { 'zDepth-1': zDepth === 1 });

  return _react2.default.createElement(
    'div',
    { style: styles.wrap },
    _react2.default.createElement('div', { style: styles.bg }),
    _react2.default.createElement(
      'div',
      { style: styles.content },
      children
    )
  );
};

Raised.propTypes = {
  background: _propTypes2.default.string,
  zDepth: _propTypes2.default.oneOf([0, 1, 2, 3, 4, 5]),
  radius: _propTypes2.default.number,
  styles: _propTypes2.default.object
};

Raised.defaultProps = {
  background: '#fff',
  zDepth: 1,
  radius: 2,
  styles: {}
};

exports.default = Raised;

/***/ }),
/* 831 */
/***/ (function(module, exports, __nested_webpack_require_4123349__) {

var Stack = __nested_webpack_require_4123349__(187),
    assignMergeValue = __nested_webpack_require_4123349__(431),
    baseFor = __nested_webpack_require_4123349__(408),
    baseMergeDeep = __nested_webpack_require_4123349__(832),
    isObject = __nested_webpack_require_4123349__(45),
    keysIn = __nested_webpack_require_4123349__(121),
    safeGet = __nested_webpack_require_4123349__(432);

/**
 * The base implementation of `_.merge` without support for multiple sources.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {number} srcIndex The index of `source`.
 * @param {Function} [customizer] The function to customize merged values.
 * @param {Object} [stack] Tracks traversed source values and their merged
 *  counterparts.
 */
function baseMerge(object, source, srcIndex, customizer, stack) {
  if (object === source) {
    return;
  }
  baseFor(source, function(srcValue, key) {
    stack || (stack = new Stack);
    if (isObject(srcValue)) {
      baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
    }
    else {
      var newValue = customizer
        ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
        : undefined;

      if (newValue === undefined) {
        newValue = srcValue;
      }
      assignMergeValue(object, key, newValue);
    }
  }, keysIn);
}

module.exports = baseMerge;


/***/ }),
/* 832 */
/***/ (function(module, exports, __nested_webpack_require_4124765__) {

var assignMergeValue = __nested_webpack_require_4124765__(431),
    cloneBuffer = __nested_webpack_require_4124765__(427),
    cloneTypedArray = __nested_webpack_require_4124765__(429),
    copyArray = __nested_webpack_require_4124765__(196),
    initCloneObject = __nested_webpack_require_4124765__(430),
    isArguments = __nested_webpack_require_4124765__(184),
    isArray = __nested_webpack_require_4124765__(31),
    isArrayLikeObject = __nested_webpack_require_4124765__(833),
    isBuffer = __nested_webpack_require_4124765__(185),
    isFunction = __nested_webpack_require_4124765__(277),
    isObject = __nested_webpack_require_4124765__(45),
    isPlainObject = __nested_webpack_require_4124765__(412),
    isTypedArray = __nested_webpack_require_4124765__(273),
    safeGet = __nested_webpack_require_4124765__(432),
    toPlainObject = __nested_webpack_require_4124765__(834);

/**
 * A specialized version of `baseMerge` for arrays and objects which performs
 * deep merges and tracks traversed objects enabling objects with circular
 * references to be merged.
 *
 * @private
 * @param {Object} object The destination object.
 * @param {Object} source The source object.
 * @param {string} key The key of the value to merge.
 * @param {number} srcIndex The index of `source`.
 * @param {Function} mergeFunc The function to merge values.
 * @param {Function} [customizer] The function to customize assigned values.
 * @param {Object} [stack] Tracks traversed source values and their merged
 *  counterparts.
 */
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
  var objValue = safeGet(object, key),
      srcValue = safeGet(source, key),
      stacked = stack.get(srcValue);

  if (stacked) {
    assignMergeValue(object, key, stacked);
    return;
  }
  var newValue = customizer
    ? customizer(objValue, srcValue, (key + ''), object, source, stack)
    : undefined;

  var isCommon = newValue === undefined;

  if (isCommon) {
    var isArr = isArray(srcValue),
        isBuff = !isArr && isBuffer(srcValue),
        isTyped = !isArr && !isBuff && isTypedArray(srcValue);

    newValue = srcValue;
    if (isArr || isBuff || isTyped) {
      if (isArray(objValue)) {
        newValue = objValue;
      }
      else if (isArrayLikeObject(objValue)) {
        newValue = copyArray(objValue);
      }
      else if (isBuff) {
        isCommon = false;
        newValue = cloneBuffer(srcValue, true);
      }
      else if (isTyped) {
        isCommon = false;
        newValue = cloneTypedArray(srcValue, true);
      }
      else {
        newValue = [];
      }
    }
    else if (isPlainObject(srcValue) || isArguments(srcValue)) {
      newValue = objValue;
      if (isArguments(objValue)) {
        newValue = toPlainObject(objValue);
      }
      else if (!isObject(objValue) || isFunction(objValue)) {
        newValue = initCloneObject(srcValue);
      }
    }
    else {
      isCommon = false;
    }
  }
  if (isCommon) {
    // Recursively merge objects and arrays (susceptible to call stack limits).
    stack.set(srcValue, newValue);
    mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
    stack['delete'](srcValue);
  }
  assignMergeValue(object, key, newValue);
}

module.exports = baseMergeDeep;


/***/ }),
/* 833 */
/***/ (function(module, exports, __nested_webpack_require_4127898__) {

var isArrayLike = __nested_webpack_require_4127898__(98),
    isObjectLike = __nested_webpack_require_4127898__(56);

/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}

module.exports = isArrayLikeObject;


/***/ }),
/* 834 */
/***/ (function(module, exports, __nested_webpack_require_4128716__) {

var copyObject = __nested_webpack_require_4128716__(100),
    keysIn = __nested_webpack_require_4128716__(121);

/**
 * Converts `value` to a plain object flattening inherited enumerable string
 * keyed properties of `value` to own properties of the plain object.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {Object} Returns the converted plain object.
 * @example
 *
 * function Foo() {
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.assign({ 'a': 1 }, new Foo);
 * // => { 'a': 1, 'b': 2 }
 *
 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
 * // => { 'a': 1, 'b': 2, 'c': 3 }
 */
function toPlainObject(value) {
  return copyObject(value, keysIn(value));
}

module.exports = toPlainObject;


/***/ }),
/* 835 */
/***/ (function(module, exports, __nested_webpack_require_4129544__) {

var constant = __nested_webpack_require_4129544__(836),
    defineProperty = __nested_webpack_require_4129544__(426),
    identity = __nested_webpack_require_4129544__(143);

/**
 * The base implementation of `setToString` without support for hot loop shorting.
 *
 * @private
 * @param {Function} func The function to modify.
 * @param {Function} string The `toString` result.
 * @returns {Function} Returns `func`.
 */
var baseSetToString = !defineProperty ? identity : function(func, string) {
  return defineProperty(func, 'toString', {
    'configurable': true,
    'enumerable': false,
    'value': constant(string),
    'writable': true
  });
};

module.exports = baseSetToString;


/***/ }),
/* 836 */
/***/ (function(module, exports) {

/**
 * Creates a function that returns `value`.
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Util
 * @param {*} value The value to return from the new function.
 * @returns {Function} Returns the new constant function.
 * @example
 *
 * var objects = _.times(2, _.constant({ 'a': 1 }));
 *
 * console.log(objects);
 * // => [{ 'a': 1 }, { 'a': 1 }]
 *
 * console.log(objects[0] === objects[1]);
 * // => true
 */
function constant(value) {
  return function() {
    return value;
  };
}

module.exports = constant;


/***/ }),
/* 837 */
/***/ (function(module, exports, __nested_webpack_require_4130852__) {

"use strict";


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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4130852__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4130852__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _throttle = __nested_webpack_require_4130852__(838);

var _throttle2 = _interopRequireDefault(_throttle);

var _saturation = __nested_webpack_require_4130852__(840);

var saturation = _interopRequireWildcard(_saturation);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Saturation = exports.Saturation = function (_ref) {
  _inherits(Saturation, _ref);

  function Saturation(props) {
    _classCallCheck(this, Saturation);

    var _this = _possibleConstructorReturn(this, (Saturation.__proto__ || Object.getPrototypeOf(Saturation)).call(this, props));

    _this.handleChange = function (e, skip) {
      _this.props.onChange && _this.throttle(_this.props.onChange, saturation.calculateChange(e, skip, _this.props, _this.container), e);
    };

    _this.handleMouseDown = function (e) {
      _this.handleChange(e, true);
      window.addEventListener('mousemove', _this.handleChange);
      window.addEventListener('mouseup', _this.handleMouseUp);
    };

    _this.handleMouseUp = function () {
      _this.unbindEventListeners();
    };

    _this.throttle = (0, _throttle2.default)(function (fn, data, e) {
      fn(data, e);
    }, 50);
    return _this;
  }

  _createClass(Saturation, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.throttle.cancel();
      this.unbindEventListeners();
    }
  }, {
    key: 'unbindEventListeners',
    value: function unbindEventListeners() {
      window.removeEventListener('mousemove', this.handleChange);
      window.removeEventListener('mouseup', this.handleMouseUp);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _ref2 = this.props.style || {},
          color = _ref2.color,
          white = _ref2.white,
          black = _ref2.black,
          pointer = _ref2.pointer,
          circle = _ref2.circle;

      var styles = (0, _reactcss2.default)({
        'default': {
          color: {
            absolute: '0px 0px 0px 0px',
            background: 'hsl(' + this.props.hsl.h + ',100%, 50%)',
            borderRadius: this.props.radius
          },
          white: {
            absolute: '0px 0px 0px 0px',
            borderRadius: this.props.radius
          },
          black: {
            absolute: '0px 0px 0px 0px',
            boxShadow: this.props.shadow,
            borderRadius: this.props.radius
          },
          pointer: {
            position: 'absolute',
            top: -(this.props.hsv.v * 100) + 100 + '%',
            left: this.props.hsv.s * 100 + '%',
            cursor: 'default'
          },
          circle: {
            width: '4px',
            height: '4px',
            boxShadow: '0 0 0 1.5px #fff, inset 0 0 1px 1px rgba(0,0,0,.3),\n            0 0 1px 2px rgba(0,0,0,.4)',
            borderRadius: '50%',
            cursor: 'hand',
            transform: 'translate(-2px, -2px)'
          }
        },
        'custom': {
          color: color,
          white: white,
          black: black,
          pointer: pointer,
          circle: circle
        }
      }, { 'custom': !!this.props.style });

      return _react2.default.createElement(
        'div',
        {
          style: styles.color,
          ref: function ref(container) {
            return _this2.container = container;
          },
          onMouseDown: this.handleMouseDown,
          onTouchMove: this.handleChange,
          onTouchStart: this.handleChange
        },
        _react2.default.createElement(
          'style',
          null,
          '\n          .saturation-white {\n            background: -webkit-linear-gradient(to right, #fff, rgba(255,255,255,0));\n            background: linear-gradient(to right, #fff, rgba(255,255,255,0));\n          }\n          .saturation-black {\n            background: -webkit-linear-gradient(to top, #000, rgba(0,0,0,0));\n            background: linear-gradient(to top, #000, rgba(0,0,0,0));\n          }\n        '
        ),
        _react2.default.createElement(
          'div',
          { style: styles.white, className: 'saturation-white' },
          _react2.default.createElement('div', { style: styles.black, className: 'saturation-black' }),
          _react2.default.createElement(
            'div',
            { style: styles.pointer },
            this.props.pointer ? _react2.default.createElement(this.props.pointer, this.props) : _react2.default.createElement('div', { style: styles.circle })
          )
        )
      );
    }
  }]);

  return Saturation;
}(_react.PureComponent || _react.Component);

exports.default = Saturation;

/***/ }),
/* 838 */
/***/ (function(module, exports, __nested_webpack_require_4137570__) {

var debounce = __nested_webpack_require_4137570__(435),
    isObject = __nested_webpack_require_4137570__(45);

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a throttled function that only invokes `func` at most once per
 * every `wait` milliseconds. The throttled function comes with a `cancel`
 * method to cancel delayed `func` invocations and a `flush` method to
 * immediately invoke them. Provide `options` to indicate whether `func`
 * should be invoked on the leading and/or trailing edge of the `wait`
 * timeout. The `func` is invoked with the last arguments provided to the
 * throttled function. Subsequent calls to the throttled function return the
 * result of the last `func` invocation.
 *
 * **Note:** If `leading` and `trailing` options are `true`, `func` is
 * invoked on the trailing edge of the timeout only if the throttled function
 * is invoked more than once during the `wait` timeout.
 *
 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
 *
 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
 * for details over the differences between `_.throttle` and `_.debounce`.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Function
 * @param {Function} func The function to throttle.
 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
 * @param {Object} [options={}] The options object.
 * @param {boolean} [options.leading=true]
 *  Specify invoking on the leading edge of the timeout.
 * @param {boolean} [options.trailing=true]
 *  Specify invoking on the trailing edge of the timeout.
 * @returns {Function} Returns the new throttled function.
 * @example
 *
 * // Avoid excessively updating the position while scrolling.
 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
 *
 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
 * jQuery(element).on('click', throttled);
 *
 * // Cancel the trailing throttled invocation.
 * jQuery(window).on('popstate', throttled.cancel);
 */
function throttle(func, wait, options) {
  var leading = true,
      trailing = true;

  if (typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  if (isObject(options)) {
    leading = 'leading' in options ? !!options.leading : leading;
    trailing = 'trailing' in options ? !!options.trailing : trailing;
  }
  return debounce(func, wait, {
    'leading': leading,
    'maxWait': wait,
    'trailing': trailing
  });
}

module.exports = throttle;


/***/ }),
/* 839 */
/***/ (function(module, exports, __nested_webpack_require_4140363__) {

var root = __nested_webpack_require_4140363__(41);

/**
 * Gets the timestamp of the number of milliseconds that have elapsed since
 * the Unix epoch (1 January 1970 00:00:00 UTC).
 *
 * @static
 * @memberOf _
 * @since 2.4.0
 * @category Date
 * @returns {number} Returns the timestamp.
 * @example
 *
 * _.defer(function(stamp) {
 *   console.log(_.now() - stamp);
 * }, _.now());
 * // => Logs the number of milliseconds it took for the deferred invocation.
 */
var now = function() {
  return root.Date.now();
};

module.exports = now;


/***/ }),
/* 840 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var calculateChange = exports.calculateChange = function calculateChange(e, skip, props, container) {
  e.preventDefault();

  var _container$getBoundin = container.getBoundingClientRect(),
      containerWidth = _container$getBoundin.width,
      containerHeight = _container$getBoundin.height;

  var x = typeof e.pageX === 'number' ? e.pageX : e.touches[0].pageX;
  var y = typeof e.pageY === 'number' ? e.pageY : e.touches[0].pageY;
  var left = x - (container.getBoundingClientRect().left + window.pageXOffset);
  var top = y - (container.getBoundingClientRect().top + window.pageYOffset);

  if (left < 0) {
    left = 0;
  } else if (left > containerWidth) {
    left = containerWidth;
  } else if (top < 0) {
    top = 0;
  } else if (top > containerHeight) {
    top = containerHeight;
  }

  var saturation = left * 100 / containerWidth;
  var bright = -(top * 100 / containerHeight) + 100;

  return {
    h: props.hsl.h,
    s: saturation,
    v: bright,
    a: props.hsl.a,
    source: 'rgb'
  };
};

/***/ }),
/* 841 */
/***/ (function(module, exports, __nested_webpack_require_4142139__) {

module.exports = __nested_webpack_require_4142139__(147);


/***/ }),
/* 842 */
/***/ (function(module, exports, __nested_webpack_require_4142261__) {

var __WEBPACK_AMD_DEFINE_RESULT__;// TinyColor v1.4.1
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License

(function(Math) {

var trimLeft = /^\s+/,
    trimRight = /\s+$/,
    tinyCounter = 0,
    mathRound = Math.round,
    mathMin = Math.min,
    mathMax = Math.max,
    mathRandom = Math.random;

function tinycolor (color, opts) {

    color = (color) ? color : '';
    opts = opts || { };

    // If input is already a tinycolor, return itself
    if (color instanceof tinycolor) {
       return color;
    }
    // If we are called as a function, call using new instead
    if (!(this instanceof tinycolor)) {
        return new tinycolor(color, opts);
    }

    var rgb = inputToRGB(color);
    this._originalInput = color,
    this._r = rgb.r,
    this._g = rgb.g,
    this._b = rgb.b,
    this._a = rgb.a,
    this._roundA = mathRound(100*this._a) / 100,
    this._format = opts.format || rgb.format;
    this._gradientType = opts.gradientType;

    // Don't let the range of [0,255] come back in [0,1].
    // Potentially lose a little bit of precision here, but will fix issues where
    // .5 gets interpreted as half of the total, instead of half of 1
    // If it was supposed to be 128, this was already taken care of by `inputToRgb`
    if (this._r < 1) { this._r = mathRound(this._r); }
    if (this._g < 1) { this._g = mathRound(this._g); }
    if (this._b < 1) { this._b = mathRound(this._b); }

    this._ok = rgb.ok;
    this._tc_id = tinyCounter++;
}

tinycolor.prototype = {
    isDark: function() {
        return this.getBrightness() < 128;
    },
    isLight: function() {
        return !this.isDark();
    },
    isValid: function() {
        return this._ok;
    },
    getOriginalInput: function() {
      return this._originalInput;
    },
    getFormat: function() {
        return this._format;
    },
    getAlpha: function() {
        return this._a;
    },
    getBrightness: function() {
        //http://www.w3.org/TR/AERT#color-contrast
        var rgb = this.toRgb();
        return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
    },
    getLuminance: function() {
        //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
        var rgb = this.toRgb();
        var RsRGB, GsRGB, BsRGB, R, G, B;
        RsRGB = rgb.r/255;
        GsRGB = rgb.g/255;
        BsRGB = rgb.b/255;

        if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
        if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
        if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
        return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
    },
    setAlpha: function(value) {
        this._a = boundAlpha(value);
        this._roundA = mathRound(100*this._a) / 100;
        return this;
    },
    toHsv: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
    },
    toHsvString: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
        return (this._a == 1) ?
          "hsv("  + h + ", " + s + "%, " + v + "%)" :
          "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
    },
    toHsl: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
    },
    toHslString: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
        return (this._a == 1) ?
          "hsl("  + h + ", " + s + "%, " + l + "%)" :
          "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
    },
    toHex: function(allow3Char) {
        return rgbToHex(this._r, this._g, this._b, allow3Char);
    },
    toHexString: function(allow3Char) {
        return '#' + this.toHex(allow3Char);
    },
    toHex8: function(allow4Char) {
        return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
    },
    toHex8String: function(allow4Char) {
        return '#' + this.toHex8(allow4Char);
    },
    toRgb: function() {
        return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
    },
    toRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
          "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
    },
    toPercentageRgb: function() {
        return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
    },
    toPercentageRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
          "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
    },
    toName: function() {
        if (this._a === 0) {
            return "transparent";
        }

        if (this._a < 1) {
            return false;
        }

        return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
    },
    toFilter: function(secondColor) {
        var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
        var secondHex8String = hex8String;
        var gradientType = this._gradientType ? "GradientType = 1, " : "";

        if (secondColor) {
            var s = tinycolor(secondColor);
            secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
        }

        return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
    },
    toString: function(format) {
        var formatSet = !!format;
        format = format || this._format;

        var formattedString = false;
        var hasAlpha = this._a < 1 && this._a >= 0;
        var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");

        if (needsAlphaFormat) {
            // Special case for "transparent", all other non-alpha formats
            // will return rgba when there is transparency.
            if (format === "name" && this._a === 0) {
                return this.toName();
            }
            return this.toRgbString();
        }
        if (format === "rgb") {
            formattedString = this.toRgbString();
        }
        if (format === "prgb") {
            formattedString = this.toPercentageRgbString();
        }
        if (format === "hex" || format === "hex6") {
            formattedString = this.toHexString();
        }
        if (format === "hex3") {
            formattedString = this.toHexString(true);
        }
        if (format === "hex4") {
            formattedString = this.toHex8String(true);
        }
        if (format === "hex8") {
            formattedString = this.toHex8String();
        }
        if (format === "name") {
            formattedString = this.toName();
        }
        if (format === "hsl") {
            formattedString = this.toHslString();
        }
        if (format === "hsv") {
            formattedString = this.toHsvString();
        }

        return formattedString || this.toHexString();
    },
    clone: function() {
        return tinycolor(this.toString());
    },

    _applyModification: function(fn, args) {
        var color = fn.apply(null, [this].concat([].slice.call(args)));
        this._r = color._r;
        this._g = color._g;
        this._b = color._b;
        this.setAlpha(color._a);
        return this;
    },
    lighten: function() {
        return this._applyModification(lighten, arguments);
    },
    brighten: function() {
        return this._applyModification(brighten, arguments);
    },
    darken: function() {
        return this._applyModification(darken, arguments);
    },
    desaturate: function() {
        return this._applyModification(desaturate, arguments);
    },
    saturate: function() {
        return this._applyModification(saturate, arguments);
    },
    greyscale: function() {
        return this._applyModification(greyscale, arguments);
    },
    spin: function() {
        return this._applyModification(spin, arguments);
    },

    _applyCombination: function(fn, args) {
        return fn.apply(null, [this].concat([].slice.call(args)));
    },
    analogous: function() {
        return this._applyCombination(analogous, arguments);
    },
    complement: function() {
        return this._applyCombination(complement, arguments);
    },
    monochromatic: function() {
        return this._applyCombination(monochromatic, arguments);
    },
    splitcomplement: function() {
        return this._applyCombination(splitcomplement, arguments);
    },
    triad: function() {
        return this._applyCombination(triad, arguments);
    },
    tetrad: function() {
        return this._applyCombination(tetrad, arguments);
    }
};

// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
    if (typeof color == "object") {
        var newColor = {};
        for (var i in color) {
            if (color.hasOwnProperty(i)) {
                if (i === "a") {
                    newColor[i] = color[i];
                }
                else {
                    newColor[i] = convertToPercentage(color[i]);
                }
            }
        }
        color = newColor;
    }

    return tinycolor(color, opts);
};

// Given a string or object, convert that input to RGB
// Possible string inputs:
//
//     "red"
//     "#f00" or "f00"
//     "#ff0000" or "ff0000"
//     "#ff000000" or "ff000000"
//     "rgb 255 0 0" or "rgb (255, 0, 0)"
//     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
//     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
//     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
//     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
//     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
//     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;
    var s = null;
    var v = null;
    var l = null;
    var ok = false;
    var format = false;

    if (typeof color == "string") {
        color = stringInputToObject(color);
    }

    if (typeof color == "object") {
        if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s, v);
            ok = true;
            format = "hsv";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s = convertToPercentage(color.s);
            l = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s, l);
            ok = true;
            format = "hsl";
        }

        if (color.hasOwnProperty("a")) {
            a = color.a;
        }
    }

    a = boundAlpha(a);

    return {
        ok: ok,
        format: color.format || format,
        r: mathMin(255, mathMax(rgb.r, 0)),
        g: mathMin(255, mathMax(rgb.g, 0)),
        b: mathMin(255, mathMax(rgb.b, 0)),
        a: a
    };
}


// Conversion Functions
// --------------------

// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
    return {
        r: bound01(r, 255) * 255,
        g: bound01(g, 255) * 255,
        b: bound01(b, 255) * 255
    };
}

// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min) {
        h = s = 0; // achromatic
    }
    else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }

        h /= 6;
    }

    return { h: h, s: s, l: l };
}

// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
    var r, g, b;

    h = bound01(h, 360);
    s = bound01(s, 100);
    l = bound01(l, 100);

    function hue2rgb(p, q, t) {
        if(t < 0) t += 1;
        if(t > 1) t -= 1;
        if(t < 1/6) return p + (q - p) * 6 * t;
        if(t < 1/2) return q;
        if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
        return p;
    }

    if(s === 0) {
        r = g = b = l; // achromatic
    }
    else {
        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, v = max;

    var d = max - min;
    s = max === 0 ? 0 : d / max;

    if(max == min) {
        h = 0; // achromatic
    }
    else {
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }
    return { h: h, s: s, v: v };
}

// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
 function hsvToRgb(h, s, v) {

    h = bound01(h, 360) * 6;
    s = bound01(s, 100);
    v = bound01(v, 100);

    var i = Math.floor(h),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s),
        mod = i % 6,
        r = [v, q, p, p, t, v][mod],
        g = [t, v, v, q, p, p][mod],
        b = [p, p, t, v, v, q][mod];

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    // Return a 3 character hex if possible
    if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
    }

    return hex.join("");
}

// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b are contained in the set [0, 255] and
// a in [0, 1]. Returns a 4 or 8 character rgba hex
function rgbaToHex(r, g, b, a, allow4Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16)),
        pad2(convertDecimalToHex(a))
    ];

    // Return a 4 character hex if possible
    if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
    }

    return hex.join("");
}

// `rgbaToArgbHex`
// Converts an RGBA color to an ARGB Hex8 string
// Rarely used, but required for "toFilter()"
function rgbaToArgbHex(r, g, b, a) {

    var hex = [
        pad2(convertDecimalToHex(a)),
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    return hex.join("");
}

// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
    if (!color1 || !color2) { return false; }
    return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};

tinycolor.random = function() {
    return tinycolor.fromRatio({
        r: mathRandom(),
        g: mathRandom(),
        b: mathRandom()
    });
};


// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

function desaturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s -= amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function saturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s += amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function greyscale(color) {
    return tinycolor(color).desaturate(100);
}

function lighten (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l += amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

function brighten(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var rgb = tinycolor(color).toRgb();
    rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
    rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
    rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
    return tinycolor(rgb);
}

function darken (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l -= amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
    var hsl = tinycolor(color).toHsl();
    var hue = (hsl.h + amount) % 360;
    hsl.h = hue < 0 ? 360 + hue : hue;
    return tinycolor(hsl);
}

// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

function complement(color) {
    var hsl = tinycolor(color).toHsl();
    hsl.h = (hsl.h + 180) % 360;
    return tinycolor(hsl);
}

function triad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
    ];
}

function tetrad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
    ];
}

function splitcomplement(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
        tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
    ];
}

function analogous(color, results, slices) {
    results = results || 6;
    slices = slices || 30;

    var hsl = tinycolor(color).toHsl();
    var part = 360 / slices;
    var ret = [tinycolor(color)];

    for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
        hsl.h = (hsl.h + part) % 360;
        ret.push(tinycolor(hsl));
    }
    return ret;
}

function monochromatic(color, results) {
    results = results || 6;
    var hsv = tinycolor(color).toHsv();
    var h = hsv.h, s = hsv.s, v = hsv.v;
    var ret = [];
    var modification = 1 / results;

    while (results--) {
        ret.push(tinycolor({ h: h, s: s, v: v}));
        v = (v + modification) % 1;
    }

    return ret;
}

// Utility Functions
// ---------------------

tinycolor.mix = function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
};


// Readability Functions
// ---------------------
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)

// `contrast`
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
tinycolor.readability = function(color1, color2) {
    var c1 = tinycolor(color1);
    var c2 = tinycolor(color2);
    return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
};

// `isReadable`
// Ensure that foreground and background color combinations meet WCAG2 guidelines.
// The third argument is an optional Object.
//      the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
//      the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.

// *Example*
//    tinycolor.isReadable("#000", "#111") => false
//    tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
tinycolor.isReadable = function(color1, color2, wcag2) {
    var readability = tinycolor.readability(color1, color2);
    var wcag2Parms, out;

    out = false;

    wcag2Parms = validateWCAG2Parms(wcag2);
    switch (wcag2Parms.level + wcag2Parms.size) {
        case "AAsmall":
        case "AAAlarge":
            out = readability >= 4.5;
            break;
        case "AAlarge":
            out = readability >= 3;
            break;
        case "AAAsmall":
            out = readability >= 7;
            break;
    }
    return out;

};

// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// Optionally returns Black or White if the most readable color is unreadable.
// *Example*
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
tinycolor.mostReadable = function(baseColor, colorList, args) {
    var bestColor = null;
    var bestScore = 0;
    var readability;
    var includeFallbackColors, level, size ;
    args = args || {};
    includeFallbackColors = args.includeFallbackColors ;
    level = args.level;
    size = args.size;

    for (var i= 0; i < colorList.length ; i++) {
        readability = tinycolor.readability(baseColor, colorList[i]);
        if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
        }
    }

    if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
        return bestColor;
    }
    else {
        args.includeFallbackColors=false;
        return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
    }
};


// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
    aliceblue: "f0f8ff",
    antiquewhite: "faebd7",
    aqua: "0ff",
    aquamarine: "7fffd4",
    azure: "f0ffff",
    beige: "f5f5dc",
    bisque: "ffe4c4",
    black: "000",
    blanchedalmond: "ffebcd",
    blue: "00f",
    blueviolet: "8a2be2",
    brown: "a52a2a",
    burlywood: "deb887",
    burntsienna: "ea7e5d",
    cadetblue: "5f9ea0",
    chartreuse: "7fff00",
    chocolate: "d2691e",
    coral: "ff7f50",
    cornflowerblue: "6495ed",
    cornsilk: "fff8dc",
    crimson: "dc143c",
    cyan: "0ff",
    darkblue: "00008b",
    darkcyan: "008b8b",
    darkgoldenrod: "b8860b",
    darkgray: "a9a9a9",
    darkgreen: "006400",
    darkgrey: "a9a9a9",
    darkkhaki: "bdb76b",
    darkmagenta: "8b008b",
    darkolivegreen: "556b2f",
    darkorange: "ff8c00",
    darkorchid: "9932cc",
    darkred: "8b0000",
    darksalmon: "e9967a",
    darkseagreen: "8fbc8f",
    darkslateblue: "483d8b",
    darkslategray: "2f4f4f",
    darkslategrey: "2f4f4f",
    darkturquoise: "00ced1",
    darkviolet: "9400d3",
    deeppink: "ff1493",
    deepskyblue: "00bfff",
    dimgray: "696969",
    dimgrey: "696969",
    dodgerblue: "1e90ff",
    firebrick: "b22222",
    floralwhite: "fffaf0",
    forestgreen: "228b22",
    fuchsia: "f0f",
    gainsboro: "dcdcdc",
    ghostwhite: "f8f8ff",
    gold: "ffd700",
    goldenrod: "daa520",
    gray: "808080",
    green: "008000",
    greenyellow: "adff2f",
    grey: "808080",
    honeydew: "f0fff0",
    hotpink: "ff69b4",
    indianred: "cd5c5c",
    indigo: "4b0082",
    ivory: "fffff0",
    khaki: "f0e68c",
    lavender: "e6e6fa",
    lavenderblush: "fff0f5",
    lawngreen: "7cfc00",
    lemonchiffon: "fffacd",
    lightblue: "add8e6",
    lightcoral: "f08080",
    lightcyan: "e0ffff",
    lightgoldenrodyellow: "fafad2",
    lightgray: "d3d3d3",
    lightgreen: "90ee90",
    lightgrey: "d3d3d3",
    lightpink: "ffb6c1",
    lightsalmon: "ffa07a",
    lightseagreen: "20b2aa",
    lightskyblue: "87cefa",
    lightslategray: "789",
    lightslategrey: "789",
    lightsteelblue: "b0c4de",
    lightyellow: "ffffe0",
    lime: "0f0",
    limegreen: "32cd32",
    linen: "faf0e6",
    magenta: "f0f",
    maroon: "800000",
    mediumaquamarine: "66cdaa",
    mediumblue: "0000cd",
    mediumorchid: "ba55d3",
    mediumpurple: "9370db",
    mediumseagreen: "3cb371",
    mediumslateblue: "7b68ee",
    mediumspringgreen: "00fa9a",
    mediumturquoise: "48d1cc",
    mediumvioletred: "c71585",
    midnightblue: "191970",
    mintcream: "f5fffa",
    mistyrose: "ffe4e1",
    moccasin: "ffe4b5",
    navajowhite: "ffdead",
    navy: "000080",
    oldlace: "fdf5e6",
    olive: "808000",
    olivedrab: "6b8e23",
    orange: "ffa500",
    orangered: "ff4500",
    orchid: "da70d6",
    palegoldenrod: "eee8aa",
    palegreen: "98fb98",
    paleturquoise: "afeeee",
    palevioletred: "db7093",
    papayawhip: "ffefd5",
    peachpuff: "ffdab9",
    peru: "cd853f",
    pink: "ffc0cb",
    plum: "dda0dd",
    powderblue: "b0e0e6",
    purple: "800080",
    rebeccapurple: "663399",
    red: "f00",
    rosybrown: "bc8f8f",
    royalblue: "4169e1",
    saddlebrown: "8b4513",
    salmon: "fa8072",
    sandybrown: "f4a460",
    seagreen: "2e8b57",
    seashell: "fff5ee",
    sienna: "a0522d",
    silver: "c0c0c0",
    skyblue: "87ceeb",
    slateblue: "6a5acd",
    slategray: "708090",
    slategrey: "708090",
    snow: "fffafa",
    springgreen: "00ff7f",
    steelblue: "4682b4",
    tan: "d2b48c",
    teal: "008080",
    thistle: "d8bfd8",
    tomato: "ff6347",
    turquoise: "40e0d0",
    violet: "ee82ee",
    wheat: "f5deb3",
    white: "fff",
    whitesmoke: "f5f5f5",
    yellow: "ff0",
    yellowgreen: "9acd32"
};

// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);


// Utilities
// ---------

// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
    var flipped = { };
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            flipped[o[i]] = i;
        }
    }
    return flipped;
}

// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
    a = parseFloat(a);

    if (isNaN(a) || a < 0 || a > 1) {
        a = 1;
    }

    return a;
}

// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
    if (isOnePointZero(n)) { n = "100%"; }

    var processPercent = isPercentage(n);
    n = mathMin(max, mathMax(0, parseFloat(n)));

    // Automatically convert percentage into number
    if (processPercent) {
        n = parseInt(n * max, 10) / 100;
    }

    // Handle floating point rounding errors
    if ((Math.abs(n - max) < 0.000001)) {
        return 1;
    }

    // Convert into [0, 1] range if it isn't already
    return (n % max) / parseFloat(max);
}

// Force a number between 0 and 1
function clamp01(val) {
    return mathMin(1, mathMax(0, val));
}

// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
    return parseInt(val, 16);
}

// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
    return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}

// Check to see if string passed in is a percentage
function isPercentage(n) {
    return typeof n === "string" && n.indexOf('%') != -1;
}

// Force a hex value to have 2 characters
function pad2(c) {
    return c.length == 1 ? '0' + c : '' + c;
}

// Replace a decimal with it's percentage value
function convertToPercentage(n) {
    if (n <= 1) {
        n = (n * 100) + "%";
    }

    return n;
}

// Converts a decimal to a hex value
function convertDecimalToHex(d) {
    return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
    return (parseIntFromHex(h) / 255);
}

var matchers = (function() {

    // <http://www.w3.org/TR/css3-values/#integers>
    var CSS_INTEGER = "[-\\+]?\\d+%?";

    // <http://www.w3.org/TR/css3-values/#number-value>
    var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

    // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
    var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

    // Actual matching.
    // Parentheses and commas are optional, but not required.
    // Whitespace can take the place of commas or opening paren
    var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
    var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

    return {
        CSS_UNIT: new RegExp(CSS_UNIT),
        rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
        rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
        hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
        hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
        hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
        hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
        hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
        hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
    };
})();

// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
function isValidCSSUnit(color) {
    return !!matchers.CSS_UNIT.exec(color);
}

// `stringInputToObject`
// Permissive string parsing.  Take in a number of formats, and output an object
// based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {

    color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
    var named = false;
    if (names[color]) {
        color = names[color];
        named = true;
    }
    else if (color == 'transparent') {
        return { r: 0, g: 0, b: 0, a: 0, format: "name" };
    }

    // Try to match string input using regular expressions.
    // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
    // Just return an object and let the conversion functions handle that.
    // This way the result will be the same whether the tinycolor is initialized with string or object.
    var match;
    if ((match = matchers.rgb.exec(color))) {
        return { r: match[1], g: match[2], b: match[3] };
    }
    if ((match = matchers.rgba.exec(color))) {
        return { r: match[1], g: match[2], b: match[3], a: match[4] };
    }
    if ((match = matchers.hsl.exec(color))) {
        return { h: match[1], s: match[2], l: match[3] };
    }
    if ((match = matchers.hsla.exec(color))) {
        return { h: match[1], s: match[2], l: match[3], a: match[4] };
    }
    if ((match = matchers.hsv.exec(color))) {
        return { h: match[1], s: match[2], v: match[3] };
    }
    if ((match = matchers.hsva.exec(color))) {
        return { h: match[1], s: match[2], v: match[3], a: match[4] };
    }
    if ((match = matchers.hex8.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            a: convertHexToDecimal(match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex6.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            format: named ? "name" : "hex"
        };
    }
    if ((match = matchers.hex4.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            a: convertHexToDecimal(match[4] + '' + match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex3.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            format: named ? "name" : "hex"
        };
    }

    return false;
}

function validateWCAG2Parms(parms) {
    // return valid WCAG2 parms for isReadable.
    // If input parms are invalid, return {"level":"AA", "size":"small"}
    var level, size;
    parms = parms || {"level":"AA", "size":"small"};
    level = (parms.level || "AA").toUpperCase();
    size = (parms.size || "small").toLowerCase();
    if (level !== "AA" && level !== "AAA") {
        level = "AA";
    }
    if (size !== "small" && size !== "large") {
        size = "small";
    }
    return {"level":level, "size":size};
}

// Node: Export function
if (  true && module.exports) {
    module.exports = tinycolor;
}
// AMD/requirejs: Define the module
else if (true) {
    !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {return tinycolor;}).call(exports, __nested_webpack_require_4142261__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// Browser: Expose to window
else {}

})(Math);


/***/ }),
/* 843 */
/***/ (function(module, exports, __nested_webpack_require_4179158__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4179158__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4179158__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _interaction = __nested_webpack_require_4179158__(844);

var _Checkboard = __nested_webpack_require_4179158__(289);

var _Checkboard2 = _interopRequireDefault(_Checkboard);

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

var ENTER = 13;

var Swatch = exports.Swatch = function Swatch(_ref) {
  var color = _ref.color,
      style = _ref.style,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onHover = _ref.onHover,
      _ref$title = _ref.title,
      title = _ref$title === undefined ? color : _ref$title,
      children = _ref.children,
      focus = _ref.focus,
      _ref$focusStyle = _ref.focusStyle,
      focusStyle = _ref$focusStyle === undefined ? {} : _ref$focusStyle;

  var transparent = color === 'transparent';
  var styles = (0, _reactcss2.default)({
    default: {
      swatch: _extends({
        background: color,
        height: '100%',
        width: '100%',
        cursor: 'pointer',
        position: 'relative',
        outline: 'none'
      }, style, focus ? focusStyle : {})
    }
  });

  var handleClick = function handleClick(e) {
    return onClick(color, e);
  };
  var handleKeyDown = function handleKeyDown(e) {
    return e.keyCode === ENTER && onClick(color, e);
  };
  var handleHover = function handleHover(e) {
    return onHover(color, e);
  };

  var optionalEvents = {};
  if (onHover) {
    optionalEvents.onMouseOver = handleHover;
  }

  return _react2.default.createElement(
    'div',
    _extends({
      style: styles.swatch,
      onClick: handleClick,
      title: title,
      tabIndex: 0,
      onKeyDown: handleKeyDown
    }, optionalEvents),
    children,
    transparent && _react2.default.createElement(_Checkboard2.default, {
      borderRadius: styles.swatch.borderRadius,
      boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)'
    })
  );
};

exports.default = (0, _interaction.handleFocus)(Swatch);

/***/ }),
/* 844 */
/***/ (function(module, exports, __nested_webpack_require_4181735__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4181735__(1);

var _react2 = _interopRequireDefault(_react);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable no-invalid-this */


var handleFocus = exports.handleFocus = function handleFocus(Component) {
  var Span = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'span';
  return function (_React$Component) {
    _inherits(Focus, _React$Component);

    function Focus() {
      var _ref;

      var _temp, _this, _ret;

      _classCallCheck(this, Focus);

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

      return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Focus.__proto__ || Object.getPrototypeOf(Focus)).call.apply(_ref, [this].concat(args))), _this), _this.state = { focus: false }, _this.handleFocus = function () {
        return _this.setState({ focus: true });
      }, _this.handleBlur = function () {
        return _this.setState({ focus: false });
      }, _temp), _possibleConstructorReturn(_this, _ret);
    }

    _createClass(Focus, [{
      key: 'render',
      value: function render() {
        return _react2.default.createElement(
          Span,
          { onFocus: this.handleFocus, onBlur: this.handleBlur },
          _react2.default.createElement(Component, _extends({}, this.props, this.state))
        );
      }
    }]);

    return Focus;
  }(_react2.default.Component);
};

/***/ }),
/* 845 */
/***/ (function(module, exports, __nested_webpack_require_4185183__) {

"use strict";


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

var _react = __nested_webpack_require_4185183__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4185183__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var AlphaPointer = exports.AlphaPointer = function AlphaPointer(_ref) {
  var direction = _ref.direction;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '18px',
        height: '18px',
        borderRadius: '50%',
        transform: 'translate(-9px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    },
    'vertical': {
      picker: {
        transform: 'translate(-3px, -9px)'
      }
    }
  }, { vertical: direction === 'vertical' });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = AlphaPointer;

/***/ }),
/* 846 */
/***/ (function(module, exports, __nested_webpack_require_4186317__) {

"use strict";


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

var _react = __nested_webpack_require_4186317__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4186317__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4186317__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4186317__(46);

var _merge2 = _interopRequireDefault(_merge);

var _color = __nested_webpack_require_4186317__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4186317__(22);

var _BlockSwatches = __nested_webpack_require_4186317__(847);

var _BlockSwatches2 = _interopRequireDefault(_BlockSwatches);

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

var Block = exports.Block = function Block(_ref) {
  var onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      hex = _ref.hex,
      colors = _ref.colors,
      width = _ref.width,
      triangle = _ref.triangle,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var transparent = hex === 'transparent';
  var handleChange = function handleChange(hexCode, e) {
    _color2.default.isValidHex(hexCode) && onChange({
      hex: hexCode,
      source: 'hex'
    }, e);
  };

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        background: '#fff',
        boxShadow: '0 1px rgba(0,0,0,.1)',
        borderRadius: '6px',
        position: 'relative'
      },
      head: {
        height: '110px',
        background: hex,
        borderRadius: '6px 6px 0 0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative'
      },
      body: {
        padding: '10px'
      },
      label: {
        fontSize: '18px',
        color: _color2.default.getContrastingColor(hex),
        position: 'relative'
      },
      triangle: {
        width: '0px',
        height: '0px',
        borderStyle: 'solid',
        borderWidth: '0 10px 10px 10px',
        borderColor: 'transparent transparent ' + hex + ' transparent',
        position: 'absolute',
        top: '-10px',
        left: '50%',
        marginLeft: '-10px'
      },
      input: {
        width: '100%',
        fontSize: '12px',
        color: '#666',
        border: '0px',
        outline: 'none',
        height: '22px',
        boxShadow: 'inset 0 0 0 1px #ddd',
        borderRadius: '4px',
        padding: '0 7px',
        boxSizing: 'border-box'
      }
    },
    'hide-triangle': {
      triangle: {
        display: 'none'
      }
    }
  }, passedStyles), { 'hide-triangle': triangle === 'hide' });

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'block-picker ' + className },
    _react2.default.createElement('div', { style: styles.triangle }),
    _react2.default.createElement(
      'div',
      { style: styles.head },
      transparent && _react2.default.createElement(_common.Checkboard, { borderRadius: '6px 6px 0 0' }),
      _react2.default.createElement(
        'div',
        { style: styles.label },
        hex
      )
    ),
    _react2.default.createElement(
      'div',
      { style: styles.body },
      _react2.default.createElement(_BlockSwatches2.default, { colors: colors, onClick: handleChange, onSwatchHover: onSwatchHover }),
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input },
        value: hex,
        onChange: handleChange
      })
    )
  );
};

Block.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  triangle: _propTypes2.default.oneOf(['top', 'hide']),
  styles: _propTypes2.default.object
};

Block.defaultProps = {
  width: 170,
  colors: ['#D9E3F0', '#F47373', '#697689', '#37D67A', '#2CCCE4', '#555555', '#dce775', '#ff8a65', '#ba68c8'],
  triangle: 'top',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Block);

/***/ }),
/* 847 */
/***/ (function(module, exports, __nested_webpack_require_4190670__) {

"use strict";


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

var _react = __nested_webpack_require_4190670__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4190670__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4190670__(70);

var _map2 = _interopRequireDefault(_map);

var _common = __nested_webpack_require_4190670__(22);

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

var BlockSwatches = exports.BlockSwatches = function BlockSwatches(_ref) {
  var colors = _ref.colors,
      onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatches: {
        marginRight: '-10px'
      },
      swatch: {
        width: '22px',
        height: '22px',
        float: 'left',
        marginRight: '10px',
        marginBottom: '10px',
        borderRadius: '4px'
      },
      clear: {
        clear: 'both'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.swatches },
    (0, _map2.default)(colors, function (c) {
      return _react2.default.createElement(_common.Swatch, {
        key: c,
        color: c,
        style: styles.swatch,
        onClick: onClick,
        onHover: onSwatchHover,
        focusStyle: {
          boxShadow: '0 0 4px ' + c
        }
      });
    }),
    _react2.default.createElement('div', { style: styles.clear })
  );
};

exports.default = BlockSwatches;

/***/ }),
/* 848 */
/***/ (function(module, exports, __nested_webpack_require_4192298__) {

"use strict";


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

var _react = __nested_webpack_require_4192298__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4192298__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4192298__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4192298__(70);

var _map2 = _interopRequireDefault(_map);

var _merge = __nested_webpack_require_4192298__(46);

var _merge2 = _interopRequireDefault(_merge);

var _materialColors = __nested_webpack_require_4192298__(438);

var material = _interopRequireWildcard(_materialColors);

var _common = __nested_webpack_require_4192298__(22);

var _CircleSwatch = __nested_webpack_require_4192298__(849);

var _CircleSwatch2 = _interopRequireDefault(_CircleSwatch);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

var Circle = exports.Circle = function Circle(_ref) {
  var width = _ref.width,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      colors = _ref.colors,
      hex = _ref.hex,
      circleSize = _ref.circleSize,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      circleSpacing = _ref.circleSpacing,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        display: 'flex',
        flexWrap: 'wrap',
        marginRight: -circleSpacing,
        marginBottom: -circleSpacing
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(hexCode, e) {
    return onChange({ hex: hexCode, source: 'hex' }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'circle-picker ' + className },
    (0, _map2.default)(colors, function (c) {
      return _react2.default.createElement(_CircleSwatch2.default, {
        key: c,
        color: c,
        onClick: handleChange,
        onSwatchHover: onSwatchHover,
        active: hex === c.toLowerCase(),
        circleSize: circleSize,
        circleSpacing: circleSpacing
      });
    })
  );
};

Circle.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  circleSize: _propTypes2.default.number,
  circleSpacing: _propTypes2.default.number,
  styles: _propTypes2.default.object
};

Circle.defaultProps = {
  width: 252,
  circleSize: 28,
  circleSpacing: 14,
  colors: [material.red['500'], material.pink['500'], material.purple['500'], material.deepPurple['500'], material.indigo['500'], material.blue['500'], material.lightBlue['500'], material.cyan['500'], material.teal['500'], material.green['500'], material.lightGreen['500'], material.lime['500'], material.yellow['500'], material.amber['500'], material.orange['500'], material.deepOrange['500'], material.brown['500'], material.blueGrey['500']],
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Circle);

/***/ }),
/* 849 */
/***/ (function(module, exports, __nested_webpack_require_4195750__) {

"use strict";


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

var _react = __nested_webpack_require_4195750__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4195750__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __nested_webpack_require_4195750__(22);

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

var CircleSwatch = exports.CircleSwatch = function CircleSwatch(_ref) {
  var color = _ref.color,
      onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover,
      hover = _ref.hover,
      active = _ref.active,
      circleSize = _ref.circleSize,
      circleSpacing = _ref.circleSpacing;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatch: {
        width: circleSize,
        height: circleSize,
        marginRight: circleSpacing,
        marginBottom: circleSpacing,
        transform: 'scale(1)',
        transition: '100ms transform ease'
      },
      Swatch: {
        borderRadius: '50%',
        background: 'transparent',
        boxShadow: 'inset 0 0 0 ' + circleSize / 2 + 'px ' + color,
        transition: '100ms box-shadow ease'
      }
    },
    'hover': {
      swatch: {
        transform: 'scale(1.2)'
      }
    },
    'active': {
      Swatch: {
        boxShadow: 'inset 0 0 0 3px ' + color
      }
    }
  }, { hover: hover, active: active });

  return _react2.default.createElement(
    'div',
    { style: styles.swatch },
    _react2.default.createElement(_common.Swatch, {
      style: styles.Swatch,
      color: color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: { boxShadow: styles.Swatch.boxShadow + ', 0 0 5px ' + color }
    })
  );
};

CircleSwatch.defaultProps = {
  circleSize: 28,
  circleSpacing: 14
};

exports.default = (0, _reactcss.handleHover)(CircleSwatch);

/***/ }),
/* 850 */
/***/ (function(module, exports, __nested_webpack_require_4197730__) {

"use strict";


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

var _react = __nested_webpack_require_4197730__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4197730__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4197730__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4197730__(46);

var _merge2 = _interopRequireDefault(_merge);

var _common = __nested_webpack_require_4197730__(22);

var _ChromeFields = __nested_webpack_require_4197730__(851);

var _ChromeFields2 = _interopRequireDefault(_ChromeFields);

var _ChromePointer = __nested_webpack_require_4197730__(853);

var _ChromePointer2 = _interopRequireDefault(_ChromePointer);

var _ChromePointerCircle = __nested_webpack_require_4197730__(854);

var _ChromePointerCircle2 = _interopRequireDefault(_ChromePointerCircle);

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

var Chrome = exports.Chrome = function Chrome(_ref) {
  var onChange = _ref.onChange,
      disableAlpha = _ref.disableAlpha,
      rgb = _ref.rgb,
      hsl = _ref.hsl,
      hsv = _ref.hsv,
      hex = _ref.hex,
      renderers = _ref.renderers,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      picker: {
        background: '#fff',
        borderRadius: '2px',
        boxShadow: '0 0 2px rgba(0,0,0,.3), 0 4px 8px rgba(0,0,0,.3)',
        boxSizing: 'initial',
        width: '225px',
        fontFamily: 'Menlo'
      },
      saturation: {
        width: '100%',
        paddingBottom: '55%',
        position: 'relative',
        borderRadius: '2px 2px 0 0',
        overflow: 'hidden'
      },
      Saturation: {
        radius: '2px 2px 0 0'
      },
      body: {
        padding: '16px 16px 12px'
      },
      controls: {
        display: 'flex'
      },
      color: {
        width: '32px'
      },
      swatch: {
        marginTop: '6px',
        width: '16px',
        height: '16px',
        borderRadius: '8px',
        position: 'relative',
        overflow: 'hidden'
      },
      active: {
        absolute: '0px 0px 0px 0px',
        borderRadius: '8px',
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.1)',
        background: 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + rgb.a + ')',
        zIndex: '2'
      },
      toggles: {
        flex: '1'
      },
      hue: {
        height: '10px',
        position: 'relative',
        marginBottom: '8px'
      },
      Hue: {
        radius: '2px'
      },
      alpha: {
        height: '10px',
        position: 'relative'
      },
      Alpha: {
        radius: '2px'
      }
    },
    'disableAlpha': {
      color: {
        width: '22px'
      },
      alpha: {
        display: 'none'
      },
      hue: {
        marginBottom: '0px'
      },
      swatch: {
        width: '10px',
        height: '10px',
        marginTop: '0px'
      }
    }
  }, passedStyles), { disableAlpha: disableAlpha });

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'chrome-picker ' + className },
    _react2.default.createElement(
      'div',
      { style: styles.saturation },
      _react2.default.createElement(_common.Saturation, {
        style: styles.Saturation,
        hsl: hsl,
        hsv: hsv,
        pointer: _ChromePointerCircle2.default,
        onChange: onChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.body },
      _react2.default.createElement(
        'div',
        { style: styles.controls, className: 'flexbox-fix' },
        _react2.default.createElement(
          'div',
          { style: styles.color },
          _react2.default.createElement(
            'div',
            { style: styles.swatch },
            _react2.default.createElement('div', { style: styles.active }),
            _react2.default.createElement(_common.Checkboard, { renderers: renderers })
          )
        ),
        _react2.default.createElement(
          'div',
          { style: styles.toggles },
          _react2.default.createElement(
            'div',
            { style: styles.hue },
            _react2.default.createElement(_common.Hue, {
              style: styles.Hue,
              hsl: hsl,
              pointer: _ChromePointer2.default,
              onChange: onChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.alpha },
            _react2.default.createElement(_common.Alpha, {
              style: styles.Alpha,
              rgb: rgb,
              hsl: hsl,
              pointer: _ChromePointer2.default,
              renderers: renderers,
              onChange: onChange
            })
          )
        )
      ),
      _react2.default.createElement(_ChromeFields2.default, {
        rgb: rgb,
        hsl: hsl,
        hex: hex,
        onChange: onChange,
        disableAlpha: disableAlpha
      })
    )
  );
};

Chrome.propTypes = {
  disableAlpha: _propTypes2.default.bool,
  styles: _propTypes2.default.object
};

Chrome.defaultProps = {
  disableAlpha: false,
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Chrome);

/***/ }),
/* 851 */
/***/ (function(module, exports, __nested_webpack_require_4203233__) {

"use strict";


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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4203233__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4203233__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __nested_webpack_require_4203233__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4203233__(22);

var _UnfoldMoreHorizontalIcon = __nested_webpack_require_4203233__(852);

var _UnfoldMoreHorizontalIcon2 = _interopRequireDefault(_UnfoldMoreHorizontalIcon);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint-disable react/no-did-mount-set-state, no-param-reassign */

var ChromeFields = exports.ChromeFields = function (_React$Component) {
  _inherits(ChromeFields, _React$Component);

  function ChromeFields() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, ChromeFields);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = ChromeFields.__proto__ || Object.getPrototypeOf(ChromeFields)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      view: ''
    }, _this.toggleViews = function () {
      if (_this.state.view === 'hex') {
        _this.setState({ view: 'rgb' });
      } else if (_this.state.view === 'rgb') {
        _this.setState({ view: 'hsl' });
      } else if (_this.state.view === 'hsl') {
        if (_this.props.hsl.a === 1) {
          _this.setState({ view: 'hex' });
        } else {
          _this.setState({ view: 'rgb' });
        }
      }
    }, _this.handleChange = function (data, e) {
      if (data.hex) {
        _color2.default.isValidHex(data.hex) && _this.props.onChange({
          hex: data.hex,
          source: 'hex'
        }, e);
      } else if (data.r || data.g || data.b) {
        _this.props.onChange({
          r: data.r || _this.props.rgb.r,
          g: data.g || _this.props.rgb.g,
          b: data.b || _this.props.rgb.b,
          source: 'rgb'
        }, e);
      } else if (data.a) {
        if (data.a < 0) {
          data.a = 0;
        } else if (data.a > 1) {
          data.a = 1;
        }

        _this.props.onChange({
          h: _this.props.hsl.h,
          s: _this.props.hsl.s,
          l: _this.props.hsl.l,
          a: Math.round(data.a * 100) / 100,
          source: 'rgb'
        }, e);
      } else if (data.h || data.s || data.l) {
        // Remove any occurances of '%'.
        if (typeof data.s === 'string' && data.s.includes('%')) {
          data.s = data.s.replace('%', '');
        }
        if (typeof data.l === 'string' && data.l.includes('%')) {
          data.l = data.l.replace('%', '');
        }

        _this.props.onChange({
          h: data.h || _this.props.hsl.h,
          s: Number(data.s && data.s || _this.props.hsl.s),
          l: Number(data.l && data.l || _this.props.hsl.l),
          source: 'hsl'
        }, e);
      }
    }, _this.showHighlight = function (e) {
      e.currentTarget.style.background = '#eee';
    }, _this.hideHighlight = function (e) {
      e.currentTarget.style.background = 'transparent';
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(ChromeFields, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      if (this.props.hsl.a === 1 && this.state.view !== 'hex') {
        this.setState({ view: 'hex' });
      } else if (this.state.view !== 'rgb' && this.state.view !== 'hsl') {
        this.setState({ view: 'rgb' });
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      if (nextProps.hsl.a !== 1 && this.state.view === 'hex') {
        this.setState({ view: 'rgb' });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var styles = (0, _reactcss2.default)({
        'default': {
          wrap: {
            paddingTop: '16px',
            display: 'flex'
          },
          fields: {
            flex: '1',
            display: 'flex',
            marginLeft: '-6px'
          },
          field: {
            paddingLeft: '6px',
            width: '100%'
          },
          alpha: {
            paddingLeft: '6px',
            width: '100%'
          },
          toggle: {
            width: '32px',
            textAlign: 'right',
            position: 'relative'
          },
          icon: {
            marginRight: '-4px',
            marginTop: '12px',
            cursor: 'pointer',
            position: 'relative'
          },
          iconHighlight: {
            position: 'absolute',
            width: '24px',
            height: '28px',
            background: '#eee',
            borderRadius: '4px',
            top: '10px',
            left: '12px',
            display: 'none'
          },
          input: {
            fontSize: '11px',
            color: '#333',
            width: '100%',
            borderRadius: '2px',
            border: 'none',
            boxShadow: 'inset 0 0 0 1px #dadada',
            height: '21px',
            textAlign: 'center'
          },
          label: {
            textTransform: 'uppercase',
            fontSize: '11px',
            lineHeight: '11px',
            color: '#969696',
            textAlign: 'center',
            display: 'block',
            marginTop: '12px'
          },
          svg: {
            fill: '#333',
            width: '24px',
            height: '24px',
            border: '1px transparent solid',
            borderRadius: '5px'
          }
        },
        'disableAlpha': {
          alpha: {
            display: 'none'
          }
        }
      }, this.props, this.state);

      var fields = void 0;
      if (this.state.view === 'hex') {
        fields = _react2.default.createElement(
          'div',
          { style: styles.fields, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'hex', value: this.props.hex,
              onChange: this.handleChange
            })
          )
        );
      } else if (this.state.view === 'rgb') {
        fields = _react2.default.createElement(
          'div',
          { style: styles.fields, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'r',
              value: this.props.rgb.r,
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'g',
              value: this.props.rgb.g,
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'b',
              value: this.props.rgb.b,
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.alpha },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'a',
              value: this.props.rgb.a,
              arrowOffset: 0.01,
              onChange: this.handleChange
            })
          )
        );
      } else if (this.state.view === 'hsl') {
        fields = _react2.default.createElement(
          'div',
          { style: styles.fields, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'h',
              value: Math.round(this.props.hsl.h),
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 's',
              value: Math.round(this.props.hsl.s * 100) + '%',
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.field },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'l',
              value: Math.round(this.props.hsl.l * 100) + '%',
              onChange: this.handleChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.alpha },
            _react2.default.createElement(_common.EditableInput, {
              style: { input: styles.input, label: styles.label },
              label: 'a',
              value: this.props.hsl.a,
              arrowOffset: 0.01,
              onChange: this.handleChange
            })
          )
        );
      }

      return _react2.default.createElement(
        'div',
        { style: styles.wrap, className: 'flexbox-fix' },
        fields,
        _react2.default.createElement(
          'div',
          { style: styles.toggle },
          _react2.default.createElement(
            'div',
            { style: styles.icon, onClick: this.toggleViews, ref: function ref(icon) {
                return _this2.icon = icon;
              } },
            _react2.default.createElement(_UnfoldMoreHorizontalIcon2.default, {
              style: styles.svg,
              onMouseOver: this.showHighlight,
              onMouseEnter: this.showHighlight,
              onMouseOut: this.hideHighlight
            })
          )
        )
      );
    }
  }]);

  return ChromeFields;
}(_react2.default.Component);

exports.default = ChromeFields;

/***/ }),
/* 852 */
/***/ (function(module, exports, __nested_webpack_require_4215470__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4215470__(1);

var _react2 = _interopRequireDefault(_react);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var DEFAULT_SIZE = 24;

exports.default = function (_ref) {
  var _ref$fill = _ref.fill,
      fill = _ref$fill === undefined ? 'currentColor' : _ref$fill,
      _ref$width = _ref.width,
      width = _ref$width === undefined ? DEFAULT_SIZE : _ref$width,
      _ref$height = _ref.height,
      height = _ref$height === undefined ? DEFAULT_SIZE : _ref$height,
      _ref$style = _ref.style,
      style = _ref$style === undefined ? {} : _ref$style,
      props = _objectWithoutProperties(_ref, ['fill', 'width', 'height', 'style']);

  return _react2.default.createElement(
    'svg',
    _extends({
      viewBox: '0 0 ' + DEFAULT_SIZE + ' ' + DEFAULT_SIZE,
      style: _extends({ fill: fill, width: width, height: height }, style)
    }, props),
    _react2.default.createElement('path', { d: 'M12,18.17L8.83,15L7.42,16.41L12,21L16.59,16.41L15.17,15M12,5.83L15.17,9L16.58,7.59L12,3L7.41,7.59L8.83,9L12,5.83Z' })
  );
};

/***/ }),
/* 853 */
/***/ (function(module, exports, __nested_webpack_require_4217215__) {

"use strict";


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

var _react = __nested_webpack_require_4217215__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4217215__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var ChromePointer = exports.ChromePointer = function ChromePointer() {
  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '12px',
        height: '12px',
        borderRadius: '6px',
        transform: 'translate(-6px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = ChromePointer;

/***/ }),
/* 854 */
/***/ (function(module, exports, __nested_webpack_require_4218183__) {

"use strict";


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

var _react = __nested_webpack_require_4218183__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4218183__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var ChromePointerCircle = exports.ChromePointerCircle = function ChromePointerCircle() {
  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '12px',
        height: '12px',
        borderRadius: '6px',
        boxShadow: 'inset 0 0 0 1px #fff',
        transform: 'translate(-6px, -6px)'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = ChromePointerCircle;

/***/ }),
/* 855 */
/***/ (function(module, exports, __nested_webpack_require_4219123__) {

"use strict";


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

var _react = __nested_webpack_require_4219123__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4219123__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4219123__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4219123__(70);

var _map2 = _interopRequireDefault(_map);

var _merge = __nested_webpack_require_4219123__(46);

var _merge2 = _interopRequireDefault(_merge);

var _color = __nested_webpack_require_4219123__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4219123__(22);

var _CompactColor = __nested_webpack_require_4219123__(856);

var _CompactColor2 = _interopRequireDefault(_CompactColor);

var _CompactFields = __nested_webpack_require_4219123__(857);

var _CompactFields2 = _interopRequireDefault(_CompactFields);

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

var Compact = exports.Compact = function Compact(_ref) {
  var onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      colors = _ref.colors,
      hex = _ref.hex,
      rgb = _ref.rgb,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      Compact: {
        background: '#f6f6f6',
        radius: '4px'
      },
      compact: {
        paddingTop: '5px',
        paddingLeft: '5px',
        boxSizing: 'initial',
        width: '240px'
      },
      clear: {
        clear: 'both'
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(data, e) {
    if (data.hex) {
      _color2.default.isValidHex(data.hex) && onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    } else {
      onChange(data, e);
    }
  };

  return _react2.default.createElement(
    _common.Raised,
    { style: styles.Compact, styles: passedStyles },
    _react2.default.createElement(
      'div',
      { style: styles.compact, className: 'compact-picker ' + className },
      _react2.default.createElement(
        'div',
        null,
        (0, _map2.default)(colors, function (c) {
          return _react2.default.createElement(_CompactColor2.default, {
            key: c,
            color: c,
            active: c.toLowerCase() === hex,
            onClick: handleChange,
            onSwatchHover: onSwatchHover
          });
        }),
        _react2.default.createElement('div', { style: styles.clear })
      ),
      _react2.default.createElement(_CompactFields2.default, { hex: hex, rgb: rgb, onChange: handleChange })
    )
  );
};

Compact.propTypes = {
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  styles: _propTypes2.default.object
};

Compact.defaultProps = {
  colors: ['#4D4D4D', '#999999', '#FFFFFF', '#F44E3B', '#FE9200', '#FCDC00', '#DBDF00', '#A4DD00', '#68CCCA', '#73D8FF', '#AEA1FF', '#FDA1FF', '#333333', '#808080', '#cccccc', '#D33115', '#E27300', '#FCC400', '#B0BC00', '#68BC00', '#16A5A5', '#009CE0', '#7B64FF', '#FA28FF', '#000000', '#666666', '#B3B3B3', '#9F0500', '#C45100', '#FB9E00', '#808900', '#194D33', '#0C797D', '#0062B1', '#653294', '#AB149E'],
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Compact);

/***/ }),
/* 856 */
/***/ (function(module, exports, __nested_webpack_require_4222662__) {

"use strict";


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

var _react = __nested_webpack_require_4222662__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4222662__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __nested_webpack_require_4222662__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4222662__(22);

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

var CompactColor = exports.CompactColor = function CompactColor(_ref) {
  var color = _ref.color,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onSwatchHover = _ref.onSwatchHover,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      color: {
        background: color,
        width: '15px',
        height: '15px',
        float: 'left',
        marginRight: '5px',
        marginBottom: '5px',
        position: 'relative',
        cursor: 'pointer'
      },
      dot: {
        absolute: '5px 5px 5px 5px',
        background: _color2.default.getContrastingColor(color),
        borderRadius: '50%',
        opacity: '0'
      }
    },
    'active': {
      dot: {
        opacity: '1'
      }
    },
    'color-#FFFFFF': {
      color: {
        boxShadow: 'inset 0 0 0 1px #ddd'
      },
      dot: {
        background: '#000'
      }
    },
    'transparent': {
      dot: {
        background: '#000'
      }
    }
  }, { active: active, 'color-#FFFFFF': color === '#FFFFFF', 'transparent': color === 'transparent' });

  return _react2.default.createElement(
    _common.Swatch,
    {
      style: styles.color,
      color: color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: { boxShadow: '0 0 4px ' + color }
    },
    _react2.default.createElement('div', { style: styles.dot })
  );
};

exports.default = CompactColor;

/***/ }),
/* 857 */
/***/ (function(module, exports, __nested_webpack_require_4224730__) {

"use strict";


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

var _react = __nested_webpack_require_4224730__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4224730__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __nested_webpack_require_4224730__(22);

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

var CompactFields = exports.CompactFields = function CompactFields(_ref) {
  var hex = _ref.hex,
      rgb = _ref.rgb,
      onChange = _ref.onChange;

  var styles = (0, _reactcss2.default)({
    'default': {
      fields: {
        display: 'flex',
        paddingBottom: '6px',
        paddingRight: '5px',
        position: 'relative'
      },
      active: {
        position: 'absolute',
        top: '6px',
        left: '5px',
        height: '9px',
        width: '9px',
        background: hex
      },
      HEXwrap: {
        flex: '6',
        position: 'relative'
      },
      HEXinput: {
        width: '80%',
        padding: '0px',
        paddingLeft: '20%',
        border: 'none',
        outline: 'none',
        background: 'none',
        fontSize: '12px',
        color: '#333',
        height: '16px'
      },
      HEXlabel: {
        display: 'none'
      },
      RGBwrap: {
        flex: '3',
        position: 'relative'
      },
      RGBinput: {
        width: '70%',
        padding: '0px',
        paddingLeft: '30%',
        border: 'none',
        outline: 'none',
        background: 'none',
        fontSize: '12px',
        color: '#333',
        height: '16px'
      },
      RGBlabel: {
        position: 'absolute',
        top: '3px',
        left: '0px',
        lineHeight: '16px',
        textTransform: 'uppercase',
        fontSize: '12px',
        color: '#999'
      }
    }
  });

  var handleChange = function handleChange(data, e) {
    if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        source: 'rgb'
      }, e);
    } else {
      onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    }
  };

  return _react2.default.createElement(
    'div',
    { style: styles.fields, className: 'flexbox-fix' },
    _react2.default.createElement('div', { style: styles.active }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel },
      label: 'hex',
      value: hex,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'r',
      value: rgb.r,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'g',
      value: rgb.g,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'b',
      value: rgb.b,
      onChange: handleChange
    })
  );
};

exports.default = CompactFields;

/***/ }),
/* 858 */
/***/ (function(module, exports, __nested_webpack_require_4228104__) {

"use strict";


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

var _react = __nested_webpack_require_4228104__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4228104__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4228104__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4228104__(70);

var _map2 = _interopRequireDefault(_map);

var _merge = __nested_webpack_require_4228104__(46);

var _merge2 = _interopRequireDefault(_merge);

var _common = __nested_webpack_require_4228104__(22);

var _GithubSwatch = __nested_webpack_require_4228104__(859);

var _GithubSwatch2 = _interopRequireDefault(_GithubSwatch);

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

var Github = exports.Github = function Github(_ref) {
  var width = _ref.width,
      colors = _ref.colors,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      triangle = _ref.triangle,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        background: '#fff',
        border: '1px solid rgba(0,0,0,0.2)',
        boxShadow: '0 3px 12px rgba(0,0,0,0.15)',
        borderRadius: '4px',
        position: 'relative',
        padding: '5px',
        display: 'flex',
        flexWrap: 'wrap'
      },
      triangle: {
        position: 'absolute',
        border: '7px solid transparent',
        borderBottomColor: '#fff'
      },
      triangleShadow: {
        position: 'absolute',
        border: '8px solid transparent',
        borderBottomColor: 'rgba(0,0,0,0.15)'
      }
    },
    'hide-triangle': {
      triangle: {
        display: 'none'
      },
      triangleShadow: {
        display: 'none'
      }
    },
    'top-left-triangle': {
      triangle: {
        top: '-14px',
        left: '10px'
      },
      triangleShadow: {
        top: '-16px',
        left: '9px'
      }
    },
    'top-right-triangle': {
      triangle: {
        top: '-14px',
        right: '10px'
      },
      triangleShadow: {
        top: '-16px',
        right: '9px'
      }
    },
    'bottom-left-triangle': {
      triangle: {
        top: '35px',
        left: '10px',
        transform: 'rotate(180deg)'
      },
      triangleShadow: {
        top: '37px',
        left: '9px',
        transform: 'rotate(180deg)'
      }
    },
    'bottom-right-triangle': {
      triangle: {
        top: '35px',
        right: '10px',
        transform: 'rotate(180deg)'
      },
      triangleShadow: {
        top: '37px',
        right: '9px',
        transform: 'rotate(180deg)'
      }
    }
  }, passedStyles), {
    'hide-triangle': triangle === 'hide',
    'top-left-triangle': triangle === 'top-left',
    'top-right-triangle': triangle === 'top-right',
    'bottom-left-triangle': triangle == 'bottom-left',
    'bottom-right-triangle': triangle === 'bottom-right'
  });

  var handleChange = function handleChange(hex, e) {
    return onChange({ hex: hex, source: 'hex' }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'github-picker ' + className },
    _react2.default.createElement('div', { style: styles.triangleShadow }),
    _react2.default.createElement('div', { style: styles.triangle }),
    (0, _map2.default)(colors, function (c) {
      return _react2.default.createElement(_GithubSwatch2.default, {
        color: c,
        key: c,
        onClick: handleChange,
        onSwatchHover: onSwatchHover
      });
    })
  );
};

Github.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  triangle: _propTypes2.default.oneOf(['hide', 'top-left', 'top-right', 'bottom-left', 'bottom-right']),
  styles: _propTypes2.default.object
};

Github.defaultProps = {
  width: 200,
  colors: ['#B80000', '#DB3E00', '#FCCB00', '#008B02', '#006B76', '#1273DE', '#004DCF', '#5300EB', '#EB9694', '#FAD0C3', '#FEF3BD', '#C1E1C5', '#BEDADC', '#C4DEF6', '#BED3F3', '#D4C4FB'],
  triangle: 'top-left',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Github);

/***/ }),
/* 859 */
/***/ (function(module, exports, __nested_webpack_require_4232631__) {

"use strict";


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

var _react = __nested_webpack_require_4232631__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4232631__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __nested_webpack_require_4232631__(22);

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

var GithubSwatch = exports.GithubSwatch = function GithubSwatch(_ref) {
  var hover = _ref.hover,
      color = _ref.color,
      onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover;

  var hoverSwatch = {
    position: 'relative',
    zIndex: '2',
    outline: '2px solid #fff',
    boxShadow: '0 0 5px 2px rgba(0,0,0,0.25)'
  };

  var styles = (0, _reactcss2.default)({
    'default': {
      swatch: {
        width: '25px',
        height: '25px',
        fontSize: '0'
      }
    },
    'hover': {
      swatch: hoverSwatch
    }
  }, { hover: hover });

  return _react2.default.createElement(
    'div',
    { style: styles.swatch },
    _react2.default.createElement(_common.Swatch, {
      color: color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: hoverSwatch
    })
  );
};

exports.default = (0, _reactcss.handleHover)(GithubSwatch);

/***/ }),
/* 860 */
/***/ (function(module, exports, __nested_webpack_require_4234030__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4234030__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4234030__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4234030__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4234030__(46);

var _merge2 = _interopRequireDefault(_merge);

var _common = __nested_webpack_require_4234030__(22);

var _HuePointer = __nested_webpack_require_4234030__(861);

var _HuePointer2 = _interopRequireDefault(_HuePointer);

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

var HuePicker = exports.HuePicker = function HuePicker(_ref) {
  var width = _ref.width,
      height = _ref.height,
      onChange = _ref.onChange,
      hsl = _ref.hsl,
      direction = _ref.direction,
      pointer = _ref.pointer,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      picker: {
        position: 'relative',
        width: width,
        height: height
      },
      hue: {
        radius: '2px'
      }
    }
  }, passedStyles));

  // Overwrite to provide pure hue color
  var handleChange = function handleChange(data) {
    return onChange({ a: 1, h: data.h, l: 0.5, s: 1 });
  };

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'hue-picker ' + className },
    _react2.default.createElement(_common.Hue, _extends({}, styles.hue, {
      hsl: hsl,
      pointer: pointer,
      onChange: handleChange,
      direction: direction
    }))
  );
};

HuePicker.propTypes = {
  styles: _propTypes2.default.object
};
HuePicker.defaultProps = {
  width: '316px',
  height: '16px',
  direction: 'horizontal',
  pointer: _HuePointer2.default,
  styles: {}
};

exports.default = (0, _common.ColorWrap)(HuePicker);

/***/ }),
/* 861 */
/***/ (function(module, exports, __nested_webpack_require_4236495__) {

"use strict";


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

var _react = __nested_webpack_require_4236495__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4236495__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var SliderPointer = exports.SliderPointer = function SliderPointer(_ref) {
  var direction = _ref.direction;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '18px',
        height: '18px',
        borderRadius: '50%',
        transform: 'translate(-9px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    },
    'vertical': {
      picker: {
        transform: 'translate(-3px, -9px)'
      }
    }
  }, { vertical: direction === 'vertical' });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = SliderPointer;

/***/ }),
/* 862 */
/***/ (function(module, exports, __nested_webpack_require_4237634__) {

"use strict";


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

var _react = __nested_webpack_require_4237634__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4237634__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4237634__(46);

var _merge2 = _interopRequireDefault(_merge);

var _color = __nested_webpack_require_4237634__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4237634__(22);

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

var Material = exports.Material = function Material(_ref) {
  var onChange = _ref.onChange,
      hex = _ref.hex,
      rgb = _ref.rgb,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      material: {
        width: '98px',
        height: '98px',
        padding: '16px',
        fontFamily: 'Roboto'
      },
      HEXwrap: {
        position: 'relative'
      },
      HEXinput: {
        width: '100%',
        marginTop: '12px',
        fontSize: '15px',
        color: '#333',
        padding: '0px',
        border: '0px',
        borderBottom: '2px solid ' + hex,
        outline: 'none',
        height: '30px'
      },
      HEXlabel: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        fontSize: '11px',
        color: '#999999',
        textTransform: 'capitalize'
      },
      Hex: {
        style: {}
      },
      RGBwrap: {
        position: 'relative'
      },
      RGBinput: {
        width: '100%',
        marginTop: '12px',
        fontSize: '15px',
        color: '#333',
        padding: '0px',
        border: '0px',
        borderBottom: '1px solid #eee',
        outline: 'none',
        height: '30px'
      },
      RGBlabel: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        fontSize: '11px',
        color: '#999999',
        textTransform: 'capitalize'
      },
      split: {
        display: 'flex',
        marginRight: '-10px',
        paddingTop: '11px'
      },
      third: {
        flex: '1',
        paddingRight: '10px'
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(data, e) {
    if (data.hex) {
      _color2.default.isValidHex(data.hex) && onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    } else if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        source: 'rgb'
      }, e);
    }
  };

  return _react2.default.createElement(
    _common.Raised,
    { styles: passedStyles },
    _react2.default.createElement(
      'div',
      { style: styles.material, className: 'material-picker ' + className },
      _react2.default.createElement(_common.EditableInput, {
        style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel },
        label: 'hex',
        value: hex,
        onChange: handleChange
      }),
      _react2.default.createElement(
        'div',
        { style: styles.split, className: 'flexbox-fix' },
        _react2.default.createElement(
          'div',
          { style: styles.third },
          _react2.default.createElement(_common.EditableInput, {
            style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
            label: 'r', value: rgb.r,
            onChange: handleChange
          })
        ),
        _react2.default.createElement(
          'div',
          { style: styles.third },
          _react2.default.createElement(_common.EditableInput, {
            style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
            label: 'g',
            value: rgb.g,
            onChange: handleChange
          })
        ),
        _react2.default.createElement(
          'div',
          { style: styles.third },
          _react2.default.createElement(_common.EditableInput, {
            style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
            label: 'b',
            value: rgb.b,
            onChange: handleChange
          })
        )
      )
    )
  );
};

exports.default = (0, _common.ColorWrap)(Material);

/***/ }),
/* 863 */
/***/ (function(module, exports, __nested_webpack_require_4242194__) {

"use strict";


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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = __nested_webpack_require_4242194__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4242194__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4242194__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4242194__(46);

var _merge2 = _interopRequireDefault(_merge);

var _common = __nested_webpack_require_4242194__(22);

var _PhotoshopFields = __nested_webpack_require_4242194__(864);

var _PhotoshopFields2 = _interopRequireDefault(_PhotoshopFields);

var _PhotoshopPointerCircle = __nested_webpack_require_4242194__(865);

var _PhotoshopPointerCircle2 = _interopRequireDefault(_PhotoshopPointerCircle);

var _PhotoshopPointer = __nested_webpack_require_4242194__(866);

var _PhotoshopPointer2 = _interopRequireDefault(_PhotoshopPointer);

var _PhotoshopButton = __nested_webpack_require_4242194__(867);

var _PhotoshopButton2 = _interopRequireDefault(_PhotoshopButton);

var _PhotoshopPreviews = __nested_webpack_require_4242194__(868);

var _PhotoshopPreviews2 = _interopRequireDefault(_PhotoshopPreviews);

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Photoshop = exports.Photoshop = function (_React$Component) {
  _inherits(Photoshop, _React$Component);

  function Photoshop(props) {
    _classCallCheck(this, Photoshop);

    var _this = _possibleConstructorReturn(this, (Photoshop.__proto__ || Object.getPrototypeOf(Photoshop)).call(this));

    _this.state = {
      currentColor: props.hex
    };
    return _this;
  }

  _createClass(Photoshop, [{
    key: 'render',
    value: function render() {
      var _props = this.props,
          _props$styles = _props.styles,
          passedStyles = _props$styles === undefined ? {} : _props$styles,
          _props$className = _props.className,
          className = _props$className === undefined ? '' : _props$className;

      var styles = (0, _reactcss2.default)((0, _merge2.default)({
        'default': {
          picker: {
            background: '#DCDCDC',
            borderRadius: '4px',
            boxShadow: '0 0 0 1px rgba(0,0,0,.25), 0 8px 16px rgba(0,0,0,.15)',
            boxSizing: 'initial',
            width: '513px'
          },
          head: {
            backgroundImage: 'linear-gradient(-180deg, #F0F0F0 0%, #D4D4D4 100%)',
            borderBottom: '1px solid #B1B1B1',
            boxShadow: 'inset 0 1px 0 0 rgba(255,255,255,.2), inset 0 -1px 0 0 rgba(0,0,0,.02)',
            height: '23px',
            lineHeight: '24px',
            borderRadius: '4px 4px 0 0',
            fontSize: '13px',
            color: '#4D4D4D',
            textAlign: 'center'
          },
          body: {
            padding: '15px 15px 0',
            display: 'flex'
          },
          saturation: {
            width: '256px',
            height: '256px',
            position: 'relative',
            border: '2px solid #B3B3B3',
            borderBottom: '2px solid #F0F0F0',
            overflow: 'hidden'
          },
          hue: {
            position: 'relative',
            height: '256px',
            width: '19px',
            marginLeft: '10px',
            border: '2px solid #B3B3B3',
            borderBottom: '2px solid #F0F0F0'
          },
          controls: {
            width: '180px',
            marginLeft: '10px'
          },
          top: {
            display: 'flex'
          },
          previews: {
            width: '60px'
          },
          actions: {
            flex: '1',
            marginLeft: '20px'
          }
        }
      }, passedStyles));

      return _react2.default.createElement(
        'div',
        { style: styles.picker, className: 'photoshop-picker ' + className },
        _react2.default.createElement(
          'div',
          { style: styles.head },
          this.props.header
        ),
        _react2.default.createElement(
          'div',
          { style: styles.body, className: 'flexbox-fix' },
          _react2.default.createElement(
            'div',
            { style: styles.saturation },
            _react2.default.createElement(_common.Saturation, {
              hsl: this.props.hsl,
              hsv: this.props.hsv,
              pointer: _PhotoshopPointerCircle2.default,
              onChange: this.props.onChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.hue },
            _react2.default.createElement(_common.Hue, {
              direction: 'vertical',
              hsl: this.props.hsl,
              pointer: _PhotoshopPointer2.default,
              onChange: this.props.onChange
            })
          ),
          _react2.default.createElement(
            'div',
            { style: styles.controls },
            _react2.default.createElement(
              'div',
              { style: styles.top, className: 'flexbox-fix' },
              _react2.default.createElement(
                'div',
                { style: styles.previews },
                _react2.default.createElement(_PhotoshopPreviews2.default, {
                  rgb: this.props.rgb,
                  currentColor: this.state.currentColor
                })
              ),
              _react2.default.createElement(
                'div',
                { style: styles.actions },
                _react2.default.createElement(_PhotoshopButton2.default, { label: 'OK', onClick: this.props.onAccept, active: true }),
                _react2.default.createElement(_PhotoshopButton2.default, { label: 'Cancel', onClick: this.props.onCancel }),
                _react2.default.createElement(_PhotoshopFields2.default, {
                  onChange: this.props.onChange,
                  rgb: this.props.rgb,
                  hsv: this.props.hsv,
                  hex: this.props.hex
                })
              )
            )
          )
        )
      );
    }
  }]);

  return Photoshop;
}(_react2.default.Component);

Photoshop.propTypes = {
  header: _propTypes2.default.string,
  styles: _propTypes2.default.object
};

Photoshop.defaultProps = {
  header: 'Color Picker',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Photoshop);

/***/ }),
/* 864 */
/***/ (function(module, exports, __nested_webpack_require_4250010__) {

"use strict";


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

var _react = __nested_webpack_require_4250010__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4250010__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __nested_webpack_require_4250010__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4250010__(22);

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

var PhotoshopPicker = exports.PhotoshopPicker = function PhotoshopPicker(_ref) {
  var onChange = _ref.onChange,
      rgb = _ref.rgb,
      hsv = _ref.hsv,
      hex = _ref.hex;

  var styles = (0, _reactcss2.default)({
    'default': {
      fields: {
        paddingTop: '5px',
        paddingBottom: '9px',
        width: '80px',
        position: 'relative'
      },
      divider: {
        height: '5px'
      },
      RGBwrap: {
        position: 'relative'
      },
      RGBinput: {
        marginLeft: '40%',
        width: '40%',
        height: '18px',
        border: '1px solid #888888',
        boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC',
        marginBottom: '5px',
        fontSize: '13px',
        paddingLeft: '3px',
        marginRight: '10px'
      },
      RGBlabel: {
        left: '0px',
        width: '34px',
        textTransform: 'uppercase',
        fontSize: '13px',
        height: '18px',
        lineHeight: '22px',
        position: 'absolute'
      },
      HEXwrap: {
        position: 'relative'
      },
      HEXinput: {
        marginLeft: '20%',
        width: '80%',
        height: '18px',
        border: '1px solid #888888',
        boxShadow: 'inset 0 1px 1px rgba(0,0,0,.1), 0 1px 0 0 #ECECEC',
        marginBottom: '6px',
        fontSize: '13px',
        paddingLeft: '3px'
      },
      HEXlabel: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        width: '14px',
        textTransform: 'uppercase',
        fontSize: '13px',
        height: '18px',
        lineHeight: '22px'
      },
      fieldSymbols: {
        position: 'absolute',
        top: '5px',
        right: '-7px',
        fontSize: '13px'
      },
      symbol: {
        height: '20px',
        lineHeight: '22px',
        paddingBottom: '7px'
      }
    }
  });

  var handleChange = function handleChange(data, e) {
    if (data['#']) {
      _color2.default.isValidHex(data['#']) && onChange({
        hex: data['#'],
        source: 'hex'
      }, e);
    } else if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        source: 'rgb'
      }, e);
    } else if (data.h || data.s || data.v) {
      onChange({
        h: data.h || hsv.h,
        s: data.s || hsv.s,
        v: data.v || hsv.v,
        source: 'hsv'
      }, e);
    }
  };

  return _react2.default.createElement(
    'div',
    { style: styles.fields },
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'h',
      value: Math.round(hsv.h),
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 's',
      value: Math.round(hsv.s * 100),
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'v',
      value: Math.round(hsv.v * 100),
      onChange: handleChange
    }),
    _react2.default.createElement('div', { style: styles.divider }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'r',
      value: rgb.r,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'g',
      value: rgb.g,
      onChange: handleChange
    }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.RGBwrap, input: styles.RGBinput, label: styles.RGBlabel },
      label: 'b',
      value: rgb.b,
      onChange: handleChange
    }),
    _react2.default.createElement('div', { style: styles.divider }),
    _react2.default.createElement(_common.EditableInput, {
      style: { wrap: styles.HEXwrap, input: styles.HEXinput, label: styles.HEXlabel },
      label: '#',
      value: hex.replace('#', ''),
      onChange: handleChange
    }),
    _react2.default.createElement(
      'div',
      { style: styles.fieldSymbols },
      _react2.default.createElement(
        'div',
        { style: styles.symbol },
        '\xB0'
      ),
      _react2.default.createElement(
        'div',
        { style: styles.symbol },
        '%'
      ),
      _react2.default.createElement(
        'div',
        { style: styles.symbol },
        '%'
      )
    )
  );
};

exports.default = PhotoshopPicker;

/***/ }),
/* 865 */
/***/ (function(module, exports, __nested_webpack_require_4255300__) {

"use strict";


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

var _react = __nested_webpack_require_4255300__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4255300__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var PhotoshopPointerCircle = exports.PhotoshopPointerCircle = function PhotoshopPointerCircle(_ref) {
  var hsl = _ref.hsl;

  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '12px',
        height: '12px',
        borderRadius: '6px',
        boxShadow: 'inset 0 0 0 1px #fff',
        transform: 'translate(-6px, -6px)'
      }
    },
    'black-outline': {
      picker: {
        boxShadow: 'inset 0 0 0 1px #000'
      }
    }
  }, { 'black-outline': hsl.l > 0.5 });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = PhotoshopPointerCircle;

/***/ }),
/* 866 */
/***/ (function(module, exports, __nested_webpack_require_4256412__) {

"use strict";


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

var _react = __nested_webpack_require_4256412__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4256412__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var PhotoshopPointerCircle = exports.PhotoshopPointerCircle = function PhotoshopPointerCircle() {
  var styles = (0, _reactcss2.default)({
    'default': {
      triangle: {
        width: 0,
        height: 0,
        borderStyle: 'solid',
        borderWidth: '4px 0 4px 6px',
        borderColor: 'transparent transparent transparent #fff',
        position: 'absolute',
        top: '1px',
        left: '1px'
      },
      triangleBorder: {
        width: 0,
        height: 0,
        borderStyle: 'solid',
        borderWidth: '5px 0 5px 8px',
        borderColor: 'transparent transparent transparent #555'
      },

      left: {
        Extend: 'triangleBorder',
        transform: 'translate(-13px, -4px)'
      },
      leftInside: {
        Extend: 'triangle',
        transform: 'translate(-8px, -5px)'
      },

      right: {
        Extend: 'triangleBorder',
        transform: 'translate(20px, -14px) rotate(180deg)'
      },
      rightInside: {
        Extend: 'triangle',
        transform: 'translate(-8px, -5px)'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.pointer },
    _react2.default.createElement(
      'div',
      { style: styles.left },
      _react2.default.createElement('div', { style: styles.leftInside })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.right },
      _react2.default.createElement('div', { style: styles.rightInside })
    )
  );
};

exports.default = PhotoshopPointerCircle;

/***/ }),
/* 867 */
/***/ (function(module, exports, __nested_webpack_require_4258401__) {

"use strict";


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

var _react = __nested_webpack_require_4258401__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4258401__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var PhotoshopBotton = exports.PhotoshopBotton = function PhotoshopBotton(_ref) {
  var onClick = _ref.onClick,
      label = _ref.label,
      children = _ref.children,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      button: {
        backgroundImage: 'linear-gradient(-180deg, #FFFFFF 0%, #E6E6E6 100%)',
        border: '1px solid #878787',
        borderRadius: '2px',
        height: '20px',
        boxShadow: '0 1px 0 0 #EAEAEA',
        fontSize: '14px',
        color: '#000',
        lineHeight: '20px',
        textAlign: 'center',
        marginBottom: '10px',
        cursor: 'pointer'
      }
    },
    'active': {
      button: {
        boxShadow: '0 0 0 1px #878787'
      }
    }
  }, { active: active });

  return _react2.default.createElement(
    'div',
    { style: styles.button, onClick: onClick },
    label || children
  );
};

exports.default = PhotoshopBotton;

/***/ }),
/* 868 */
/***/ (function(module, exports, __nested_webpack_require_4259810__) {

"use strict";


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

var _react = __nested_webpack_require_4259810__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4259810__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var PhotoshopPreviews = exports.PhotoshopPreviews = function PhotoshopPreviews(_ref) {
  var rgb = _ref.rgb,
      currentColor = _ref.currentColor;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatches: {
        border: '1px solid #B3B3B3',
        borderBottom: '1px solid #F0F0F0',
        marginBottom: '2px',
        marginTop: '1px'
      },
      new: {
        height: '34px',
        background: 'rgb(' + rgb.r + ',' + rgb.g + ', ' + rgb.b + ')',
        boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 1px 0 #000'
      },
      current: {
        height: '34px',
        background: currentColor,
        boxShadow: 'inset 1px 0 0 #000, inset -1px 0 0 #000, inset 0 -1px 0 #000'
      },
      label: {
        fontSize: '14px',
        color: '#000',
        textAlign: 'center'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    null,
    _react2.default.createElement(
      'div',
      { style: styles.label },
      'new'
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatches },
      _react2.default.createElement('div', { style: styles.new }),
      _react2.default.createElement('div', { style: styles.current })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.label },
      'current'
    )
  );
};

exports.default = PhotoshopPreviews;

/***/ }),
/* 869 */
/***/ (function(module, exports, __nested_webpack_require_4261664__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4261664__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4261664__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4261664__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4261664__(46);

var _merge2 = _interopRequireDefault(_merge);

var _common = __nested_webpack_require_4261664__(22);

var _SketchFields = __nested_webpack_require_4261664__(870);

var _SketchFields2 = _interopRequireDefault(_SketchFields);

var _SketchPresetColors = __nested_webpack_require_4261664__(871);

var _SketchPresetColors2 = _interopRequireDefault(_SketchPresetColors);

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

var Sketch = exports.Sketch = function Sketch(_ref) {
  var width = _ref.width,
      rgb = _ref.rgb,
      hex = _ref.hex,
      hsv = _ref.hsv,
      hsl = _ref.hsl,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      disableAlpha = _ref.disableAlpha,
      presetColors = _ref.presetColors,
      renderers = _ref.renderers,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': _extends({
      picker: {
        width: width,
        padding: '10px 10px 0',
        boxSizing: 'initial',
        background: '#fff',
        borderRadius: '4px',
        boxShadow: '0 0 0 1px rgba(0,0,0,.15), 0 8px 16px rgba(0,0,0,.15)'
      },
      saturation: {
        width: '100%',
        paddingBottom: '75%',
        position: 'relative',
        overflow: 'hidden'
      },
      Saturation: {
        radius: '3px',
        shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      },
      controls: {
        display: 'flex'
      },
      sliders: {
        padding: '4px 0',
        flex: '1'
      },
      color: {
        width: '24px',
        height: '24px',
        position: 'relative',
        marginTop: '4px',
        marginLeft: '4px',
        borderRadius: '3px'
      },
      activeColor: {
        absolute: '0px 0px 0px 0px',
        borderRadius: '2px',
        background: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgb.a + ')',
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      },
      hue: {
        position: 'relative',
        height: '10px',
        overflow: 'hidden'
      },
      Hue: {
        radius: '2px',
        shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      },

      alpha: {
        position: 'relative',
        height: '10px',
        marginTop: '4px',
        overflow: 'hidden'
      },
      Alpha: {
        radius: '2px',
        shadow: 'inset 0 0 0 1px rgba(0,0,0,.15), inset 0 0 4px rgba(0,0,0,.25)'
      }
    }, passedStyles),
    'disableAlpha': {
      color: {
        height: '10px'
      },
      hue: {
        height: '10px'
      },
      alpha: {
        display: 'none'
      }
    }
  }, passedStyles), { disableAlpha: disableAlpha });

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'sketch-picker ' + className },
    _react2.default.createElement(
      'div',
      { style: styles.saturation },
      _react2.default.createElement(_common.Saturation, {
        style: styles.Saturation,
        hsl: hsl,
        hsv: hsv,
        onChange: onChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.controls, className: 'flexbox-fix' },
      _react2.default.createElement(
        'div',
        { style: styles.sliders },
        _react2.default.createElement(
          'div',
          { style: styles.hue },
          _react2.default.createElement(_common.Hue, {
            style: styles.Hue,
            hsl: hsl,
            onChange: onChange
          })
        ),
        _react2.default.createElement(
          'div',
          { style: styles.alpha },
          _react2.default.createElement(_common.Alpha, {
            style: styles.Alpha,
            rgb: rgb,
            hsl: hsl,
            renderers: renderers,
            onChange: onChange
          })
        )
      ),
      _react2.default.createElement(
        'div',
        { style: styles.color },
        _react2.default.createElement(_common.Checkboard, null),
        _react2.default.createElement('div', { style: styles.activeColor })
      )
    ),
    _react2.default.createElement(_SketchFields2.default, {
      rgb: rgb,
      hsl: hsl,
      hex: hex,
      onChange: onChange,
      disableAlpha: disableAlpha
    }),
    _react2.default.createElement(_SketchPresetColors2.default, {
      colors: presetColors,
      onClick: onChange,
      onSwatchHover: onSwatchHover
    })
  );
};

Sketch.propTypes = {
  disableAlpha: _propTypes2.default.bool,
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  styles: _propTypes2.default.object
};

Sketch.defaultProps = {
  disableAlpha: false,
  width: 200,
  styles: {},
  presetColors: ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF']
};

exports.default = (0, _common.ColorWrap)(Sketch);

/***/ }),
/* 870 */
/***/ (function(module, exports, __nested_webpack_require_4267556__) {

"use strict";


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

var _react = __nested_webpack_require_4267556__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4267556__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __nested_webpack_require_4267556__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4267556__(22);

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

/* eslint-disable no-param-reassign */

var SketchFields = exports.SketchFields = function SketchFields(_ref) {
  var onChange = _ref.onChange,
      rgb = _ref.rgb,
      hsl = _ref.hsl,
      hex = _ref.hex,
      disableAlpha = _ref.disableAlpha;

  var styles = (0, _reactcss2.default)({
    'default': {
      fields: {
        display: 'flex',
        paddingTop: '4px'
      },
      single: {
        flex: '1',
        paddingLeft: '6px'
      },
      alpha: {
        flex: '1',
        paddingLeft: '6px'
      },
      double: {
        flex: '2'
      },
      input: {
        width: '80%',
        padding: '4px 10% 3px',
        border: 'none',
        boxShadow: 'inset 0 0 0 1px #ccc',
        fontSize: '11px'
      },
      label: {
        display: 'block',
        textAlign: 'center',
        fontSize: '11px',
        color: '#222',
        paddingTop: '3px',
        paddingBottom: '4px',
        textTransform: 'capitalize'
      }
    },
    'disableAlpha': {
      alpha: {
        display: 'none'
      }
    }
  }, { disableAlpha: disableAlpha });

  var handleChange = function handleChange(data, e) {
    if (data.hex) {
      _color2.default.isValidHex(data.hex) && onChange({
        hex: data.hex,
        source: 'hex'
      }, e);
    } else if (data.r || data.g || data.b) {
      onChange({
        r: data.r || rgb.r,
        g: data.g || rgb.g,
        b: data.b || rgb.b,
        a: rgb.a,
        source: 'rgb'
      }, e);
    } else if (data.a) {
      if (data.a < 0) {
        data.a = 0;
      } else if (data.a > 100) {
        data.a = 100;
      }

      data.a /= 100;
      onChange({
        h: hsl.h,
        s: hsl.s,
        l: hsl.l,
        a: data.a,
        source: 'rgb'
      }, e);
    }
  };

  return _react2.default.createElement(
    'div',
    { style: styles.fields, className: 'flexbox-fix' },
    _react2.default.createElement(
      'div',
      { style: styles.double },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'hex',
        value: hex.replace('#', ''),
        onChange: handleChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.single },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'r',
        value: rgb.r,
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '255'
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.single },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'g',
        value: rgb.g,
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '255'
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.single },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'b',
        value: rgb.b,
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '255'
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.alpha },
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input, label: styles.label },
        label: 'a',
        value: Math.round(rgb.a * 100),
        onChange: handleChange,
        dragLabel: 'true',
        dragMax: '100'
      })
    )
  );
};

exports.default = SketchFields;

/***/ }),
/* 871 */
/***/ (function(module, exports, __nested_webpack_require_4271752__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4271752__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4271752__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4271752__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _common = __nested_webpack_require_4271752__(22);

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

var SketchPresetColors = exports.SketchPresetColors = function SketchPresetColors(_ref) {
  var colors = _ref.colors,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onSwatchHover = _ref.onSwatchHover;

  var styles = (0, _reactcss2.default)({
    'default': {
      colors: {
        margin: '0 -10px',
        padding: '10px 0 0 10px',
        borderTop: '1px solid #eee',
        display: 'flex',
        flexWrap: 'wrap',
        position: 'relative'
      },
      swatchWrap: {
        width: '16px',
        height: '16px',
        margin: '0 10px 10px 0'
      },
      swatch: {
        borderRadius: '3px',
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15)'
      }
    },
    'no-presets': {
      colors: {
        display: 'none'
      }
    }
  }, {
    'no-presets': !colors || !colors.length
  });

  var handleClick = function handleClick(hex, e) {
    onClick({
      hex: hex,
      source: 'hex'
    }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.colors, className: 'flexbox-fix' },
    colors.map(function (colorObjOrString) {
      var c = typeof colorObjOrString === 'string' ? { color: colorObjOrString } : colorObjOrString;
      var key = '' + c.color + (c.title || '');
      return _react2.default.createElement(
        'div',
        { key: key, style: styles.swatchWrap },
        _react2.default.createElement(_common.Swatch, _extends({}, c, {
          style: styles.swatch,
          onClick: handleClick,
          onHover: onSwatchHover,
          focusStyle: {
            boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.15), 0 0 4px ' + c.color
          }
        }))
      );
    })
  );
};

SketchPresetColors.propTypes = {
  colors: _propTypes2.default.arrayOf(_propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.shape({
    color: _propTypes2.default.string,
    title: _propTypes2.default.string
  })])).isRequired
};

exports.default = SketchPresetColors;

/***/ }),
/* 872 */
/***/ (function(module, exports, __nested_webpack_require_4274653__) {

"use strict";


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

var _react = __nested_webpack_require_4274653__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4274653__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4274653__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _merge = __nested_webpack_require_4274653__(46);

var _merge2 = _interopRequireDefault(_merge);

var _common = __nested_webpack_require_4274653__(22);

var _SliderSwatches = __nested_webpack_require_4274653__(873);

var _SliderSwatches2 = _interopRequireDefault(_SliderSwatches);

var _SliderPointer = __nested_webpack_require_4274653__(875);

var _SliderPointer2 = _interopRequireDefault(_SliderPointer);

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

var Slider = exports.Slider = function Slider(_ref) {
  var hsl = _ref.hsl,
      onChange = _ref.onChange,
      pointer = _ref.pointer,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      hue: {
        height: '12px',
        position: 'relative'
      },
      Hue: {
        radius: '2px'
      }
    }
  }, passedStyles));

  return _react2.default.createElement(
    'div',
    { style: styles.wrap || '', className: 'slider-picker ' + className },
    _react2.default.createElement(
      'div',
      { style: styles.hue },
      _react2.default.createElement(_common.Hue, {
        style: styles.Hue,
        hsl: hsl,
        pointer: pointer,
        onChange: onChange
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatches },
      _react2.default.createElement(_SliderSwatches2.default, { hsl: hsl, onClick: onChange })
    )
  );
};

Slider.propTypes = {
  styles: _propTypes2.default.object
};
Slider.defaultProps = {
  pointer: _SliderPointer2.default,
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Slider);

/***/ }),
/* 873 */
/***/ (function(module, exports, __nested_webpack_require_4276887__) {

"use strict";


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

var _react = __nested_webpack_require_4276887__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4276887__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _SliderSwatch = __nested_webpack_require_4276887__(874);

var _SliderSwatch2 = _interopRequireDefault(_SliderSwatch);

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

var SliderSwatches = exports.SliderSwatches = function SliderSwatches(_ref) {
  var onClick = _ref.onClick,
      hsl = _ref.hsl;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatches: {
        marginTop: '20px'
      },
      swatch: {
        boxSizing: 'border-box',
        width: '20%',
        paddingRight: '1px',
        float: 'left'
      },
      clear: {
        clear: 'both'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.swatches },
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.80',
        active: Math.round(hsl.l * 100) / 100 === 0.80 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick,
        first: true
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.65',
        active: Math.round(hsl.l * 100) / 100 === 0.65 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.50',
        active: Math.round(hsl.l * 100) / 100 === 0.50 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.35',
        active: Math.round(hsl.l * 100) / 100 === 0.35 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick
      })
    ),
    _react2.default.createElement(
      'div',
      { style: styles.swatch },
      _react2.default.createElement(_SliderSwatch2.default, {
        hsl: hsl,
        offset: '.20',
        active: Math.round(hsl.l * 100) / 100 === 0.20 && Math.round(hsl.s * 100) / 100 === 0.50,
        onClick: onClick,
        last: true
      })
    ),
    _react2.default.createElement('div', { style: styles.clear })
  );
};

exports.default = SliderSwatches;

/***/ }),
/* 874 */
/***/ (function(module, exports, __nested_webpack_require_4279742__) {

"use strict";


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

var _react = __nested_webpack_require_4279742__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4279742__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var SliderSwatch = exports.SliderSwatch = function SliderSwatch(_ref) {
  var hsl = _ref.hsl,
      offset = _ref.offset,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      active = _ref.active,
      first = _ref.first,
      last = _ref.last;

  var styles = (0, _reactcss2.default)({
    'default': {
      swatch: {
        height: '12px',
        background: 'hsl(' + hsl.h + ', 50%, ' + offset * 100 + '%)',
        cursor: 'pointer'
      }
    },
    'first': {
      swatch: {
        borderRadius: '2px 0 0 2px'
      }
    },
    'last': {
      swatch: {
        borderRadius: '0 2px 2px 0'
      }
    },
    'active': {
      swatch: {
        transform: 'scaleY(1.8)',
        borderRadius: '3.6px/2px'
      }
    }
  }, { active: active, first: first, last: last });

  var handleClick = function handleClick(e) {
    return onClick({
      h: hsl.h,
      s: 0.5,
      l: offset,
      source: 'hsl'
    }, e);
  };

  return _react2.default.createElement('div', { style: styles.swatch, onClick: handleClick });
};

exports.default = SliderSwatch;

/***/ }),
/* 875 */
/***/ (function(module, exports, __nested_webpack_require_4281346__) {

"use strict";


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

var _react = __nested_webpack_require_4281346__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4281346__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

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

var SliderPointer = exports.SliderPointer = function SliderPointer() {
  var styles = (0, _reactcss2.default)({
    'default': {
      picker: {
        width: '14px',
        height: '14px',
        borderRadius: '6px',
        transform: 'translate(-7px, -1px)',
        backgroundColor: 'rgb(248, 248, 248)',
        boxShadow: '0 1px 4px 0 rgba(0, 0, 0, 0.37)'
      }
    }
  });

  return _react2.default.createElement('div', { style: styles.picker });
};

exports.default = SliderPointer;

/***/ }),
/* 876 */
/***/ (function(module, exports, __nested_webpack_require_4282314__) {

"use strict";


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

var _react = __nested_webpack_require_4282314__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4282314__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4282314__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4282314__(70);

var _map2 = _interopRequireDefault(_map);

var _merge = __nested_webpack_require_4282314__(46);

var _merge2 = _interopRequireDefault(_merge);

var _color = __nested_webpack_require_4282314__(57);

var _color2 = _interopRequireDefault(_color);

var _materialColors = __nested_webpack_require_4282314__(438);

var material = _interopRequireWildcard(_materialColors);

var _common = __nested_webpack_require_4282314__(22);

var _SwatchesGroup = __nested_webpack_require_4282314__(877);

var _SwatchesGroup2 = _interopRequireDefault(_SwatchesGroup);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

var Swatches = exports.Swatches = function Swatches(_ref) {
  var width = _ref.width,
      height = _ref.height,
      onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      colors = _ref.colors,
      hex = _ref.hex,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      picker: {
        width: width,
        height: height
      },
      overflow: {
        height: height,
        overflowY: 'scroll'
      },
      body: {
        padding: '16px 0 6px 16px'
      },
      clear: {
        clear: 'both'
      }
    }
  }, passedStyles));

  var handleChange = function handleChange(data, e) {
    _color2.default.isValidHex(data) && onChange({
      hex: data,
      source: 'hex'
    }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.picker, className: 'swatches-picker ' + className },
    _react2.default.createElement(
      _common.Raised,
      null,
      _react2.default.createElement(
        'div',
        { style: styles.overflow },
        _react2.default.createElement(
          'div',
          { style: styles.body },
          (0, _map2.default)(colors, function (group) {
            return _react2.default.createElement(_SwatchesGroup2.default, {
              key: group.toString(),
              group: group,
              active: hex,
              onClick: handleChange,
              onSwatchHover: onSwatchHover
            });
          }),
          _react2.default.createElement('div', { style: styles.clear })
        )
      )
    )
  );
};

Swatches.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  height: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.arrayOf(_propTypes2.default.string)),
  styles: _propTypes2.default.object

  /* eslint-disable max-len */
};Swatches.defaultProps = {
  width: 320,
  height: 240,
  colors: [[material.red['900'], material.red['700'], material.red['500'], material.red['300'], material.red['100']], [material.pink['900'], material.pink['700'], material.pink['500'], material.pink['300'], material.pink['100']], [material.purple['900'], material.purple['700'], material.purple['500'], material.purple['300'], material.purple['100']], [material.deepPurple['900'], material.deepPurple['700'], material.deepPurple['500'], material.deepPurple['300'], material.deepPurple['100']], [material.indigo['900'], material.indigo['700'], material.indigo['500'], material.indigo['300'], material.indigo['100']], [material.blue['900'], material.blue['700'], material.blue['500'], material.blue['300'], material.blue['100']], [material.lightBlue['900'], material.lightBlue['700'], material.lightBlue['500'], material.lightBlue['300'], material.lightBlue['100']], [material.cyan['900'], material.cyan['700'], material.cyan['500'], material.cyan['300'], material.cyan['100']], [material.teal['900'], material.teal['700'], material.teal['500'], material.teal['300'], material.teal['100']], ['#194D33', material.green['700'], material.green['500'], material.green['300'], material.green['100']], [material.lightGreen['900'], material.lightGreen['700'], material.lightGreen['500'], material.lightGreen['300'], material.lightGreen['100']], [material.lime['900'], material.lime['700'], material.lime['500'], material.lime['300'], material.lime['100']], [material.yellow['900'], material.yellow['700'], material.yellow['500'], material.yellow['300'], material.yellow['100']], [material.amber['900'], material.amber['700'], material.amber['500'], material.amber['300'], material.amber['100']], [material.orange['900'], material.orange['700'], material.orange['500'], material.orange['300'], material.orange['100']], [material.deepOrange['900'], material.deepOrange['700'], material.deepOrange['500'], material.deepOrange['300'], material.deepOrange['100']], [material.brown['900'], material.brown['700'], material.brown['500'], material.brown['300'], material.brown['100']], [material.blueGrey['900'], material.blueGrey['700'], material.blueGrey['500'], material.blueGrey['300'], material.blueGrey['100']], ['#000000', '#525252', '#969696', '#D9D9D9', '#FFFFFF']],
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Swatches);

/***/ }),
/* 877 */
/***/ (function(module, exports, __nested_webpack_require_4288204__) {

"use strict";


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

var _react = __nested_webpack_require_4288204__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4288204__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4288204__(70);

var _map2 = _interopRequireDefault(_map);

var _SwatchesColor = __nested_webpack_require_4288204__(878);

var _SwatchesColor2 = _interopRequireDefault(_SwatchesColor);

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

var SwatchesGroup = exports.SwatchesGroup = function SwatchesGroup(_ref) {
  var onClick = _ref.onClick,
      onSwatchHover = _ref.onSwatchHover,
      group = _ref.group,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      group: {
        paddingBottom: '10px',
        width: '40px',
        float: 'left',
        marginRight: '10px'
      }
    }
  });

  return _react2.default.createElement(
    'div',
    { style: styles.group },
    (0, _map2.default)(group, function (color, i) {
      return _react2.default.createElement(_SwatchesColor2.default, {
        key: color,
        color: color,
        active: color.toLowerCase() === active,
        first: i === 0,
        last: i === group.length - 1,
        onClick: onClick,
        onSwatchHover: onSwatchHover
      });
    })
  );
};

exports.default = SwatchesGroup;

/***/ }),
/* 878 */
/***/ (function(module, exports, __nested_webpack_require_4289744__) {

"use strict";


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

var _react = __nested_webpack_require_4289744__(1);

var _react2 = _interopRequireDefault(_react);

var _reactcss = __nested_webpack_require_4289744__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _color = __nested_webpack_require_4289744__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4289744__(22);

var _CheckIcon = __nested_webpack_require_4289744__(879);

var _CheckIcon2 = _interopRequireDefault(_CheckIcon);

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

var SwatchesColor = exports.SwatchesColor = function SwatchesColor(_ref) {
  var color = _ref.color,
      _ref$onClick = _ref.onClick,
      onClick = _ref$onClick === undefined ? function () {} : _ref$onClick,
      onSwatchHover = _ref.onSwatchHover,
      first = _ref.first,
      last = _ref.last,
      active = _ref.active;

  var styles = (0, _reactcss2.default)({
    'default': {
      color: {
        width: '40px',
        height: '24px',
        cursor: 'pointer',
        background: color,
        marginBottom: '1px'
      },
      check: {
        color: _color2.default.getContrastingColor(color),
        marginLeft: '8px',
        display: 'none'
      }
    },
    'first': {
      color: {
        overflow: 'hidden',
        borderRadius: '2px 2px 0 0'
      }
    },
    'last': {
      color: {
        overflow: 'hidden',
        borderRadius: '0 0 2px 2px'
      }
    },
    'active': {
      check: {
        display: 'block'
      }
    },
    'color-#FFFFFF': {
      color: {
        boxShadow: 'inset 0 0 0 1px #ddd'
      },
      check: {
        color: '#333'
      }
    },
    'transparent': {
      check: {
        color: '#333'
      }
    }
  }, {
    first: first,
    last: last,
    active: active,
    'color-#FFFFFF': color === '#FFFFFF',
    'transparent': color === 'transparent'
  });

  return _react2.default.createElement(
    _common.Swatch,
    {
      color: color,
      style: styles.color,
      onClick: onClick,
      onHover: onSwatchHover,
      focusStyle: { boxShadow: '0 0 4px ' + color }
    },
    _react2.default.createElement(
      'div',
      { style: styles.check },
      _react2.default.createElement(_CheckIcon2.default, null)
    )
  );
};

exports.default = SwatchesColor;

/***/ }),
/* 879 */
/***/ (function(module, exports, __nested_webpack_require_4292195__) {

"use strict";


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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = __nested_webpack_require_4292195__(1);

var _react2 = _interopRequireDefault(_react);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var DEFAULT_SIZE = 24;

exports.default = function (_ref) {
  var _ref$fill = _ref.fill,
      fill = _ref$fill === undefined ? 'currentColor' : _ref$fill,
      _ref$width = _ref.width,
      width = _ref$width === undefined ? DEFAULT_SIZE : _ref$width,
      _ref$height = _ref.height,
      height = _ref$height === undefined ? DEFAULT_SIZE : _ref$height,
      _ref$style = _ref.style,
      style = _ref$style === undefined ? {} : _ref$style,
      props = _objectWithoutProperties(_ref, ['fill', 'width', 'height', 'style']);

  return _react2.default.createElement(
    'svg',
    _extends({
      viewBox: '0 0 ' + DEFAULT_SIZE + ' ' + DEFAULT_SIZE,
      style: _extends({ fill: fill, width: width, height: height }, style)
    }, props),
    _react2.default.createElement('path', { d: 'M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z' })
  );
};

/***/ }),
/* 880 */
/***/ (function(module, exports, __nested_webpack_require_4293882__) {

"use strict";


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

var _react = __nested_webpack_require_4293882__(1);

var _react2 = _interopRequireDefault(_react);

var _propTypes = __nested_webpack_require_4293882__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactcss = __nested_webpack_require_4293882__(13);

var _reactcss2 = _interopRequireDefault(_reactcss);

var _map = __nested_webpack_require_4293882__(70);

var _map2 = _interopRequireDefault(_map);

var _merge = __nested_webpack_require_4293882__(46);

var _merge2 = _interopRequireDefault(_merge);

var _color = __nested_webpack_require_4293882__(57);

var _color2 = _interopRequireDefault(_color);

var _common = __nested_webpack_require_4293882__(22);

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

var Twitter = exports.Twitter = function Twitter(_ref) {
  var onChange = _ref.onChange,
      onSwatchHover = _ref.onSwatchHover,
      hex = _ref.hex,
      colors = _ref.colors,
      width = _ref.width,
      triangle = _ref.triangle,
      _ref$styles = _ref.styles,
      passedStyles = _ref$styles === undefined ? {} : _ref$styles,
      _ref$className = _ref.className,
      className = _ref$className === undefined ? '' : _ref$className;

  var styles = (0, _reactcss2.default)((0, _merge2.default)({
    'default': {
      card: {
        width: width,
        background: '#fff',
        border: '0 solid rgba(0,0,0,0.25)',
        boxShadow: '0 1px 4px rgba(0,0,0,0.25)',
        borderRadius: '4px',
        position: 'relative'
      },
      body: {
        padding: '15px 9px 9px 15px'
      },
      label: {
        fontSize: '18px',
        color: '#fff'
      },
      triangle: {
        width: '0px',
        height: '0px',
        borderStyle: 'solid',
        borderWidth: '0 9px 10px 9px',
        borderColor: 'transparent transparent #fff transparent',
        position: 'absolute'
      },
      triangleShadow: {
        width: '0px',
        height: '0px',
        borderStyle: 'solid',
        borderWidth: '0 9px 10px 9px',
        borderColor: 'transparent transparent rgba(0,0,0,.1) transparent',
        position: 'absolute'
      },
      hash: {
        background: '#F0F0F0',
        height: '30px',
        width: '30px',
        borderRadius: '4px 0 0 4px',
        float: 'left',
        color: '#98A1A4',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      },
      input: {
        width: '100px',
        fontSize: '14px',
        color: '#666',
        border: '0px',
        outline: 'none',
        height: '28px',
        boxShadow: 'inset 0 0 0 1px #F0F0F0',
        boxSizing: 'content-box',
        borderRadius: '0 4px 4px 0',
        float: 'left',
        paddingLeft: '8px'
      },
      swatch: {
        width: '30px',
        height: '30px',
        float: 'left',
        borderRadius: '4px',
        margin: '0 6px 6px 0'
      },
      clear: {
        clear: 'both'
      }
    },
    'hide-triangle': {
      triangle: {
        display: 'none'
      },
      triangleShadow: {
        display: 'none'
      }
    },
    'top-left-triangle': {
      triangle: {
        top: '-10px',
        left: '12px'
      },
      triangleShadow: {
        top: '-11px',
        left: '12px'
      }
    },
    'top-right-triangle': {
      triangle: {
        top: '-10px',
        right: '12px'
      },
      triangleShadow: {
        top: '-11px',
        right: '12px'
      }
    }
  }, passedStyles), {
    'hide-triangle': triangle === 'hide',
    'top-left-triangle': triangle === 'top-left',
    'top-right-triangle': triangle === 'top-right'
  });

  var handleChange = function handleChange(hexcode, e) {
    _color2.default.isValidHex(hexcode) && onChange({
      hex: hexcode,
      source: 'hex'
    }, e);
  };

  return _react2.default.createElement(
    'div',
    { style: styles.card, className: 'twitter-picker ' + className },
    _react2.default.createElement('div', { style: styles.triangleShadow }),
    _react2.default.createElement('div', { style: styles.triangle }),
    _react2.default.createElement(
      'div',
      { style: styles.body },
      (0, _map2.default)(colors, function (c, i) {
        return _react2.default.createElement(_common.Swatch, {
          key: i,
          color: c,
          hex: c,
          style: styles.swatch,
          onClick: handleChange,
          onHover: onSwatchHover,
          focusStyle: {
            boxShadow: '0 0 4px ' + c
          }
        });
      }),
      _react2.default.createElement(
        'div',
        { style: styles.hash },
        '#'
      ),
      _react2.default.createElement(_common.EditableInput, {
        style: { input: styles.input },
        value: hex.replace('#', ''),
        onChange: handleChange
      }),
      _react2.default.createElement('div', { style: styles.clear })
    )
  );
};

Twitter.propTypes = {
  width: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]),
  triangle: _propTypes2.default.oneOf(['hide', 'top-left', 'top-right']),
  colors: _propTypes2.default.arrayOf(_propTypes2.default.string),
  styles: _propTypes2.default.object
};

Twitter.defaultProps = {
  width: 276,
  colors: ['#FF6900', '#FCB900', '#7BDCB5', '#00D084', '#8ED1FC', '#0693E3', '#ABB8C3', '#EB144C', '#F78DA7', '#9900EF'],
  triangle: 'top-left',
  styles: {}
};

exports.default = (0, _common.ColorWrap)(Twitter);

/***/ }),
/* 881 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),
/* 882 */
/***/ (function(module, exports, __nested_webpack_require_4299511__) {

"use strict";


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

var _defineProperty2 = __nested_webpack_require_4299511__(883);

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _assign = __nested_webpack_require_4299511__(44);

var _assign2 = _interopRequireDefault(_assign);

var _themes = __nested_webpack_require_4299511__(327);

var _icons = __nested_webpack_require_4299511__(266);

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

var osm = {
  type: 'osm-tiles',
  datatype: ['map-tiles'],
  local: true,
  orientation: '2d',
  hidden: true,
  name: 'OSM Tiles',
  thumbnail: _icons.svgGeoMapIcon,
  availableOptions: ['minPos', 'maxPos', 'maxZoom', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'name'],
  defaultOptions: {
    minPos: -180,
    maxPos: 180,
    maxZoom: 19,
    labelPosition: 'bottomRight',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0
  }
};

var mapbox = {
  type: 'mapbox-tiles',
  datatype: ['map-tiles'],
  local: true,
  orientation: '2d',
  hidden: true,
  name: 'Mapbox Tiles',
  thumbnail: _icons.svgGeoMapIcon,
  availableOptions: ['style', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'name'],
  defaultOptions: {
    style: 'mapbox.streets',
    labelPosition: 'bottomRight',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0
  }
};

var TRACKS_INFO = exports.TRACKS_INFO = [osm, (0, _assign2['default'])({}, osm, { type: 'osm' }), mapbox, (0, _assign2['default'])({}, mapbox, { type: 'mapbox' }), {
  type: 'left-axis',
  datatype: ['axis'],
  local: true,
  orientation: '1d-vertical',
  name: 'Left Axis',
  thumbnail: _icons.svgVertical1DAxisIcon,
  availableOptions: ['minWidth'],
  defaultOptions: {
    minWidth: 100
  }
}, {
  type: 'top-axis',
  datatype: ['axis'],
  local: true,
  orientation: '1d-horizontal',
  name: 'Top Axis',
  thumbnail: _icons.svg1DAxisIcon,
  defaultOptions: {}
}, {
  type: 'horizontal-rule',
  datatype: ['x-coord'],
  local: true,
  orientation: 'whole',
  name: 'Horizontal Rule',
  thumbnail: null,
  availableOptions: ['color'],
  defaultOptions: {
    color: 'black'
  }
}, {
  type: 'vertical-rule',
  datatype: ['y-coord'],
  local: true,
  orientation: 'whole',
  name: 'Vertical Rule',
  thumbnail: null,
  availableOptions: ['color'],
  defaultOptions: {
    color: 'black'
  }
}, {
  type: 'cross-rule',
  datatype: ['xy-coord'],
  local: true,
  orientation: 'whole',
  name: 'Cross Rule',
  thumbnail: null,
  availableOptions: ['color'],
  defaultOptions: {
    color: 'black'
  }
}, {
  type: 'simple-svg',
  datatype: [],
  local: false,
  orientation: '2d',
  exportable: true,
  availableOptions: ['minWidth', 'minHeight'],
  defaultOptions: {
    minWidth: 100,
    minHeight: 100
  }
}, {
  type: 'heatmap',
  datatype: ['matrix'],
  local: false,
  orientation: '2d',
  thumbnail: _icons.svg2DHeatmapIcon,
  exportable: true,
  availableOptions: ['backgroundColor', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'colorRange', 'colorbarBackgroundColor', 'maxZoom', 'minWidth', 'minHeight', 'dataTransform', 'colorbarPosition', 'trackBorderWidth', 'trackBorderColor', 'heatmapValueScaling', 'showMousePosition', 'mousePositionColor', 'showTooltip', 'extent', 'zeroValueColor'],
  defaultOptions: {
    backgroundColor: '#eeeeee',
    labelPosition: 'bottomRight',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: true,
    labelShowAssembly: true,
    colorRange: [
    // corresponding to the fall colormap
    'white', 'rgba(245,166,35,1.0)', 'rgba(208,2,27,1.0)', 'black'],
    colorbarBackgroundColor: '#ffffff',
    maxZoom: null,
    minWidth: 100,
    minHeight: 100,
    colorbarPosition: 'topRight',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    heatmapValueScaling: 'log',
    showMousePosition: false,
    mousePositionColor: '#000000',
    showTooltip: false,
    extent: 'full',
    zeroValueColor: null
  },
  defaultOptionsByTheme: (0, _defineProperty3['default'])({}, _themes.THEME_DARK, {
    backgroundColor: '#000000',
    colorRange: [
    // corresponding to the inverted fall colormap
    'black', 'rgba(208,2,27,1.0)', 'rgba(245,166,35,1.0)', 'white'],
    colorbarBackgroundColor: '#000000',
    labelColor: '#ffffff',
    labelBackgroundColor: '#000000',
    trackBorderColor: '#ffffff',
    mousePositionColor: '#ffffff'
  })
}, {
  type: 'linear-heatmap',
  aliases: ['horizontal-heatmap', 'vertical-heatmap'],
  datatype: ['matrix'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  thumbnail: _icons.svg2DHeatmapIcon,
  defaultOptions: {
    backgroundColor: '#eeeeee',
    labelPosition: 'bottomRight',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: true,
    labelShowAssembly: true,
    labelColor: 'black',
    colorRange: [
    // corresponding to the fall colormap
    'white', 'rgba(245,166,35,1.0)', 'rgba(208,2,27,1.0)', 'black'],
    maxZoom: null,
    minWidth: 100,
    minHeight: 40,
    trackBorderWidth: 0,
    trackBorderColor: 'black'
  },
  availableOptions: ['backgroundColor', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'colorRange', 'maxZoom', 'minWidth', 'minHeight', 'dataTransform', 'oneDHeatmapFlipped', 'colorbarPosition', 'trackBorderWidth', 'trackBorderColor', 'heatmapValueScaling']
}, {
  type: 'line',
  aliases: ['horizontal-line', 'vertical-line'],
  datatype: ['vector'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  thumbnail: _icons.svgHorizontalLineIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundColor', 'labelBackgroundOpacity', 'axisLabelFormatting', 'axisPositionHorizontal', 'axisMargin', 'lineStrokeWidth', 'lineStrokeColor', 'valueScaling', 'valueScaleMin', 'valueScaleMax', 'trackBorderWidth', 'trackBorderColor', 'trackType', 'showMousePosition', 'showTooltip', 'mousePositionColor', 'aggregationMode', 'minHeight'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelBackgroundColor: 'white',
    labelShowResolution: false,
    labelShowAssembly: true,
    axisLabelFormatting: 'scientific',
    axisPositionHorizontal: 'right',
    lineStrokeColor: 'blue',
    lineStrokeWidth: 1,
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    labelTextOpacity: 0.4,
    showMousePosition: false,
    minHeight: 20,
    mousePositionColor: '#000000',
    showTooltip: false
  },
  defaultOptionsByTheme: (0, _defineProperty3['default'])({}, _themes.THEME_DARK, {
    labelColor: '#ffffff',
    labelBackgroundColor: '#000000',
    trackBorderColor: '#ffffff',
    mousePositionColor: '#ffffff'
  })
}, {
  type: '1d-heatmap',
  aliases: ['horizontal-1d-heatmap', 'vertical-1d-heatmap'],
  datatype: ['vector'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  thumbnail: _icons.svgHorizontal1dHeatmap,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'axisPositionHorizontal', 'axisMargin', 'colorRange', 'valueScaling', 'trackBorderWidth', 'trackBorderColor', 'trackType', 'showMousePosition', 'showTooltip', 'mousePositionColor', 'aggregationMode'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: false,
    labelShowAssembly: true,
    axisPositionHorizontal: 'right',
    colorRange: [
    // corresponding to the fall colormap
    'white', 'rgba(245,166,35,1.0)', 'rgba(208,2,27,1.0)', 'black'],
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    labelTextOpacity: 0.4,
    showMousePosition: false,
    mousePositionColor: '#000000',
    showTooltip: false
  }
}, {
  type: 'vector-heatmap',
  aliases: ['horizontal-vector-heatmap', 'vertical-vector-heatmap'],
  datatype: ['vector'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  minHeight: 1,
  thumbnail: null,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'valueScaling', 'labelTextOpacity', 'labelBackgroundOpacity', 'colorRange', 'trackBorderWidth', 'trackBorderColor', 'trackType', 'heatmapValueScaling'],
  defaultOptions: {
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: false,
    labelShowAssembly: true,
    labelColor: 'black',
    labelTextOpacity: 0.4,
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    heatmapValueScaling: 'log'
  }
}, {
  type: 'multivec',
  aliases: ['horizontal-multivec', 'vertical-multivec'],
  datatype: ['multivec'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  thumbnail: null,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'minHeight', 'valueScaling', 'labelTextOpacity', 'labelBackgroundOpacity', 'colorRange', 'trackBorderWidth', 'trackBorderColor', 'trackType', 'heatmapValueScaling', 'selectRows', 'selectRowsAggregationMode', 'selectRowsAggregationWithRelativeHeight', 'selectRowsAggregationMethod', 'colorbarBackgroundColor', 'colorbarPosition', 'zeroValueColor'],
  defaultOptions: {
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: true,
    labelShowAssembly: true,
    labelColor: 'black',
    labelTextOpacity: 0.4,
    minHeight: 100,
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    heatmapValueScaling: 'log',
    selectRows: null,
    selectRowsAggregationMode: 'mean',
    selectRowsAggregationWithRelativeHeight: true,
    selectRowsAggregationMethod: 'client',
    colorbarBackgroundColor: '#ffffff',
    colorbarPosition: 'topRight',
    zeroValueColor: null
  },
  defaultOptionsByTheme: (0, _defineProperty3['default'])({}, _themes.THEME_DARK, {
    colorbarBackgroundColor: '#000000'
  })
}, {
  type: 'point',
  aliases: ['horizontal-point', 'vertical-point'],
  datatype: ['vector'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'axisLabelFormatting', 'axisPositionHorizontal', 'axisMargin', 'pointColor', 'pointSize', 'valueScaling', 'trackBorderWidth', 'trackBorderColor'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: false,
    labelShowAssembly: true,
    axisLabelFormatting: 'scientific',
    axisPositionHorizontal: 'right',
    pointColor: 'red',
    pointSize: 3,
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    labelTextOpacity: 0.4
  }
}, {
  type: 'divergent-bar',
  aliases: ['horizontal-divergent-bar', 'vertical-divergent-bar'],
  datatype: ['vector'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'axisLabelFormatting', 'axisPositionHorizontal', 'axisMargin', 'barFillColorTop', 'barFillColorBottom', 'valueScaling', 'trackBorderWidth', 'trackBorderColor', 'barOpacity'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: false,
    labelShowAssembly: true,
    axisPositionHorizontal: 'right',
    axisLabelFormatting: 'scientific',
    barFillColorBottom: 'red',
    barFillColorTop: 'green',
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    labelTextOpacity: 0.4,
    barOpacity: 1
  }
}, {
  type: 'bar',
  aliases: ['horizontal-bar', 'vertical-bar'],
  datatype: ['vector'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  availableOptions: ['align', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelShowResolution', 'labelShowAssembly', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'axisLabelFormatting', 'axisPositionHorizontal', 'axisMargin', 'barFillColor', 'colorRange', 'colorRangeGradient', 'valueScaling', 'valueScaleMin', 'valueScaleMax', 'trackBorderWidth', 'trackBorderColor', 'barOpacity', 'showMousePosition', 'showTooltip', 'aggregationMode', 'zeroLineVisible', 'zeroLineColor', 'zeroLineOpacity'],
  defaultOptions: {
    align: 'bottom',
    labelColor: '[glyph-color]',
    labelPosition: 'topLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    labelShowResolution: false,
    labelShowAssembly: true,
    axisLabelFormatting: 'scientific',
    axisPositionHorizontal: 'right',
    barFillColor: 'darkgreen',
    valueScaling: 'linear',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    labelTextOpacity: 0.4,
    barOpacity: 1
  }
}, {
  type: '2d-tiles',
  datatype: ['matrix'],
  local: false,
  orientation: '2d',
  name: '2D Tile Outlines',
  thumbnail: _icons.svg2DTilesIcon
}, {
  type: '1d-value-interval',
  aliases: ['horizontal-1d-value-interval', 'vertical-1d-value-interval'],
  datatype: ['bed-value'],
  local: false,
  orientation: ['1d-horizontal'],
  rotatable: true,
  name: '1D Rectangles',
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'axisPositionHorizontal', 'axisMargin'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'bottomLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    axisPositionHorizontal: 'left',
    lineStrokeColor: 'blue',
    valueScaling: 'linear'
  }
}, {
  type: 'stacked-interval',
  aliases: ['top-stacked-interval', 'left-stacked-interval'],
  datatype: ['stacked-interval'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  thumbnail: 'horizontal-stacked-interval.png',
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity']
}, {
  type: 'viewport-projection-vertical',
  datatype: ['1d-projection'],
  local: true,
  hidden: true,
  projection: true,
  orientation: '1d-vertical',
  name: 'Viewport Projection',
  thumbnail: 'viewport-projection-center.png',
  availableOptions: ['projectionFillColor', 'projectionStrokeColor', 'strokeWidth'],
  defaultOptions: {
    projectionFillColor: '#777',
    projectionStrokeColor: '#777',
    projectionFillOpacity: 0.3,
    projectionStrokeOpacity: 0.7,
    strokeWidth: 1
  }
}, {
  type: 'viewport-projection-horizontal',
  datatype: ['1d-projection'],
  local: true,
  hidden: true,
  projection: true,
  orientation: '1d-horizontal',
  name: 'Viewport Projection',
  thumbnail: 'viewport-projection-center.png',
  availableOptions: ['projectionFillColor', 'projectionStrokeColor', 'strokeWidth'],
  defaultOptions: {
    projectionFillColor: '#777',
    projectionStrokeColor: '#777',
    projectionFillOpacity: 0.3,
    projectionStrokeOpacity: 0.7,
    strokeWidth: 1
  }
}, {
  type: 'viewport-projection-center',
  datatype: ['2d-projection'],
  local: true,
  hidden: true,
  projection: true,
  orientation: '2d',
  name: 'Viewport Projection',
  thumbnail: 'viewport-projection-center.png',
  availableOptions: ['projectionFillColor', 'projectionStrokeColor', 'strokeWidth'],
  defaultOptions: {
    projectionFillColor: '#777',
    projectionStrokeColor: '#777',
    projectionFillOpacity: 0.3,
    projectionStrokeOpacity: 0.7,
    strokeWidth: 1
  }
}, {
  type: 'gene-annotations',
  aliases: ['horizontal-gene-annotations', 'vertical-gene-annotations'],
  datatype: ['gene-annotation'],
  local: false,
  defaultHeight: 90,
  defaultWidth: 90,
  rotatable: true,
  orientation: '1d-horizontal',
  name: 'Gene Annotations',
  thumbnail: _icons.svgGeneAnnotationsIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundColor', 'labelBackgroundOpacity', 'minHeight', 'plusStrandColor', 'minusStrandColor', 'trackBorderWidth', 'trackBorderColor', 'showMousePosition', 'mousePositionColor', 'fontSize', 'geneAnnotationHeight', 'geneLabelPosition', 'geneStrandSpacing'],
  defaultOptions: {
    fontSize: 10,
    labelColor: 'black',
    labelBackgroundColor: '#ffffff',
    labelPosition: 'hidden',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    minHeight: 24,
    plusStrandColor: 'blue',
    minusStrandColor: 'red',
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    showMousePosition: false,
    mousePositionColor: '#000000',
    geneAnnotationHeight: 16,
    geneLabelPosition: 'outside',
    geneStrandSpacing: 4
  },
  defaultOptionsByTheme: (0, _defineProperty3['default'])({}, _themes.THEME_DARK, {
    labelColor: '#ffffff',
    labelBackgroundColor: '#000000',
    trackBorderColor: '#ffffff',
    mousePositionColor: '#ffffff',
    plusStrandColor: '#40a0ff'
  })
}, {
  type: 'arrowhead-domains',
  datatype: ['arrowhead-domains'],
  local: false,
  orientation: '2d',
  name: 'Arrowhead Domains',
  thumbnail: _icons.svgArrowheadDomainsIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'trackBorderWidth', 'trackBorderColor'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'hidden',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    trackBorderWidth: 0,
    trackBorderColor: 'black'
  }
}, {
  type: 'linear-2d-rectangle-domains',
  aliases: ['horizontal-2d-rectangle-domains', 'vertical-2d-rectangle-domains'],
  datatype: ['2d-rectangle-domains'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  name: 'Horizontal 2D Rectangle Domains',
  thumbnail: _icons.svgArrowheadDomainsIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'trackBorderWidth', 'trackBorderColor', 'rectangleDomainFillColor', 'rectangleDomainStrokeColor', 'rectangleDomainOpacity', 'minSquareSize'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'bottomLeft',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    rectangleDomainFillColor: 'grey',
    rectangleDomainStrokeColor: 'black',
    rectangleDomainOpacity: 0.6,
    minSquareSize: 'none'
  }
}, {
  type: '2d-rectangle-domains',
  datatype: ['2d-rectangle-domains'],
  local: false,
  orientation: '2d',
  name: '2D Rectangle Domains',
  thumbnail: _icons.svgArrowheadDomainsIcon,
  availableOptions: ['flipDiagonal', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'trackBorderWidth', 'trackBorderColor', 'rectangleDomainFillColor', 'rectangleDomainFillOpacity', 'rectangleDomainStrokeColor', 'rectangleDomainOpacity', 'minSquareSize'],
  defaultOptions: {
    flipDiagonal: 'none',
    labelColor: 'black',
    labelPosition: 'hidden',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    rectangleDomainFillColor: 'grey',
    rectangleDomainFillOpacity: 0.4,
    rectangleDomainStrokeColor: 'black',
    rectangleDomainOpacity: 0.6,
    minSquareSize: 'none'
  }
}, {
  type: 'horizontal-1d-annotations',
  datatype: ['nothing'], // Unfortunately one has to specify something here
  local: false,
  orientation: '1d-horizontal',
  name: 'Horizontal 1D Annotations',
  thumbnail: null,
  availableOptions: ['fill', 'fillOpacity', 'stroke', 'strokeOpacity', 'strokeWidth', 'strokePos', 'regions'],
  defaultOptions: {
    fill: 'red',
    fillOpacity: 0.2,
    stroke: 'red',
    strokeOpacity: 0,
    strokeWidth: 1,
    regions: [],
    strokePos: []
  }
}, {
  type: 'vertical-1d-annotations',
  datatype: ['nothing'], // Unfortunately one has to specify something here
  local: false,
  orientation: '1d-vertical',
  name: 'Vertical 1D Annotations',
  thumbnail: null,
  availableOptions: ['fill', 'fillOpacity', 'stroke', 'strokeOpacity', 'regions'],
  defaultOptions: {
    fill: 'red',
    fillOpacity: '0.2',
    stroke: 'red',
    strokeOpacity: '0',
    regions: []
  }
}, {
  type: '2d-annotations',
  datatype: ['2d-annotations'],
  local: false,
  orientation: '2d',
  name: '2D Annotations',
  thumbnail: _icons.svgArrowheadDomainsIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor', 'labelTextOpacity', 'labelBackgroundOpacity', 'trackBorderWidth', 'trackBorderColor', 'rectangleDomainFillColor', 'rectangleDomainStrokeColor', 'rectangleDomainOpacity', 'minSquareSize', 'isClickable', 'hoverColor', 'selectColor', 'exclude', 'trackBorderBgWidth', 'trackBorderBgColor', 'trackBorderBgAlpha'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'hidden',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    rectangleDomainFillColor: 'grey',
    rectangleDomainStrokeColor: 'black',
    rectangleDomainOpacity: 0.6,
    minSquareSize: 'none',
    isClickable: false,
    hoverColor: 'orange',
    selectColor: 'fuchsia',
    exclude: [],
    trackBorderBgWidth: 0,
    trackBorderBgColor: 'black',
    trackBorderBgAlpha: 0.33
  }
}, {
  type: 'square-markers',
  datatype: ['bedpe'],
  local: false,
  orientation: '2d',
  name: 'Square Markers',
  thumbnail: _icons.svgArrowheadDomainsIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'labelColor'],
  defaultOptions: {
    labelColor: 'black',
    labelPosition: 'hidden',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    trackBorderWidth: 0,
    trackBorderColor: 'black'
  }
}, {
  type: 'combined',
  datatype: 'any',
  local: true,
  orientation: 'any'
}, {
  type: 'horizontal-chromosome-grid',
  datatype: ['chromsizes'],
  local: false,
  orientation: '1d-horizontal',
  name: 'Chromosome Grid',
  chromInfoPath: '//s3.amazonaws.com/pkerp/data/hg19/chromSizes.tsv',
  thumbnail: null,
  availableOptions: ['lineStrokeWidth', 'lineStrokeColor', 'showMousePosition'],
  defaultOptions: {
    lineStrokeWidth: 1,
    lineStrokeColor: 'grey',
    showMousePosition: false
  }
}, {
  type: 'vertical-chromosome-grid',
  datatype: ['chromsizes'],
  local: false,
  orientation: '1d-vertical',
  name: 'Chromosome Grid',
  chromInfoPath: '//s3.amazonaws.com/pkerp/data/hg19/chromSizes.tsv',
  thumbnail: null,
  availableOptions: ['lineStrokeWidth', 'lineStrokeColor', 'showMousePosition'],
  defaultOptions: {
    lineStrokeWidth: 1,
    lineStrokeColor: 'grey',
    showMousePosition: false
  }
}, {
  type: '2d-chromosome-grid',
  datatype: ['chromsizes'],
  local: false,
  orientation: '2d',
  name: 'Chromosome Grid',
  chromInfoPath: '//s3.amazonaws.com/pkerp/data/hg19/chromSizes.tsv',
  thumbnail: null,
  availableOptions: ['lineStrokeWidth', 'lineStrokeColor'],
  defaultOptions: {
    lineStrokeWidth: 1,
    lineStrokeColor: 'grey'
  }
}, {
  type: '2d-chromosome-annotations',
  datatype: ['chromsizes'],
  local: true,
  orientation: '2d',
  name: '2D Chromosome Annotations',
  thumbnail: null,
  hidden: true
}, {
  type: '2d-chromosome-labels',
  datatype: ['chromsizes'],
  local: true,
  orientation: '2d',
  name: 'Pairwise Chromosome Labels',
  thumbnail: null
}, {
  type: 'chromosome-labels',
  aliases: ['horizontal-chromosome-labels', 'vertical-chromosome-labels'],
  datatype: ['chromsizes'],
  orientation: '1d-horizontal',
  rotatable: true,
  minHeight: 35,
  defaultHeight: 30,
  name: 'Chromosome Axis',
  thumbnail: null,
  availableOptions: ['color', 'stroke', 'fontSize', 'fontIsLeftAligned', 'showMousePosition', 'mousePositionColor', 'tickPositions', 'tickFormat', 'reverseOrientation'],
  defaultOptions: {
    color: '#808080',
    stroke: '#ffffff',
    fontSize: 12,
    fontIsLeftAligned: false,
    showMousePosition: false,
    mousePositionColor: '#000000',
    reverseOrientation: false
  },
  defaultOptionsByTheme: (0, _defineProperty3['default'])({}, _themes.THEME_DARK, {
    color: '#808080',
    stroke: '#000000',
    mousePositionColor: '#ffffff'
  })
}, {
  type: 'vertical-1d-tiles',
  datatype: ['1d-tiles'],
  local: false,
  orientation: '1d-vertical',
  name: 'Vertical 1D Tile Outlines',
  thumbnail: _icons.svgVertical1DTilesIcon
}, {
  type: 'horizontal-1d-tiles',
  datatype: ['vector', 'stacked-interval', 'gene-annotation'],
  local: false,
  orientation: '1d-horizontal',
  name: 'Horizontal 1D Tile Outlines',
  thumbnail: _icons.svg1DTilesIcon
}, {
  type: 'osm-2d-tile-ids',
  datatype: ['map-tiles'],
  local: false,
  orientation: '2d',
  name: 'OSM Tile Outlines',
  thumbnail: _icons.svg2DTilesIcon,
  availableOptions: ['minPos', 'maxPos', 'maxZoom', 'labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'name'],
  defaultOptions: {
    minPos: -180,
    maxPos: 180,
    maxZoom: 19,
    labelPosition: 'bottomRight',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0
  }
}, {
  type: 'raster-tiles',
  datatype: ['map-tiles'],
  local: true,
  orientation: '2d',
  hidden: true,
  name: 'Raster Tiles',
  thumbnail: _icons.svgGeoMapIcon,
  availableOptions: ['labelPosition', 'labelLeftMargin', 'labelRightMargin', 'labelTopMargin', 'labelBottomMargin', 'name'],
  defaultOptions: {
    labelPosition: 'bottomRight',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0
  }
}, {
  type: 'image-tiles',
  datatype: ['image-tiles'],
  local: true,
  orientation: '2d',
  hidden: true,
  name: 'Image Tiles',
  thumbnail: null
}, {
  type: 'bedlike',
  datatype: ['bedlike'],
  aliases: ['vertical-bedlike'],
  local: false,
  orientation: '1d-horizontal',
  rotatable: true,
  name: 'BED-like track',
  thumbnail: null,
  availableOptions: ['alternating', 'annotationHeight', 'annotationStyle', 'fillColor', 'fillOpacity', 'fontColor', 'fontSize', 'minusStrandColor', 'plusStrandColor', 'labelBottomMargin', 'labelColor', 'labelLeftMargin', 'labelPosition', 'labelRightMargin', 'labelTopMargin', 'labelTextOpacity', 'labelBackgroundOpacity', 'maxAnnotationHeight', 'minHeight', 'trackBorderWidth', 'trackBorderColor', 'valueColumn', 'colorEncoding', 'colorRange', 'colorEncodingRange', 'separatePlusMinusStrands', 'showTexts', 'axisPositionHorizontal', 'axisMargin'],
  defaultOptions: {
    alternating: false,
    annotationStyle: 'box',
    fillColor: 'blue',
    fillOpacity: 0.3,
    fontSize: '10',
    axisPositionHorizontal: 'right',
    labelColor: 'black',
    labelPosition: 'hidden',
    labelLeftMargin: 0,
    labelRightMargin: 0,
    labelTopMargin: 0,
    labelBottomMargin: 0,
    minHeight: 20,
    maxAnnotationHeight: null,
    trackBorderWidth: 0,
    trackBorderColor: 'black',
    valueColumn: null,
    colorEncoding: 'itemRgb',
    showTexts: false,
    colorRange: ['#000000', '#652537', '#bf5458', '#fba273', '#ffffe0'],
    colorEncodingRange: false,
    separatePlusMinusStrands: true,
    annotationHeight: 16
  }
}, {
  type: 'empty',
  datatype: [],
  orientation: '1d-horizontal',
  name: 'Empty track',
  thumbnail: null,
  availableOptions: [],
  defaultOptions: {}
}];

exports['default'] = TRACKS_INFO;

/***/ }),
/* 883 */
/***/ (function(module, exports, __nested_webpack_require_4329121__) {

"use strict";


exports.__esModule = true;

var _defineProperty = __nested_webpack_require_4329121__(131);

var _defineProperty2 = _interopRequireDefault(_defineProperty);

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

exports.default = function (obj, key, value) {
  if (key in obj) {
    (0, _defineProperty2.default)(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
};

/***/ }),
/* 884 */
/***/ (function(module, exports, __nested_webpack_require_4329721__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_4329721__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _ = __nested_webpack_require_4329721__(11);

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

var TRACKS_INFO_BY_TYPE = exports.TRACKS_INFO_BY_TYPE = _.TRACKS_INFO.reduce(function (tracksByType, track) {
  tracksByType[track.type] = track;
  if (track.aliases) {
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = (0, _getIterator3['default'])(track.aliases), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var alias = _step.value;

        tracksByType[alias] = track;
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator['return']) {
          _iterator['return']();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }
  }
  return tracksByType;
}, {});

exports['default'] = TRACKS_INFO_BY_TYPE;

/***/ }),
/* 885 */
/***/ (function(module, exports, __nested_webpack_require_4331114__) {

"use strict";


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

var _set = __nested_webpack_require_4331114__(38);

var _set2 = _interopRequireDefault(_set);

var _ = __nested_webpack_require_4331114__(11);

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

var POSITIONS_BY_DATATYPE = exports.POSITIONS_BY_DATATYPE = _.TRACKS_INFO.reduce(function (positionsByDatatype, track) {
  for (var i = 0; i < track.datatype.length; i++) {
    var datatype = track.datatype[i];

    if (positionsByDatatype[datatype]) {
      positionsByDatatype[datatype].add(track.orientation);
    } else {
      positionsByDatatype[datatype] = new _set2['default']();
    }

    return positionsByDatatype;
  }

  return {};
}, {});

exports['default'] = POSITIONS_BY_DATATYPE;

/***/ }),
/* 886 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var DEFAULT_TRACKS_FOR_DATATYPE = exports.DEFAULT_TRACKS_FOR_DATATYPE = {
  chromsizes: {
    center: '2d-chromosome-grid',
    top: 'chromosome-labels',
    left: 'chromosome-labels',
    bottom: 'chromosome-labels',
    right: 'chromosome-labels'
  },
  matrix: {
    center: 'heatmap',
    top: 'linear-heatmap',
    left: 'linear-heatmap',
    right: 'linear-heatmap',
    bottom: 'linear-heatmap'
  },
  vector: {
    top: 'bar',
    bottom: 'bar',
    left: 'bar',
    right: 'bar'
  },
  'geo-json': {
    center: 'geo-json'
  },
  'gene-annotation': {
    top: 'gene-annotations',
    bottom: 'gene-annotations',
    left: 'gene-annotations',
    right: 'gene-annotations'
  },
  bedlike: {
    top: 'bedlike',
    bottom: 'bedlike',
    left: 'vertical-bedlike',
    right: 'vertical-bedlike'
  }
};

exports['default'] = DEFAULT_TRACKS_FOR_DATATYPE;

/***/ }),
/* 887 */
/***/ (function(module, exports, __nested_webpack_require_4333047__) {

"use strict";


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

var _d3Array = __nested_webpack_require_4333047__(8);

var d3Array = _interopRequireWildcard(_d3Array);

var _d3Axis = __nested_webpack_require_4333047__(316);

var d3Axis = _interopRequireWildcard(_d3Axis);

var _d3Brush = __nested_webpack_require_4333047__(83);

var d3Brush = _interopRequireWildcard(_d3Brush);

var _d3Color = __nested_webpack_require_4333047__(9);

var d3Color = _interopRequireWildcard(_d3Color);

var _d3Drag = __nested_webpack_require_4333047__(84);

var d3Drag = _interopRequireWildcard(_d3Drag);

var _d3Dsv = __nested_webpack_require_4333047__(104);

var d3Dsv = _interopRequireWildcard(_d3Dsv);

var _d3Format = __nested_webpack_require_4333047__(20);

var d3Format = _interopRequireWildcard(_d3Format);

var _d3Geo = __nested_webpack_require_4333047__(1087);

var d3Geo = _interopRequireWildcard(_d3Geo);

var _d3Queue = __nested_webpack_require_4333047__(1089);

var d3Queue = _interopRequireWildcard(_d3Queue);

var _d3Request = __nested_webpack_require_4333047__(1088);

var d3Request = _interopRequireWildcard(_d3Request);

var _d3Scale = __nested_webpack_require_4333047__(28);

var d3Scale = _interopRequireWildcard(_d3Scale);

var _d3Selection = __nested_webpack_require_4333047__(0);

var d3Selection = _interopRequireWildcard(_d3Selection);

var _d3Transition = __nested_webpack_require_4333047__(85);

var d3Transition = _interopRequireWildcard(_d3Transition);

var _d3Zoom = __nested_webpack_require_4333047__(157);

var d3Zoom = _interopRequireWildcard(_d3Zoom);

var _slugid = __nested_webpack_require_4333047__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _mixwith = __nested_webpack_require_4333047__(81);

var _ = __nested_webpack_require_4333047__(11);

var configs = _interopRequireWildcard(_);

var _utils = __nested_webpack_require_4333047__(10);

var utils = _interopRequireWildcard(_utils);

var _Annotations1dTrack = __nested_webpack_require_4333047__(365);

var _Annotations1dTrack2 = _interopRequireDefault(_Annotations1dTrack);

var _Annotations2dTrack = __nested_webpack_require_4333047__(364);

var _Annotations2dTrack2 = _interopRequireDefault(_Annotations2dTrack);

var _ArrowheadDomainsTrack = __nested_webpack_require_4333047__(363);

var _ArrowheadDomainsTrack2 = _interopRequireDefault(_ArrowheadDomainsTrack);

var _BarTrack = __nested_webpack_require_4333047__(259);

var _BarTrack2 = _interopRequireDefault(_BarTrack);

var _BedLikeTrack = __nested_webpack_require_4333047__(352);

var _BedLikeTrack2 = _interopRequireDefault(_BedLikeTrack);

var _CNVIntervalTrack = __nested_webpack_require_4333047__(362);

var _CNVIntervalTrack2 = _interopRequireDefault(_CNVIntervalTrack);

var _Chromosome2DAnnotations = __nested_webpack_require_4333047__(370);

var _Chromosome2DAnnotations2 = _interopRequireDefault(_Chromosome2DAnnotations);

var _Chromosome2DLabels = __nested_webpack_require_4333047__(368);

var _Chromosome2DLabels2 = _interopRequireDefault(_Chromosome2DLabels);

var _ChromosomeGrid = __nested_webpack_require_4333047__(369);

var _ChromosomeGrid2 = _interopRequireDefault(_ChromosomeGrid);

var _CombinedTrack = __nested_webpack_require_4333047__(256);

var _CombinedTrack2 = _interopRequireDefault(_CombinedTrack);

var _CrossRule = __nested_webpack_require_4333047__(378);

var _CrossRule2 = _interopRequireDefault(_CrossRule);

var _DivergentBarTrack = __nested_webpack_require_4333047__(360);

var _DivergentBarTrack2 = _interopRequireDefault(_DivergentBarTrack);

var _HeatmapTiledPixiTrack = __nested_webpack_require_4333047__(135);

var _HeatmapTiledPixiTrack2 = _interopRequireDefault(_HeatmapTiledPixiTrack);

var _Horizontal1dHeatmapTrack = __nested_webpack_require_4333047__(361);

var _Horizontal1dHeatmapTrack2 = _interopRequireDefault(_Horizontal1dHeatmapTrack);

var _Horizontal2DDomainsTrack = __nested_webpack_require_4333047__(366);

var _Horizontal2DDomainsTrack2 = _interopRequireDefault(_Horizontal2DDomainsTrack);

var _HorizontalChromosomeLabels = __nested_webpack_require_4333047__(371);

var _HorizontalChromosomeLabels2 = _interopRequireDefault(_HorizontalChromosomeLabels);

var _HorizontalGeneAnnotationsTrack = __nested_webpack_require_4333047__(260);

var _HorizontalGeneAnnotationsTrack2 = _interopRequireDefault(_HorizontalGeneAnnotationsTrack);

var _HorizontalHeatmapTrack = __nested_webpack_require_4333047__(372);

var _HorizontalHeatmapTrack2 = _interopRequireDefault(_HorizontalHeatmapTrack);

var _HorizontalLine1DPixiTrack = __nested_webpack_require_4333047__(116);

var _HorizontalLine1DPixiTrack2 = _interopRequireDefault(_HorizontalLine1DPixiTrack);

var _HorizontalMultivecTrack = __nested_webpack_require_4333047__(359);

var _HorizontalMultivecTrack2 = _interopRequireDefault(_HorizontalMultivecTrack);

var _HorizontalPoint1DPixiTrack = __nested_webpack_require_4333047__(358);

var _HorizontalPoint1DPixiTrack2 = _interopRequireDefault(_HorizontalPoint1DPixiTrack);

var _HorizontalRule = __nested_webpack_require_4333047__(377);

var _HorizontalRule2 = _interopRequireDefault(_HorizontalRule);

var _HorizontalTiled1DPixiTrack = __nested_webpack_require_4333047__(115);

var _HorizontalTiled1DPixiTrack2 = _interopRequireDefault(_HorizontalTiled1DPixiTrack);

var _HorizontalTiledPlot = __nested_webpack_require_4333047__(392);

var _HorizontalTiledPlot2 = _interopRequireDefault(_HorizontalTiledPlot);

var _HorizontalTrack = __nested_webpack_require_4333047__(394);

var _HorizontalTrack2 = _interopRequireDefault(_HorizontalTrack);

var _Id2DTiledPixiTrack = __nested_webpack_require_4333047__(254);

var _Id2DTiledPixiTrack2 = _interopRequireDefault(_Id2DTiledPixiTrack);

var _IdHorizontal1DTiledPixiTrack = __nested_webpack_require_4333047__(347);

var _IdHorizontal1DTiledPixiTrack2 = _interopRequireDefault(_IdHorizontal1DTiledPixiTrack);

var _IdVertical1DTiledPixiTrack = __nested_webpack_require_4333047__(348);

var _IdVertical1DTiledPixiTrack2 = _interopRequireDefault(_IdVertical1DTiledPixiTrack);

var _LeftAxisTrack = __nested_webpack_require_4333047__(351);

var _LeftAxisTrack2 = _interopRequireDefault(_LeftAxisTrack);

var _MapboxTilesTrack = __nested_webpack_require_4333047__(380);

var _MapboxTilesTrack2 = _interopRequireDefault(_MapboxTilesTrack);

var _MoveableTrack = __nested_webpack_require_4333047__(265);

var _MoveableTrack2 = _interopRequireDefault(_MoveableTrack);

var _OSMTileIdsTrack = __nested_webpack_require_4333047__(379);

var _OSMTileIdsTrack2 = _interopRequireDefault(_OSMTileIdsTrack);

var _OSMTilesTrack = __nested_webpack_require_4333047__(141);

var _OSMTilesTrack2 = _interopRequireDefault(_OSMTilesTrack);

var _OverlayTrack = __nested_webpack_require_4333047__(357);

var _OverlayTrack2 = _interopRequireDefault(_OverlayTrack);

var _PixiTrack = __nested_webpack_require_4333047__(40);

var _PixiTrack2 = _interopRequireDefault(_PixiTrack);

var _RasterTilesTrack = __nested_webpack_require_4333047__(381);

var _RasterTilesTrack2 = _interopRequireDefault(_RasterTilesTrack);

var _SVGTrack = __nested_webpack_require_4333047__(80);

var _SVGTrack2 = _interopRequireDefault(_SVGTrack);

var _SquareMarkersTrack = __nested_webpack_require_4333047__(367);

var _SquareMarkersTrack2 = _interopRequireDefault(_SquareMarkersTrack);

var _Tiled1DPixiTrack = __nested_webpack_require_4333047__(255);

var _Tiled1DPixiTrack2 = _interopRequireDefault(_Tiled1DPixiTrack);

var _TiledPixiTrack = __nested_webpack_require_4333047__(79);

var _TiledPixiTrack2 = _interopRequireDefault(_TiledPixiTrack);

var _TopAxisTrack = __nested_webpack_require_4333047__(350);

var _TopAxisTrack2 = _interopRequireDefault(_TopAxisTrack);

var _Track = __nested_webpack_require_4333047__(177);

var _Track2 = _interopRequireDefault(_Track);

var _ValueIntervalTrack = __nested_webpack_require_4333047__(373);

var _ValueIntervalTrack2 = _interopRequireDefault(_ValueIntervalTrack);

var _VerticalRule = __nested_webpack_require_4333047__(262);

var _VerticalRule2 = _interopRequireDefault(_VerticalRule);

var _VerticalTiled1DPixiTrack = __nested_webpack_require_4333047__(349);

var _VerticalTiled1DPixiTrack2 = _interopRequireDefault(_VerticalTiled1DPixiTrack);

var _VerticalTrack = __nested_webpack_require_4333047__(396);

var _VerticalTrack2 = _interopRequireDefault(_VerticalTrack);

var _ViewportTracker2D = __nested_webpack_require_4333047__(374);

var _ViewportTracker2D2 = _interopRequireDefault(_ViewportTracker2D);

var _ViewportTracker2DPixi = __nested_webpack_require_4333047__(888);

var _ViewportTracker2DPixi2 = _interopRequireDefault(_ViewportTracker2DPixi);

var _ViewportTrackerHorizontal = __nested_webpack_require_4333047__(375);

var _ViewportTrackerHorizontal2 = _interopRequireDefault(_ViewportTrackerHorizontal);

var _ViewportTrackerVertical = __nested_webpack_require_4333047__(376);

var _ViewportTrackerVertical2 = _interopRequireDefault(_ViewportTrackerVertical);

var _ContextMenuItem = __nested_webpack_require_4333047__(67);

var _ContextMenuItem2 = _interopRequireDefault(_ContextMenuItem);

var _DataFetcher = __nested_webpack_require_4333047__(245);

var _DataFetcher2 = _interopRequireDefault(_DataFetcher);

var _factories = __nested_webpack_require_4333047__(889);

var _factories2 = _interopRequireDefault(_factories);

var _services = __nested_webpack_require_4333047__(24);

var services = _interopRequireWildcard(_services);

var _ChromosomeInfo = __nested_webpack_require_4333047__(73);

var _ChromosomeInfo2 = _interopRequireDefault(_ChromosomeInfo);

var _SearchField = __nested_webpack_require_4333047__(140);

var _SearchField2 = _interopRequireDefault(_SearchField);

var _genbankFetcher = __nested_webpack_require_4333047__(383);

var _genbankFetcher2 = _interopRequireDefault(_genbankFetcher);

var _localTileFetcher = __nested_webpack_require_4333047__(389);

var _localTileFetcher2 = _interopRequireDefault(_localTileFetcher);

var _getDataFetcher = __nested_webpack_require_4333047__(382);

var _getDataFetcher2 = _interopRequireDefault(_getDataFetcher);

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

// Services


// Utils
var libraries = {
  d3Array: d3Array,
  d3Axis: d3Axis,
  d3Brush: d3Brush,
  d3Color: d3Color,
  d3Drag: d3Drag,
  d3Dsv: d3Dsv,
  d3Format: d3Format,
  d3Geo: d3Geo,
  d3Queue: d3Queue,
  d3Request: d3Request,
  d3Scale: d3Scale,
  d3Selection: d3Selection,
  d3Transition: d3Transition,
  d3Zoom: d3Zoom,
  PIXI: configs.GLOBALS.PIXI,
  mix: _mixwith.mix,
  slugid: _slugid2['default']
};

// Data Fetchers


// Chromosomes


// Factories


// Tracks


// Configs
/**
 * Code that is available to plugin tracks.
 */

// Libraries


var tracks = {
  Annotations1dTrack: _Annotations1dTrack2['default'],
  Annotations2dTrack: _Annotations2dTrack2['default'],
  ArrowheadDomainsTrack: _ArrowheadDomainsTrack2['default'],
  BarTrack: _BarTrack2['default'],
  BedLikeTrack: _BedLikeTrack2['default'],
  CNVIntervalTrack: _CNVIntervalTrack2['default'],
  Chromosome2DAnnotations: _Chromosome2DAnnotations2['default'],
  Chromosome2DLabels: _Chromosome2DLabels2['default'],
  ChromosomeGrid: _ChromosomeGrid2['default'],
  CombinedTrack: _CombinedTrack2['default'],
  CrossRule: _CrossRule2['default'],
  DivergentBarTrack: _DivergentBarTrack2['default'],
  HeatmapTiledPixiTrack: _HeatmapTiledPixiTrack2['default'],
  Horizontal1dHeatmapTrack: _Horizontal1dHeatmapTrack2['default'],
  Horizontal2DDomainsTrack: _Horizontal2DDomainsTrack2['default'],
  HorizontalChromosomeLabels: _HorizontalChromosomeLabels2['default'],
  HorizontalGeneAnnotationsTrack: _HorizontalGeneAnnotationsTrack2['default'],
  HorizontalHeatmapTrack: _HorizontalHeatmapTrack2['default'],
  HorizontalLine1DPixiTrack: _HorizontalLine1DPixiTrack2['default'],
  HorizontalMultivecTrack: _HorizontalMultivecTrack2['default'],
  HorizontalPoint1DPixiTrack: _HorizontalPoint1DPixiTrack2['default'],
  HorizontalRule: _HorizontalRule2['default'],
  HorizontalTiled1DPixiTrack: _HorizontalTiled1DPixiTrack2['default'],
  HorizontalTiledPlot: _HorizontalTiledPlot2['default'],
  HorizontalTrack: _HorizontalTrack2['default'],
  Id2DTiledPixiTrack: _Id2DTiledPixiTrack2['default'],
  IdHorizontal1DTiledPixiTrack: _IdHorizontal1DTiledPixiTrack2['default'],
  IdVertical1DTiledPixiTrack: _IdVertical1DTiledPixiTrack2['default'],
  LeftAxisTrack: _LeftAxisTrack2['default'],
  MapboxTilesTrack: _MapboxTilesTrack2['default'],
  MoveableTrack: _MoveableTrack2['default'],
  OSMTileIdsTrack: _OSMTileIdsTrack2['default'],
  OSMTilesTrack: _OSMTilesTrack2['default'],
  OverlayTrack: _OverlayTrack2['default'],
  PixiTrack: _PixiTrack2['default'],
  RasterTilesTrack: _RasterTilesTrack2['default'],
  SVGTrack: _SVGTrack2['default'],
  SquareMarkersTrack: _SquareMarkersTrack2['default'],
  Tiled1DPixiTrack: _Tiled1DPixiTrack2['default'],
  TiledPixiTrack: _TiledPixiTrack2['default'],
  TopAxisTrack: _TopAxisTrack2['default'],
  Track: _Track2['default'],
  ValueIntervalTrack: _ValueIntervalTrack2['default'],
  VerticalRule: _VerticalRule2['default'],
  VerticalTiled1DPixiTrack: _VerticalTiled1DPixiTrack2['default'],
  VerticalTrack: _VerticalTrack2['default'],
  ViewportTracker2D: _ViewportTracker2D2['default'],
  ViewportTracker2DPixi: _ViewportTracker2DPixi2['default'],
  ViewportTrackerHorizontal: _ViewportTrackerHorizontal2['default'],
  ViewportTrackerVertical: _ViewportTrackerVertical2['default']
};

var factories = {
  ContextMenuItem: _ContextMenuItem2['default'],
  DataFetcher: _DataFetcher2['default'],
  LruCache: _factories2['default']
};

var chromosomes = {
  ChromosomeInfo: _ChromosomeInfo2['default'],
  SearchField: _SearchField2['default']
};

var dataFetchers = {
  DataFetcher: _DataFetcher2['default'],
  GBKDataFetcher: _genbankFetcher2['default'],
  LocalDataFetcher: _localTileFetcher2['default'],
  getDataFetcher: _getDataFetcher2['default']
};

exports['default'] = {
  chromosomes: chromosomes,
  libraries: libraries,
  tracks: tracks,
  dataFetchers: dataFetchers,
  factories: factories,
  services: services,
  utils: utils,
  configs: configs,
  // Defined globally by webpack.
  VERSION: "1.11.9"
};

/***/ }),
/* 888 */
/***/ (function(module, exports, __nested_webpack_require_4346435__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_4346435__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_4346435__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_4346435__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_4346435__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = __nested_webpack_require_4346435__(14);

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = __nested_webpack_require_4346435__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _slugid = __nested_webpack_require_4346435__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _PixiTrack2 = __nested_webpack_require_4346435__(40);

var _PixiTrack3 = _interopRequireDefault(_PixiTrack2);

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

var ViewportTracker2D = function (_PixiTrack) {
  (0, _inherits3['default'])(ViewportTracker2D, _PixiTrack);

  function ViewportTracker2D(context, options) {
    (0, _classCallCheck3['default'])(this, ViewportTracker2D);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (ViewportTracker2D.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTracker2D)).call(this, context, options));

    var registerViewportChanged = context.registerViewportChanged,
        removeViewportChanged = context.removeViewportChanged;


    var uid = _slugid2['default'].nice();
    _this.uid = uid;

    _this.removeViewportChanged = removeViewportChanged;
    _this.viewportXDomain = null;
    _this.viewportYDomain = null;

    registerViewportChanged(uid, _this.viewportChanged.bind(_this));

    // the viewport will call this.viewportChanged immediately upon
    // hearing registerViewportChanged
    // console.log('constructor...', this.uid);
    return _this;
  }

  (0, _createClass3['default'])(ViewportTracker2D, [{
    key: 'viewportChanged',
    value: function () {
      function viewportChanged(viewportXScale, viewportYScale) {
        // console.log('viewportChanged:');

        var viewportXDomain = viewportXScale.domain();
        var viewportYDomain = viewportYScale.domain();

        this.viewportXDomain = viewportXDomain;
        this.viewportYDomain = viewportYDomain;

        // console.log('vpc:', this.uid);
        this.draw();
      }

      return viewportChanged;
    }()
  }, {
    key: 'draw',
    value: function () {
      function draw() {
        var graphics = this.pMain;

        if (!this.viewportXDomain || !this.viewportYDomain) {
          return;
        }

        graphics.clear();
        graphics.lineStyle(1, 0x0000ff, 1);
        graphics.beginFill(0xff700b, 1);

        var x = this._xScale(this.viewportXDomain[0]);
        var y = this._yScale(this.viewportYDomain[0]);
        var width = this._xScale(this.viewportXDomain[1]) - this._xScale(this.viewportXDomain[0]);
        var height = this._yScale(this.viewportYDomain[1]) - this._yScale(this.viewportYDomain[0]);

        // console.log('drawing viewport:', x, y, width, height);

        this.pMain.drawRect(x, y, width, height);
      }

      return draw;
    }()
  }, {
    key: 'zoomed',
    value: function () {
      function zoomed(newXScale, newYScale) {
        this.xScale(newXScale);
        this.yScale(newYScale);

        this.draw();
      }

      return zoomed;
    }()
  }, {
    key: 'setPosition',
    value: function () {
      function setPosition(newPosition) {
        (0, _get3['default'])(ViewportTracker2D.prototype.__proto__ || (0, _getPrototypeOf2['default'])(ViewportTracker2D.prototype), 'setPosition', this).call(this, newPosition);

        this.pMain.position.y = this.position[1];
        this.pMain.position.x = this.position[0];

        // console.log('sp:', this.uid);
        this.draw();
      }

      return setPosition;
    }()
  }]);
  return ViewportTracker2D;
}(_PixiTrack3['default']);

exports['default'] = ViewportTracker2D;

/***/ }),
/* 889 */
/***/ (function(module, exports, __nested_webpack_require_4350634__) {

"use strict";


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

var _LruCache = __nested_webpack_require_4350634__(890);

Object.defineProperty(exports, 'default', {
  enumerable: true,
  get: function () {
    function get() {
      return _interopRequireDefault(_LruCache)['default'];
    }

    return get;
  }()
});

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

/***/ }),
/* 890 */
/***/ (function(module, exports, __nested_webpack_require_4351134__) {

"use strict";


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

var _assign = __nested_webpack_require_4351134__(44);

var _assign2 = _interopRequireDefault(_assign);

var _typeof2 = __nested_webpack_require_4351134__(94);

var _typeof3 = _interopRequireDefault(_typeof2);

var _keys = __nested_webpack_require_4351134__(18);

var _keys2 = _interopRequireDefault(_keys);

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

/**
 * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most
 * recently used items while discarding least recently used items when its limit
 * is reached.
 *
 * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson <http://hunch.se/>
 * See README.md for details.
 *
 * Illustration of the design:
 *
 *       entry             entry             entry             entry
 *       ______            ______            ______            ______
 *      | head |.newer => |      |.newer => |      |.newer => | tail |
 *      |  A   |          |  B   |          |  C   |          |  D   |
 *      |______| <= older.|______| <= older.|______| <= older.|______|
 *
 *  removed  <--  <--  <--  <--  <--  <--  <--  <--  <--  <--  <--  added
 */
function LruCache(limit) {
  // Current size of the cache. (Read-only).
  this.size = 0;
  // Maximum number of items this cache can hold.
  this.limit = limit;
  this._keymap = {};
}

/**
 * Put <value> into the cache associated with <key>. Returns the entry which was
 * removed to make room for the new entry. Otherwise undefined is returned
 * (i.e. if there was enough room already).
 */
function put(key, value) {
  var entry = { key: key, value: value };
  // Note: No protection agains replacing, and thus orphan entries. By design.
  this._keymap[key] = entry;
  if (this.tail) {
    // link previous tail to the new tail (entry)
    this.tail.newer = entry;
    entry.older = this.tail;
  } else {
    // we're first in -- yay
    this.head = entry;
  }
  // add new entry to the end of the linked list -- it's now the freshest entry.
  this.tail = entry;
  if (this.size === this.limit) {
    // we hit the limit -- remove the head
    return this.shift();
  }
  // increase the size counter
  this.size += 1;
  return undefined;
}

/**
 * Purge the least recently used (oldest) entry from the cache. Returns the
 * removed entry or undefined if the cache was empty.
 *
 * If you need to perform any form of finalization of purged items, this is a
 * good place to do it. Simply override/replace this function:
 *
 *   var c = new LruCache(123);
 *   c.shift = function() {
 *     var entry = LruCache.prototype.shift.call(this);
 *     doSomethingWith(entry);
 *     return entry;
 *   }
 */
function shift() {
  // todo: handle special case when limit === 1
  var entry = this.head;
  if (entry) {
    if (this.head.newer) {
      // advance the list
      this.head = this.head.newer;
      this.head.older = undefined;
    } else {
      // the cache is exhausted
      this.head = undefined;
      this.tail = undefined;
    }
    // Remove last strong reference to <entry> and remove links from the purged
    // entry being returned:
    entry.newer = undefined;
    entry.older = undefined;
    // delete is slow, but we need to do this to avoid uncontrollable growth:
    delete this._keymap[entry.key];
    this.size -= 1;
  }
  return entry;
}

/**
 * Get and register recent use of <key>. Returns the value associated with <key>
 * or undefined if not in cache.
 */
function get(key, returnEntry) {
  // First, find our cache entry
  var entry = this._keymap[key];
  if (entry === undefined) return undefined; // Not cached. Sorry.
  // As <key> was found in the cache, register it as being requested recently
  if (entry === this.tail) {
    // Already the most recenlty used entry, so no need to update the list
    return returnEntry ? entry : entry.value;
  }
  // HEAD--------------TAIL
  //   <.older   .newer>
  //  <--- add direction --
  //   A  B  C  <D>  E
  if (entry.newer) {
    if (entry === this.head) this.head = entry.newer;
    entry.newer.older = entry.older; // C <-- E.
  }
  if (entry.older) entry.older.newer = entry.newer; // C. --> E
  entry.newer = undefined; // D --x
  entry.older = this.tail; // D. --> E
  if (this.tail) this.tail.newer = entry; // E. <-- D
  this.tail = entry;

  return returnEntry ? entry : entry.value;
}

// ----------------------------------------------------------------------------
// Following code is optional and can be removed without breaking the core
// functionality.

/**
 * Check if <key> is in the cache without registering recent use. Feasible if
 * you do not want to chage the state of the cache, but only "peek" at it.
 * Returns the entry associated with <key> if found, or undefined if not found.
 */
function find(key) {
  return this._keymap[key];
}

/**
 * Update the value of entry with <key>. Returns the old value, or undefined if
 * entry was not in the cache.
 */
function set(key, value) {
  var entry = this.get(key, true);
  var oldvalue = void 0;
  if (entry) {
    oldvalue = entry.value;
    entry.value = value;
  } else {
    oldvalue = this.put(key, value);
    if (oldvalue) oldvalue = oldvalue.value;
  }
  return oldvalue;
}

/**
 * Remove entry <key> from cache and return its value. Returns undefined if not
 * found.
 */
function remove(key) {
  var entry = this._keymap[key];
  if (!entry) return undefined;
  delete this._keymap[entry.key]; // need to do delete unfortunately
  if (entry.newer && entry.older) {
    // relink the older entry with the newer entry
    entry.older.newer = entry.newer;
    entry.newer.older = entry.older;
  } else if (entry.newer) {
    // remove the link to us
    entry.newer.older = undefined;
    // link the newer entry to head
    this.head = entry.newer;
  } else if (entry.older) {
    // remove the link to us
    entry.older.newer = undefined;
    // link the newer entry to head
    this.tail = entry.older;
  } else {
    this.head = undefined;
    this.tail = undefined;
  }

  this.size -= 1;
  return entry.value;
}

/** Removes all entries */
function removeAll() {
  // This should be safe, as we never expose strong refrences to the outside
  this.head = undefined;
  this.tail = undefined;
  this.size = 0;
  this._keymap = {};
}

/**
 * Return an array containing all keys of entries stored in the cache object, in
 * arbitrary order.
 */
function keys() {
  return (0, _keys2['default'])(this._keymap);
}

/**
 * Call `fun` for each entry. Starting with the newest entry if `desc` is a true
 * value, otherwise starts with the oldest (head) enrty and moves towards the
 * tail.
 *
 * `fun` is called with 3 arguments in the context `context`:
 *   `fun.call(context, Object key, Object value, LruCache self)`
 */
function forEach(fun, context, desc) {
  var entry = void 0;
  /* eslint-disable no-param-reassign */
  if (context === true) {
    desc = true;
    context = undefined;
  } else if ((typeof context === 'undefined' ? 'undefined' : (0, _typeof3['default'])(context)) !== 'object') {
    context = this;
  }
  /* eslint-enable */
  if (desc) {
    entry = this.tail;
    while (entry) {
      fun.call(context, entry.key, entry.value, this);
      entry = entry.older;
    }
  } else {
    entry = this.head;
    while (entry) {
      fun.call(context, entry.key, entry.value, this);
      entry = entry.newer;
    }
  }
}

/** Returns a JSON (array) representation */
function toJSON() {
  var s = [];
  var entry = this.head;
  while (entry) {
    s.push({ key: entry.key.toJSON(), value: entry.value.toJSON() });
    entry = entry.newer;
  }
  return s;
}

/** Returns a String representation */
function toString() {
  var s = '';
  var entry = this.head;
  while (entry) {
    s += String(String(entry.key)) + ':' + String(entry.value);
    entry = entry.newer;
    if (entry) s += ' < ';
  }
  return s;
}

(0, _assign2['default'])(LruCache.prototype, {
  put: put,
  get: get,
  find: find,
  keys: keys,
  set: set,
  shift: shift,
  remove: remove,
  removeAll: removeAll,
  forEach: forEach,
  toJSON: toJSON,
  toString: toString
});

exports['default'] = LruCache;

/***/ }),
/* 891 */
/***/ (function(module, exports, __nested_webpack_require_4359376__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_4359376__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _toConsumableArray2 = __nested_webpack_require_4359376__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _values = __nested_webpack_require_4359376__(37);

var _values2 = _interopRequireDefault(_values);

var _set = __nested_webpack_require_4359376__(38);

var _set2 = _interopRequireDefault(_set);

var _ = __nested_webpack_require_4359376__(11);

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

/**
 * Return a list of the available track types, given a set of data types
 * and an orientation
 *
 * Arguments
 * ---------
 *
 *  datatypes: list
 *      E.g. ['heatmap', 'vector']
 *
 *  orientation: string
 *      E.g. 'top'
 *
 * Return
 * ------
 *
 *  A list of track-types:
 *      E.g. ['top-line', 'top-rectangle']
 */
var AVAILABLE_TRACK_TYPES = exports.AVAILABLE_TRACK_TYPES = function AVAILABLE_TRACK_TYPES(datatypes, orientation) {
  var datatypesToTrackTypes = (0, _.DATATYPE_TO_TRACK_TYPE)(orientation);
  var availableTrackTypes = new _set2['default']((0, _values2['default'])(datatypesToTrackTypes).flatMap(function (x) {
    return x;
  }));

  var _loop = function _loop(datatype) {
    // datatype should actually be an array of datatypes
    var dataTypeSet = new _set2['default'](datatype);

    availableTrackTypes = new _set2['default']([].concat((0, _toConsumableArray3['default'])(availableTrackTypes)).filter(function (x) {
      return x.datatype.filter(function (y) {
        return dataTypeSet.has(y);
      }).length > 0;
    }));
  };

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3['default'])(datatypes), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var datatype = _step.value;

      _loop(datatype);
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator['return']) {
        _iterator['return']();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return [].concat((0, _toConsumableArray3['default'])(availableTrackTypes));
};

exports['default'] = AVAILABLE_TRACK_TYPES;

/***/ }),
/* 892 */
/***/ (function(module, exports, __nested_webpack_require_4361959__) {

"use strict";


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

var _reduce = __nested_webpack_require_4361959__(439);

var _reduce2 = _interopRequireDefault(_reduce);

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

/**
 * Function for flattening a nested array. It returns a curried reducer.
 * @param   {array}  Nested array
 * @return  {array}  Flatt array
 */
var flatten = (0, _reduce2['default'])(function (a, b) {
  return a.concat(b);
}, []);

exports['default'] = flatten;

/***/ }),
/* 893 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Functional version of `Array.forEach`. More flexible and applicable to
 *   other array-like data types.
 * @param   {function}  f  Modifier function applied on every item of the
 *   array.
 * @return  {*}  Modified array-like variable.
 */
var forEach = function forEach(f) {
  return function (x) {
    return Array.prototype.forEach.call(x, f);
  };
};

exports["default"] = forEach;

/***/ }),
/* 894 */
/***/ (function(module, exports, __nested_webpack_require_4363128__) {

"use strict";


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

var _cloneEvent = __nested_webpack_require_4363128__(323);

var _cloneEvent2 = _interopRequireDefault(_cloneEvent);

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

/**
 * Forward an event by cloning and dispatching it.
 * @param   {object}  event  Event to be forwarded.
 * @param   {object}  target  Target HTML element for the event.
 */
var forwardEvent = function forwardEvent(event, target) {
  target.dispatchEvent((0, _cloneEvent2['default'])(event));
};

exports['default'] = forwardEvent;

/***/ }),
/* 895 */
/***/ (function(module, exports, __nested_webpack_require_4363823__) {

"use strict";


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

var _ = __nested_webpack_require_4363823__(10);

var genomeLociToPixels = function genomeLociToPixels(genomeLoci, chromInfo) {
  return [(0, _.chrToAbs)(genomeLoci[0], genomeLoci[1], chromInfo), (0, _.chrToAbs)(genomeLoci[2], genomeLoci[3], chromInfo)];
};

exports['default'] = genomeLociToPixels;

/***/ }),
/* 896 */
/***/ (function(module, exports, __nested_webpack_require_4364267__) {

"use strict";


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

var _slicedToArray2 = __nested_webpack_require_4364267__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

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

/**
 * Using the [genomicStart, genomicEnd] range, get an array of "chromosome chunks",
 * where each chunk range starts and ends with the same chromosome.
 * Start a new chromosome chunk at each chromosome boundary.
 * @param {array} chromSizes Array of [chrName, chrLen] tuples.
 * @param {object} genomicStart A genomic position object returned from abs2genomic { chr, pos }.
 * @param {object} genomicEnd A genomic position object returned from abs2genomic { chr, pos }.
 * @param {number} binSize The resolution / bin size.
 * @param {number} tileSize The tile size (probably 256).
 * @returns {array} Returns array of [chrName, zStart, zEnd] tuples.
 */
function genomicRangeToChromosomeChunks(chromSizes, genomicStart, genomicEnd, binSize, tileSize) {
  var chrStart = genomicStart.chr,
      chrStartPos = genomicStart.pos;
  var chrEnd = genomicEnd.chr,
      chrEndPos = genomicEnd.pos;


  var chrChunks = [];
  if (chrStart === chrEnd) {
    // This tile does _not_ cross a chromosome boundary.
    var chrName = chrStart;
    var zStart = Math.floor(chrStartPos / binSize);
    var zEnd = Math.min(zStart + tileSize, Math.ceil(chrEndPos / binSize));

    chrChunks.push([chrName, zStart, zEnd]);
  } else {
    // This tile does cross a chromosome boundary.
    var zRemaining = tileSize;
    var chrStartIndex = chromSizes.findIndex(function (_ref) {
      var _ref2 = (0, _slicedToArray3["default"])(_ref, 1),
          chrName = _ref2[0];

      return chrName === chrStart;
    });
    var chrEndIndex = chromSizes.findIndex(function (_ref3) {
      var _ref4 = (0, _slicedToArray3["default"])(_ref3, 1),
          chrName = _ref4[0];

      return chrName === chrEnd;
    });

    // Create a separate chunk for each chromosome that lies within the range.
    for (var chrIndex = chrStartIndex; chrIndex <= chrEndIndex; chrIndex++) {
      var chrChunkStart = void 0;
      var chrChunkEnd = void 0;

      var _chromSizes$chrIndex = (0, _slicedToArray3["default"])(chromSizes[chrIndex], 2),
          currChrName = _chromSizes$chrIndex[0],
          currChrLen = _chromSizes$chrIndex[1];

      if (chrIndex < chrEndIndex) {
        // If the current chromosome is before the end chromosome, then we want the chunk to end at the end of the current chromosome.
        if (chrIndex === chrStartIndex) {
          // If this is the start chromosome, we may want to start at somewhere past 0.
          chrChunkStart = chrStartPos;
        } else {
          // If this is not the start chromosome, then it is somewhere in the middle, and we want to start at 0.
          chrChunkStart = 0;
        }
        chrChunkEnd = currChrLen;
      } else {
        // The current chromosome is the end chromosome, so we may want the chunk to end before the end of the chromosome.
        chrChunkStart = 0;
        chrChunkEnd = chrEndPos;
      }

      var _zStart = Math.floor(chrChunkStart / binSize);
      var _zEnd = Math.min(_zStart + zRemaining, Math.ceil(chrChunkEnd / binSize));

      chrChunks.push([currChrName, _zStart, _zEnd]);
      zRemaining -= _zEnd - _zStart;
    }
  }
  return chrChunks;
}

exports["default"] = genomicRangeToChromosomeChunks;

/***/ }),
/* 897 */
/***/ (function(module, exports, __nested_webpack_require_4367814__) {

"use strict";


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

var _configs = __nested_webpack_require_4367814__(11);

/**
 * Gets the default track as defined in utils/default-tracks-for-datatype.js
 *
 * @param  {string} datatype The datatype to get the default track for
 * @param  {string} position   top, bottom, left, right, center
 * @param  {array} availableTracks   list of tracks to choose from,
 * typically obtained from AVAILABLE_TRACK_TYPES(...)
 * @return {object}  an element of availableTracks or undefined
 */
var getDefaultTrackForDatatype = function getDefaultTrackForDatatype(datatype, position, availableTracks) {
  if (availableTracks.length === 0) {
    return undefined;
  }

  if (availableTracks.length === 1) {
    return availableTracks[0];
  }

  var usedTrack = availableTracks[0];
  var defaultTrackType = _configs.DEFAULT_TRACKS_FOR_DATATYPE[datatype] !== undefined ? _configs.DEFAULT_TRACKS_FOR_DATATYPE[datatype][position] : undefined;

  if (defaultTrackType !== undefined) {
    // If we found a default track type for this datatype,
    // get the definition of this track from the list of available tracks.
    usedTrack = availableTracks.find(function (tt) {
      return tt.type === defaultTrackType;
    }) || usedTrack;
  }

  return usedTrack;
}; // Configs
exports['default'] = getDefaultTrackForDatatype;

/***/ }),
/* 898 */
/***/ (function(module, exports, __nested_webpack_require_4369247__) {

"use strict";


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

var _elementResizeListener = __nested_webpack_require_4369247__(440);

var _elementResizeListener2 = _interopRequireDefault(_elementResizeListener);

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

var getElementDim = function getElementDim(element) {
  _elementResizeListener2['default'].listen();

  return [element.clientWidth, element.clientHeight];
};

exports['default'] = getElementDim;

/***/ }),
/* 899 */
/***/ (function(module, exports, __nested_webpack_require_4369837__) {

"use strict";


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

var _keys = __nested_webpack_require_4369837__(18);

var _keys2 = _interopRequireDefault(_keys);

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

/**
 * Return the track object for the track corresponding to this uid
 *
 * Null or undefined if none.
 */
var getTrackByUid = function getTrackByUid(tracks, uid) {
  var found = null;

  var checkTrack = function checkTrack(track) {
    if (track.uid === uid) found = track;
    if (track.type.substr(0, 8) === 'combined') track.contents.forEach(checkTrack);
    return null;
  };

  (0, _keys2['default'])(tracks).map(function (trackType) {
    return tracks[trackType];
  }).filter(function (tracksByPos) {
    return tracksByPos.filter;
  }).reduce(function (a, b) {
    return a.concat(b);
  }, []).forEach(checkTrack);

  return found;
};

exports['default'] = getTrackByUid;

/***/ }),
/* 900 */
/***/ (function(module, exports, __nested_webpack_require_4370862__) {

"use strict";


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

var _keys = __nested_webpack_require_4370862__(18);

var _keys2 = _interopRequireDefault(_keys);

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

/**
 * Get a track's config (not the track object) from a higlass component.
 *
 * @param  {HiGlassComponent} hgc      HiGlassComponent object
 * @param  {string} viewUid  The uid of the view
 * @param  {string} trackUid The uid of the track
 * @return {object}          Track conf if found else null
 */
var getTrackConfFromHGC = function getTrackConfFromHGC(hgc, viewUid, trackUid) {
  var views = hgc.state.views;
  var myView = views[viewUid];
  if (!myView) return null;

  var found = null;

  var checkTrack = function checkTrack(track) {
    if (track.uid === trackUid) found = track;
    if (track.type.substr(0, 8) === 'combined') track.contents.forEach(checkTrack);
    return null;
  };

  var tracks = myView.tracks;

  (0, _keys2['default'])(tracks).map(function (trackType) {
    return tracks[trackType];
  }).filter(function (tracksByPos) {
    return tracksByPos.filter;
  }).reduce(function (a, b) {
    return a.concat(b);
  }, []).forEach(checkTrack);

  return found;
};

exports['default'] = getTrackConfFromHGC;

/***/ }),
/* 901 */
/***/ (function(module, exports, __nested_webpack_require_4372240__) {

"use strict";


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

var _values = __nested_webpack_require_4372240__(37);

var _values2 = _interopRequireDefault(_values);

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

var getTrackObjById = function getTrackObjById(tiledPlots, viewId, trackId) {
  var tiledPlot = viewId ? tiledPlots[viewId] : (0, _values2['default'])(tiledPlots)[0];

  if (!tiledPlot) {
    if (!viewId) console.warn('No views available.');else console.warn('Could\'t find view with id "' + String(viewId) + '"');
    return undefined;
  }

  var track = tiledPlot.trackRenderer.trackDefObjects[trackId];

  if (!track) {
    (0, _values2['default'])(tiledPlot.trackRenderer.trackDefObjects).map(function (trackDef) {
      return trackDef.trackObject;
    }).filter(function (trackObj) {
      return trackObj.childTracks;
    }).forEach(function (combinedTrack) {
      if (combinedTrack.createdTracks[trackId]) {
        track = combinedTrack.createdTracks[trackId];
      }
    });
  } else {
    track = track.trackObject;
  }

  return track;
};

exports['default'] = getTrackObjById;

/***/ }),
/* 902 */
/***/ (function(module, exports, __nested_webpack_require_4373480__) {

"use strict";


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

var _visitPositionedTracks = __nested_webpack_require_4373480__(443);

var _visitPositionedTracks2 = _interopRequireDefault(_visitPositionedTracks);

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

/**
 * Get a track's orientation by its UID.
 */
var getTrackPositionByUid = function getTrackPositionByUid(positionedTracks, uid) {
  var position = null;

  (0, _visitPositionedTracks2['default'])(positionedTracks, function (track, trackPosition) {
    if (track.uid === uid) {
      position = trackPosition;
    }
  });

  return position;
};

exports['default'] = getTrackPositionByUid;

/***/ }),
/* 903 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var gradient = function gradient(steps) {
  var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100;
  var fromX = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  var fromY = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  var toX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  var toY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 100;

  var canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;

  var ctx = canvas.getContext('2d');
  var grd = ctx.createLinearGradient(fromX, fromY, toX, toY);

  steps.forEach(function (step) {
    grd.addColorStop(step.from, step.color);
  });

  ctx.fillStyle = grd;
  ctx.fillRect(0, 0, width, height);

  return canvas;
};

exports['default'] = gradient;

/***/ }),
/* 904 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Test whether a DOM element is the parent of another DOM element.
 *
 * @param {object} el - Potential child element.
 * @param {object} target - Target parent element which is tested to have `el`
 *   as a child.
 * @return  {Boolean}  If `true` `el` has `target` as a parent.
 */
var hasParent = function hasParent(el, target) {
  var _el = el;

  while (_el && _el !== target && _el.tagName !== 'HTML') {
    _el = _el.parentNode;
  }

  if (_el === target) {
    return true;
  }

  return false;
};

exports['default'] = hasParent;

/***/ }),
/* 905 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Convert a HEX string into a HEX integer. E.g., #FF0000 is translated to
 *   16711680.
 * @param   {string}  str  HEX string
 * @return  {integer}  HEX number
 */
var hexStrToInt = function hexStrToInt(str) {
  return parseInt(str.replace(/^#/, ''), 16);
};

exports['default'] = hexStrToInt;

/***/ }),
/* 906 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * An adventure into the abyss of void!
 * @return  {undefined}  The explorers find nothing but void.
 */
var intoTheVoid = function intoTheVoid() {};

exports["default"] = intoTheVoid;

/***/ }),
/* 907 */
/***/ (function(module, exports, __nested_webpack_require_4376888__) {

"use strict";


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

var _keys = __nested_webpack_require_4376888__(18);

var _keys2 = _interopRequireDefault(_keys);

var _CombinedTrack = __nested_webpack_require_4376888__(256);

var _CombinedTrack2 = _interopRequireDefault(_CombinedTrack);

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

var isTrackOrChildTrack = function isTrackOrChildTrack(testTrack, track) {
  if (track === testTrack) return true;
  if (track instanceof _CombinedTrack2['default']) {
    return (0, _keys2['default'])(track.createdTracks).map(function (trackName) {
      return track.createdTracks[trackName];
    }).some(function (createdTrack) {
      return isTrackOrChildTrack(testTrack, createdTrack);
    });
  }
  return false;
};

exports['default'] = isTrackOrChildTrack;

/***/ }),
/* 908 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Check if a 2D or 1D point is within a rectangle or range
 * @param   {number}  x  The point's X coordinate.
 * @param   {number}  y  The point's Y coordinate.
 * @param   {number}  minX  The rectangle's start X coordinate.
 * @param   {number}  maxX  The rectangle's start X coordinate.
 * @param   {number}  minY  The rectangle's start X coordinate.
 * @param   {number}  maxY  The rectangle's start X coordinate.
 * @return  {boolean}  If `true` the [x,y] point is in the rectangle.
 */
var isWithin = function isWithin(x, y, minX, maxX, minY, maxY) {
  var is1d = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
  return is1d ? x >= minX && x <= maxX || y >= minY && y <= maxY : x >= minX && x <= maxX && y >= minY && y <= maxY;
};

exports["default"] = isWithin;

/***/ }),
/* 909 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var invGudermannian = exports.invGudermannian = function invGudermannian(y) {
  return Math.log(Math.tan((y + Math.PI / 2) / 2));
};

/**
 * Translate latitude to Y in the Mercator projection
 * @param   {number}  lat  Latitude.
 * @param   {number}  zoom  Zoom level
 * @return  {number}  Y coordinate in the Mercator projection.
 */
var latToY = function latToY(lat, zoom) {
  var latRad = lat * Math.PI / 180.0;

  // "map-centric" latitude, in radians:
  latRad = invGudermannian(latRad);

  return Math.pow(2, zoom) * (Math.PI - latRad) / (2 * Math.PI);
};

exports["default"] = latToY;

/***/ }),
/* 910 */
/***/ (function(module, exports, __nested_webpack_require_4379518__) {

"use strict";


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

var _services = __nested_webpack_require_4379518__(24);

var _ = __nested_webpack_require_4379518__(10);

var loadChromInfos = function loadChromInfos(views) {
  return (0, _.objVals)(views).map(function (view) {
    return view.chromInfoPath;
  }).forEach(function (chromInfoPath) {
    return _services.chromInfo.get(chromInfoPath);
  });
};

exports['default'] = loadChromInfos;

/***/ }),
/* 911 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Convert longitude to the X coordinate in the Mercator projection.
 * @param   {number}  lng  Longitude
 * @param   {number}  zoom  Zoom level
 * @return  {number}  X coordinate in the Mercator projection.
 */
var lngToX = function lngToX(lng, zoom) {
  return Math.pow(2, zoom) * (lng + 180.0) / 360.0;
};

exports["default"] = lngToX;

/***/ }),
/* 912 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Fast version of `Math.max`. Based on
 *   https://jsperf.com/math-min-max-vs-ternary-vs-if/24 `Math.max` is not
 *   very fast
 * @param   {number}  a  Value A
 * @param   {number}  b  Value B
 * @return  {boolean}  If `true` A is greater than B.
 */
var max = function max(a, b) {
  return a > b ? a : b;
};

exports["default"] = max;

/***/ }),
/* 913 */
/***/ (function(module, exports, __nested_webpack_require_4381034__) {

"use strict";


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

var _minSafeInteger = __nested_webpack_require_4381034__(63);

var _minSafeInteger2 = _interopRequireDefault(_minSafeInteger);

exports["default"] = maxNonZero;

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

var epsilon = 0.0000001;

function maxNonZero(data) {
  /**
   * Calculate the minimum non-zero value in the data
   *
   * Parameters
   * ----------
   *  data: Float32Array
   *    An array of values
   *
   * Returns
   * -------
   *  minNonZero: float
   *    The minimum non-zero value in the array
   */
  var maxNonZeroNum = _minSafeInteger2["default"];

  for (var i = 0; i < data.length; i++) {
    var x = data[i];

    if (x < epsilon && x > -epsilon) {
      continue;
    }

    if (x > maxNonZeroNum) {
      maxNonZeroNum = x;
    }
  }

  return maxNonZeroNum;
}

/***/ }),
/* 914 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Fast version of `Math.min`. Based on
 *   https://jsperf.com/math-min-max-vs-ternary-vs-if/24 `Math.max` is not
 *   very fast
 * @param   {number}  a  Value A
 * @param   {number}  b  Value B
 * @return  {boolean}  If `true` A is smaller than B.
 */
var min = function min(a, b) {
  return a < b ? a : b;
};

exports["default"] = min;

/***/ }),
/* 915 */
/***/ (function(module, exports, __nested_webpack_require_4382523__) {

"use strict";


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

var _maxSafeInteger = __nested_webpack_require_4382523__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

exports["default"] = minNonZero;

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

var epsilon = 0.0000001;

function minNonZero(data) {
  /**
   * Calculate the minimum non-zero value in the data
   *
   * Parameters
   * ----------
   *  data: Float32Array
   *    An array of values
   *
   * Returns
   * -------
   *  minNonZero: float
   *    The minimum non-zero value in the array
   */
  var minNonZeroNum = _maxSafeInteger2["default"];

  for (var i = 0; i < data.length; i++) {
    var x = data[i];

    if (x < epsilon && x > -epsilon) {
      continue;
    }

    if (x < minNonZeroNum) {
      minNonZeroNum = x;
    }
  }

  return minNonZeroNum;
}

/***/ }),
/* 916 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Non-negative modulo function. E.g., `mod(-1, 5) === 4` while `-1 % 5 === -1`.
 *
 * @param  {Integer}  n  Dividend
 * @param  {Integer}  m  Divisor
 * @return  {Integer}  Remainder
 */
var mod = function mod(n, m) {
  return (n % m + m) % m;
};

exports["default"] = mod;

/***/ }),
/* 917 */
/***/ (function(module, exports, __nested_webpack_require_4383948__) {

"use strict";


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

var _isNan = __nested_webpack_require_4383948__(30);

var _isNan2 = _interopRequireDefault(_isNan);

var _cwise = __nested_webpack_require_4383948__(445);

var _cwise2 = _interopRequireDefault(_cwise);

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

var ndarrayAssign = function ndarrayAssign(target, source) {
  var numSource = +source;
  var isScalar = !(0, _isNan2['default'])(numSource);

  if (isScalar) {
    (0, _cwise2['default'])({
      args: ['array', 'scalar'],
      body: 'function assigns(a, s) { a = s; }'
    })(target, numSource);
  } else {
    var ty = target.shape[0];
    var tx = target.shape[1];
    var sy = source.shape[0];
    var sx = source.shape[1];

    if (ty !== sy || tx !== sx) {
      console.warn('Cannot assign source to target ndarray as the dimensions do not match', ty, sy, tx, sx);
      return;
    }

    (0, _cwise2['default'])({
      args: ['array', 'array'],
      body: 'function assign(a, b) { a = b; }'
    })(target, source);
  }
};

exports['default'] = ndarrayAssign;

/***/ }),
/* 918 */
/***/ (function(module, exports, __nested_webpack_require_4385152__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var esprima = __nested_webpack_require_4385152__(919)
var uniq = __nested_webpack_require_4385152__(446)

var PREFIX_COUNTER = 0

function CompiledArgument(name, lvalue, rvalue) {
  this.name = name
  this.lvalue = lvalue
  this.rvalue = rvalue
  this.count = 0
}

function CompiledRoutine(body, args, thisVars, localVars) {
  this.body = body
  this.args = args
  this.thisVars = thisVars
  this.localVars = localVars
}

function isGlobal(identifier) {
  if(identifier === "eval") {
    throw new Error("cwise-parser: eval() not allowed")
  }
  if(typeof window !== "undefined") {
    return identifier in window
  } else if(typeof global !== "undefined") {
    return identifier in global
  } else if(typeof self !== "undefined") {
    return identifier in self
  } else {
    return false
  }
}

function getArgNames(ast) {
  var params = ast.body[0].expression.callee.params
  var names = new Array(params.length)
  for(var i=0; i<params.length; ++i) {
    names[i] = params[i].name
  }
  return names
}

function preprocess(func) {
  var src = ["(", func, ")()"].join("")
  var ast = esprima.parse(src, { range: true })
  
  //Compute new prefix
  var prefix = "_inline_" + (PREFIX_COUNTER++) + "_"
  
  //Parse out arguments
  var argNames = getArgNames(ast)
  var compiledArgs = new Array(argNames.length)
  for(var i=0; i<argNames.length; ++i) {
    compiledArgs[i] = new CompiledArgument([prefix, "arg", i, "_"].join(""), false, false)
  }
  
  //Create temporary data structure for source rewriting
  var exploded = new Array(src.length)
  for(var i=0, n=src.length; i<n; ++i) {
    exploded[i] = src.charAt(i)
  }
  
  //Local variables
  var localVars = []
  var thisVars = []
  var computedThis = false
  
  //Retrieves a local variable
  function createLocal(id) {
    var nstr = prefix + id.replace(/\_/g, "__")
    localVars.push(nstr)
    return nstr
  }
  
  //Creates a this variable
  function createThisVar(id) {
    var nstr = "this_" + id.replace(/\_/g, "__")
    thisVars.push(nstr)
    return nstr
  }
  
  //Rewrites an ast node
  function rewrite(node, nstr) {
    var lo = node.range[0], hi = node.range[1]
    for(var i=lo+1; i<hi; ++i) {
      exploded[i] = ""
    }
    exploded[lo] = nstr
  }
  
  //Remove any underscores
  function escapeString(str) {
    return "'"+(str.replace(/\_/g, "\\_").replace(/\'/g, "\'"))+"'"
  }
  
  //Returns the source of an identifier
  function source(node) {
    return exploded.slice(node.range[0], node.range[1]).join("")
  }
  
  //Computes the usage of a node
  var LVALUE = 1
  var RVALUE = 2
  function getUsage(node) {
    if(node.parent.type === "AssignmentExpression") {
      if(node.parent.left === node) {
        if(node.parent.operator === "=") {
          return LVALUE
        }
        return LVALUE|RVALUE
      }
    }
    if(node.parent.type === "UpdateExpression") {
      return LVALUE|RVALUE
    }
    return RVALUE
  }
  
  //Handle visiting a node
  (function visit(node, parent) {
    node.parent = parent
    if(node.type === "MemberExpression") {
      //Handle member expression
      if(node.computed) {
        visit(node.object, node)
        visit(node.property, node)
      } else if(node.object.type === "ThisExpression") {
        rewrite(node, createThisVar(node.property.name))
      } else {
        visit(node.object, node)
      }
    } else if(node.type === "ThisExpression") {
      throw new Error("cwise-parser: Computed this is not allowed")
    } else if(node.type === "Identifier") {
      //Handle identifier
      var name = node.name
      var argNo = argNames.indexOf(name)
      if(argNo >= 0) {
        var carg = compiledArgs[argNo]
        var usage = getUsage(node)
        if(usage & LVALUE) {
          carg.lvalue = true
        }
        if(usage & RVALUE) {
          carg.rvalue = true
        }
        ++carg.count
        rewrite(node, carg.name)
      } else if(isGlobal(name)) {
        //Don't rewrite globals
      } else {
        rewrite(node, createLocal(name))
      }
    } else if(node.type === "Literal") {
      if(typeof node.value === "string") {
        rewrite(node, escapeString(node.value))
      }
    } else if(node.type === "WithStatement") {
      throw new Error("cwise-parser: with() statements not allowed")
    } else {
      //Visit all children
      var keys = Object.keys(node)
      for(var i=0, n=keys.length; i<n; ++i) {
        if(keys[i] === "parent") {
          continue
        }
        var value = node[keys[i]]
        if(value) {
          if(value instanceof Array) {
            for(var j=0; j<value.length; ++j) {
              if(value[j] && typeof value[j].type === "string") {
                visit(value[j], node)
              }
            }
          } else if(typeof value.type === "string") {
            visit(value, node)
          }
        }
      }
    }
  })(ast.body[0].expression.callee.body, undefined)
  
  //Remove duplicate variables
  uniq(localVars)
  uniq(thisVars)
  
  //Return body
  var routine = new CompiledRoutine(source(ast.body[0].expression.callee.body), compiledArgs, thisVars, localVars)
  return routine
}

module.exports = preprocess
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4385152__(27)))

/***/ }),
/* 919 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
  Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
  Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint bitwise:true plusplus:true */
/*global esprima:true, define:true, exports:true, window: true,
throwErrorTolerant: true,
throwError: true, generateStatement: true, peek: true,
parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
parseFunctionDeclaration: true, parseFunctionExpression: true,
parseFunctionSourceElements: true, parseVariableIdentifier: true,
parseLeftHandSideExpression: true,
parseUnaryExpression: true,
parseStatement: true, parseSourceElement: true */

(function (root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.

    /* istanbul ignore next */
    if (true) {
        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else {}
}(this, function (exports) {
    'use strict';

    var Token,
        TokenName,
        FnExprTokens,
        Syntax,
        PropertyKind,
        Messages,
        Regex,
        SyntaxTreeDelegate,
        source,
        strict,
        index,
        lineNumber,
        lineStart,
        length,
        delegate,
        lookahead,
        state,
        extra;

    Token = {
        BooleanLiteral: 1,
        EOF: 2,
        Identifier: 3,
        Keyword: 4,
        NullLiteral: 5,
        NumericLiteral: 6,
        Punctuator: 7,
        StringLiteral: 8,
        RegularExpression: 9
    };

    TokenName = {};
    TokenName[Token.BooleanLiteral] = 'Boolean';
    TokenName[Token.EOF] = '<end>';
    TokenName[Token.Identifier] = 'Identifier';
    TokenName[Token.Keyword] = 'Keyword';
    TokenName[Token.NullLiteral] = 'Null';
    TokenName[Token.NumericLiteral] = 'Numeric';
    TokenName[Token.Punctuator] = 'Punctuator';
    TokenName[Token.StringLiteral] = 'String';
    TokenName[Token.RegularExpression] = 'RegularExpression';

    // A function following one of those tokens is an expression.
    FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
                    'return', 'case', 'delete', 'throw', 'void',
                    // assignment operators
                    '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
                    '&=', '|=', '^=', ',',
                    // binary/unary operators
                    '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
                    '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
                    '<=', '<', '>', '!=', '!=='];

    Syntax = {
        AssignmentExpression: 'AssignmentExpression',
        ArrayExpression: 'ArrayExpression',
        BlockStatement: 'BlockStatement',
        BinaryExpression: 'BinaryExpression',
        BreakStatement: 'BreakStatement',
        CallExpression: 'CallExpression',
        CatchClause: 'CatchClause',
        ConditionalExpression: 'ConditionalExpression',
        ContinueStatement: 'ContinueStatement',
        DoWhileStatement: 'DoWhileStatement',
        DebuggerStatement: 'DebuggerStatement',
        EmptyStatement: 'EmptyStatement',
        ExpressionStatement: 'ExpressionStatement',
        ForStatement: 'ForStatement',
        ForInStatement: 'ForInStatement',
        FunctionDeclaration: 'FunctionDeclaration',
        FunctionExpression: 'FunctionExpression',
        Identifier: 'Identifier',
        IfStatement: 'IfStatement',
        Literal: 'Literal',
        LabeledStatement: 'LabeledStatement',
        LogicalExpression: 'LogicalExpression',
        MemberExpression: 'MemberExpression',
        NewExpression: 'NewExpression',
        ObjectExpression: 'ObjectExpression',
        Program: 'Program',
        Property: 'Property',
        ReturnStatement: 'ReturnStatement',
        SequenceExpression: 'SequenceExpression',
        SwitchStatement: 'SwitchStatement',
        SwitchCase: 'SwitchCase',
        ThisExpression: 'ThisExpression',
        ThrowStatement: 'ThrowStatement',
        TryStatement: 'TryStatement',
        UnaryExpression: 'UnaryExpression',
        UpdateExpression: 'UpdateExpression',
        VariableDeclaration: 'VariableDeclaration',
        VariableDeclarator: 'VariableDeclarator',
        WhileStatement: 'WhileStatement',
        WithStatement: 'WithStatement'
    };

    PropertyKind = {
        Data: 1,
        Get: 2,
        Set: 4
    };

    // Error messages should be identical to V8.
    Messages = {
        UnexpectedToken:  'Unexpected token %0',
        UnexpectedNumber:  'Unexpected number',
        UnexpectedString:  'Unexpected string',
        UnexpectedIdentifier:  'Unexpected identifier',
        UnexpectedReserved:  'Unexpected reserved word',
        UnexpectedEOS:  'Unexpected end of input',
        NewlineAfterThrow:  'Illegal newline after throw',
        InvalidRegExp: 'Invalid regular expression',
        UnterminatedRegExp:  'Invalid regular expression: missing /',
        InvalidLHSInAssignment:  'Invalid left-hand side in assignment',
        InvalidLHSInForIn:  'Invalid left-hand side in for-in',
        MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
        NoCatchOrFinally:  'Missing catch or finally after try',
        UnknownLabel: 'Undefined label \'%0\'',
        Redeclaration: '%0 \'%1\' has already been declared',
        IllegalContinue: 'Illegal continue statement',
        IllegalBreak: 'Illegal break statement',
        IllegalReturn: 'Illegal return statement',
        StrictModeWith:  'Strict mode code may not include a with statement',
        StrictCatchVariable:  'Catch variable may not be eval or arguments in strict mode',
        StrictVarName:  'Variable name may not be eval or arguments in strict mode',
        StrictParamName:  'Parameter name eval or arguments is not allowed in strict mode',
        StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
        StrictFunctionName:  'Function name may not be eval or arguments in strict mode',
        StrictOctalLiteral:  'Octal literals are not allowed in strict mode.',
        StrictDelete:  'Delete of an unqualified identifier in strict mode.',
        StrictDuplicateProperty:  'Duplicate data property in object literal not allowed in strict mode',
        AccessorDataProperty:  'Object literal may not have data and accessor property with the same name',
        AccessorGetSet:  'Object literal may not have multiple get/set accessors with the same name',
        StrictLHSAssignment:  'Assignment to eval or arguments is not allowed in strict mode',
        StrictLHSPostfix:  'Postfix increment/decrement may not have eval or arguments operand in strict mode',
        StrictLHSPrefix:  'Prefix increment/decrement may not have eval or arguments operand in strict mode',
        StrictReservedWord:  'Use of future reserved word in strict mode'
    };

    // See also tools/generate-unicode-regex.py.
    Regex = {
        NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'),
        NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0\u08A2-\u08AC\u08E4-\u08FE\u0900-\u0963\u0966-\u096F\u0971-\u0977\u0979-\u097F\u0981-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C82\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F0\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191C\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1D00-\u1DE6\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA697\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7B\uAA80-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE26\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]')
    };

    // Ensure the condition is true, otherwise throw an error.
    // This is only to have a better contract semantic, i.e. another safety net
    // to catch a logic error. The condition shall be fulfilled in normal case.
    // Do NOT use this to enforce a certain condition on any user input.

    function assert(condition, message) {
        /* istanbul ignore if */
        if (!condition) {
            throw new Error('ASSERT: ' + message);
        }
    }

    function isDecimalDigit(ch) {
        return (ch >= 48 && ch <= 57);   // 0..9
    }

    function isHexDigit(ch) {
        return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
    }

    function isOctalDigit(ch) {
        return '01234567'.indexOf(ch) >= 0;
    }


    // 7.2 White Space

    function isWhiteSpace(ch) {
        return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
            (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
    }

    // 7.3 Line Terminators

    function isLineTerminator(ch) {
        return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
    }

    // 7.6 Identifier Names and Identifiers

    function isIdentifierStart(ch) {
        return (ch === 0x24) || (ch === 0x5F) ||  // $ (dollar) and _ (underscore)
            (ch >= 0x41 && ch <= 0x5A) ||         // A..Z
            (ch >= 0x61 && ch <= 0x7A) ||         // a..z
            (ch === 0x5C) ||                      // \ (backslash)
            ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
    }

    function isIdentifierPart(ch) {
        return (ch === 0x24) || (ch === 0x5F) ||  // $ (dollar) and _ (underscore)
            (ch >= 0x41 && ch <= 0x5A) ||         // A..Z
            (ch >= 0x61 && ch <= 0x7A) ||         // a..z
            (ch >= 0x30 && ch <= 0x39) ||         // 0..9
            (ch === 0x5C) ||                      // \ (backslash)
            ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
    }

    // 7.6.1.2 Future Reserved Words

    function isFutureReservedWord(id) {
        switch (id) {
        case 'class':
        case 'enum':
        case 'export':
        case 'extends':
        case 'import':
        case 'super':
            return true;
        default:
            return false;
        }
    }

    function isStrictModeReservedWord(id) {
        switch (id) {
        case 'implements':
        case 'interface':
        case 'package':
        case 'private':
        case 'protected':
        case 'public':
        case 'static':
        case 'yield':
        case 'let':
            return true;
        default:
            return false;
        }
    }

    function isRestrictedWord(id) {
        return id === 'eval' || id === 'arguments';
    }

    // 7.6.1.1 Keywords

    function isKeyword(id) {
        if (strict && isStrictModeReservedWord(id)) {
            return true;
        }

        // 'const' is specialized as Keyword in V8.
        // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next.
        // Some others are from future reserved words.

        switch (id.length) {
        case 2:
            return (id === 'if') || (id === 'in') || (id === 'do');
        case 3:
            return (id === 'var') || (id === 'for') || (id === 'new') ||
                (id === 'try') || (id === 'let');
        case 4:
            return (id === 'this') || (id === 'else') || (id === 'case') ||
                (id === 'void') || (id === 'with') || (id === 'enum');
        case 5:
            return (id === 'while') || (id === 'break') || (id === 'catch') ||
                (id === 'throw') || (id === 'const') || (id === 'yield') ||
                (id === 'class') || (id === 'super');
        case 6:
            return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
                (id === 'switch') || (id === 'export') || (id === 'import');
        case 7:
            return (id === 'default') || (id === 'finally') || (id === 'extends');
        case 8:
            return (id === 'function') || (id === 'continue') || (id === 'debugger');
        case 10:
            return (id === 'instanceof');
        default:
            return false;
        }
    }

    // 7.4 Comments

    function addComment(type, value, start, end, loc) {
        var comment, attacher;

        assert(typeof start === 'number', 'Comment must have valid position');

        // Because the way the actual token is scanned, often the comments
        // (if any) are skipped twice during the lexical analysis.
        // Thus, we need to skip adding a comment if the comment array already
        // handled it.
        if (state.lastCommentStart >= start) {
            return;
        }
        state.lastCommentStart = start;

        comment = {
            type: type,
            value: value
        };
        if (extra.range) {
            comment.range = [start, end];
        }
        if (extra.loc) {
            comment.loc = loc;
        }
        extra.comments.push(comment);
        if (extra.attachComment) {
            extra.leadingComments.push(comment);
            extra.trailingComments.push(comment);
        }
    }

    function skipSingleLineComment(offset) {
        var start, loc, ch, comment;

        start = index - offset;
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart - offset
            }
        };

        while (index < length) {
            ch = source.charCodeAt(index);
            ++index;
            if (isLineTerminator(ch)) {
                if (extra.comments) {
                    comment = source.slice(start + offset, index - 1);
                    loc.end = {
                        line: lineNumber,
                        column: index - lineStart - 1
                    };
                    addComment('Line', comment, start, index - 1, loc);
                }
                if (ch === 13 && source.charCodeAt(index) === 10) {
                    ++index;
                }
                ++lineNumber;
                lineStart = index;
                return;
            }
        }

        if (extra.comments) {
            comment = source.slice(start + offset, index);
            loc.end = {
                line: lineNumber,
                column: index - lineStart
            };
            addComment('Line', comment, start, index, loc);
        }
    }

    function skipMultiLineComment() {
        var start, loc, ch, comment;

        if (extra.comments) {
            start = index - 2;
            loc = {
                start: {
                    line: lineNumber,
                    column: index - lineStart - 2
                }
            };
        }

        while (index < length) {
            ch = source.charCodeAt(index);
            if (isLineTerminator(ch)) {
                if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
                    ++index;
                }
                ++lineNumber;
                ++index;
                lineStart = index;
                if (index >= length) {
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
                }
            } else if (ch === 0x2A) {
                // Block comment ends with '*/'.
                if (source.charCodeAt(index + 1) === 0x2F) {
                    ++index;
                    ++index;
                    if (extra.comments) {
                        comment = source.slice(start + 2, index - 2);
                        loc.end = {
                            line: lineNumber,
                            column: index - lineStart
                        };
                        addComment('Block', comment, start, index, loc);
                    }
                    return;
                }
                ++index;
            } else {
                ++index;
            }
        }

        throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    }

    function skipComment() {
        var ch, start;

        start = (index === 0);
        while (index < length) {
            ch = source.charCodeAt(index);

            if (isWhiteSpace(ch)) {
                ++index;
            } else if (isLineTerminator(ch)) {
                ++index;
                if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
                    ++index;
                }
                ++lineNumber;
                lineStart = index;
                start = true;
            } else if (ch === 0x2F) { // U+002F is '/'
                ch = source.charCodeAt(index + 1);
                if (ch === 0x2F) {
                    ++index;
                    ++index;
                    skipSingleLineComment(2);
                    start = true;
                } else if (ch === 0x2A) {  // U+002A is '*'
                    ++index;
                    ++index;
                    skipMultiLineComment();
                } else {
                    break;
                }
            } else if (start && ch === 0x2D) { // U+002D is '-'
                // U+003E is '>'
                if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
                    // '-->' is a single-line comment
                    index += 3;
                    skipSingleLineComment(3);
                } else {
                    break;
                }
            } else if (ch === 0x3C) { // U+003C is '<'
                if (source.slice(index + 1, index + 4) === '!--') {
                    ++index; // `<`
                    ++index; // `!`
                    ++index; // `-`
                    ++index; // `-`
                    skipSingleLineComment(4);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }

    function scanHexEscape(prefix) {
        var i, len, ch, code = 0;

        len = (prefix === 'u') ? 4 : 2;
        for (i = 0; i < len; ++i) {
            if (index < length && isHexDigit(source[index])) {
                ch = source[index++];
                code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
            } else {
                return '';
            }
        }
        return String.fromCharCode(code);
    }

    function getEscapedIdentifier() {
        var ch, id;

        ch = source.charCodeAt(index++);
        id = String.fromCharCode(ch);

        // '\u' (U+005C, U+0075) denotes an escaped character.
        if (ch === 0x5C) {
            if (source.charCodeAt(index) !== 0x75) {
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
            }
            ++index;
            ch = scanHexEscape('u');
            if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
            }
            id = ch;
        }

        while (index < length) {
            ch = source.charCodeAt(index);
            if (!isIdentifierPart(ch)) {
                break;
            }
            ++index;
            id += String.fromCharCode(ch);

            // '\u' (U+005C, U+0075) denotes an escaped character.
            if (ch === 0x5C) {
                id = id.substr(0, id.length - 1);
                if (source.charCodeAt(index) !== 0x75) {
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
                }
                ++index;
                ch = scanHexEscape('u');
                if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
                    throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
                }
                id += ch;
            }
        }

        return id;
    }

    function getIdentifier() {
        var start, ch;

        start = index++;
        while (index < length) {
            ch = source.charCodeAt(index);
            if (ch === 0x5C) {
                // Blackslash (U+005C) marks Unicode escape sequence.
                index = start;
                return getEscapedIdentifier();
            }
            if (isIdentifierPart(ch)) {
                ++index;
            } else {
                break;
            }
        }

        return source.slice(start, index);
    }

    function scanIdentifier() {
        var start, id, type;

        start = index;

        // Backslash (U+005C) starts an escaped character.
        id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();

        // There is no keyword or literal with only one character.
        // Thus, it must be an identifier.
        if (id.length === 1) {
            type = Token.Identifier;
        } else if (isKeyword(id)) {
            type = Token.Keyword;
        } else if (id === 'null') {
            type = Token.NullLiteral;
        } else if (id === 'true' || id === 'false') {
            type = Token.BooleanLiteral;
        } else {
            type = Token.Identifier;
        }

        return {
            type: type,
            value: id,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }


    // 7.7 Punctuators

    function scanPunctuator() {
        var start = index,
            code = source.charCodeAt(index),
            code2,
            ch1 = source[index],
            ch2,
            ch3,
            ch4;

        switch (code) {

        // Check for most common single-character punctuators.
        case 0x2E:  // . dot
        case 0x28:  // ( open bracket
        case 0x29:  // ) close bracket
        case 0x3B:  // ; semicolon
        case 0x2C:  // , comma
        case 0x7B:  // { open curly brace
        case 0x7D:  // } close curly brace
        case 0x5B:  // [
        case 0x5D:  // ]
        case 0x3A:  // :
        case 0x3F:  // ?
        case 0x7E:  // ~
            ++index;
            if (extra.tokenize) {
                if (code === 0x28) {
                    extra.openParenToken = extra.tokens.length;
                } else if (code === 0x7B) {
                    extra.openCurlyToken = extra.tokens.length;
                }
            }
            return {
                type: Token.Punctuator,
                value: String.fromCharCode(code),
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };

        default:
            code2 = source.charCodeAt(index + 1);

            // '=' (U+003D) marks an assignment or comparison operator.
            if (code2 === 0x3D) {
                switch (code) {
                case 0x2B:  // +
                case 0x2D:  // -
                case 0x2F:  // /
                case 0x3C:  // <
                case 0x3E:  // >
                case 0x5E:  // ^
                case 0x7C:  // |
                case 0x25:  // %
                case 0x26:  // &
                case 0x2A:  // *
                    index += 2;
                    return {
                        type: Token.Punctuator,
                        value: String.fromCharCode(code) + String.fromCharCode(code2),
                        lineNumber: lineNumber,
                        lineStart: lineStart,
                        start: start,
                        end: index
                    };

                case 0x21: // !
                case 0x3D: // =
                    index += 2;

                    // !== and ===
                    if (source.charCodeAt(index) === 0x3D) {
                        ++index;
                    }
                    return {
                        type: Token.Punctuator,
                        value: source.slice(start, index),
                        lineNumber: lineNumber,
                        lineStart: lineStart,
                        start: start,
                        end: index
                    };
                }
            }
        }

        // 4-character punctuator: >>>=

        ch4 = source.substr(index, 4);

        if (ch4 === '>>>=') {
            index += 4;
            return {
                type: Token.Punctuator,
                value: ch4,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }

        // 3-character punctuators: === !== >>> <<= >>=

        ch3 = ch4.substr(0, 3);

        if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
            index += 3;
            return {
                type: Token.Punctuator,
                value: ch3,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }

        // Other 2-character punctuators: ++ -- << >> && ||
        ch2 = ch3.substr(0, 2);

        if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') {
            index += 2;
            return {
                type: Token.Punctuator,
                value: ch2,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }

        // 1-character punctuators: < > = ! + - * % & | ^ /
        if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
            ++index;
            return {
                type: Token.Punctuator,
                value: ch1,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }

        throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
    }

    // 7.8.3 Numeric Literals

    function scanHexLiteral(start) {
        var number = '';

        while (index < length) {
            if (!isHexDigit(source[index])) {
                break;
            }
            number += source[index++];
        }

        if (number.length === 0) {
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
        }

        if (isIdentifierStart(source.charCodeAt(index))) {
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
        }

        return {
            type: Token.NumericLiteral,
            value: parseInt('0x' + number, 16),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    function scanOctalLiteral(start) {
        var number = '0' + source[index++];
        while (index < length) {
            if (!isOctalDigit(source[index])) {
                break;
            }
            number += source[index++];
        }

        if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
        }

        return {
            type: Token.NumericLiteral,
            value: parseInt(number, 8),
            octal: true,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    function isImplicitOctalLiteral() {
        var i, ch;

        // Implicit octal, unless there is a non-octal digit.
        // (Annex B.1.1 on Numeric Literals)
        for (i = index + 1; i < length; ++i) {
            ch = source[i];
            if (ch === '8' || ch === '9') {
                return false;
            }
            if (!isOctalDigit(ch)) {
                return true;
            }
        }

        return true;
    }

    function scanNumericLiteral() {
        var number, start, ch;

        ch = source[index];
        assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
            'Numeric literal must start with a decimal digit or a decimal point');

        start = index;
        number = '';
        if (ch !== '.') {
            number = source[index++];
            ch = source[index];

            // Hex number starts with '0x'.
            // Octal number starts with '0'.
            if (number === '0') {
                if (ch === 'x' || ch === 'X') {
                    ++index;
                    return scanHexLiteral(start);
                }
                if (isOctalDigit(ch)) {
                    if (isImplicitOctalLiteral()) {
                        return scanOctalLiteral(start);
                    }
                }
            }

            while (isDecimalDigit(source.charCodeAt(index))) {
                number += source[index++];
            }
            ch = source[index];
        }

        if (ch === '.') {
            number += source[index++];
            while (isDecimalDigit(source.charCodeAt(index))) {
                number += source[index++];
            }
            ch = source[index];
        }

        if (ch === 'e' || ch === 'E') {
            number += source[index++];

            ch = source[index];
            if (ch === '+' || ch === '-') {
                number += source[index++];
            }
            if (isDecimalDigit(source.charCodeAt(index))) {
                while (isDecimalDigit(source.charCodeAt(index))) {
                    number += source[index++];
                }
            } else {
                throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
            }
        }

        if (isIdentifierStart(source.charCodeAt(index))) {
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
        }

        return {
            type: Token.NumericLiteral,
            value: parseFloat(number),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    // 7.8.4 String Literals

    function scanStringLiteral() {
        var str = '', quote, start, ch, code, unescaped, restore, octal = false, startLineNumber, startLineStart;
        startLineNumber = lineNumber;
        startLineStart = lineStart;

        quote = source[index];
        assert((quote === '\'' || quote === '"'),
            'String literal must starts with a quote');

        start = index;
        ++index;

        while (index < length) {
            ch = source[index++];

            if (ch === quote) {
                quote = '';
                break;
            } else if (ch === '\\') {
                ch = source[index++];
                if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
                    switch (ch) {
                    case 'u':
                    case 'x':
                        restore = index;
                        unescaped = scanHexEscape(ch);
                        if (unescaped) {
                            str += unescaped;
                        } else {
                            index = restore;
                            str += ch;
                        }
                        break;
                    case 'n':
                        str += '\n';
                        break;
                    case 'r':
                        str += '\r';
                        break;
                    case 't':
                        str += '\t';
                        break;
                    case 'b':
                        str += '\b';
                        break;
                    case 'f':
                        str += '\f';
                        break;
                    case 'v':
                        str += '\x0B';
                        break;

                    default:
                        if (isOctalDigit(ch)) {
                            code = '01234567'.indexOf(ch);

                            // \0 is not octal escape sequence
                            if (code !== 0) {
                                octal = true;
                            }

                            if (index < length && isOctalDigit(source[index])) {
                                octal = true;
                                code = code * 8 + '01234567'.indexOf(source[index++]);

                                // 3 digits are only allowed when string starts
                                // with 0, 1, 2, 3
                                if ('0123'.indexOf(ch) >= 0 &&
                                        index < length &&
                                        isOctalDigit(source[index])) {
                                    code = code * 8 + '01234567'.indexOf(source[index++]);
                                }
                            }
                            str += String.fromCharCode(code);
                        } else {
                            str += ch;
                        }
                        break;
                    }
                } else {
                    ++lineNumber;
                    if (ch ===  '\r' && source[index] === '\n') {
                        ++index;
                    }
                    lineStart = index;
                }
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                break;
            } else {
                str += ch;
            }
        }

        if (quote !== '') {
            throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
        }

        return {
            type: Token.StringLiteral,
            value: str,
            octal: octal,
            startLineNumber: startLineNumber,
            startLineStart: startLineStart,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }

    function testRegExp(pattern, flags) {
        var value;
        try {
            value = new RegExp(pattern, flags);
        } catch (e) {
            throwError({}, Messages.InvalidRegExp);
        }
        return value;
    }

    function scanRegExpBody() {
        var ch, str, classMarker, terminated, body;

        ch = source[index];
        assert(ch === '/', 'Regular expression literal must start with a slash');
        str = source[index++];

        classMarker = false;
        terminated = false;
        while (index < length) {
            ch = source[index++];
            str += ch;
            if (ch === '\\') {
                ch = source[index++];
                // ECMA-262 7.8.5
                if (isLineTerminator(ch.charCodeAt(0))) {
                    throwError({}, Messages.UnterminatedRegExp);
                }
                str += ch;
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                throwError({}, Messages.UnterminatedRegExp);
            } else if (classMarker) {
                if (ch === ']') {
                    classMarker = false;
                }
            } else {
                if (ch === '/') {
                    terminated = true;
                    break;
                } else if (ch === '[') {
                    classMarker = true;
                }
            }
        }

        if (!terminated) {
            throwError({}, Messages.UnterminatedRegExp);
        }

        // Exclude leading and trailing slash.
        body = str.substr(1, str.length - 2);
        return {
            value: body,
            literal: str
        };
    }

    function scanRegExpFlags() {
        var ch, str, flags, restore;

        str = '';
        flags = '';
        while (index < length) {
            ch = source[index];
            if (!isIdentifierPart(ch.charCodeAt(0))) {
                break;
            }

            ++index;
            if (ch === '\\' && index < length) {
                ch = source[index];
                if (ch === 'u') {
                    ++index;
                    restore = index;
                    ch = scanHexEscape('u');
                    if (ch) {
                        flags += ch;
                        for (str += '\\u'; restore < index; ++restore) {
                            str += source[restore];
                        }
                    } else {
                        index = restore;
                        flags += 'u';
                        str += '\\u';
                    }
                    throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
                } else {
                    str += '\\';
                    throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
                }
            } else {
                flags += ch;
                str += ch;
            }
        }

        return {
            value: flags,
            literal: str
        };
    }

    function scanRegExp() {
        var start, body, flags, pattern, value;

        lookahead = null;
        skipComment();
        start = index;

        body = scanRegExpBody();
        flags = scanRegExpFlags();
        value = testRegExp(body.value, flags.value);

        if (extra.tokenize) {
            return {
                type: Token.RegularExpression,
                value: value,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }

        return {
            literal: body.literal + flags.literal,
            value: value,
            start: start,
            end: index
        };
    }

    function collectRegex() {
        var pos, loc, regex, token;

        skipComment();

        pos = index;
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart
            }
        };

        regex = scanRegExp();
        loc.end = {
            line: lineNumber,
            column: index - lineStart
        };

        /* istanbul ignore next */
        if (!extra.tokenize) {
            // Pop the previous token, which is likely '/' or '/='
            if (extra.tokens.length > 0) {
                token = extra.tokens[extra.tokens.length - 1];
                if (token.range[0] === pos && token.type === 'Punctuator') {
                    if (token.value === '/' || token.value === '/=') {
                        extra.tokens.pop();
                    }
                }
            }

            extra.tokens.push({
                type: 'RegularExpression',
                value: regex.literal,
                range: [pos, index],
                loc: loc
            });
        }

        return regex;
    }

    function isIdentifierName(token) {
        return token.type === Token.Identifier ||
            token.type === Token.Keyword ||
            token.type === Token.BooleanLiteral ||
            token.type === Token.NullLiteral;
    }

    function advanceSlash() {
        var prevToken,
            checkToken;
        // Using the following algorithm:
        // https://github.com/mozilla/sweet.js/wiki/design
        prevToken = extra.tokens[extra.tokens.length - 1];
        if (!prevToken) {
            // Nothing before that: it cannot be a division.
            return collectRegex();
        }
        if (prevToken.type === 'Punctuator') {
            if (prevToken.value === ']') {
                return scanPunctuator();
            }
            if (prevToken.value === ')') {
                checkToken = extra.tokens[extra.openParenToken - 1];
                if (checkToken &&
                        checkToken.type === 'Keyword' &&
                        (checkToken.value === 'if' ||
                         checkToken.value === 'while' ||
                         checkToken.value === 'for' ||
                         checkToken.value === 'with')) {
                    return collectRegex();
                }
                return scanPunctuator();
            }
            if (prevToken.value === '}') {
                // Dividing a function by anything makes little sense,
                // but we have to check for that.
                if (extra.tokens[extra.openCurlyToken - 3] &&
                        extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
                    // Anonymous function.
                    checkToken = extra.tokens[extra.openCurlyToken - 4];
                    if (!checkToken) {
                        return scanPunctuator();
                    }
                } else if (extra.tokens[extra.openCurlyToken - 4] &&
                        extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
                    // Named function.
                    checkToken = extra.tokens[extra.openCurlyToken - 5];
                    if (!checkToken) {
                        return collectRegex();
                    }
                } else {
                    return scanPunctuator();
                }
                // checkToken determines whether the function is
                // a declaration or an expression.
                if (FnExprTokens.indexOf(checkToken.value) >= 0) {
                    // It is an expression.
                    return scanPunctuator();
                }
                // It is a declaration.
                return collectRegex();
            }
            return collectRegex();
        }
        if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
            return collectRegex();
        }
        return scanPunctuator();
    }

    function advance() {
        var ch;

        skipComment();

        if (index >= length) {
            return {
                type: Token.EOF,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: index,
                end: index
            };
        }

        ch = source.charCodeAt(index);

        if (isIdentifierStart(ch)) {
            return scanIdentifier();
        }

        // Very common: ( and ) and ;
        if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
            return scanPunctuator();
        }

        // String literal starts with single quote (U+0027) or double quote (U+0022).
        if (ch === 0x27 || ch === 0x22) {
            return scanStringLiteral();
        }


        // Dot (.) U+002E can also start a floating-point number, hence the need
        // to check the next character.
        if (ch === 0x2E) {
            if (isDecimalDigit(source.charCodeAt(index + 1))) {
                return scanNumericLiteral();
            }
            return scanPunctuator();
        }

        if (isDecimalDigit(ch)) {
            return scanNumericLiteral();
        }

        // Slash (/) U+002F can also start a regex.
        if (extra.tokenize && ch === 0x2F) {
            return advanceSlash();
        }

        return scanPunctuator();
    }

    function collectToken() {
        var loc, token, range, value;

        skipComment();
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart
            }
        };

        token = advance();
        loc.end = {
            line: lineNumber,
            column: index - lineStart
        };

        if (token.type !== Token.EOF) {
            value = source.slice(token.start, token.end);
            extra.tokens.push({
                type: TokenName[token.type],
                value: value,
                range: [token.start, token.end],
                loc: loc
            });
        }

        return token;
    }

    function lex() {
        var token;

        token = lookahead;
        index = token.end;
        lineNumber = token.lineNumber;
        lineStart = token.lineStart;

        lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();

        index = token.end;
        lineNumber = token.lineNumber;
        lineStart = token.lineStart;

        return token;
    }

    function peek() {
        var pos, line, start;

        pos = index;
        line = lineNumber;
        start = lineStart;
        lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
        index = pos;
        lineNumber = line;
        lineStart = start;
    }

    function Position(line, column) {
        this.line = line;
        this.column = column;
    }

    function SourceLocation(startLine, startColumn, line, column) {
        this.start = new Position(startLine, startColumn);
        this.end = new Position(line, column);
    }

    SyntaxTreeDelegate = {

        name: 'SyntaxTree',

        processComment: function (node) {
            var lastChild, trailingComments;

            if (node.type === Syntax.Program) {
                if (node.body.length > 0) {
                    return;
                }
            }

            if (extra.trailingComments.length > 0) {
                if (extra.trailingComments[0].range[0] >= node.range[1]) {
                    trailingComments = extra.trailingComments;
                    extra.trailingComments = [];
                } else {
                    extra.trailingComments.length = 0;
                }
            } else {
                if (extra.bottomRightStack.length > 0 &&
                        extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments &&
                        extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments[0].range[0] >= node.range[1]) {
                    trailingComments = extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
                    delete extra.bottomRightStack[extra.bottomRightStack.length - 1].trailingComments;
                }
            }

            // Eating the stack.
            while (extra.bottomRightStack.length > 0 && extra.bottomRightStack[extra.bottomRightStack.length - 1].range[0] >= node.range[0]) {
                lastChild = extra.bottomRightStack.pop();
            }

            if (lastChild) {
                if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
                    node.leadingComments = lastChild.leadingComments;
                    delete lastChild.leadingComments;
                }
            } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
                node.leadingComments = extra.leadingComments;
                extra.leadingComments = [];
            }


            if (trailingComments) {
                node.trailingComments = trailingComments;
            }

            extra.bottomRightStack.push(node);
        },

        markEnd: function (node, startToken) {
            if (extra.range) {
                node.range = [startToken.start, index];
            }
            if (extra.loc) {
                node.loc = new SourceLocation(
                    startToken.startLineNumber === undefined ?  startToken.lineNumber : startToken.startLineNumber,
                    startToken.start - (startToken.startLineStart === undefined ?  startToken.lineStart : startToken.startLineStart),
                    lineNumber,
                    index - lineStart
                );
                this.postProcess(node);
            }

            if (extra.attachComment) {
                this.processComment(node);
            }
            return node;
        },

        postProcess: function (node) {
            if (extra.source) {
                node.loc.source = extra.source;
            }
            return node;
        },

        createArrayExpression: function (elements) {
            return {
                type: Syntax.ArrayExpression,
                elements: elements
            };
        },

        createAssignmentExpression: function (operator, left, right) {
            return {
                type: Syntax.AssignmentExpression,
                operator: operator,
                left: left,
                right: right
            };
        },

        createBinaryExpression: function (operator, left, right) {
            var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
                        Syntax.BinaryExpression;
            return {
                type: type,
                operator: operator,
                left: left,
                right: right
            };
        },

        createBlockStatement: function (body) {
            return {
                type: Syntax.BlockStatement,
                body: body
            };
        },

        createBreakStatement: function (label) {
            return {
                type: Syntax.BreakStatement,
                label: label
            };
        },

        createCallExpression: function (callee, args) {
            return {
                type: Syntax.CallExpression,
                callee: callee,
                'arguments': args
            };
        },

        createCatchClause: function (param, body) {
            return {
                type: Syntax.CatchClause,
                param: param,
                body: body
            };
        },

        createConditionalExpression: function (test, consequent, alternate) {
            return {
                type: Syntax.ConditionalExpression,
                test: test,
                consequent: consequent,
                alternate: alternate
            };
        },

        createContinueStatement: function (label) {
            return {
                type: Syntax.ContinueStatement,
                label: label
            };
        },

        createDebuggerStatement: function () {
            return {
                type: Syntax.DebuggerStatement
            };
        },

        createDoWhileStatement: function (body, test) {
            return {
                type: Syntax.DoWhileStatement,
                body: body,
                test: test
            };
        },

        createEmptyStatement: function () {
            return {
                type: Syntax.EmptyStatement
            };
        },

        createExpressionStatement: function (expression) {
            return {
                type: Syntax.ExpressionStatement,
                expression: expression
            };
        },

        createForStatement: function (init, test, update, body) {
            return {
                type: Syntax.ForStatement,
                init: init,
                test: test,
                update: update,
                body: body
            };
        },

        createForInStatement: function (left, right, body) {
            return {
                type: Syntax.ForInStatement,
                left: left,
                right: right,
                body: body,
                each: false
            };
        },

        createFunctionDeclaration: function (id, params, defaults, body) {
            return {
                type: Syntax.FunctionDeclaration,
                id: id,
                params: params,
                defaults: defaults,
                body: body,
                rest: null,
                generator: false,
                expression: false
            };
        },

        createFunctionExpression: function (id, params, defaults, body) {
            return {
                type: Syntax.FunctionExpression,
                id: id,
                params: params,
                defaults: defaults,
                body: body,
                rest: null,
                generator: false,
                expression: false
            };
        },

        createIdentifier: function (name) {
            return {
                type: Syntax.Identifier,
                name: name
            };
        },

        createIfStatement: function (test, consequent, alternate) {
            return {
                type: Syntax.IfStatement,
                test: test,
                consequent: consequent,
                alternate: alternate
            };
        },

        createLabeledStatement: function (label, body) {
            return {
                type: Syntax.LabeledStatement,
                label: label,
                body: body
            };
        },

        createLiteral: function (token) {
            return {
                type: Syntax.Literal,
                value: token.value,
                raw: source.slice(token.start, token.end)
            };
        },

        createMemberExpression: function (accessor, object, property) {
            return {
                type: Syntax.MemberExpression,
                computed: accessor === '[',
                object: object,
                property: property
            };
        },

        createNewExpression: function (callee, args) {
            return {
                type: Syntax.NewExpression,
                callee: callee,
                'arguments': args
            };
        },

        createObjectExpression: function (properties) {
            return {
                type: Syntax.ObjectExpression,
                properties: properties
            };
        },

        createPostfixExpression: function (operator, argument) {
            return {
                type: Syntax.UpdateExpression,
                operator: operator,
                argument: argument,
                prefix: false
            };
        },

        createProgram: function (body) {
            return {
                type: Syntax.Program,
                body: body
            };
        },

        createProperty: function (kind, key, value) {
            return {
                type: Syntax.Property,
                key: key,
                value: value,
                kind: kind
            };
        },

        createReturnStatement: function (argument) {
            return {
                type: Syntax.ReturnStatement,
                argument: argument
            };
        },

        createSequenceExpression: function (expressions) {
            return {
                type: Syntax.SequenceExpression,
                expressions: expressions
            };
        },

        createSwitchCase: function (test, consequent) {
            return {
                type: Syntax.SwitchCase,
                test: test,
                consequent: consequent
            };
        },

        createSwitchStatement: function (discriminant, cases) {
            return {
                type: Syntax.SwitchStatement,
                discriminant: discriminant,
                cases: cases
            };
        },

        createThisExpression: function () {
            return {
                type: Syntax.ThisExpression
            };
        },

        createThrowStatement: function (argument) {
            return {
                type: Syntax.ThrowStatement,
                argument: argument
            };
        },

        createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
            return {
                type: Syntax.TryStatement,
                block: block,
                guardedHandlers: guardedHandlers,
                handlers: handlers,
                finalizer: finalizer
            };
        },

        createUnaryExpression: function (operator, argument) {
            if (operator === '++' || operator === '--') {
                return {
                    type: Syntax.UpdateExpression,
                    operator: operator,
                    argument: argument,
                    prefix: true
                };
            }
            return {
                type: Syntax.UnaryExpression,
                operator: operator,
                argument: argument,
                prefix: true
            };
        },

        createVariableDeclaration: function (declarations, kind) {
            return {
                type: Syntax.VariableDeclaration,
                declarations: declarations,
                kind: kind
            };
        },

        createVariableDeclarator: function (id, init) {
            return {
                type: Syntax.VariableDeclarator,
                id: id,
                init: init
            };
        },

        createWhileStatement: function (test, body) {
            return {
                type: Syntax.WhileStatement,
                test: test,
                body: body
            };
        },

        createWithStatement: function (object, body) {
            return {
                type: Syntax.WithStatement,
                object: object,
                body: body
            };
        }
    };

    // Return true if there is a line terminator before the next token.

    function peekLineTerminator() {
        var pos, line, start, found;

        pos = index;
        line = lineNumber;
        start = lineStart;
        skipComment();
        found = lineNumber !== line;
        index = pos;
        lineNumber = line;
        lineStart = start;

        return found;
    }

    // Throw an exception

    function throwError(token, messageFormat) {
        var error,
            args = Array.prototype.slice.call(arguments, 2),
            msg = messageFormat.replace(
                /%(\d)/g,
                function (whole, index) {
                    assert(index < args.length, 'Message reference must be in range');
                    return args[index];
                }
            );

        if (typeof token.lineNumber === 'number') {
            error = new Error('Line ' + token.lineNumber + ': ' + msg);
            error.index = token.start;
            error.lineNumber = token.lineNumber;
            error.column = token.start - lineStart + 1;
        } else {
            error = new Error('Line ' + lineNumber + ': ' + msg);
            error.index = index;
            error.lineNumber = lineNumber;
            error.column = index - lineStart + 1;
        }

        error.description = msg;
        throw error;
    }

    function throwErrorTolerant() {
        try {
            throwError.apply(null, arguments);
        } catch (e) {
            if (extra.errors) {
                extra.errors.push(e);
            } else {
                throw e;
            }
        }
    }


    // Throw an exception because of the token.

    function throwUnexpected(token) {
        if (token.type === Token.EOF) {
            throwError(token, Messages.UnexpectedEOS);
        }

        if (token.type === Token.NumericLiteral) {
            throwError(token, Messages.UnexpectedNumber);
        }

        if (token.type === Token.StringLiteral) {
            throwError(token, Messages.UnexpectedString);
        }

        if (token.type === Token.Identifier) {
            throwError(token, Messages.UnexpectedIdentifier);
        }

        if (token.type === Token.Keyword) {
            if (isFutureReservedWord(token.value)) {
                throwError(token, Messages.UnexpectedReserved);
            } else if (strict && isStrictModeReservedWord(token.value)) {
                throwErrorTolerant(token, Messages.StrictReservedWord);
                return;
            }
            throwError(token, Messages.UnexpectedToken, token.value);
        }

        // BooleanLiteral, NullLiteral, or Punctuator.
        throwError(token, Messages.UnexpectedToken, token.value);
    }

    // Expect the next token to match the specified punctuator.
    // If not, an exception will be thrown.

    function expect(value) {
        var token = lex();
        if (token.type !== Token.Punctuator || token.value !== value) {
            throwUnexpected(token);
        }
    }

    // Expect the next token to match the specified keyword.
    // If not, an exception will be thrown.

    function expectKeyword(keyword) {
        var token = lex();
        if (token.type !== Token.Keyword || token.value !== keyword) {
            throwUnexpected(token);
        }
    }

    // Return true if the next token matches the specified punctuator.

    function match(value) {
        return lookahead.type === Token.Punctuator && lookahead.value === value;
    }

    // Return true if the next token matches the specified keyword

    function matchKeyword(keyword) {
        return lookahead.type === Token.Keyword && lookahead.value === keyword;
    }

    // Return true if the next token is an assignment operator

    function matchAssign() {
        var op;

        if (lookahead.type !== Token.Punctuator) {
            return false;
        }
        op = lookahead.value;
        return op === '=' ||
            op === '*=' ||
            op === '/=' ||
            op === '%=' ||
            op === '+=' ||
            op === '-=' ||
            op === '<<=' ||
            op === '>>=' ||
            op === '>>>=' ||
            op === '&=' ||
            op === '^=' ||
            op === '|=';
    }

    function consumeSemicolon() {
        var line, oldIndex = index, oldLineNumber = lineNumber,
            oldLineStart = lineStart, oldLookahead = lookahead;

        // Catch the very common case first: immediately a semicolon (U+003B).
        if (source.charCodeAt(index) === 0x3B || match(';')) {
            lex();
            return;
        }

        line = lineNumber;
        skipComment();
        if (lineNumber !== line) {
            index = oldIndex;
            lineNumber = oldLineNumber;
            lineStart = oldLineStart;
            lookahead = oldLookahead;
            return;
        }

        if (lookahead.type !== Token.EOF && !match('}')) {
            throwUnexpected(lookahead);
        }
    }

    // Return true if provided expression is LeftHandSideExpression

    function isLeftHandSide(expr) {
        return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
    }

    // 11.1.4 Array Initialiser

    function parseArrayInitialiser() {
        var elements = [], startToken;

        startToken = lookahead;
        expect('[');

        while (!match(']')) {
            if (match(',')) {
                lex();
                elements.push(null);
            } else {
                elements.push(parseAssignmentExpression());

                if (!match(']')) {
                    expect(',');
                }
            }
        }

        lex();

        return delegate.markEnd(delegate.createArrayExpression(elements), startToken);
    }

    // 11.1.5 Object Initialiser

    function parsePropertyFunction(param, first) {
        var previousStrict, body, startToken;

        previousStrict = strict;
        startToken = lookahead;
        body = parseFunctionSourceElements();
        if (first && strict && isRestrictedWord(param[0].name)) {
            throwErrorTolerant(first, Messages.StrictParamName);
        }
        strict = previousStrict;
        return delegate.markEnd(delegate.createFunctionExpression(null, param, [], body), startToken);
    }

    function parseObjectPropertyKey() {
        var token, startToken;

        startToken = lookahead;
        token = lex();

        // Note: This function is called only from parseObjectProperty(), where
        // EOF and Punctuator tokens are already filtered out.

        if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
            if (strict && token.octal) {
                throwErrorTolerant(token, Messages.StrictOctalLiteral);
            }
            return delegate.markEnd(delegate.createLiteral(token), startToken);
        }

        return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
    }

    function parseObjectProperty() {
        var token, key, id, value, param, startToken;

        token = lookahead;
        startToken = lookahead;

        if (token.type === Token.Identifier) {

            id = parseObjectPropertyKey();

            // Property Assignment: Getter and Setter.

            if (token.value === 'get' && !match(':')) {
                key = parseObjectPropertyKey();
                expect('(');
                expect(')');
                value = parsePropertyFunction([]);
                return delegate.markEnd(delegate.createProperty('get', key, value), startToken);
            }
            if (token.value === 'set' && !match(':')) {
                key = parseObjectPropertyKey();
                expect('(');
                token = lookahead;
                if (token.type !== Token.Identifier) {
                    expect(')');
                    throwErrorTolerant(token, Messages.UnexpectedToken, token.value);
                    value = parsePropertyFunction([]);
                } else {
                    param = [ parseVariableIdentifier() ];
                    expect(')');
                    value = parsePropertyFunction(param, token);
                }
                return delegate.markEnd(delegate.createProperty('set', key, value), startToken);
            }
            expect(':');
            value = parseAssignmentExpression();
            return delegate.markEnd(delegate.createProperty('init', id, value), startToken);
        }
        if (token.type === Token.EOF || token.type === Token.Punctuator) {
            throwUnexpected(token);
        } else {
            key = parseObjectPropertyKey();
            expect(':');
            value = parseAssignmentExpression();
            return delegate.markEnd(delegate.createProperty('init', key, value), startToken);
        }
    }

    function parseObjectInitialiser() {
        var properties = [], property, name, key, kind, map = {}, toString = String, startToken;

        startToken = lookahead;

        expect('{');

        while (!match('}')) {
            property = parseObjectProperty();

            if (property.key.type === Syntax.Identifier) {
                name = property.key.name;
            } else {
                name = toString(property.key.value);
            }
            kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;

            key = '$' + name;
            if (Object.prototype.hasOwnProperty.call(map, key)) {
                if (map[key] === PropertyKind.Data) {
                    if (strict && kind === PropertyKind.Data) {
                        throwErrorTolerant({}, Messages.StrictDuplicateProperty);
                    } else if (kind !== PropertyKind.Data) {
                        throwErrorTolerant({}, Messages.AccessorDataProperty);
                    }
                } else {
                    if (kind === PropertyKind.Data) {
                        throwErrorTolerant({}, Messages.AccessorDataProperty);
                    } else if (map[key] & kind) {
                        throwErrorTolerant({}, Messages.AccessorGetSet);
                    }
                }
                map[key] |= kind;
            } else {
                map[key] = kind;
            }

            properties.push(property);

            if (!match('}')) {
                expect(',');
            }
        }

        expect('}');

        return delegate.markEnd(delegate.createObjectExpression(properties), startToken);
    }

    // 11.1.6 The Grouping Operator

    function parseGroupExpression() {
        var expr;

        expect('(');

        expr = parseExpression();

        expect(')');

        return expr;
    }


    // 11.1 Primary Expressions

    function parsePrimaryExpression() {
        var type, token, expr, startToken;

        if (match('(')) {
            return parseGroupExpression();
        }

        if (match('[')) {
            return parseArrayInitialiser();
        }

        if (match('{')) {
            return parseObjectInitialiser();
        }

        type = lookahead.type;
        startToken = lookahead;

        if (type === Token.Identifier) {
            expr =  delegate.createIdentifier(lex().value);
        } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
            if (strict && lookahead.octal) {
                throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
            }
            expr = delegate.createLiteral(lex());
        } else if (type === Token.Keyword) {
            if (matchKeyword('function')) {
                return parseFunctionExpression();
            }
            if (matchKeyword('this')) {
                lex();
                expr = delegate.createThisExpression();
            } else {
                throwUnexpected(lex());
            }
        } else if (type === Token.BooleanLiteral) {
            token = lex();
            token.value = (token.value === 'true');
            expr = delegate.createLiteral(token);
        } else if (type === Token.NullLiteral) {
            token = lex();
            token.value = null;
            expr = delegate.createLiteral(token);
        } else if (match('/') || match('/=')) {
            if (typeof extra.tokens !== 'undefined') {
                expr = delegate.createLiteral(collectRegex());
            } else {
                expr = delegate.createLiteral(scanRegExp());
            }
            peek();
        } else {
            throwUnexpected(lex());
        }

        return delegate.markEnd(expr, startToken);
    }

    // 11.2 Left-Hand-Side Expressions

    function parseArguments() {
        var args = [];

        expect('(');

        if (!match(')')) {
            while (index < length) {
                args.push(parseAssignmentExpression());
                if (match(')')) {
                    break;
                }
                expect(',');
            }
        }

        expect(')');

        return args;
    }

    function parseNonComputedProperty() {
        var token, startToken;

        startToken = lookahead;
        token = lex();

        if (!isIdentifierName(token)) {
            throwUnexpected(token);
        }

        return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
    }

    function parseNonComputedMember() {
        expect('.');

        return parseNonComputedProperty();
    }

    function parseComputedMember() {
        var expr;

        expect('[');

        expr = parseExpression();

        expect(']');

        return expr;
    }

    function parseNewExpression() {
        var callee, args, startToken;

        startToken = lookahead;
        expectKeyword('new');
        callee = parseLeftHandSideExpression();
        args = match('(') ? parseArguments() : [];

        return delegate.markEnd(delegate.createNewExpression(callee, args), startToken);
    }

    function parseLeftHandSideExpressionAllowCall() {
        var expr, args, property, startToken, previousAllowIn = state.allowIn;

        startToken = lookahead;
        state.allowIn = true;
        expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();

        for (;;) {
            if (match('.')) {
                property = parseNonComputedMember();
                expr = delegate.createMemberExpression('.', expr, property);
            } else if (match('(')) {
                args = parseArguments();
                expr = delegate.createCallExpression(expr, args);
            } else if (match('[')) {
                property = parseComputedMember();
                expr = delegate.createMemberExpression('[', expr, property);
            } else {
                break;
            }
            delegate.markEnd(expr, startToken);
        }
        state.allowIn = previousAllowIn;

        return expr;
    }

    function parseLeftHandSideExpression() {
        var expr, property, startToken;
        assert(state.allowIn, 'callee of new expression always allow in keyword.');

        startToken = lookahead;

        expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();

        while (match('.') || match('[')) {
            if (match('[')) {
                property = parseComputedMember();
                expr = delegate.createMemberExpression('[', expr, property);
            } else {
                property = parseNonComputedMember();
                expr = delegate.createMemberExpression('.', expr, property);
            }
            delegate.markEnd(expr, startToken);
        }
        return expr;
    }

    // 11.3 Postfix Expressions

    function parsePostfixExpression() {
        var expr, token, startToken = lookahead;

        expr = parseLeftHandSideExpressionAllowCall();

        if (lookahead.type === Token.Punctuator) {
            if ((match('++') || match('--')) && !peekLineTerminator()) {
                // 11.3.1, 11.3.2
                if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                    throwErrorTolerant({}, Messages.StrictLHSPostfix);
                }

                if (!isLeftHandSide(expr)) {
                    throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
                }

                token = lex();
                expr = delegate.markEnd(delegate.createPostfixExpression(token.value, expr), startToken);
            }
        }

        return expr;
    }

    // 11.4 Unary Operators

    function parseUnaryExpression() {
        var token, expr, startToken;

        if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
            expr = parsePostfixExpression();
        } else if (match('++') || match('--')) {
            startToken = lookahead;
            token = lex();
            expr = parseUnaryExpression();
            // 11.4.4, 11.4.5
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                throwErrorTolerant({}, Messages.StrictLHSPrefix);
            }

            if (!isLeftHandSide(expr)) {
                throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
            }

            expr = delegate.createUnaryExpression(token.value, expr);
            expr = delegate.markEnd(expr, startToken);
        } else if (match('+') || match('-') || match('~') || match('!')) {
            startToken = lookahead;
            token = lex();
            expr = parseUnaryExpression();
            expr = delegate.createUnaryExpression(token.value, expr);
            expr = delegate.markEnd(expr, startToken);
        } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
            startToken = lookahead;
            token = lex();
            expr = parseUnaryExpression();
            expr = delegate.createUnaryExpression(token.value, expr);
            expr = delegate.markEnd(expr, startToken);
            if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
                throwErrorTolerant({}, Messages.StrictDelete);
            }
        } else {
            expr = parsePostfixExpression();
        }

        return expr;
    }

    function binaryPrecedence(token, allowIn) {
        var prec = 0;

        if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
            return 0;
        }

        switch (token.value) {
        case '||':
            prec = 1;
            break;

        case '&&':
            prec = 2;
            break;

        case '|':
            prec = 3;
            break;

        case '^':
            prec = 4;
            break;

        case '&':
            prec = 5;
            break;

        case '==':
        case '!=':
        case '===':
        case '!==':
            prec = 6;
            break;

        case '<':
        case '>':
        case '<=':
        case '>=':
        case 'instanceof':
            prec = 7;
            break;

        case 'in':
            prec = allowIn ? 7 : 0;
            break;

        case '<<':
        case '>>':
        case '>>>':
            prec = 8;
            break;

        case '+':
        case '-':
            prec = 9;
            break;

        case '*':
        case '/':
        case '%':
            prec = 11;
            break;

        default:
            break;
        }

        return prec;
    }

    // 11.5 Multiplicative Operators
    // 11.6 Additive Operators
    // 11.7 Bitwise Shift Operators
    // 11.8 Relational Operators
    // 11.9 Equality Operators
    // 11.10 Binary Bitwise Operators
    // 11.11 Binary Logical Operators

    function parseBinaryExpression() {
        var marker, markers, expr, token, prec, stack, right, operator, left, i;

        marker = lookahead;
        left = parseUnaryExpression();

        token = lookahead;
        prec = binaryPrecedence(token, state.allowIn);
        if (prec === 0) {
            return left;
        }
        token.prec = prec;
        lex();

        markers = [marker, lookahead];
        right = parseUnaryExpression();

        stack = [left, token, right];

        while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {

            // Reduce: make a binary expression from the three topmost entries.
            while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
                right = stack.pop();
                operator = stack.pop().value;
                left = stack.pop();
                expr = delegate.createBinaryExpression(operator, left, right);
                markers.pop();
                marker = markers[markers.length - 1];
                delegate.markEnd(expr, marker);
                stack.push(expr);
            }

            // Shift.
            token = lex();
            token.prec = prec;
            stack.push(token);
            markers.push(lookahead);
            expr = parseUnaryExpression();
            stack.push(expr);
        }

        // Final reduce to clean-up the stack.
        i = stack.length - 1;
        expr = stack[i];
        markers.pop();
        while (i > 1) {
            expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
            i -= 2;
            marker = markers.pop();
            delegate.markEnd(expr, marker);
        }

        return expr;
    }


    // 11.12 Conditional Operator

    function parseConditionalExpression() {
        var expr, previousAllowIn, consequent, alternate, startToken;

        startToken = lookahead;

        expr = parseBinaryExpression();

        if (match('?')) {
            lex();
            previousAllowIn = state.allowIn;
            state.allowIn = true;
            consequent = parseAssignmentExpression();
            state.allowIn = previousAllowIn;
            expect(':');
            alternate = parseAssignmentExpression();

            expr = delegate.createConditionalExpression(expr, consequent, alternate);
            delegate.markEnd(expr, startToken);
        }

        return expr;
    }

    // 11.13 Assignment Operators

    function parseAssignmentExpression() {
        var token, left, right, node, startToken;

        token = lookahead;
        startToken = lookahead;

        node = left = parseConditionalExpression();

        if (matchAssign()) {
            // LeftHandSideExpression
            if (!isLeftHandSide(left)) {
                throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
            }

            // 11.13.1
            if (strict && left.type === Syntax.Identifier && isRestrictedWord(left.name)) {
                throwErrorTolerant(token, Messages.StrictLHSAssignment);
            }

            token = lex();
            right = parseAssignmentExpression();
            node = delegate.markEnd(delegate.createAssignmentExpression(token.value, left, right), startToken);
        }

        return node;
    }

    // 11.14 Comma Operator

    function parseExpression() {
        var expr, startToken = lookahead;

        expr = parseAssignmentExpression();

        if (match(',')) {
            expr = delegate.createSequenceExpression([ expr ]);

            while (index < length) {
                if (!match(',')) {
                    break;
                }
                lex();
                expr.expressions.push(parseAssignmentExpression());
            }

            delegate.markEnd(expr, startToken);
        }

        return expr;
    }

    // 12.1 Block

    function parseStatementList() {
        var list = [],
            statement;

        while (index < length) {
            if (match('}')) {
                break;
            }
            statement = parseSourceElement();
            if (typeof statement === 'undefined') {
                break;
            }
            list.push(statement);
        }

        return list;
    }

    function parseBlock() {
        var block, startToken;

        startToken = lookahead;
        expect('{');

        block = parseStatementList();

        expect('}');

        return delegate.markEnd(delegate.createBlockStatement(block), startToken);
    }

    // 12.2 Variable Statement

    function parseVariableIdentifier() {
        var token, startToken;

        startToken = lookahead;
        token = lex();

        if (token.type !== Token.Identifier) {
            throwUnexpected(token);
        }

        return delegate.markEnd(delegate.createIdentifier(token.value), startToken);
    }

    function parseVariableDeclaration(kind) {
        var init = null, id, startToken;

        startToken = lookahead;
        id = parseVariableIdentifier();

        // 12.2.1
        if (strict && isRestrictedWord(id.name)) {
            throwErrorTolerant({}, Messages.StrictVarName);
        }

        if (kind === 'const') {
            expect('=');
            init = parseAssignmentExpression();
        } else if (match('=')) {
            lex();
            init = parseAssignmentExpression();
        }

        return delegate.markEnd(delegate.createVariableDeclarator(id, init), startToken);
    }

    function parseVariableDeclarationList(kind) {
        var list = [];

        do {
            list.push(parseVariableDeclaration(kind));
            if (!match(',')) {
                break;
            }
            lex();
        } while (index < length);

        return list;
    }

    function parseVariableStatement() {
        var declarations;

        expectKeyword('var');

        declarations = parseVariableDeclarationList();

        consumeSemicolon();

        return delegate.createVariableDeclaration(declarations, 'var');
    }

    // kind may be `const` or `let`
    // Both are experimental and not in the specification yet.
    // see http://wiki.ecmascript.org/doku.php?id=harmony:const
    // and http://wiki.ecmascript.org/doku.php?id=harmony:let
    function parseConstLetDeclaration(kind) {
        var declarations, startToken;

        startToken = lookahead;

        expectKeyword(kind);

        declarations = parseVariableDeclarationList(kind);

        consumeSemicolon();

        return delegate.markEnd(delegate.createVariableDeclaration(declarations, kind), startToken);
    }

    // 12.3 Empty Statement

    function parseEmptyStatement() {
        expect(';');
        return delegate.createEmptyStatement();
    }

    // 12.4 Expression Statement

    function parseExpressionStatement() {
        var expr = parseExpression();
        consumeSemicolon();
        return delegate.createExpressionStatement(expr);
    }

    // 12.5 If statement

    function parseIfStatement() {
        var test, consequent, alternate;

        expectKeyword('if');

        expect('(');

        test = parseExpression();

        expect(')');

        consequent = parseStatement();

        if (matchKeyword('else')) {
            lex();
            alternate = parseStatement();
        } else {
            alternate = null;
        }

        return delegate.createIfStatement(test, consequent, alternate);
    }

    // 12.6 Iteration Statements

    function parseDoWhileStatement() {
        var body, test, oldInIteration;

        expectKeyword('do');

        oldInIteration = state.inIteration;
        state.inIteration = true;

        body = parseStatement();

        state.inIteration = oldInIteration;

        expectKeyword('while');

        expect('(');

        test = parseExpression();

        expect(')');

        if (match(';')) {
            lex();
        }

        return delegate.createDoWhileStatement(body, test);
    }

    function parseWhileStatement() {
        var test, body, oldInIteration;

        expectKeyword('while');

        expect('(');

        test = parseExpression();

        expect(')');

        oldInIteration = state.inIteration;
        state.inIteration = true;

        body = parseStatement();

        state.inIteration = oldInIteration;

        return delegate.createWhileStatement(test, body);
    }

    function parseForVariableDeclaration() {
        var token, declarations, startToken;

        startToken = lookahead;
        token = lex();
        declarations = parseVariableDeclarationList();

        return delegate.markEnd(delegate.createVariableDeclaration(declarations, token.value), startToken);
    }

    function parseForStatement() {
        var init, test, update, left, right, body, oldInIteration, previousAllowIn = state.allowIn;

        init = test = update = null;

        expectKeyword('for');

        expect('(');

        if (match(';')) {
            lex();
        } else {
            if (matchKeyword('var') || matchKeyword('let')) {
                state.allowIn = false;
                init = parseForVariableDeclaration();
                state.allowIn = previousAllowIn;

                if (init.declarations.length === 1 && matchKeyword('in')) {
                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                }
            } else {
                state.allowIn = false;
                init = parseExpression();
                state.allowIn = previousAllowIn;

                if (matchKeyword('in')) {
                    // LeftHandSideExpression
                    if (!isLeftHandSide(init)) {
                        throwErrorTolerant({}, Messages.InvalidLHSInForIn);
                    }

                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                }
            }

            if (typeof left === 'undefined') {
                expect(';');
            }
        }

        if (typeof left === 'undefined') {

            if (!match(';')) {
                test = parseExpression();
            }
            expect(';');

            if (!match(')')) {
                update = parseExpression();
            }
        }

        expect(')');

        oldInIteration = state.inIteration;
        state.inIteration = true;

        body = parseStatement();

        state.inIteration = oldInIteration;

        return (typeof left === 'undefined') ?
                delegate.createForStatement(init, test, update, body) :
                delegate.createForInStatement(left, right, body);
    }

    // 12.7 The continue statement

    function parseContinueStatement() {
        var label = null, key;

        expectKeyword('continue');

        // Optimize the most common form: 'continue;'.
        if (source.charCodeAt(index) === 0x3B) {
            lex();

            if (!state.inIteration) {
                throwError({}, Messages.IllegalContinue);
            }

            return delegate.createContinueStatement(null);
        }

        if (peekLineTerminator()) {
            if (!state.inIteration) {
                throwError({}, Messages.IllegalContinue);
            }

            return delegate.createContinueStatement(null);
        }

        if (lookahead.type === Token.Identifier) {
            label = parseVariableIdentifier();

            key = '$' + label.name;
            if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError({}, Messages.UnknownLabel, label.name);
            }
        }

        consumeSemicolon();

        if (label === null && !state.inIteration) {
            throwError({}, Messages.IllegalContinue);
        }

        return delegate.createContinueStatement(label);
    }

    // 12.8 The break statement

    function parseBreakStatement() {
        var label = null, key;

        expectKeyword('break');

        // Catch the very common case first: immediately a semicolon (U+003B).
        if (source.charCodeAt(index) === 0x3B) {
            lex();

            if (!(state.inIteration || state.inSwitch)) {
                throwError({}, Messages.IllegalBreak);
            }

            return delegate.createBreakStatement(null);
        }

        if (peekLineTerminator()) {
            if (!(state.inIteration || state.inSwitch)) {
                throwError({}, Messages.IllegalBreak);
            }

            return delegate.createBreakStatement(null);
        }

        if (lookahead.type === Token.Identifier) {
            label = parseVariableIdentifier();

            key = '$' + label.name;
            if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError({}, Messages.UnknownLabel, label.name);
            }
        }

        consumeSemicolon();

        if (label === null && !(state.inIteration || state.inSwitch)) {
            throwError({}, Messages.IllegalBreak);
        }

        return delegate.createBreakStatement(label);
    }

    // 12.9 The return statement

    function parseReturnStatement() {
        var argument = null;

        expectKeyword('return');

        if (!state.inFunctionBody) {
            throwErrorTolerant({}, Messages.IllegalReturn);
        }

        // 'return' followed by a space and an identifier is very common.
        if (source.charCodeAt(index) === 0x20) {
            if (isIdentifierStart(source.charCodeAt(index + 1))) {
                argument = parseExpression();
                consumeSemicolon();
                return delegate.createReturnStatement(argument);
            }
        }

        if (peekLineTerminator()) {
            return delegate.createReturnStatement(null);
        }

        if (!match(';')) {
            if (!match('}') && lookahead.type !== Token.EOF) {
                argument = parseExpression();
            }
        }

        consumeSemicolon();

        return delegate.createReturnStatement(argument);
    }

    // 12.10 The with statement

    function parseWithStatement() {
        var object, body;

        if (strict) {
            // TODO(ikarienator): Should we update the test cases instead?
            skipComment();
            throwErrorTolerant({}, Messages.StrictModeWith);
        }

        expectKeyword('with');

        expect('(');

        object = parseExpression();

        expect(')');

        body = parseStatement();

        return delegate.createWithStatement(object, body);
    }

    // 12.10 The swith statement

    function parseSwitchCase() {
        var test, consequent = [], statement, startToken;

        startToken = lookahead;
        if (matchKeyword('default')) {
            lex();
            test = null;
        } else {
            expectKeyword('case');
            test = parseExpression();
        }
        expect(':');

        while (index < length) {
            if (match('}') || matchKeyword('default') || matchKeyword('case')) {
                break;
            }
            statement = parseStatement();
            consequent.push(statement);
        }

        return delegate.markEnd(delegate.createSwitchCase(test, consequent), startToken);
    }

    function parseSwitchStatement() {
        var discriminant, cases, clause, oldInSwitch, defaultFound;

        expectKeyword('switch');

        expect('(');

        discriminant = parseExpression();

        expect(')');

        expect('{');

        cases = [];

        if (match('}')) {
            lex();
            return delegate.createSwitchStatement(discriminant, cases);
        }

        oldInSwitch = state.inSwitch;
        state.inSwitch = true;
        defaultFound = false;

        while (index < length) {
            if (match('}')) {
                break;
            }
            clause = parseSwitchCase();
            if (clause.test === null) {
                if (defaultFound) {
                    throwError({}, Messages.MultipleDefaultsInSwitch);
                }
                defaultFound = true;
            }
            cases.push(clause);
        }

        state.inSwitch = oldInSwitch;

        expect('}');

        return delegate.createSwitchStatement(discriminant, cases);
    }

    // 12.13 The throw statement

    function parseThrowStatement() {
        var argument;

        expectKeyword('throw');

        if (peekLineTerminator()) {
            throwError({}, Messages.NewlineAfterThrow);
        }

        argument = parseExpression();

        consumeSemicolon();

        return delegate.createThrowStatement(argument);
    }

    // 12.14 The try statement

    function parseCatchClause() {
        var param, body, startToken;

        startToken = lookahead;
        expectKeyword('catch');

        expect('(');
        if (match(')')) {
            throwUnexpected(lookahead);
        }

        param = parseVariableIdentifier();
        // 12.14.1
        if (strict && isRestrictedWord(param.name)) {
            throwErrorTolerant({}, Messages.StrictCatchVariable);
        }

        expect(')');
        body = parseBlock();
        return delegate.markEnd(delegate.createCatchClause(param, body), startToken);
    }

    function parseTryStatement() {
        var block, handlers = [], finalizer = null;

        expectKeyword('try');

        block = parseBlock();

        if (matchKeyword('catch')) {
            handlers.push(parseCatchClause());
        }

        if (matchKeyword('finally')) {
            lex();
            finalizer = parseBlock();
        }

        if (handlers.length === 0 && !finalizer) {
            throwError({}, Messages.NoCatchOrFinally);
        }

        return delegate.createTryStatement(block, [], handlers, finalizer);
    }

    // 12.15 The debugger statement

    function parseDebuggerStatement() {
        expectKeyword('debugger');

        consumeSemicolon();

        return delegate.createDebuggerStatement();
    }

    // 12 Statements

    function parseStatement() {
        var type = lookahead.type,
            expr,
            labeledBody,
            key,
            startToken;

        if (type === Token.EOF) {
            throwUnexpected(lookahead);
        }

        if (type === Token.Punctuator && lookahead.value === '{') {
            return parseBlock();
        }

        startToken = lookahead;

        if (type === Token.Punctuator) {
            switch (lookahead.value) {
            case ';':
                return delegate.markEnd(parseEmptyStatement(), startToken);
            case '(':
                return delegate.markEnd(parseExpressionStatement(), startToken);
            default:
                break;
            }
        }

        if (type === Token.Keyword) {
            switch (lookahead.value) {
            case 'break':
                return delegate.markEnd(parseBreakStatement(), startToken);
            case 'continue':
                return delegate.markEnd(parseContinueStatement(), startToken);
            case 'debugger':
                return delegate.markEnd(parseDebuggerStatement(), startToken);
            case 'do':
                return delegate.markEnd(parseDoWhileStatement(), startToken);
            case 'for':
                return delegate.markEnd(parseForStatement(), startToken);
            case 'function':
                return delegate.markEnd(parseFunctionDeclaration(), startToken);
            case 'if':
                return delegate.markEnd(parseIfStatement(), startToken);
            case 'return':
                return delegate.markEnd(parseReturnStatement(), startToken);
            case 'switch':
                return delegate.markEnd(parseSwitchStatement(), startToken);
            case 'throw':
                return delegate.markEnd(parseThrowStatement(), startToken);
            case 'try':
                return delegate.markEnd(parseTryStatement(), startToken);
            case 'var':
                return delegate.markEnd(parseVariableStatement(), startToken);
            case 'while':
                return delegate.markEnd(parseWhileStatement(), startToken);
            case 'with':
                return delegate.markEnd(parseWithStatement(), startToken);
            default:
                break;
            }
        }

        expr = parseExpression();

        // 12.12 Labelled Statements
        if ((expr.type === Syntax.Identifier) && match(':')) {
            lex();

            key = '$' + expr.name;
            if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError({}, Messages.Redeclaration, 'Label', expr.name);
            }

            state.labelSet[key] = true;
            labeledBody = parseStatement();
            delete state.labelSet[key];
            return delegate.markEnd(delegate.createLabeledStatement(expr, labeledBody), startToken);
        }

        consumeSemicolon();

        return delegate.markEnd(delegate.createExpressionStatement(expr), startToken);
    }

    // 13 Function Definition

    function parseFunctionSourceElements() {
        var sourceElement, sourceElements = [], token, directive, firstRestricted,
            oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, startToken;

        startToken = lookahead;
        expect('{');

        while (index < length) {
            if (lookahead.type !== Token.StringLiteral) {
                break;
            }
            token = lookahead;

            sourceElement = parseSourceElement();
            sourceElements.push(sourceElement);
            if (sourceElement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        oldLabelSet = state.labelSet;
        oldInIteration = state.inIteration;
        oldInSwitch = state.inSwitch;
        oldInFunctionBody = state.inFunctionBody;

        state.labelSet = {};
        state.inIteration = false;
        state.inSwitch = false;
        state.inFunctionBody = true;

        while (index < length) {
            if (match('}')) {
                break;
            }
            sourceElement = parseSourceElement();
            if (typeof sourceElement === 'undefined') {
                break;
            }
            sourceElements.push(sourceElement);
        }

        expect('}');

        state.labelSet = oldLabelSet;
        state.inIteration = oldInIteration;
        state.inSwitch = oldInSwitch;
        state.inFunctionBody = oldInFunctionBody;

        return delegate.markEnd(delegate.createBlockStatement(sourceElements), startToken);
    }

    function parseParams(firstRestricted) {
        var param, params = [], token, stricted, paramSet, key, message;
        expect('(');

        if (!match(')')) {
            paramSet = {};
            while (index < length) {
                token = lookahead;
                param = parseVariableIdentifier();
                key = '$' + token.value;
                if (strict) {
                    if (isRestrictedWord(token.value)) {
                        stricted = token;
                        message = Messages.StrictParamName;
                    }
                    if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
                        stricted = token;
                        message = Messages.StrictParamDupe;
                    }
                } else if (!firstRestricted) {
                    if (isRestrictedWord(token.value)) {
                        firstRestricted = token;
                        message = Messages.StrictParamName;
                    } else if (isStrictModeReservedWord(token.value)) {
                        firstRestricted = token;
                        message = Messages.StrictReservedWord;
                    } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) {
                        firstRestricted = token;
                        message = Messages.StrictParamDupe;
                    }
                }
                params.push(param);
                paramSet[key] = true;
                if (match(')')) {
                    break;
                }
                expect(',');
            }
        }

        expect(')');

        return {
            params: params,
            stricted: stricted,
            firstRestricted: firstRestricted,
            message: message
        };
    }

    function parseFunctionDeclaration() {
        var id, params = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, startToken;

        startToken = lookahead;

        expectKeyword('function');
        token = lookahead;
        id = parseVariableIdentifier();
        if (strict) {
            if (isRestrictedWord(token.value)) {
                throwErrorTolerant(token, Messages.StrictFunctionName);
            }
        } else {
            if (isRestrictedWord(token.value)) {
                firstRestricted = token;
                message = Messages.StrictFunctionName;
            } else if (isStrictModeReservedWord(token.value)) {
                firstRestricted = token;
                message = Messages.StrictReservedWord;
            }
        }

        tmp = parseParams(firstRestricted);
        params = tmp.params;
        stricted = tmp.stricted;
        firstRestricted = tmp.firstRestricted;
        if (tmp.message) {
            message = tmp.message;
        }

        previousStrict = strict;
        body = parseFunctionSourceElements();
        if (strict && firstRestricted) {
            throwError(firstRestricted, message);
        }
        if (strict && stricted) {
            throwErrorTolerant(stricted, message);
        }
        strict = previousStrict;

        return delegate.markEnd(delegate.createFunctionDeclaration(id, params, [], body), startToken);
    }

    function parseFunctionExpression() {
        var token, id = null, stricted, firstRestricted, message, tmp, params = [], body, previousStrict, startToken;

        startToken = lookahead;
        expectKeyword('function');

        if (!match('(')) {
            token = lookahead;
            id = parseVariableIdentifier();
            if (strict) {
                if (isRestrictedWord(token.value)) {
                    throwErrorTolerant(token, Messages.StrictFunctionName);
                }
            } else {
                if (isRestrictedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictFunctionName;
                } else if (isStrictModeReservedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictReservedWord;
                }
            }
        }

        tmp = parseParams(firstRestricted);
        params = tmp.params;
        stricted = tmp.stricted;
        firstRestricted = tmp.firstRestricted;
        if (tmp.message) {
            message = tmp.message;
        }

        previousStrict = strict;
        body = parseFunctionSourceElements();
        if (strict && firstRestricted) {
            throwError(firstRestricted, message);
        }
        if (strict && stricted) {
            throwErrorTolerant(stricted, message);
        }
        strict = previousStrict;

        return delegate.markEnd(delegate.createFunctionExpression(id, params, [], body), startToken);
    }

    // 14 Program

    function parseSourceElement() {
        if (lookahead.type === Token.Keyword) {
            switch (lookahead.value) {
            case 'const':
            case 'let':
                return parseConstLetDeclaration(lookahead.value);
            case 'function':
                return parseFunctionDeclaration();
            default:
                return parseStatement();
            }
        }

        if (lookahead.type !== Token.EOF) {
            return parseStatement();
        }
    }

    function parseSourceElements() {
        var sourceElement, sourceElements = [], token, directive, firstRestricted;

        while (index < length) {
            token = lookahead;
            if (token.type !== Token.StringLiteral) {
                break;
            }

            sourceElement = parseSourceElement();
            sourceElements.push(sourceElement);
            if (sourceElement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        while (index < length) {
            sourceElement = parseSourceElement();
            /* istanbul ignore if */
            if (typeof sourceElement === 'undefined') {
                break;
            }
            sourceElements.push(sourceElement);
        }
        return sourceElements;
    }

    function parseProgram() {
        var body, startToken;

        skipComment();
        peek();
        startToken = lookahead;
        strict = false;

        body = parseSourceElements();
        return delegate.markEnd(delegate.createProgram(body), startToken);
    }

    function filterTokenLocation() {
        var i, entry, token, tokens = [];

        for (i = 0; i < extra.tokens.length; ++i) {
            entry = extra.tokens[i];
            token = {
                type: entry.type,
                value: entry.value
            };
            if (extra.range) {
                token.range = entry.range;
            }
            if (extra.loc) {
                token.loc = entry.loc;
            }
            tokens.push(token);
        }

        extra.tokens = tokens;
    }

    function tokenize(code, options) {
        var toString,
            token,
            tokens;

        toString = String;
        if (typeof code !== 'string' && !(code instanceof String)) {
            code = toString(code);
        }

        delegate = SyntaxTreeDelegate;
        source = code;
        index = 0;
        lineNumber = (source.length > 0) ? 1 : 0;
        lineStart = 0;
        length = source.length;
        lookahead = null;
        state = {
            allowIn: true,
            labelSet: {},
            inFunctionBody: false,
            inIteration: false,
            inSwitch: false,
            lastCommentStart: -1
        };

        extra = {};

        // Options matching.
        options = options || {};

        // Of course we collect tokens here.
        options.tokens = true;
        extra.tokens = [];
        extra.tokenize = true;
        // The following two fields are necessary to compute the Regex tokens.
        extra.openParenToken = -1;
        extra.openCurlyToken = -1;

        extra.range = (typeof options.range === 'boolean') && options.range;
        extra.loc = (typeof options.loc === 'boolean') && options.loc;

        if (typeof options.comment === 'boolean' && options.comment) {
            extra.comments = [];
        }
        if (typeof options.tolerant === 'boolean' && options.tolerant) {
            extra.errors = [];
        }

        try {
            peek();
            if (lookahead.type === Token.EOF) {
                return extra.tokens;
            }

            token = lex();
            while (lookahead.type !== Token.EOF) {
                try {
                    token = lex();
                } catch (lexError) {
                    token = lookahead;
                    if (extra.errors) {
                        extra.errors.push(lexError);
                        // We have to break on the first error
                        // to avoid infinite loops.
                        break;
                    } else {
                        throw lexError;
                    }
                }
            }

            filterTokenLocation();
            tokens = extra.tokens;
            if (typeof extra.comments !== 'undefined') {
                tokens.comments = extra.comments;
            }
            if (typeof extra.errors !== 'undefined') {
                tokens.errors = extra.errors;
            }
        } catch (e) {
            throw e;
        } finally {
            extra = {};
        }
        return tokens;
    }

    function parse(code, options) {
        var program, toString;

        toString = String;
        if (typeof code !== 'string' && !(code instanceof String)) {
            code = toString(code);
        }

        delegate = SyntaxTreeDelegate;
        source = code;
        index = 0;
        lineNumber = (source.length > 0) ? 1 : 0;
        lineStart = 0;
        length = source.length;
        lookahead = null;
        state = {
            allowIn: true,
            labelSet: {},
            inFunctionBody: false,
            inIteration: false,
            inSwitch: false,
            lastCommentStart: -1
        };

        extra = {};
        if (typeof options !== 'undefined') {
            extra.range = (typeof options.range === 'boolean') && options.range;
            extra.loc = (typeof options.loc === 'boolean') && options.loc;
            extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;

            if (extra.loc && options.source !== null && options.source !== undefined) {
                extra.source = toString(options.source);
            }

            if (typeof options.tokens === 'boolean' && options.tokens) {
                extra.tokens = [];
            }
            if (typeof options.comment === 'boolean' && options.comment) {
                extra.comments = [];
            }
            if (typeof options.tolerant === 'boolean' && options.tolerant) {
                extra.errors = [];
            }
            if (extra.attachComment) {
                extra.range = true;
                extra.comments = [];
                extra.bottomRightStack = [];
                extra.trailingComments = [];
                extra.leadingComments = [];
            }
        }

        try {
            program = parseProgram();
            if (typeof extra.comments !== 'undefined') {
                program.comments = extra.comments;
            }
            if (typeof extra.tokens !== 'undefined') {
                filterTokenLocation();
                program.tokens = extra.tokens;
            }
            if (typeof extra.errors !== 'undefined') {
                program.errors = extra.errors;
            }
        } catch (e) {
            throw e;
        } finally {
            extra = {};
        }

        return program;
    }

    // Sync with *.json manifests.
    exports.version = '1.2.5';

    exports.tokenize = tokenize;

    exports.parse = parse;

    // Deep copy.
   /* istanbul ignore next */
    exports.Syntax = (function () {
        var name, types = {};

        if (typeof Object.create === 'function') {
            types = Object.create(null);
        }

        for (name in Syntax) {
            if (Syntax.hasOwnProperty(name)) {
                types[name] = Syntax[name];
            }
        }

        if (typeof Object.freeze === 'function') {
            Object.freeze(types);
        }

        return types;
    }());

}));
/* vim: set sw=4 ts=4 et tw=80 : */


/***/ }),
/* 920 */
/***/ (function(module, exports, __nested_webpack_require_4513590__) {

"use strict";


var createThunk = __nested_webpack_require_4513590__(921)

function Procedure() {
  this.argTypes = []
  this.shimArgs = []
  this.arrayArgs = []
  this.arrayBlockIndices = []
  this.scalarArgs = []
  this.offsetArgs = []
  this.offsetArgIndex = []
  this.indexArgs = []
  this.shapeArgs = []
  this.funcName = ""
  this.pre = null
  this.body = null
  this.post = null
  this.debug = false
}

function compileCwise(user_args) {
  //Create procedure
  var proc = new Procedure()
  
  //Parse blocks
  proc.pre    = user_args.pre
  proc.body   = user_args.body
  proc.post   = user_args.post

  //Parse arguments
  var proc_args = user_args.args.slice(0)
  proc.argTypes = proc_args
  for(var i=0; i<proc_args.length; ++i) {
    var arg_type = proc_args[i]
    if(arg_type === "array" || (typeof arg_type === "object" && arg_type.blockIndices)) {
      proc.argTypes[i] = "array"
      proc.arrayArgs.push(i)
      proc.arrayBlockIndices.push(arg_type.blockIndices ? arg_type.blockIndices : 0)
      proc.shimArgs.push("array" + i)
      if(i < proc.pre.args.length && proc.pre.args[i].count>0) {
        throw new Error("cwise: pre() block may not reference array args")
      }
      if(i < proc.post.args.length && proc.post.args[i].count>0) {
        throw new Error("cwise: post() block may not reference array args")
      }
    } else if(arg_type === "scalar") {
      proc.scalarArgs.push(i)
      proc.shimArgs.push("scalar" + i)
    } else if(arg_type === "index") {
      proc.indexArgs.push(i)
      if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
        throw new Error("cwise: pre() block may not reference array index")
      }
      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
        throw new Error("cwise: body() block may not write to array index")
      }
      if(i < proc.post.args.length && proc.post.args[i].count > 0) {
        throw new Error("cwise: post() block may not reference array index")
      }
    } else if(arg_type === "shape") {
      proc.shapeArgs.push(i)
      if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
        throw new Error("cwise: pre() block may not write to array shape")
      }
      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
        throw new Error("cwise: body() block may not write to array shape")
      }
      if(i < proc.post.args.length && proc.post.args[i].lvalue) {
        throw new Error("cwise: post() block may not write to array shape")
      }
    } else if(typeof arg_type === "object" && arg_type.offset) {
      proc.argTypes[i] = "offset"
      proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
      proc.offsetArgIndex.push(i)
    } else {
      throw new Error("cwise: Unknown argument type " + proc_args[i])
    }
  }
  
  //Make sure at least one array argument was specified
  if(proc.arrayArgs.length <= 0) {
    throw new Error("cwise: No array arguments specified")
  }
  
  //Make sure arguments are correct
  if(proc.pre.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in pre() block")
  }
  if(proc.body.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in body() block")
  }
  if(proc.post.args.length > proc_args.length) {
    throw new Error("cwise: Too many arguments in post() block")
  }

  //Check debug flag
  proc.debug = !!user_args.printCode || !!user_args.debug
  
  //Retrieve name
  proc.funcName = user_args.funcName || "cwise"
  
  //Read in block size
  proc.blockSize = user_args.blockSize || 64

  return createThunk(proc)
}

module.exports = compileCwise


/***/ }),
/* 921 */
/***/ (function(module, exports, __nested_webpack_require_4517277__) {

"use strict";


// The function below is called when constructing a cwise function object, and does the following:
// A function object is constructed which accepts as argument a compilation function and returns another function.
// It is this other function that is eventually returned by createThunk, and this function is the one that actually
// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed.
// The compilation passed to the first function object is used for compiling new functions.
// Once this function object is created, it is called with compile as argument, where the first argument of compile
// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise).
// So createThunk roughly works like this:
// function createThunk(proc) {
//   var thunk = function(compileBound) {
//     var CACHED = {}
//     return function(arrays and scalars) {
//       if (dtype and order of arrays in CACHED) {
//         var func = CACHED[dtype and order of arrays]
//       } else {
//         var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays)
//       }
//       return func(arrays and scalars)
//     }
//   }
//   return thunk(compile.bind1(proc))
// }

var compile = __nested_webpack_require_4517277__(922)

function createThunk(proc) {
  var code = ["'use strict'", "var CACHED={}"]
  var vars = []
  var thunkName = proc.funcName + "_cwise_thunk"
  
  //Build thunk
  code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join(""))
  var typesig = []
  var string_typesig = []
  var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS).
                    Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")]
  var shapeLengthConditions = [], shapeConditions = []
  // Process array arguments
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    var j = proc.arrayArgs[i]
    vars.push(["t", j, "=array", j, ".dtype,",
               "r", j, "=array", j, ".order"].join(""))
    typesig.push("t" + j)
    typesig.push("r" + j)
    string_typesig.push("t"+j)
    string_typesig.push("r"+j+".join()")
    proc_args.push("array" + j + ".data")
    proc_args.push("array" + j + ".stride")
    proc_args.push("array" + j + ".offset|0")
    if (i>0) { // Gather conditions to check for shape equality (ignoring block indices)
      shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i])))
      shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]")
    }
  }
  // Check for shape equality
  if (proc.arrayArgs.length > 1) {
    code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')")
    code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {")
    code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')")
    code.push("}")
  }
  // Process scalar arguments
  for(var i=0; i<proc.scalarArgs.length; ++i) {
    proc_args.push("scalar" + proc.scalarArgs[i])
  }
  // Check for cached function (and if not present, generate it)
  vars.push(["type=[", string_typesig.join(","), "].join()"].join(""))
  vars.push("proc=CACHED[type]")
  code.push("var " + vars.join(","))
  
  code.push(["if(!proc){",
             "CACHED[type]=proc=compile([", typesig.join(","), "])}",
             "return proc(", proc_args.join(","), ")}"].join(""))

  if(proc.debug) {
    console.log("-----Generated thunk:\n" + code.join("\n") + "\n----------")
  }
  
  //Compile thunk
  var thunk = new Function("compile", code.join("\n"))
  return thunk(compile.bind(undefined, proc))
}

module.exports = createThunk


/***/ }),
/* 922 */
/***/ (function(module, exports, __nested_webpack_require_4521573__) {

"use strict";


var uniq = __nested_webpack_require_4521573__(446)

// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index)
// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments.
function innerFill(order, proc, body) {
  var dimension = order.length
    , nargs = proc.arrayArgs.length
    , has_index = proc.indexArgs.length>0
    , code = []
    , vars = []
    , idx=0, pidx=0, i, j
  for(i=0; i<dimension; ++i) { // Iteration variables
    vars.push(["i",i,"=0"].join(""))
  }
  //Compute scan deltas
  for(j=0; j<nargs; ++j) {
    for(i=0; i<dimension; ++i) {
      pidx = idx
      idx = order[i]
      if(i === 0) { // The innermost/fastest dimension's delta is simply its stride
        vars.push(["d",j,"s",i,"=t",j,"p",idx].join(""))
      } else { // For other dimensions the delta is basically the stride minus something which essentially "rewinds" the previous (more inner) dimension
        vars.push(["d",j,"s",i,"=(t",j,"p",idx,"-s",pidx,"*t",j,"p",pidx,")"].join(""))
      }
    }
  }
  if (vars.length > 0) {
    code.push("var " + vars.join(","))
  }  
  //Scan loop
  for(i=dimension-1; i>=0; --i) { // Start at largest stride and work your way inwards
    idx = order[i]
    code.push(["for(i",i,"=0;i",i,"<s",idx,";++i",i,"){"].join(""))
  }
  //Push body of inner loop
  code.push(body)
  //Advance scan pointers
  for(i=0; i<dimension; ++i) {
    pidx = idx
    idx = order[i]
    for(j=0; j<nargs; ++j) {
      code.push(["p",j,"+=d",j,"s",i].join(""))
    }
    if(has_index) {
      if(i > 0) {
        code.push(["index[",pidx,"]-=s",pidx].join(""))
      }
      code.push(["++index[",idx,"]"].join(""))
    }
    code.push("}")
  }
  return code.join("\n")
}

// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block.
// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary.
//       I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used.
function outerFill(matched, order, proc, body) {
  var dimension = order.length
    , nargs = proc.arrayArgs.length
    , blockSize = proc.blockSize
    , has_index = proc.indexArgs.length > 0
    , code = []
  for(var i=0; i<nargs; ++i) {
    code.push(["var offset",i,"=p",i].join(""))
  }
  //Generate loops for unmatched dimensions
  // The order in which these dimensions are traversed is fairly arbitrary (from small stride to large stride, for the first argument)
  // TODO: It would be nice if the order in which these loops are placed would also be somehow "optimal" (at the very least we should check that it really doesn't hurt us if they're not).
  for(var i=matched; i<dimension; ++i) {
    code.push(["for(var j"+i+"=SS[", order[i], "]|0;j", i, ">0;){"].join("")) // Iterate back to front
    code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j).
    code.push(["s",order[i],"=j",i].join(""))
    code.push(["j",i,"=0"].join(""))
    code.push(["}else{s",order[i],"=",blockSize].join(""))
    code.push(["j",i,"-=",blockSize,"}"].join(""))
    if(has_index) {
      code.push(["index[",order[i],"]=j",i].join(""))
    }
  }
  for(var i=0; i<nargs; ++i) {
    var indexStr = ["offset"+i]
    for(var j=matched; j<dimension; ++j) {
      indexStr.push(["j",j,"*t",i,"p",order[j]].join(""))
    }
    code.push(["p",i,"=(",indexStr.join("+"),")"].join(""))
  }
  code.push(innerFill(order, proc, body))
  for(var i=matched; i<dimension; ++i) {
    code.push("}")
  }
  return code.join("\n")
}

//Count the number of compatible inner orders
// This is the length of the longest common prefix of the arrays in orders.
// Each array in orders lists the dimensions of the correspond ndarray in order of increasing stride.
// This is thus the maximum number of dimensions that can be efficiently traversed by simple nested loops for all arrays.
function countMatches(orders) {
  var matched = 0, dimension = orders[0].length
  while(matched < dimension) {
    for(var j=1; j<orders.length; ++j) {
      if(orders[j][matched] !== orders[0][matched]) {
        return matched
      }
    }
    ++matched
  }
  return matched
}

//Processes a block according to the given data types
// Replaces variable names by different ones, either "local" ones (that are then ferried in and out of the given array) or ones matching the arguments that the function performing the ultimate loop will accept.
function processBlock(block, proc, dtypes) {
  var code = block.body
  var pre = []
  var post = []
  for(var i=0; i<block.args.length; ++i) {
    var carg = block.args[i]
    if(carg.count <= 0) {
      continue
    }
    var re = new RegExp(carg.name, "g")
    var ptrStr = ""
    var arrNum = proc.arrayArgs.indexOf(i)
    switch(proc.argTypes[i]) {
      case "offset":
        var offArgIndex = proc.offsetArgIndex.indexOf(i)
        var offArg = proc.offsetArgs[offArgIndex]
        arrNum = offArg.array
        ptrStr = "+q" + offArgIndex // Adds offset to the "pointer" in the array
      case "array":
        ptrStr = "p" + arrNum + ptrStr
        var localStr = "l" + i
        var arrStr = "a" + arrNum
        if (proc.arrayBlockIndices[arrNum] === 0) { // Argument to body is just a single value from this array
          if(carg.count === 1) { // Argument/array used only once(?)
            if(dtypes[arrNum] === "generic") {
              if(carg.lvalue) {
                pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
                code = code.replace(re, localStr)
                post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
              } else {
                code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
              }
            } else {
              code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
            }
          } else if(dtypes[arrNum] === "generic") {
            pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
            code = code.replace(re, localStr)
            if(carg.lvalue) {
              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
            }
          } else {
            pre.push(["var ", localStr, "=", arrStr, "[", ptrStr, "]"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
            code = code.replace(re, localStr)
            if(carg.lvalue) {
              post.push([arrStr, "[", ptrStr, "]=", localStr].join(""))
            }
          }
        } else { // Argument to body is a "block"
          var reStrArr = [carg.name], ptrStrArr = [ptrStr]
          for(var j=0; j<Math.abs(proc.arrayBlockIndices[arrNum]); j++) {
            reStrArr.push("\\s*\\[([^\\]]+)\\]")
            ptrStrArr.push("$" + (j+1) + "*t" + arrNum + "b" + j) // Matched index times stride
          }
          re = new RegExp(reStrArr.join(""), "g")
          ptrStr = ptrStrArr.join("+")
          if(dtypes[arrNum] === "generic") {
            /*if(carg.lvalue) {
              pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
              code = code.replace(re, localStr)
              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
            } else {
              code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
            }*/
            throw new Error("cwise: Generic arrays not supported in combination with blocks!")
          } else {
            // This does not produce any local variables, even if variables are used multiple times. It would be possible to do so, but it would complicate things quite a bit.
            code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
          }
        }
      break
      case "scalar":
        code = code.replace(re, "Y" + proc.scalarArgs.indexOf(i))
      break
      case "index":
        code = code.replace(re, "index")
      break
      case "shape":
        code = code.replace(re, "shape")
      break
    }
  }
  return [pre.join("\n"), code, post.join("\n")].join("\n").trim()
}

function typeSummary(dtypes) {
  var summary = new Array(dtypes.length)
  var allEqual = true
  for(var i=0; i<dtypes.length; ++i) {
    var t = dtypes[i]
    var digits = t.match(/\d+/)
    if(!digits) {
      digits = ""
    } else {
      digits = digits[0]
    }
    if(t.charAt(0) === 0) {
      summary[i] = "u" + t.charAt(1) + digits
    } else {
      summary[i] = t.charAt(0) + digits
    }
    if(i > 0) {
      allEqual = allEqual && summary[i] === summary[i-1]
    }
  }
  if(allEqual) {
    return summary[0]
  }
  return summary.join("")
}

//Generates a cwise operator
function generateCWiseOp(proc, typesig) {

  //Compute dimension
  // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg.
  var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0
  var orders = new Array(proc.arrayArgs.length)
  var dtypes = new Array(proc.arrayArgs.length)
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    dtypes[i] = typesig[2*i]
    orders[i] = typesig[2*i+1]
  }
  
  //Determine where block and loop indices start and end
  var blockBegin = [], blockEnd = [] // These indices are exposed as blocks
  var loopBegin = [], loopEnd = [] // These indices are iterated over
  var loopOrders = [] // orders restricted to the loop indices
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    if (proc.arrayBlockIndices[i]<0) {
      loopBegin.push(0)
      loopEnd.push(dimension)
      blockBegin.push(dimension)
      blockEnd.push(dimension+proc.arrayBlockIndices[i])
    } else {
      loopBegin.push(proc.arrayBlockIndices[i]) // Non-negative
      loopEnd.push(proc.arrayBlockIndices[i]+dimension)
      blockBegin.push(0)
      blockEnd.push(proc.arrayBlockIndices[i])
    }
    var newOrder = []
    for(var j=0; j<orders[i].length; j++) {
      if (loopBegin[i]<=orders[i][j] && orders[i][j]<loopEnd[i]) {
        newOrder.push(orders[i][j]-loopBegin[i]) // If this is a loop index, put it in newOrder, subtracting loopBegin, to make sure that all loopOrders are using a common set of indices.
      }
    }
    loopOrders.push(newOrder)
  }

  //First create arguments for procedure
  var arglist = ["SS"] // SS is the overall shape over which we iterate
  var code = ["'use strict'"]
  var vars = []
  
  for(var j=0; j<dimension; ++j) {
    vars.push(["s", j, "=SS[", j, "]"].join("")) // The limits for each dimension.
  }
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    arglist.push("a"+i) // Actual data array
    arglist.push("t"+i) // Strides
    arglist.push("p"+i) // Offset in the array at which the data starts (also used for iterating over the data)
    
    for(var j=0; j<dimension; ++j) { // Unpack the strides into vars for looping
      vars.push(["t",i,"p",j,"=t",i,"[",loopBegin[i]+j,"]"].join(""))
    }
    
    for(var j=0; j<Math.abs(proc.arrayBlockIndices[i]); ++j) { // Unpack the strides into vars for block iteration
      vars.push(["t",i,"b",j,"=t",i,"[",blockBegin[i]+j,"]"].join(""))
    }
  }
  for(var i=0; i<proc.scalarArgs.length; ++i) {
    arglist.push("Y" + i)
  }
  if(proc.shapeArgs.length > 0) {
    vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example)
  }
  if(proc.indexArgs.length > 0) {
    // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes.
    var zeros = new Array(dimension)
    for(var i=0; i<dimension; ++i) {
      zeros[i] = "0"
    }
    vars.push(["index=[", zeros.join(","), "]"].join(""))
  }
  for(var i=0; i<proc.offsetArgs.length; ++i) { // Offset arguments used for stencil operations
    var off_arg = proc.offsetArgs[i]
    var init_string = []
    for(var j=0; j<off_arg.offset.length; ++j) {
      if(off_arg.offset[j] === 0) {
        continue
      } else if(off_arg.offset[j] === 1) {
        init_string.push(["t", off_arg.array, "p", j].join(""))      
      } else {
        init_string.push([off_arg.offset[j], "*t", off_arg.array, "p", j].join(""))
      }
    }
    if(init_string.length === 0) {
      vars.push("q" + i + "=0")
    } else {
      vars.push(["q", i, "=", init_string.join("+")].join(""))
    }
  }

  //Prepare this variables
  var thisVars = uniq([].concat(proc.pre.thisVars)
                      .concat(proc.body.thisVars)
                      .concat(proc.post.thisVars))
  vars = vars.concat(thisVars)
  if (vars.length > 0) {
    code.push("var " + vars.join(","))
  }
  for(var i=0; i<proc.arrayArgs.length; ++i) {
    code.push("p"+i+"|=0")
  }
  
  //Inline prelude
  if(proc.pre.body.length > 3) {
    code.push(processBlock(proc.pre, proc, dtypes))
  }

  //Process body
  var body = processBlock(proc.body, proc, dtypes)
  var matched = countMatches(loopOrders)
  if(matched < dimension) {
    code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example.
  } else {
    code.push(innerFill(loopOrders[0], proc, body))
  }

  //Inline epilog
  if(proc.post.body.length > 3) {
    code.push(processBlock(proc.post, proc, dtypes))
  }
  
  if(proc.debug) {
    console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------")
  }
  
  var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("")
  var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join(""))
  return f()
}
module.exports = generateCWiseOp


/***/ }),
/* 923 */
/***/ (function(module, exports, __nested_webpack_require_4536501__) {

"use strict";


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

var _ndarray = __nested_webpack_require_4536501__(136);

var _ndarray2 = _interopRequireDefault(_ndarray);

var _ndarrayToList = __nested_webpack_require_4536501__(447);

var _ndarrayToList2 = _interopRequireDefault(_ndarrayToList);

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

var ndarrayFlatten = function ndarrayFlatten(arr) {
  if (arr.shape.length === 1) return arr;

  return (0, _ndarray2['default'])((0, _ndarrayToList2['default'])(arr));
};

exports['default'] = ndarrayFlatten;

/***/ }),
/* 924 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var numericifyVersion = function numericifyVersion(version) {
  var parts = version.split('.');
  var tailLen = parts.slice(1).join('').length;
  return +parts.join('') / Math.pow(10, tailLen);
};

exports['default'] = numericifyVersion;

/***/ }),
/* 925 */
/***/ (function(module, exports, __nested_webpack_require_4537571__) {

"use strict";


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

var _keys = __nested_webpack_require_4537571__(18);

var _keys2 = _interopRequireDefault(_keys);

var _ = __nested_webpack_require_4537571__(10);

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

/**
 * Convert an object into array which entries are the prop values of the object
 *
 * @param {Object}  obj  Object to be arrayified
 * @return {Array}  Array of the object.
 */
var objVals = function objVals(obj) {
  return (0, _.map)(function (key) {
    return obj[key];
  })((0, _keys2['default'])(obj));
};

exports['default'] = objVals;

/***/ }),
/* 926 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Logical or operator for convenience.
 * @param   {*}  a  Value A
 * @param   {*}  b  Value B
 * @return  {boolean}  If `true` one of the two or both values are truthy.
 */
var or = function or(a, b) {
  return a || b;
};

exports["default"] = or;

/***/ }),
/* 927 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Parse an array of chromsizes, for example that result
 * from reading rows of a chromsizes CSV file.
 * @param {array} data Array of [chrName, chrLen] "tuples".
 * @returns {object} Object containing properties
 * { cumPositions, chrPositions, totalLength, chromLengths }.
 */
function parseChromsizesRows(data) {
  var cumValues = [];
  var chromLengths = {};
  var chrPositions = {};

  var totalLength = 0;

  for (var i = 0; i < data.length; i++) {
    var length = Number(data[i][1]);
    totalLength += length;

    var newValue = {
      id: i,
      chr: data[i][0],
      pos: totalLength - length
    };

    cumValues.push(newValue);
    chrPositions[newValue.chr] = newValue;
    chromLengths[data[i][0]] = length;
  }

  return {
    cumPositions: cumValues,
    chrPositions: chrPositions,
    totalLength: totalLength,
    chromLengths: chromLengths
  };
}

exports["default"] = parseChromsizesRows;

/***/ }),
/* 928 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Export a PIXI text to an SVG element
 *
 * param {PIXI.Text} pixiText A PIXI.Text object that we want to create an SVG element for
 * returns {Element} A DOM SVG Element with all of the attributes set as to display
 * the given text.
 */
var pixiTextToSvg = exports.pixiTextToSvg = function pixiTextToSvg(pixiText) {
  var g = document.createElement('g');
  var t = document.createElement('text');

  if (pixiText.anchor.x === 0) {
    t.setAttribute('text-anchor', 'start');
  } else if (pixiText.anchor.x === 1) {
    t.setAttribute('text-anchor', 'end');
  } else {
    t.setAttribute('text-anchor', 'middle');
  }

  t.setAttribute('font-family', pixiText.style.fontFamily);
  t.setAttribute('font-size', pixiText.style.fontSize);
  g.setAttribute('transform', 'scale(' + String(pixiText.scale.x) + ',1)');

  t.setAttribute('fill', pixiText.style.fill);
  t.innerHTML = pixiText.text;

  g.appendChild(t);
  g.setAttribute('transform', 'translate(' + String(pixiText.x) + ',' + String(pixiText.y) + ')scale(' + String(pixiText.scale.x) + ',1)');

  return g;
};

exports['default'] = pixiTextToSvg;

/***/ }),
/* 929 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Object query language using dot-notation.
 *
 * @description  In order to query an object dynamically do:
 *   ```
 *   const myFancyObj = { my: { fancy: { property: 'Sweet!' } } };
 *   const myNotSoFancyObj = { noSoFancy: 'buh!' };
 *
 *   const myFancyQuery = q('my.fancy.property');
 *
 *   console.log(myFancyQuery(myFancyObj)) ==> 'Sweet!'
 *   console.log(myFancyQuery(myNotSoFancyObj)) ==> undefined
 *   ```
 * @param   {[type]}  queryStr  [description]
 * @return  {[type]}  [description]
 */
var q = function q(queryStr) {
  try {
    var queries = queryStr.split('.');
    return function (rootObj) {
      var obj = rootObj;
      queries.forEach(function (query) {
        obj = obj[query];
      });
      return obj;
    };
  } catch (e) {
    return undefined;
  }
};

exports['default'] = q;

/***/ }),
/* 930 */
/***/ (function(module, exports, __nested_webpack_require_4542033__) {

"use strict";


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

var _ = __nested_webpack_require_4542033__(10);

/**
 * Perform a 2D query on a 1D array
 *
 * @param  {Array}  src  Data source array.
 * @param  {Integer}  xDimSrc  X dimension of `src`.
 * @param  {Integer}  xDimOut  X dimension of `outList`.
 * @param  {Array}  xRange  X range array, e.g., `[start, end]`.
 * @param  {Array}  yRange  Y range array, e.g., `[start, end]`.
 * @param  {Integer}  xOff  X offset in regards to `outList`.
 * @param  {Integer}  yOff  Y offset in regards to `outList`.
 * @param  {Boolean}  mirrored  If `true` mirror query.
 * @param  {Array}  outList  Typed array to be set in place.
 *        1D representation of a 2D array (e.g. ass = new Uint8ClampedArray(10);)
 * @return  {Array}  Sub array.
 */
var rangeQuery2d = function rangeQuery2d(src, xDimSrc, xDimOut, xRange, yRange, mirrored) {
  var xOff = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
  var yOff = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;
  var outList = arguments[8];

  var _xRange = mirrored ? yRange : xRange;
  var _yRange = mirrored ? xRange : yRange;
  var _xOff = mirrored ? yOff : xOff;
  var _yOff = mirrored ? xOff : yOff;

  var xFrom = Math.max(0, +_xRange[0] || 0);
  var xTo = Math.max(0, +_xRange[1] || 0);
  var yFrom = Math.max(0, +_yRange[0] || 0);
  var yTo = Math.max(0, +_yRange[1] || 0);

  var subList = [];

  if (!ArrayBuffer.isView(outList)) {
    console.warn('Not supported yet');
  }

  try {
    var newList = new outList.constructor(outList.length);
    var c = 0 + _yOff;
    for (var i = yFrom; i < yTo; i++) {
      newList.set(src.slice(i * xDimSrc + xFrom, i * xDimSrc + xTo), _xOff + c * xDimOut);
      c += 1;
    }
    var acc = mirrored ? (0, _.accessorTransposition)(xDimOut, xDimOut) : undefined;
    subList = (0, _.addArrays)(outList, newList, acc);
  } catch (e) {
    // console.warn('Invalid 2D query', e);
  }

  return subList;
};

exports['default'] = rangeQuery2d;

/***/ }),
/* 931 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var relToAbsChromPos = function relToAbsChromPos(chrom, x, y, chromInfo) {
  return [chromInfo.chrPositions[chrom].pos + +x, chromInfo.chrPositions[chrom].pos + +y];
};

exports["default"] = relToAbsChromPos;

/***/ }),
/* 932 */
/***/ (function(module, exports, __nested_webpack_require_4544520__) {

"use strict";


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

var _hasClass = __nested_webpack_require_4544520__(221);

var _hasClass2 = _interopRequireDefault(_hasClass);

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

var XMLNS = 'http://www.w3.org/2000/svg';

/**
 * Remove a class from an HTML or SVG element.
 * @param   {object}  el  HTML or SVG element.
 * @param   {string}  className  Class name to be removed.
 */
var removeClass = function removeClass(el, className) {
  var reg = new RegExp('(\\s|^)' + String(className) + '(\\s|$)');

  if (el.namespaceURI === XMLNS) {
    var _class = el.getAttribute('class') || '';
    el.setAttribute('class', _class.replace(reg, ' '));
  } else if (el.classList) {
    el.classList.remove(className);
  } else if ((0, _hasClass2['default'])(el, className)) {
    el.className = el.className.replace(reg, ' ');
  }
};

exports['default'] = removeClass;

/***/ }),
/* 933 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Unsets the automatically set brush style of D3.
 * @param   {object}  el  Element which is brushed on.
 * @param   {string}  className  New class name to be set.
 */
var resetD3BrushStyle = function resetD3BrushStyle(el, className) {
  el.select('.selection').attr('fill', null).attr('fill-opacity', null).attr('stroke', null).classed(className, true);
};

exports['default'] = resetD3BrushStyle;

/***/ }),
/* 934 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
var componentToHex = function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length === 1 ? "0" + String(hex) : hex;
};

var rgbToHex = function rgbToHex(r, g, b) {
  return "#" + String(componentToHex(r)) + String(componentToHex(g)) + String(componentToHex(b));
};

exports["default"] = rgbToHex;

/***/ }),
/* 935 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Calculate the center of the scale as well as its scale
 * factor
 *
 * Assumes the two scales have the same k
 *
 * @param xScale: A d3 scale.
 * @param yScale: A d3 scale.
 * @return: [domainCenter, k]
 */
var scalesCenterAndK = function scalesCenterAndK(xScale, yScale) {
  var xCenter = xScale.invert((xScale.range()[0] + xScale.range()[1]) / 2);
  var yCenter = yScale.invert((yScale.range()[0] + yScale.range()[1]) / 2);
  var k = xScale.invert(1) - xScale.invert(0);

  return [xCenter, yCenter, k];
};

exports["default"] = scalesCenterAndK;

/***/ }),
/* 936 */
/***/ (function(module, exports, __nested_webpack_require_4547308__) {

"use strict";


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

var _toConsumableArray2 = __nested_webpack_require_4547308__(25);

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _dataToGenomicLoci = __nested_webpack_require_4547308__(326);

var _dataToGenomicLoci2 = _interopRequireDefault(_dataToGenomicLoci);

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

var scalesToGenomeLoci = exports.scalesToGenomeLoci = function scalesToGenomeLoci(xScale, yScale, chromInfo) {
  if (chromInfo === null || !xScale || !yScale) return undefined;

  var x0 = xScale.domain()[0];
  var x1 = xScale.domain()[1];
  var y0 = yScale.domain()[0];
  var y1 = yScale.domain()[1];

  return [].concat((0, _toConsumableArray3['default'])((0, _dataToGenomicLoci2['default'])(x0, x1, chromInfo)), (0, _toConsumableArray3['default'])((0, _dataToGenomicLoci2['default'])(y0, y1, chromInfo)));
};

exports['default'] = scalesToGenomeLoci;

/***/ }),
/* 937 */
/***/ (function(module, exports, __nested_webpack_require_4548408__) {

"use strict";


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

var _pubSubEs = __nested_webpack_require_4548408__(134);

var _ = __nested_webpack_require_4548408__(10);

var _configs = __nested_webpack_require_4548408__(11);

var COLOR = 0xaaaaaa;

// Configs

var ALPHA = 1.0;

/**
 * Actual interface for initializing to show the mouse location
 *
 * @param  {Object}  pubSubs  PubSub service.
 * @param  {Object}  pubSubs  Subscribed PubSub events.
 * @param  {Object}  options  Track options.
 * @param  {Function}  getScales  Getter for the track's X and Y scales.
 * @param  {Function}  getPosition  Getter for the track's position.
 * @param  {Function}  getDimensions  Getter for the track's dimensions.
 * @param  {Function}  getIsFlipped  Getter determining if a track has been
 *   flipped from horizontal to vertical.
 * @param  {Boolean}  is2d  If `true` draw both dimensions of the mouse
 *   location.
 * @param  {Boolean}  isGlobal   If `true` local and global events will trigger
 *   the mouse position drawing.
 * @return  {Object}  PIXI graphics the mouse location is drawn on.
 */
var showMousePosition = function showMousePosition(pubSub, pubSubs, options, getScales, getPosition, getDimensions, getIsFlipped, is2d, isGlobal) {
  pubSub.publish('app.animateOnMouseMove', true);

  var color = options.mousePositionColor ? (0, _.hexStrToInt)(options.mousePositionColor) : COLOR;

  var alpha = options.mousePositionAlpha || ALPHA;

  // Graphics for cursor position
  var graphics = new _configs.GLOBALS.PIXI.Graphics();

  // This clears the mouse position graphics, i.e., the mouse position will not
  // be visible afterwards.
  var clearGraphics = function clearGraphics() {
    graphics.clear();
  };

  /**
   * Draw 1D mouse location (cross) hair onto the PIXI graphics.
   *
   * @param  {Integer}   mousePos  One dimension of the mouse location
   * @param  {Boolean}   isHorizontal  If `true` the dimension to be drawn is
   *   horizontal.
   * @param  {Boolean}   isNoClear  If `true` do not clear the graphics.
   */
  var drawMousePosition = function drawMousePosition(mousePos, isHorizontal, isNoClear) {
    if (!isNoClear) clearGraphics();

    graphics.lineStyle(1, color, alpha);

    if (isHorizontal) {
      var addition = is2d ? getPosition()[0] : 0;
      graphics.moveTo(0, mousePos);
      graphics.lineTo(getDimensions()[0] + addition, mousePos);
    } else {
      var _addition = is2d ? getPosition()[1] : 0;
      graphics.moveTo(mousePos, 0);
      graphics.lineTo(mousePos, getDimensions()[1] + _addition);
    }
  };

  /**
   * Mouse move handler
   *
   * @param  {Object}  e  Event object.
   */
  var mouseMoveHandler = function mouseMoveHandler(event) {
    if (event.noHoveredTracks) {
      clearGraphics();
      return graphics;
    }

    var x = void 0;
    var y = void 0;
    if (event.isFromVerticalTrack) {
      x = event.dataY;
      y = event.dataY;
    } else {
      x = event.dataX;
      y = event.isFrom2dTrack ? event.dataY : event.dataX;
    }

    // 2d or central tracks are not offset and rather rely on a mask, i.e., the
    // top left *visible* position is *not* [0,0] but given by `getPosition()`.
    var offset = is2d ? getPosition() : [0, 0];

    // `getIsFlipped()` is `true` when a horizontal track has been flipped by 90
    // degree, i.e., is a vertical track.
    var mousePos = getIsFlipped() ? getScales()[0](y) + offset[1] : getScales()[0](x) + offset[0];

    drawMousePosition(mousePos);

    // Also draw the second dimension
    if (is2d) drawMousePosition(getScales()[1](y) + offset[1], true, true);

    return graphics;
  };

  pubSubs.push(pubSub.subscribe('app.mouseMove', mouseMoveHandler));
  pubSubs.push(pubSub.subscribe('app.mouseLeave', clearGraphics));
  pubSubs.push(pubSub.subscribe('blur', clearGraphics));

  if (isGlobal) {
    pubSubs.push(_pubSubEs.globalPubSub.subscribe('higlass.mouseMove', mouseMoveHandler));
  }

  return graphics;
};

/**
 * Public API for showing the mouse location.
 *
 * @description
 * This is just a convenience wrapper to avoid code duplication.
 * `showMousePosition` is the actual function and could be called from within
 * each class as well.
 *
 * @param  {Object}  context  Class context, i.e., `this`.
 * @param  {Boolean}  is2d   If `true` both dimensions of the mouse location
 *   should be shown. E.g., on a central track.
 * @param  {Boolean}  isGlobal   If `true` local and global events will trigger
 *   the mouse position drawing.
 * @return  {Function}  Method to remove graphics showing the mouse location.
 */
var setupShowMousePosition = function setupShowMousePosition(context) {
  var is2d = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var isGlobal = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

  var scene = is2d ? context.pMasked : context.pForeground || context.pMain;
  var getScales = function getScales() {
    return [context.xScale(), context.yScale()];
  };

  var graphics = showMousePosition(context.pubSub, context.pubSubs, context.options, getScales, context.getPosition.bind(context), context.getDimensions.bind(context), context.getProp('flipText'), is2d, isGlobal);

  scene.addChild(graphics);

  return function () {
    scene.removeChild(graphics);
  };
};

exports['default'] = setupShowMousePosition;

/***/ }),
/* 938 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Functional version of `Array.forEach`. More flexible and applicable to
 *   other array-like data types like `NodeList`.
 * @param   {function}  f  Modifier function applied on every item of the
 *   array.
 * @return  {*}  Modified array-like variable.
 */
var some = function some(f) {
  return function (x) {
    return Array.prototype.some.call(x, f);
  };
};

exports["default"] = some;

/***/ }),
/* 939 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Convenience function for a reducer to sum up a numerical array.
 * @param   {number}  a  Value A
 * @param   {number}  b  Value B
 * @return  {number}  Sum of A + B
 */
var sum = function sum(a, b) {
  return a + b;
};

exports["default"] = sum;

/***/ }),
/* 940 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Generate a SVG line
 * @param   {number}  x1  Start X
 * @param   {number}  y1  Start Y
 * @param   {number}  x2  End X
 * @param   {number}  y2  End Y
 * @param   {number}  strokeWidth  Line width
 * @param   {number}  strokeColor  Color HEX string
 * @return  {object}  SVG line object
 */
var svgLine = exports.svgLine = function svgLine(x1, y1, x2, y2, strokeWidth, strokeColor) {
  var line = document.createElement('line');

  line.setAttribute('x1', x1);
  line.setAttribute('x2', x2);
  line.setAttribute('y1', y1);
  line.setAttribute('y2', y2);

  if (strokeWidth) {
    line.setAttribute('stroke-width', strokeWidth);
  }
  if (strokeColor) {
    line.setAttribute('stroke', strokeColor);
  }

  return line;
};

exports['default'] = svgLine;

/***/ }),
/* 941 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Throttle and debounce a function call
 *
 * Throttling a function call means that the function is called at most every
 * `interval` milliseconds no matter how frequently you trigger a call.
 * Debouncing a function call means that the function is called the earliest
 * after `finalWait` milliseconds wait time where the function was not called.
 * Combining the two ensures that the function is called at most every
 * `interval` milliseconds and is ensured to be called with the very latest
 * arguments after after `finalWait` milliseconds wait time at the end.
 *
 * The following imaginary scenario describes the behavior:
 *
 * MS | interval=2 and finalWait=2
 * 01. y(f, 2, 2)(args_01) => f(args_01) call
 * 02. y(f, 2, 2)(args_02) => throttled call
 * 03. y(f, 2, 2)(args_03) => f(args_03) call
 * 04. y(f, 2, 2)(args_04) => throttled call
 * 05. y(f, 2, 2)(args_05) => f(args_05) call
 * 06. y(f, 2, 2)(args_06) => throttled call
 * 07. y(f, 2, 2)(args_07) => f(args_03) call
 * 08. y(f, 2, 2)(args_08) => throttled call
 * 09. nothing
 * 10. y(f, 2, 2)(args_10) => f(args_10) call from debouncing
 *
 * @param   {functon}  func - Function to be throttled and debounced
 * @param   {number}  interval - Throttle intevals in milliseconds
 * @param   {number}  finalWait - Debounce wait time in milliseconds
 * @return  {function} - Throttled and debounced function
 */
var throttleAndDebounce = function throttleAndDebounce(func, interval, finalWait) {
  var timeout = void 0;
  var blockedCalls = 0;

  var reset = function reset() {
    timeout = null;
  };

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

    var later = function later() {
      // Since we throttle and debounce we should check whether there were
      // actually multiple attempts to call this function after the most recent
      // throttled call. If there were no more calls we don't have to call
      // the function again.
      if (blockedCalls > 0) {
        func.apply(undefined, args);
        blockedCalls = 0;
      }
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, finalWait);
  };

  debounced.cancel = function () {
    clearTimeout(timeout);
    reset();
  };

  debounced.immediate = function () {
    func.apply(undefined, arguments);
  };

  var wait = false;
  var throttled = function throttled(request) {
    for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }

    if (!wait) {
      func.apply(undefined, args);
      debounced.apply(undefined, args);

      wait = true;
      blockedCalls = 0;

      setTimeout(function () {
        wait = false;
      }, interval);
    } else {
      blockedCalls++;
    }
  };

  return throttled;
};

exports["default"] = throttleAndDebounce;

/***/ }),
/* 942 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Convert a 1D numerical array into a canvas image
 * @param   {Float32Array}  pixData  1D data array
 * @param   {number}  w  Width
 * @param   {number}  h  Height
 * @return  {object}  Canvas object
 */
var tileToCanvas = function tileToCanvas(pixData) {
  var w = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 256;
  var h = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 256;

  var canvas = document.createElement('canvas');

  canvas.width = w;
  canvas.height = h;

  var ctx = canvas.getContext('2d');

  ctx.fillStyle = 'transparent';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  var pix = new ImageData(pixData, canvas.width, canvas.height);

  ctx.putImageData(pix, 0, 0);

  return canvas;
};

exports['default'] = tileToCanvas;

/***/ }),
/* 943 */
/***/ (function(module, exports, __nested_webpack_require_4559778__) {

"use strict";


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

var _promise = __nested_webpack_require_4559778__(62);

var _promise2 = _interopRequireDefault(_promise);

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

var timeout = function timeout(ms) {
  return new _promise2["default"](function (resolve) {
    return setTimeout(resolve, ms);
  });
};

exports["default"] = timeout;

/***/ }),
/* 944 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Calculate the total height of the horizontal and center
 * tracks in pixels
 *
 * Parameters
 * -----------
 *
 *  view : view config object
 *    A typical view configuration containing a list of tracks
 *
 * Returns
 * -------
 *  int
 *    The total height of the top, center and bottom tracks
 */
var totalTrackPixelHeight = function totalTrackPixelHeight(view) {
  // no tracks means no height
  if (!view.tracks) return 0;

  var totalHeight = 0;

  if (view.tracks.top) {
    totalHeight += view.tracks.top.map(function (x) {
      return x.height;
    }).reduce(function (a, b) {
      return a + b;
    }, 0);
  }

  if (view.tracks.center) {
    totalHeight += view.tracks.center.map(function (x) {
      return x.height;
    }).reduce(function (a, b) {
      return a + b;
    }, 0);
  }

  if (view.tracks.bottom) {
    totalHeight += view.tracks.bottom.map(function (x) {
      return x.height;
    }).reduce(function (a, b) {
      return a + b;
    }, 0);
  }

  return totalHeight;
};

exports["default"] = totalTrackPixelHeight;

/***/ }),
/* 945 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Trim trailing slash of an URL.
 * @param   {string}  url  URL to be trimmed.
 * @return  {string}  Trimmed URL.
 */
var trimTrailingSlash = function trimTrailingSlash(url) {
  return (url || '').replace(/\/$/, '');
};

exports['default'] = trimTrailingSlash;

/***/ }),
/* 946 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Factory function for a value to RGB color converter
 *
 * @param  {Function}  valueScale  Value scaling function.
 * @param  {Array}  colorScale  Color scale array.
 * @param  {Number}  pseudoCounts  Pseudo counts used as a pseudocount to
 *   prevent taking the log of 0.
 * @param  {Number}  eps  Epsilon.
 * @return  {Array}  RGB color array.
 */
var valueToColor = function valueToColor(valueScale, colorScale) {
  var pseudoCounts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  var eps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.000001;
  return function (value) {
    var rgbIdx = 255;

    if (value > eps) {
      // values less than espilon are considered NaNs and made transparent
      // (rgbIdx 255)
      rgbIdx = Math.max(0, Math.min(255, Math.floor(valueScale(value + pseudoCounts))));
    }

    return colorScale[rgbIdx];
  };
};

exports["default"] = valueToColor;

/***/ }),
/* 947 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
/**
 * Go through a list of tracks and expand combined
 * tracks.
 *
 * @param {list} tracks: A list of tracks some of which might be combined
 * @returns {list} tracks: A list of tracks without combined
 */
var expandCombinedTracks = function expandCombinedTracks(trackList) {
  var newTracks = [];

  for (var i = 0; i < trackList.length; i++) {
    if (trackList[i].contents) {
      newTracks = newTracks.concat(trackList[i].contents);
    } else {
      newTracks.push(trackList[i]);
    }
  }

  return newTracks;
};

exports["default"] = expandCombinedTracks;

/***/ }),
/* 948 */
/***/ (function(module, exports, __nested_webpack_require_4563767__) {

"use strict";


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

var _intervalTree = __nested_webpack_require_4563767__(949);

var _intervalTree2 = _interopRequireDefault(_intervalTree);

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

function segmentsToRows(segments) {
  /**
   * Partition a list of segments into an array of
   * rows containing the segments.
   *
   * @param segments: An array of segments (e.g. [{from: 10, to: 20}, {from: 18, to: 30}])
   * @return: An array of arrays of segments, representing
   *          non-overlapping rows of segments
   */
  // sort by the length of each segment
  segments.sort(function (a, b) {
    return b.to - b.from - (a.to - a.from);
  });

  var rows = [[]];
  var rowIts = [new _intervalTree2['default']()];

  // fill out each row with segments
  for (var i = 0; i < segments.length; i++) {
    var placed = false;

    for (var j = 0; j < rows.length; j++) {
      var it = rowIts[j]; // an interval tree

      var toCheck = [+segments[i].from, +segments[i].to];
      var occluded = it.intersects(toCheck);

      if (!occluded) {
        // no intersections on this row, place this segment here
        it.add(toCheck);
        rows[j].push(segments[i]);
        placed = true;
        break;
      }
    }

    if (!placed) {
      var newTree = new _intervalTree2['default']();

      newTree.add([segments[i].from, segments[i].to]);
      rows.push([segments[i]]);
      rowIts.push(newTree);
    }
  }

  return rows;
}

exports['default'] = segmentsToRows;

/***/ }),
/* 949 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports['default'] = IntervalTree;
function IntervalTreeNode(start, end, left, right) {
  /**
   * Node interval.
   * @member {Array}
   */
  this.interval = [start, end];
  /**
   * Max endpoint in subtree which starts from this node.
   * @member {Number}
   */
  this.max = -Infinity;
  /**
   * Parent node.
   * @member {IntervalTreeNode}
   */
  this.parentNode = null;
  /**
   * Left child node.
   * @member {IntervalTreeNode}
   */
  this.left = left;
  /**
   * Right child node.
   * @member {IntervalTreeNode}
   */
  this.right = right;
}

/**
 * Interval tree.
 *
 * @public
 * @constructor
 */
function IntervalTree() {
  /**
   * Root node of the tree.
   * @member {IntervalTreeNode}
   */
  this.root = null;
}

function addNode(node, side, interval) {
  var child = new IntervalTreeNode(interval[0], interval[1]);
  child.max = interval[1];
  child.parentNode = node;
  node[side] = child;
  if (node.max < interval[1]) {
    while (child) {
      if (child.max < interval[1]) {
        child.max = interval[1];
      }
      child = child.parentNode;
    }
  }
}

function addHelper(node, interval) {
  if (node.interval[0] > interval[0]) {
    if (node.left) {
      addHelper(node.left, interval);
    } else {
      addNode(node, 'left', interval);
    }
  } else if (node.right) {
    addHelper(node.right, interval);
  } else {
    addNode(node, 'right', interval);
  }
}

/**
 * Add new interval to the tree.
 *
 * @public
 * @param {Array} intreval Array with start and end points of the interval.
 */
IntervalTree.prototype.add = function () {
  function add(interval) {
    if (!this.root) {
      this.root = new IntervalTreeNode(interval[0], interval[1]);
      this.root.max = interval[1];
      return;
    }
    addHelper(this.root, interval);
  }

  return add;
}();

function contains(point, node) {
  if (!node) {
    return false;
  }
  if (node.interval[0] <= point && node.interval[1] >= point) {
    return true;
  }
  var result = false;
  var temp = void 0;
  ['left', 'right'].forEach(function (key) {
    temp = node[key];
    if (temp) {
      if (temp.max > point) {
        result = result || contains(point, temp);
      }
    }
  });
  return result;
}

/**
 * Checks or point belongs to at least one intarval from the tree.<br><br>
 * Complexity: O(log N).
 *
 * @public
 * @method
 * @param {Number} point Point which should be checked.
 * @return {Boolean} True if point belongs to one of the intervals.
 */
IntervalTree.prototype.contains = function () {
  function _contains(point) {
    return contains(point, this.root);
  }

  return _contains;
}();

function intersects(a, b) {
  return (
    // The first case checks for completely overlapping
    // intervals. Necessary because we usually consider
    // the ends to be open ended and that misses completely
    // overlapping intervals
    a[0] === b[0] && a[1] === b[1] || a[0] < b[0] && a[1] > b[0] || a[0] < b[1] && a[1] > b[1] || b[0] < a[0] && b[1] > a[0] || b[0] < a[1] && b[1] > a[1]
  );
}

function intersectsHelper(interval, node) {
  if (!node) {
    return false;
  }
  if (intersects(node.interval, interval)) {
    return true;
  }
  var result = false;
  var temp = void 0;
  ['left', 'right'].forEach(function (side) {
    temp = node[side];
    if (temp && temp.max >= interval[0]) {
      result = result || intersectsHelper(interval, temp);
    }
  });
  return result;
}

/**
 * Checks or interval belongs to at least one intarval from the tree.<br><br>
 * Complexity: O(log N).
 *
 * @public
 * @method
 * @param {Array} interval Interval which should be checked.
 * @return {Boolean} True if interval intersects with one of the intervals.
 */
IntervalTree.prototype.intersects = function () {
  function _intersects(interval) {
    return intersectsHelper(interval, this.root);
  }

  return _intersects;
}();

function heightHelper(node) {
  if (!node) {
    return 0;
  }
  return 1 + Math.max(heightHelper(node.left), heightHelper(node.right));
}

/**
 * Returns height of the tree.
 *
 * @public
 * @method
 * @return {Number} Height of the tree.
 */
IntervalTree.prototype.height = function () {
  function height() {
    return heightHelper(this.root);
  }

  return height;
}();

/**
 * Returns node with the max endpoint in subtree.
 *
 * @public
 * @method
 * @param {IntervalTreeNode} node Root node of subtree.
 * @return {IntervalTreeNode} IntervalTreeNode with the largest endpoint.
 */
IntervalTree.prototype.findMax = function () {
  function findMax(node) {
    var stack = [node];
    var current = void 0;
    var max = -Infinity;
    var maxNode = void 0;
    while (stack.length) {
      current = stack.pop();
      if (current.left) {
        stack.push(current.left);
      }
      if (current.right) {
        stack.push(current.right);
      }
      if (current.interval[1] > max) {
        max = current.interval[1];
        maxNode = current;
      }
    }
    return maxNode;
  }

  return findMax;
}();

// adjust the max value
IntervalTree.prototype._removeHelper = function () {
  function _removeHelper(interval, node) {
    if (!node) {
      return;
    }
    if (node.interval[0] === interval[0] && node.interval[1] === interval[1]) {
      // When left and right children exists
      if (node.left && node.right) {
        var replacement = node.left;
        while (replacement.left) {
          replacement = replacement.left;
        }
        var temp = replacement.interval;
        replacement.interval = node.interval;
        node.interval = temp;
        this._removeHelper(replacement.interval, node);
      } else {
        // When only left or right child exists
        var side = 'left';
        if (node.right) {
          side = 'right';
        }
        var parentNode = node.parentNode;
        if (parentNode) {
          if (parentNode.left === node) {
            parentNode.left = node[side];
          } else {
            parentNode.right = node[side];
          }
          if (node[side]) {
            node[side].parentNode = parentNode;
          }
        } else {
          this.root = node[side];
          // last node removed
          if (this.root) {
            this.root.parentNode = null;
          }
        }
      }
      // Adjust the max value
      var p = node.parentNode;
      if (p) {
        var maxNode = this.findMax(p);
        var max = maxNode.interval[1];
        while (maxNode) {
          if (maxNode.max === node.interval[1]) {
            maxNode.max = max;
            maxNode = maxNode.parentNode;
          } else {
            maxNode = false;
          }
        }
      }
    } else {
      // could be optimized
      this._removeHelper(interval, node.left);
      this._removeHelper(interval, node.right);
    }
  }

  return _removeHelper;
}();

/**
 * Remove interval from the tree.
 *
 * @public
 * @method
 * @param {Array} intreval Array with start and end of the interval.
 */
IntervalTree.prototype.remove = function () {
  function remove(interval) {
    return this._removeHelper(interval, this.root);
  }

  return remove;
}();

/***/ }),
/* 950 */
/***/ (function(module, exports, __nested_webpack_require_4572663__) {

"use strict";


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

var _getIterator2 = __nested_webpack_require_4572663__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _values = __nested_webpack_require_4572663__(37);

var _values2 = _interopRequireDefault(_values);

var _maxSafeInteger = __nested_webpack_require_4572663__(55);

var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger);

var _d3Zoom = __nested_webpack_require_4572663__(157);

var _AxisPixi = __nested_webpack_require_4572663__(179);

var _AxisPixi2 = _interopRequireDefault(_AxisPixi);

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

/**
 * The d3.range and python range functinons. Returns
 * an array of consecutive integers between start and end.
 *
 * @param  {number} start Lower limit (included in result)
 * @param  {number} end   Upper limit (not included in result)
 * @return {array}       A list of consecutive integers from start to end
 */
var range = function range(start, end) {
  var values = [];
  for (var i = start; i < end; i++) {
    values.push(i);
  }

  return values;
};

/**
 * Calculate the zoom level from a list of available resolutions
 *
 * @param {array} resolutions A list of data resolutions (e.g. [100,1000])
 * @param {function} scale The current D3 scale function describing the domain and range
 *                         of the view.
 */
var calculateZoomLevelFromResolutions = function calculateZoomLevelFromResolutions(resolutions, scale) {
  var sortedResolutions = resolutions.map(function (x) {
    return +x;
  }).sort(function (a, b) {
    return b - a;
  });

  var trackWidth = scale.range()[1] - scale.range()[0];

  var binsDisplayed = sortedResolutions.map(function (r) {
    return (scale.domain()[1] - scale.domain()[0]) / r;
  });
  var binsPerPixel = binsDisplayed.map(function (b) {
    return b / trackWidth;
  });

  // we're going to show the highest resolution that requires more than one
  // pixel per bin
  var displayableBinsPerPixel = binsPerPixel.filter(function (b) {
    return b < 1;
  });

  if (displayableBinsPerPixel.length === 0) return 0;

  return binsPerPixel.indexOf(displayableBinsPerPixel[displayableBinsPerPixel.length - 1]);
};

/**
 * Calculate the current zoom level from powers of two resolutions.
 *
 * @param {function} scale The current D3 scale function used for the view.
 * @param {number} minX The minimum possible X value
 * @param {number} maxX The maximum possible x value
 * @param {number} binsPerTile The width of each tile in whatever
 *                             unit the x-axis is (bp for genomic data).
 */
var calculateZoomLevel = function calculateZoomLevel(scale, minX, maxX, binsPerTile) {
  var rangeWidth = scale.range()[1] - scale.range()[0];

  var zoomScale = Math.max((maxX - minX) / (scale.domain()[1] - scale.domain()[0]), 1);

  // fun fact: the number 384 is halfway between 256 and 512
  // this constant determines the maximum number of pixels that
  // a tile can span
  var VIEW_RESOLUTION = 384;

  var addedZoom = Math.max(0, Math.ceil(Math.log(rangeWidth / VIEW_RESOLUTION) / Math.LN2));
  var zoomLevel = Math.round(Math.log(zoomScale) / Math.LN2) + addedZoom;

  var binsPerTileCorrection = 0;

  if (binsPerTile) {
    binsPerTileCorrection = Math.floor(Math.log(256) / Math.log(2) - Math.log(binsPerTile) / Math.log(2));
  }

  zoomLevel += binsPerTileCorrection;

  return zoomLevel;
};

/**
 * Calculate the current zoom level for a 1D track
 *
 * @param  {object} tilesetInfo The tileset info for the track. Should contain
 *                              min_pos and max_pos arrays, each of which has one
 *                              value which stores the minimum and maximum data
 *                              positions respectively.
 * @param  {function} xScale      The current D3 scale function for the track.
 * @param  {number} maxZoom     The maximum zoom level allowed by the track.
 * @return {number}                The current zoom level of the track.
 */
var calculate1DZoomLevel = function calculate1DZoomLevel(tilesetInfo, xScale, maxZoom) {
  if (typeof maxZoom === 'undefined') {
    maxZoom = _maxSafeInteger2['default'];
  }
  // offset by 2 because 1D tiles are more dense than 2D tiles
  // 1024 points per tile vs 256 for 2D tiles
  if (tilesetInfo.resolutions) {
    var zoomIndexX = calculateZoomLevelFromResolutions(tilesetInfo.resolutions, xScale, tilesetInfo.min_pos[0], tilesetInfo.max_pos[0] - 2);

    return zoomIndexX;
  }

  // the tileProxy calculateZoomLevel function only cares about the
  // difference between the minimum and maximum position
  var xZoomLevel = calculateZoomLevel(xScale, tilesetInfo.min_pos[0], tilesetInfo.max_pos[0], tilesetInfo.bins_per_dimension || tilesetInfo.tile_size);

  var zoomLevel = Math.min(xZoomLevel, maxZoom);
  return Math.max(zoomLevel, 0);
};

/**
 * Calculate the tiles that should be visible get a data domain
 * and a tileset info
 *
 * All the parameters except the first should be present in the
 * tileset_info returned by the server.
 *
 * @param zoomLevel: The zoom level at which to find the tiles (can be
 *   calculated using this.calculateZoomLevel, but needs to synchronized across
 *   both x and y scales so should be calculated externally)
 * @param scale: A d3 scale mapping data domain to visible values
 * @param minX: The minimum possible value in the dataset
 * @param maxX: The maximum possible value in the dataset
 * @param maxZoom: The maximum zoom value in this dataset
 * @param maxDim: The largest dimension of the tileset (e.g., width or height)
 *   (roughlty equal to 2 ** maxZoom * tileSize * tileResolution)
 */
var calculateTiles = function calculateTiles(zoomLevel, scale, minX, maxX, maxZoom, maxDim) {
  var zoomLevelFinal = Math.min(zoomLevel, maxZoom);

  // the ski areas are positioned according to their
  // cumulative widths, which means the tiles need to also
  // be calculated according to cumulative width

  var tileWidth = maxDim / Math.pow(2, zoomLevelFinal);
  var epsilon = 0.0000001;

  return range(Math.max(0, Math.floor((scale.domain()[0] - minX) / tileWidth)), Math.min(Math.pow(2, zoomLevelFinal), Math.ceil((scale.domain()[1] - minX - epsilon) / tileWidth)));
};

/**
 * Calculate the tiles that sould be visisble given the resolution and
 * the minX and maxX values for the region
 *
 * @param resolution: The number of base pairs per bin
 * @param scale: The scale to use to calculate the currently visible tiles
 * @param minX: The minimum x position of the tileset
 * @param maxX: The maximum x position of the tileset
 */
var calculateTilesFromResolution = function calculateTilesFromResolution(resolution, scale, minX) {
  var maxX = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : Number.MAX_VALUE;
  var pixelsPerTile = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 256;

  var epsilon = 0.0000001;
  var tileWidth = resolution * pixelsPerTile;
  var MAX_TILES = 20;

  var lowerBound = Math.max(0, Math.floor((scale.domain()[0] - minX) / tileWidth));
  var upperBound = Math.ceil(Math.min(maxX, scale.domain()[1] - minX - epsilon) / tileWidth);
  var tileRange = range(lowerBound, upperBound);

  if (tileRange.length > MAX_TILES) {
    // too many tiles visible in this range
    console.warn('Too many visible tiles: ' + String(tileRange.length) + ' truncating to ' + MAX_TILES);
    tileRange = tileRange.slice(0, MAX_TILES);
  }

  return tileRange;
};

/**
 * Calculate which tiles should be visible given a track's
 * scale.
 *
 * @param  {object} tilesetInfo The track's tileset info, containing either the `resolutions`
 *                              list or min_pos and max_pos arrays
 * @param  {function} scale     The track's D3 scale function.
 * @return {array}             A list of visible tiles (e.g. [[1,0],[1,1]])
 */
var calculate1DVisibleTiles = function calculate1DVisibleTiles(tilesetInfo, scale) {
  // if we don't know anything about this dataset, no point
  // in trying to get tiles
  if (!tilesetInfo) {
    return [];
  }

  // calculate the zoom level given the scales and the data bounds
  var zoomLevel = calculate1DZoomLevel(tilesetInfo, scale, tilesetInfo.max_zoom);

  if (tilesetInfo.resolutions) {
    var sortedResolutions = tilesetInfo.resolutions.map(function (x) {
      return +x;
    }).sort(function (a, b) {
      return b - a;
    });

    var _xTiles = calculateTilesFromResolution(sortedResolutions[zoomLevel], scale, tilesetInfo.min_pos[0], tilesetInfo.max_pos[0]);

    var _tiles = _xTiles.map(function (x) {
      return [zoomLevel, x];
    });

    return _tiles;
  }

  // x doesn't necessary mean 'x' axis, it just refers to the relevant axis
  // (x if horizontal, y if vertical)
  var xTiles = calculateTiles(zoomLevel, scale, tilesetInfo.min_pos[0], tilesetInfo.max_pos[0], tilesetInfo.max_zoom, tilesetInfo.max_width);

  var tiles = xTiles.map(function (x) {
    return [zoomLevel, x];
  });
  return tiles;
};

/**
 * Draw an axis on a track. Where on the track the axis will be drawn
 * is taken from the track's options.
 *
 * @param  {PixiTrack} track   The track to decorate with an axis.
 * @param  {d3.scale} valueScale The scale that the axis should draw.
 */
var drawAxis = function drawAxis(track, valueScale) {
  if (!track.axis) {
    track.axis = new _AxisPixi2['default'](track);
    track.pBase.addChild(track.axis.pAxis);
  }
  // either no axis position is specified
  if (!track.options.axisPositionVertical && !track.options.axisPositionHorizontal) {
    track.axis.clearAxis();
    return;
  }

  if (track.options.axisPositionVertical && track.options.axisPositionVertical === 'hidden') {
    track.axis.clearAxis();
    return;
  }

  if (track.options.axisPositionHorizontal && track.options.axisPositionHorizontal === 'hidden') {
    track.axis.clearAxis();
    return;
  }

  var margin = track.options.axisMargin || 0;

  if (track.options.axisPositionHorizontal === 'left' || track.options.axisPositionVertical === 'top') {
    // left axis are shown at the beginning of the plot
    track.axis.pAxis.position.x = track.position[0] + margin;
    track.axis.pAxis.position.y = track.position[1];

    track.axis.drawAxisRight(valueScale, track.dimensions[1]);
  } else if (track.options.axisPositionHorizontal === 'outsideLeft' || track.options.axisPositionVertical === 'outsideTop') {
    // left axis are shown at the beginning of the plot
    track.axis.pAxis.position.x = track.position[0] + margin;
    track.axis.pAxis.position.y = track.position[1];

    track.axis.drawAxisLeft(valueScale, track.dimensions[1]);
  } else if (track.options.axisPositionHorizontal === 'right' || track.options.axisPositionVertical === 'bottom') {
    track.axis.pAxis.position.x = track.position[0] + track.dimensions[0] - margin;
    track.axis.pAxis.position.y = track.position[1];
    track.axis.drawAxisLeft(valueScale, track.dimensions[1]);
  } else if (track.options.axisPositionHorizontal === 'outsideRight' || track.options.axisPositionVertical === 'outsideBottom') {
    track.axis.pAxis.position.x = track.position[0] + track.dimensions[0] - margin;
    track.axis.pAxis.position.y = track.position[1];
    track.axis.drawAxisRight(valueScale, track.dimensions[1]);
  }
};

/**
 * A track is being dragged along it's value scale axis.
 *
 * @param {object} Track The track instance being dragged.
 * @param  {number} dY The change in y position.
 */
var movedY = function movedY(track, dY) {
  // see the reasoning behind why the code in
  // zoomedY is commented out.

  var vst = track.valueScaleTransform;
  var y = vst.y,
      k = vst.k;

  var height = track.dimensions[1];

  // clamp at the bottom and top
  if (y + dY / k > -(k - 1) * height && y + dY / k < 0) {
    track.valueScaleTransform = vst.translate(0, dY / k);
  }

  (0, _values2['default'])(track.fetchedTiles).forEach(function (tile) {
    tile.graphics.position.y = track.valueScaleTransform.y;
  });

  track.animate();
};

/**
 * A track has received an event telling it to zoom along its
 * vertical axis. Update the transform describing the position
 * of its graphics.
 *
 * @param  {number} yPos        The position the zoom event took place
 * @param  {number} kMultiplier How much the zoom level should be adjusted by
 * @param  {d3.transform} transform   The track's current graphics transform.
 * @param  {number} height      The height of the track
 * @return {d3.transform}            The track's new graphics transform.
 */
var zoomedY = function zoomedY(yPos, kMultiplier, transform, height) {
  var k0 = transform.k;
  var t0 = transform.y;
  var dp = (yPos - t0) / k0;
  var k1 = Math.max(k0 / kMultiplier, 1.0);
  var t1 = k0 * dp + t0 - k1 * dp;

  // clamp at the bottom
  t1 = Math.max(t1, -(k1 - 1) * height);

  // clamp at the top
  t1 = Math.min(t1, 0);
  // right now, the point at position 162 is at position 0
  // 0 = 1 * 162 - 162
  //
  // we want that when k = 2, that point is still at position
  // 0 = 2 * 162 - t1
  //  ypos = k0 * dp + t0
  //  dp = (ypos - t0) / k0
  //  nypos = k1 * dp + t1
  //  k1 * dp + t1 = k0 * dp + t0
  //  t1 = k0 * dp +t0 - k1 * dp
  return _d3Zoom.zoomIdentity.translate(0, t1).scale(k1);
};

/**
 * Get the tile's position in its coordinate system.
 *
 * See Tiled1DPIXITrack.js
 */
var getTilePosAndDimensions = function getTilePosAndDimensions(tilesetInfo, tileId) {
  var zoomLevel = +tileId.split('.')[0];
  var xTilePos = +tileId.split('.')[1];

  // max_width should be substitutable with 2 ** tilesetInfo.max_zoom
  var totalWidth = tilesetInfo.max_width;

  var minX = tilesetInfo.min_pos[0];

  var tileWidth = totalWidth / Math.pow(2, zoomLevel);

  var tileX = minX + xTilePos * tileWidth;

  return {
    tileX: tileX,
    tileWidth: tileWidth
  };
};

/** When zooming, we want to do fast scaling rather than re-rendering
 * but if we do this too much, shapes (particularly arrowheads) get
 * distorted. This function keeps track of how stretched the track is
 * and redraws it if it becomes too distorted (tileK < 0.5 or tileK > 2) */
function stretchRects(track, graphicsAccessors) {
  (0, _values2['default'])(track.fetchedTiles)
  // tile hasn't been drawn properly because we likely got some
  // bogus data from the server
  .forEach(function (tile) {
    if (!tile.drawnAtScale) return;

    var dasRange = tile.drawnAtScale.range();
    var tRange = track._xScale.range();

    // check to make sure the track extent hasn't changed
    if (dasRange[0] !== tRange[0] || dasRange[1] !== tRange[1]) {
      track.renderTile(tile);
      return;
    }

    var tileK = (tile.drawnAtScale.domain()[1] - tile.drawnAtScale.domain()[0]) / (track._xScale.domain()[1] - track._xScale.domain()[0]);

    if (tileK > 2 || tileK < 0.5) {
      // too stretched out, needs to be re-rendered
      track.renderTile(tile);
    } else {
      // can be stretched a little bit, just need to set the scale
      var newRange = track._xScale.domain().map(tile.drawnAtScale);
      var posOffset = newRange[0];

      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = (0, _getIterator3['default'])(graphicsAccessors), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var graphicsAccessor = _step.value;

          graphicsAccessor(tile).scale.x = tileK;
          graphicsAccessor(tile).x = -posOffset * tileK;
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator['return']) {
            _iterator['return']();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
    }
  });
}

var trackUtils = {
  calculate1DVisibleTiles: calculate1DVisibleTiles,
  calculate1DZoomLevel: calculate1DZoomLevel,
  drawAxis: drawAxis,
  movedY: movedY,
  getTilePosAndDimensions: getTilePosAndDimensions,
  stretchRects: stretchRects,
  zoomedY: zoomedY
};

exports['default'] = trackUtils;

/***/ }),
/* 951 */
/***/ (function(module, exports, __nested_webpack_require_4588938__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.removeHGComponent = exports.mountHGComponent = exports.waitForTilesLoaded = exports.isWaitingOnTiles = exports.waitForJsonComplete = exports.waitForTransitionsFinished = exports.areTransitionsActive = exports.changeOptions = undefined;

var _extends2 = __nested_webpack_require_4588938__(34);

var _extends3 = _interopRequireDefault(_extends2);

var _getIterator2 = __nested_webpack_require_4588938__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _react = __nested_webpack_require_4588938__(1);

var _react2 = _interopRequireDefault(_react);

var _reactDom = __nested_webpack_require_4588938__(42);

var _reactDom2 = _interopRequireDefault(_reactDom);

var _enzyme = __nested_webpack_require_4588938__(952);

var _services = __nested_webpack_require_4588938__(24);

var _getHiglassComponents = __nested_webpack_require_4588938__(448);

var _HiGlassComponent = __nested_webpack_require_4588938__(232);

var _HiGlassComponent2 = _interopRequireDefault(_HiGlassComponent);

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

// eslint-disable-next-line import/no-extraneous-dependencies
// In this project, these methods are only used in tests,
// but plugin tracks also make use of them... so not really extraneous.

var TILE_LOADING_CHECK_INTERVAL = 100;

/**
 * Change the options of a track in higlass
 * @param  hgc      enzyme wrapper for a HiGlassComponent
 * @param  viewUid  The view uid
 * @param  trackUid The track uid
 * @param  options  An object of new options (e.g. { color: 'black'})
 * @return          nothing
 */
var changeOptions = exports.changeOptions = function changeOptions(hgc, viewUid, trackUid, options) {
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3['default'])(hgc.instance().iterateOverTracks()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var _ref = _step.value;
      var viewId = _ref.viewId,
          trackId = _ref.trackId,
          track = _ref.track;

      if (viewId === viewUid && trackId === trackUid) {
        track.options = (0, _extends3['default'])({}, track.options, options);
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator['return']) {
        _iterator['return']();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  hgc.setState(hgc.instance().state);
};

/**
 * Check if there are any active transitions that we
 * need to wait on
 *
 * Parameters
 * ----------
 *  hgc: enzyme wrapper for a HiGlassComponent
 *
 * Returns
 * -------
 *  True if any of the tracks have active transtions. False otherwise.
 */
var areTransitionsActive = exports.areTransitionsActive = function areTransitionsActive(hgc) {
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = (0, _getIterator3['default'])(hgc.iterateOverTracks()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      var track = _step2.value;

      var trackRenderer = (0, _getHiglassComponents.getTrackRenderer)(hgc, track.viewId, track.trackId);

      if (trackRenderer.activeTransitions > 0) return true;
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2['return']) {
        _iterator2['return']();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }

  return false;
};

/**
 * Wait until all transitions have finished before
 * calling the callback
 *
 * Arguments
 * ---------
 *  hgc: Enzyme wrapper for a HiGlassComponent
 *      The componentthat we're waiting on
 *  tilesLoadedCallback: function
 *      The callback to call whenever all of the tiles
 *      have been loaded.
 * Returns
 * -------
 *  Nothing
 */
var waitForTransitionsFinished = exports.waitForTransitionsFinished = function waitForTransitionsFinished(hgc, callback) {
  if (areTransitionsActive(hgc)) {
    setTimeout(function () {
      waitForTransitionsFinished(hgc, callback);
    }, TILE_LOADING_CHECK_INTERVAL);
  } else {
    callback();
  }
};

/**
 * Wait until all open JSON requests are finished
 *
 * Parameters
 * ----------
 *  finished: function
 *    A callback to call when there's no more JSON requests
 *    open
 *
 */
var waitForJsonComplete = exports.waitForJsonComplete = function waitForJsonComplete(finished) {
  if (_services.requestsInFlight > 0) {
    setTimeout(function () {
      return waitForJsonComplete(finished);
    }, TILE_LOADING_CHECK_INTERVAL);
  } else {
    finished();
  }
};

/**
 * Check if a HiGlassComponent is still waiting on tiles from a remote
 * server.
 *
 * Arguments
 * ---------
 *  hgc: enzyme wrapper for a HiGlassComponent
 *
 * Returns
 * -------
 *  True if any of the tracks are waiting for tiles, false otherwise.
 */
var isWaitingOnTiles = exports.isWaitingOnTiles = function isWaitingOnTiles(hgc) {
  var _iteratorNormalCompletion3 = true;
  var _didIteratorError3 = false;
  var _iteratorError3 = undefined;

  try {
    for (var _iterator3 = (0, _getIterator3['default'])(hgc.iterateOverTracks()), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
      var track = _step3.value;

      var trackObj = (0, _getHiglassComponents.getTrackObjectFromHGC)(hgc, track.viewId, track.trackId);

      if (!track.track.server && !track.track.tilesetUid && !(track.track.data && track.track.data.type === 'divided')) {
        continue;
      } else if (track.track.data && track.track.data.type === 'divided' || track.track.server && track.track.tilesetUid) {
        if (trackObj.originalTrack) {
          trackObj = trackObj.originalTrack;
        }

        if (!(trackObj.tilesetInfo || trackObj.chromInfo)) {
          // console.warn(
          //   `Track uuid:${trackObj.uuid} has no tileset or chromosome info`
          // );
          return true;
        }

        if (trackObj.fetching && trackObj.fetching.size) {
          return true;
        }
      } else {
        throw Error('"server" and "tilesetUid" belong together');
      }
    }
  } catch (err) {
    _didIteratorError3 = true;
    _iteratorError3 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion3 && _iterator3['return']) {
        _iterator3['return']();
      }
    } finally {
      if (_didIteratorError3) {
        throw _iteratorError3;
      }
    }
  }

  return false;
};

var waitForTilesLoaded = exports.waitForTilesLoaded = function waitForTilesLoaded(hgc, tilesLoadedCallback) {
  /**
   * Wait until all of the tiles in the HiGlassComponent are loaded
   * until calling the callback
   *
   * Arguments
   * ---------
   *  hgc: Enzyme wrapper for a HiGlassComponent
   *      The componentthat we're waiting on
   *  tilesLoadedCallback: function
   *      The callback to call whenever all of the tiles
   *      have been loaded.
   * Returns
   * -------
   *  Nothing
   */
  // console.log('jasmine.DEFAULT_TIMEOUT_INTERVAL', jasmine.DEFAULT_TIMEOUT_INTERVAL);
  if (isWaitingOnTiles(hgc)) {
    setTimeout(function () {
      waitForTilesLoaded(hgc, tilesLoadedCallback);
    }, TILE_LOADING_CHECK_INTERVAL);
  } else {
    // console.log('finished');
    tilesLoadedCallback();
  }
};

/**
 * Mount a new HiGlassComponent and unmount the previously visible one.
 *
 * @param {HTML Element} div A div element to detach and recreate for the component
 * @param {Enzyme wrapped HiGlass component} prevHgc An already mounted
 *  hgc component
 * @param {function} done The callback to call when the component is fully loaded
 */
var mountHGComponent = exports.mountHGComponent = function mountHGComponent(prevDiv, prevHgc, viewConf, done, options) {
  if (prevHgc) {
    prevHgc.unmount();
    prevHgc.detach();
  }

  if (prevDiv) {
    global.document.body.removeChild(prevDiv);
  }

  var style = options && options.style || 'width:800px; background-color: lightgreen;';
  var bounded = options && options.bounded || false;

  // console.log('check:', options && options.style)
  // console.log('style:', style, "options:", options, "style", options.style);

  var div = global.document.createElement('div');
  global.document.body.appendChild(div);

  div.setAttribute('style', style);
  div.setAttribute('id', 'simple-hg-component');

  var hgc = (0, _enzyme.mount)(_react2['default'].createElement(_HiGlassComponent2['default'], { options: { bounded: bounded }, viewConfig: viewConf }), { attachTo: div });

  hgc.update();

  waitForJsonComplete(function () {
    if (options && options.extendedDelay) {
      // Waiting for tiles to be loaded does not always mean
      // that the compoment is mounted (especially if we load the tiles
      // from the filesystem, which is quick). Wait 1000ms to make sure
      // we are really done
      var doneWithDelay = function doneWithDelay() {
        return setTimeout(function () {
          done();
        }, 1000);
      };

      waitForTilesLoaded(hgc.instance(), doneWithDelay);
    } else {
      waitForTilesLoaded(hgc.instance(), done);
    }
  });

  return [div, hgc];
};

var removeHGComponent = exports.removeHGComponent = function removeHGComponent(div) {
  if (!div) return;

  _reactDom2['default'].unmountComponentAtNode(div);
  document.body.removeChild(div);
};
/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4588938__(27)))

/***/ }),
/* 952 */
/***/ (function(module, exports, __nested_webpack_require_4598801__) {

"use strict";


var _ReactWrapper = __nested_webpack_require_4598801__(449);

var _ReactWrapper2 = _interopRequireDefault(_ReactWrapper);

var _ShallowWrapper = __nested_webpack_require_4598801__(517);

var _ShallowWrapper2 = _interopRequireDefault(_ShallowWrapper);

var _EnzymeAdapter = __nested_webpack_require_4598801__(512);

var _EnzymeAdapter2 = _interopRequireDefault(_EnzymeAdapter);

var _mount = __nested_webpack_require_4598801__(1081);

var _mount2 = _interopRequireDefault(_mount);

var _shallow = __nested_webpack_require_4598801__(1082);

var _shallow2 = _interopRequireDefault(_shallow);

var _render = __nested_webpack_require_4598801__(1083);

var _render2 = _interopRequireDefault(_render);

var _configuration = __nested_webpack_require_4598801__(315);

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

module.exports = {
  render: _render2['default'],
  shallow: _shallow2['default'],
  mount: _mount2['default'],
  ShallowWrapper: _ShallowWrapper2['default'],
  ReactWrapper: _ReactWrapper2['default'],
  configure: _configuration.merge,
  EnzymeAdapter: _EnzymeAdapter2['default']
};

/***/ }),
/* 953 */
/***/ (function(module, exports, __nested_webpack_require_4599932__) {

"use strict";


var keysShim;
if (!Object.keys) {
	// modified from https://github.com/es-shims/es5-shim
	var has = Object.prototype.hasOwnProperty;
	var toStr = Object.prototype.toString;
	var isArgs = __nested_webpack_require_4599932__(450); // eslint-disable-line global-require
	var isEnumerable = Object.prototype.propertyIsEnumerable;
	var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
	var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
	var dontEnums = [
		'toString',
		'toLocaleString',
		'valueOf',
		'hasOwnProperty',
		'isPrototypeOf',
		'propertyIsEnumerable',
		'constructor'
	];
	var equalsConstructorPrototype = function (o) {
		var ctor = o.constructor;
		return ctor && ctor.prototype === o;
	};
	var excludedKeys = {
		$applicationCache: true,
		$console: true,
		$external: true,
		$frame: true,
		$frameElement: true,
		$frames: true,
		$innerHeight: true,
		$innerWidth: true,
		$onmozfullscreenchange: true,
		$onmozfullscreenerror: true,
		$outerHeight: true,
		$outerWidth: true,
		$pageXOffset: true,
		$pageYOffset: true,
		$parent: true,
		$scrollLeft: true,
		$scrollTop: true,
		$scrollX: true,
		$scrollY: true,
		$self: true,
		$webkitIndexedDB: true,
		$webkitStorageInfo: true,
		$window: true
	};
	var hasAutomationEqualityBug = (function () {
		/* global window */
		if (typeof window === 'undefined') { return false; }
		for (var k in window) {
			try {
				if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
					try {
						equalsConstructorPrototype(window[k]);
					} catch (e) {
						return true;
					}
				}
			} catch (e) {
				return true;
			}
		}
		return false;
	}());
	var equalsConstructorPrototypeIfNotBuggy = function (o) {
		/* global window */
		if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
			return equalsConstructorPrototype(o);
		}
		try {
			return equalsConstructorPrototype(o);
		} catch (e) {
			return false;
		}
	};

	keysShim = function keys(object) {
		var isObject = object !== null && typeof object === 'object';
		var isFunction = toStr.call(object) === '[object Function]';
		var isArguments = isArgs(object);
		var isString = isObject && toStr.call(object) === '[object String]';
		var theKeys = [];

		if (!isObject && !isFunction && !isArguments) {
			throw new TypeError('Object.keys called on a non-object');
		}

		var skipProto = hasProtoEnumBug && isFunction;
		if (isString && object.length > 0 && !has.call(object, 0)) {
			for (var i = 0; i < object.length; ++i) {
				theKeys.push(String(i));
			}
		}

		if (isArguments && object.length > 0) {
			for (var j = 0; j < object.length; ++j) {
				theKeys.push(String(j));
			}
		} else {
			for (var name in object) {
				if (!(skipProto && name === 'prototype') && has.call(object, name)) {
					theKeys.push(String(name));
				}
			}
		}

		if (hasDontEnumBug) {
			var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);

			for (var k = 0; k < dontEnums.length; ++k) {
				if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
					theKeys.push(dontEnums[k]);
				}
			}
		}
		return theKeys;
	};
}
module.exports = keysShim;


/***/ }),
/* 954 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/* eslint no-invalid-this: 1 */

var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';

module.exports = function bind(that) {
    var target = this;
    if (typeof target !== 'function' || toStr.call(target) !== funcType) {
        throw new TypeError(ERROR_MESSAGE + target);
    }
    var args = slice.call(arguments, 1);

    var bound;
    var binder = function () {
        if (this instanceof bound) {
            var result = target.apply(
                this,
                args.concat(slice.call(arguments))
            );
            if (Object(result) === result) {
                return result;
            }
            return this;
        } else {
            return target.apply(
                that,
                args.concat(slice.call(arguments))
            );
        }
    };

    var boundLength = Math.max(0, target.length - args.length);
    var boundArgs = [];
    for (var i = 0; i < boundLength; i++) {
        boundArgs.push('$' + i);
    }

    bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);

    if (target.prototype) {
        var Empty = function Empty() {};
        Empty.prototype = target.prototype;
        bound.prototype = new Empty();
        Empty.prototype = null;
    }

    return bound;
};


/***/ }),
/* 955 */
/***/ (function(module, exports, __nested_webpack_require_4604773__) {

"use strict";


var define = __nested_webpack_require_4604773__(52);
var getPolyfill = __nested_webpack_require_4604773__(453);

module.exports = function shimAssign() {
	var polyfill = getPolyfill();
	define(
		Object,
		{ assign: polyfill },
		{ assign: function () { return Object.assign !== polyfill; } }
	);
	return polyfill;
};


/***/ }),
/* 956 */
/***/ (function(module) {

module.exports = {"0":65533,"128":8364,"130":8218,"131":402,"132":8222,"133":8230,"134":8224,"135":8225,"136":710,"137":8240,"138":352,"139":8249,"140":338,"142":381,"145":8216,"146":8217,"147":8220,"148":8221,"149":8226,"150":8211,"151":8212,"152":732,"153":8482,"154":353,"155":8250,"156":339,"158":382,"159":376};

/***/ }),
/* 957 */
/***/ (function(module, exports, __nested_webpack_require_4605521__) {

// DOM-Level-1-compliant structure
var NodePrototype = __nested_webpack_require_4605521__(460);
var ElementPrototype = module.exports = Object.create(NodePrototype);

var domLvl1 = {
	tagName: "name"
};

Object.keys(domLvl1).forEach(function(key) {
	var shorthand = domLvl1[key];
	Object.defineProperty(ElementPrototype, key, {
		get: function() {
			return this[shorthand] || null;
		},
		set: function(val) {
			this[shorthand] = val;
			return val;
		}
	});
});


/***/ }),
/* 958 */
/***/ (function(module, exports, __nested_webpack_require_4606050__) {

var DomHandler = __nested_webpack_require_4606050__(459);
var DomUtils = __nested_webpack_require_4606050__(101);

//TODO: make this a streamable handler
function FeedHandler(callback, options) {
    this.init(callback, options);
}

__nested_webpack_require_4606050__(58)(FeedHandler, DomHandler);

FeedHandler.prototype.init = DomHandler;

function getElements(what, where) {
    return DomUtils.getElementsByTagName(what, where, true);
}
function getOneElement(what, where) {
    return DomUtils.getElementsByTagName(what, where, true, 1)[0];
}
function fetch(what, where, recurse) {
    return DomUtils.getText(
        DomUtils.getElementsByTagName(what, where, recurse, 1)
    ).trim();
}

function addConditionally(obj, prop, what, where, recurse) {
    var tmp = fetch(what, where, recurse);
    if (tmp) obj[prop] = tmp;
}

var isValidFeed = function(value) {
    return value === "rss" || value === "feed" || value === "rdf:RDF";
};

FeedHandler.prototype.onend = function() {
    var feed = {},
        feedRoot = getOneElement(isValidFeed, this.dom),
        tmp,
        childs;

    if (feedRoot) {
        if (feedRoot.name === "feed") {
            childs = feedRoot.children;

            feed.type = "atom";
            addConditionally(feed, "id", "id", childs);
            addConditionally(feed, "title", "title", childs);
            if (
                (tmp = getOneElement("link", childs)) &&
                (tmp = tmp.attribs) &&
                (tmp = tmp.href)
            )
                feed.link = tmp;
            addConditionally(feed, "description", "subtitle", childs);
            if ((tmp = fetch("updated", childs))) feed.updated = new Date(tmp);
            addConditionally(feed, "author", "email", childs, true);

            feed.items = getElements("entry", childs).map(function(item) {
                var entry = {},
                    tmp;

                item = item.children;

                addConditionally(entry, "id", "id", item);
                addConditionally(entry, "title", "title", item);
                if (
                    (tmp = getOneElement("link", item)) &&
                    (tmp = tmp.attribs) &&
                    (tmp = tmp.href)
                )
                    entry.link = tmp;
                if ((tmp = fetch("summary", item) || fetch("content", item)))
                    entry.description = tmp;
                if ((tmp = fetch("updated", item)))
                    entry.pubDate = new Date(tmp);
                return entry;
            });
        } else {
            childs = getOneElement("channel", feedRoot.children).children;

            feed.type = feedRoot.name.substr(0, 3);
            feed.id = "";
            addConditionally(feed, "title", "title", childs);
            addConditionally(feed, "link", "link", childs);
            addConditionally(feed, "description", "description", childs);
            if ((tmp = fetch("lastBuildDate", childs)))
                feed.updated = new Date(tmp);
            addConditionally(feed, "author", "managingEditor", childs, true);

            feed.items = getElements("item", feedRoot.children).map(function(
                item
            ) {
                var entry = {},
                    tmp;

                item = item.children;

                addConditionally(entry, "id", "guid", item);
                addConditionally(entry, "title", "title", item);
                addConditionally(entry, "link", "link", item);
                addConditionally(entry, "description", "description", item);
                if ((tmp = fetch("pubDate", item)))
                    entry.pubDate = new Date(tmp);
                return entry;
            });
        }
    }
    this.dom = feed;
    DomHandler.prototype._handleCallback.call(
        this,
        feedRoot ? null : Error("couldn't find root of feed")
    );
};

module.exports = FeedHandler;


/***/ }),
/* 959 */
/***/ (function(module, exports, __nested_webpack_require_4610001__) {

var ElementType = __nested_webpack_require_4610001__(123),
    getOuterHTML = __nested_webpack_require_4610001__(299),
    isTag = ElementType.isTag;

module.exports = {
	getInnerHTML: getInnerHTML,
	getOuterHTML: getOuterHTML,
	getText: getText
};

function getInnerHTML(elem, opts){
	return elem.children ? elem.children.map(function(elem){
		return getOuterHTML(elem, opts);
	}).join("") : "";
}

function getText(elem){
	if(Array.isArray(elem)) return elem.map(getText).join("");
	if(isTag(elem) || elem.type === ElementType.CDATA) return getText(elem.children);
	if(elem.type === ElementType.Text) return elem.data;
	return "";
}


/***/ }),
/* 960 */
/***/ (function(module, exports, __nested_webpack_require_4610685__) {

var encode = __nested_webpack_require_4610685__(961),
    decode = __nested_webpack_require_4610685__(962);

exports.decode = function(data, level) {
    return (!level || level <= 0 ? decode.XML : decode.HTML)(data);
};

exports.decodeStrict = function(data, level) {
    return (!level || level <= 0 ? decode.XML : decode.HTMLStrict)(data);
};

exports.encode = function(data, level) {
    return (!level || level <= 0 ? encode.XML : encode.HTML)(data);
};

exports.encodeXML = encode.XML;

exports.encodeHTML4 = exports.encodeHTML5 = exports.encodeHTML = encode.HTML;

exports.decodeXML = exports.decodeXMLStrict = decode.XML;

exports.decodeHTML4 = exports.decodeHTML5 = exports.decodeHTML = decode.HTML;

exports.decodeHTML4Strict = exports.decodeHTML5Strict = exports.decodeHTMLStrict = decode.HTMLStrict;

exports.escape = encode.escape;


/***/ }),
/* 961 */
/***/ (function(module, exports, __nested_webpack_require_4611579__) {

var inverseXML = getInverseObj(__nested_webpack_require_4611579__(298)),
    xmlReplacer = getInverseReplacer(inverseXML);

exports.XML = getInverse(inverseXML, xmlReplacer);

var inverseHTML = getInverseObj(__nested_webpack_require_4611579__(297)),
    htmlReplacer = getInverseReplacer(inverseHTML);

exports.HTML = getInverse(inverseHTML, htmlReplacer);

function getInverseObj(obj) {
    return Object.keys(obj)
        .sort()
        .reduce(function(inverse, name) {
            inverse[obj[name]] = "&" + name + ";";
            return inverse;
        }, {});
}

function getInverseReplacer(inverse) {
    var single = [],
        multiple = [];

    Object.keys(inverse).forEach(function(k) {
        if (k.length === 1) {
            single.push("\\" + k);
        } else {
            multiple.push(k);
        }
    });

    //TODO add ranges
    multiple.unshift("[" + single.join("") + "]");

    return new RegExp(multiple.join("|"), "g");
}

var re_nonASCII = /[^\0-\x7F]/g,
    re_astralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;

function singleCharReplacer(c) {
    return (
        "&#x" +
        c
            .charCodeAt(0)
            .toString(16)
            .toUpperCase() +
        ";"
    );
}

function astralReplacer(c) {
    // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
    var high = c.charCodeAt(0);
    var low = c.charCodeAt(1);
    var codePoint = (high - 0xd800) * 0x400 + low - 0xdc00 + 0x10000;
    return "&#x" + codePoint.toString(16).toUpperCase() + ";";
}

function getInverse(inverse, re) {
    function func(name) {
        return inverse[name];
    }

    return function(data) {
        return data
            .replace(re, func)
            .replace(re_astralSymbols, astralReplacer)
            .replace(re_nonASCII, singleCharReplacer);
    };
}

var re_xmlChars = getInverseReplacer(inverseXML);

function escapeXML(data) {
    return data
        .replace(re_xmlChars, singleCharReplacer)
        .replace(re_astralSymbols, astralReplacer)
        .replace(re_nonASCII, singleCharReplacer);
}

exports.escape = escapeXML;


/***/ }),
/* 962 */
/***/ (function(module, exports, __nested_webpack_require_4613733__) {

var entityMap = __nested_webpack_require_4613733__(297),
    legacyMap = __nested_webpack_require_4613733__(458),
    xmlMap = __nested_webpack_require_4613733__(298),
    decodeCodePoint = __nested_webpack_require_4613733__(457);

var decodeXMLStrict = getStrictDecoder(xmlMap),
    decodeHTMLStrict = getStrictDecoder(entityMap);

function getStrictDecoder(map) {
    var keys = Object.keys(map).join("|"),
        replace = getReplacer(map);

    keys += "|#[xX][\\da-fA-F]+|#\\d+";

    var re = new RegExp("&(?:" + keys + ");", "g");

    return function(str) {
        return String(str).replace(re, replace);
    };
}

var decodeHTML = (function() {
    var legacy = Object.keys(legacyMap).sort(sorter);

    var keys = Object.keys(entityMap).sort(sorter);

    for (var i = 0, j = 0; i < keys.length; i++) {
        if (legacy[j] === keys[i]) {
            keys[i] += ";?";
            j++;
        } else {
            keys[i] += ";";
        }
    }

    var re = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g"),
        replace = getReplacer(entityMap);

    function replacer(str) {
        if (str.substr(-1) !== ";") str += ";";
        return replace(str);
    }

    //TODO consider creating a merged map
    return function(str) {
        return String(str).replace(re, replacer);
    };
})();

function sorter(a, b) {
    return a < b ? 1 : -1;
}

function getReplacer(map) {
    return function replace(str) {
        if (str.charAt(1) === "#") {
            if (str.charAt(2) === "X" || str.charAt(2) === "x") {
                return decodeCodePoint(parseInt(str.substr(3), 16));
            }
            return decodeCodePoint(parseInt(str.substr(2), 10));
        }
        return map[str.slice(1, -1)];
    };
}

module.exports = {
    XML: decodeXMLStrict,
    HTML: decodeHTML,
    HTMLStrict: decodeHTMLStrict
};


/***/ }),
/* 963 */
/***/ (function(module, exports) {

var getChildren = exports.getChildren = function(elem){
	return elem.children;
};

var getParent = exports.getParent = function(elem){
	return elem.parent;
};

exports.getSiblings = function(elem){
	var parent = getParent(elem);
	return parent ? getChildren(parent) : [elem];
};

exports.getAttributeValue = function(elem, name){
	return elem.attribs && elem.attribs[name];
};

exports.hasAttrib = function(elem, name){
	return !!elem.attribs && hasOwnProperty.call(elem.attribs, name);
};

exports.getName = function(elem){
	return elem.name;
};


/***/ }),
/* 964 */
/***/ (function(module, exports) {

exports.removeElement = function(elem){
	if(elem.prev) elem.prev.next = elem.next;
	if(elem.next) elem.next.prev = elem.prev;

	if(elem.parent){
		var childs = elem.parent.children;
		childs.splice(childs.lastIndexOf(elem), 1);
	}
};

exports.replaceElement = function(elem, replacement){
	var prev = replacement.prev = elem.prev;
	if(prev){
		prev.next = replacement;
	}

	var next = replacement.next = elem.next;
	if(next){
		next.prev = replacement;
	}

	var parent = replacement.parent = elem.parent;
	if(parent){
		var childs = parent.children;
		childs[childs.lastIndexOf(elem)] = replacement;
	}
};

exports.appendChild = function(elem, child){
	child.parent = elem;

	if(elem.children.push(child) !== 1){
		var sibling = elem.children[elem.children.length - 2];
		sibling.next = child;
		child.prev = sibling;
		child.next = null;
	}
};

exports.append = function(elem, next){
	var parent = elem.parent,
		currNext = elem.next;

	next.next = currNext;
	next.prev = elem;
	elem.next = next;
	next.parent = parent;

	if(currNext){
		currNext.prev = next;
		if(parent){
			var childs = parent.children;
			childs.splice(childs.lastIndexOf(currNext), 0, next);
		}
	} else if(parent){
		parent.children.push(next);
	}
};

exports.prepend = function(elem, prev){
	var parent = elem.parent;
	if(parent){
		var childs = parent.children;
		childs.splice(childs.lastIndexOf(elem), 0, prev);
	}

	if(elem.prev){
		elem.prev.next = prev;
	}
	
	prev.parent = parent;
	prev.prev = elem.prev;
	prev.next = elem;
	elem.prev = prev;
};




/***/ }),
/* 965 */
/***/ (function(module, exports, __nested_webpack_require_4617813__) {

var isTag = __nested_webpack_require_4617813__(123).isTag;

module.exports = {
	filter: filter,
	find: find,
	findOneChild: findOneChild,
	findOne: findOne,
	existsOne: existsOne,
	findAll: findAll
};

function filter(test, element, recurse, limit){
	if(!Array.isArray(element)) element = [element];

	if(typeof limit !== "number" || !isFinite(limit)){
		limit = Infinity;
	}
	return find(test, element, recurse !== false, limit);
}

function find(test, elems, recurse, limit){
	var result = [], childs;

	for(var i = 0, j = elems.length; i < j; i++){
		if(test(elems[i])){
			result.push(elems[i]);
			if(--limit <= 0) break;
		}

		childs = elems[i].children;
		if(recurse && childs && childs.length > 0){
			childs = find(test, childs, recurse, limit);
			result = result.concat(childs);
			limit -= childs.length;
			if(limit <= 0) break;
		}
	}

	return result;
}

function findOneChild(test, elems){
	for(var i = 0, l = elems.length; i < l; i++){
		if(test(elems[i])) return elems[i];
	}

	return null;
}

function findOne(test, elems){
	var elem = null;

	for(var i = 0, l = elems.length; i < l && !elem; i++){
		if(!isTag(elems[i])){
			continue;
		} else if(test(elems[i])){
			elem = elems[i];
		} else if(elems[i].children.length > 0){
			elem = findOne(test, elems[i].children);
		}
	}

	return elem;
}

function existsOne(test, elems){
	for(var i = 0, l = elems.length; i < l; i++){
		if(
			isTag(elems[i]) && (
				test(elems[i]) || (
					elems[i].children.length > 0 &&
					existsOne(test, elems[i].children)
				)
			)
		){
			return true;
		}
	}

	return false;
}

function findAll(test, elems){
	var result = [];
	for(var i = 0, j = elems.length; i < j; i++){
		if(!isTag(elems[i])) continue;
		if(test(elems[i])) result.push(elems[i]);

		if(elems[i].children.length > 0){
			result = result.concat(findAll(test, elems[i].children));
		}
	}
	return result;
}


/***/ }),
/* 966 */
/***/ (function(module, exports, __nested_webpack_require_4619758__) {

var ElementType = __nested_webpack_require_4619758__(123);
var isTag = exports.isTag = ElementType.isTag;

exports.testElement = function(options, element){
	for(var key in options){
		if(!options.hasOwnProperty(key));
		else if(key === "tag_name"){
			if(!isTag(element) || !options.tag_name(element.name)){
				return false;
			}
		} else if(key === "tag_type"){
			if(!options.tag_type(element.type)) return false;
		} else if(key === "tag_contains"){
			if(isTag(element) || !options.tag_contains(element.data)){
				return false;
			}
		} else if(!element.attribs || !options[key](element.attribs[key])){
			return false;
		}
	}
	return true;
};

var Checks = {
	tag_name: function(name){
		if(typeof name === "function"){
			return function(elem){ return isTag(elem) && name(elem.name); };
		} else if(name === "*"){
			return isTag;
		} else {
			return function(elem){ return isTag(elem) && elem.name === name; };
		}
	},
	tag_type: function(type){
		if(typeof type === "function"){
			return function(elem){ return type(elem.type); };
		} else {
			return function(elem){ return elem.type === type; };
		}
	},
	tag_contains: function(data){
		if(typeof data === "function"){
			return function(elem){ return !isTag(elem) && data(elem.data); };
		} else {
			return function(elem){ return !isTag(elem) && elem.data === data; };
		}
	}
};

function getAttribCheck(attrib, value){
	if(typeof value === "function"){
		return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
	} else {
		return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
	}
}

function combineFuncs(a, b){
	return function(elem){
		return a(elem) || b(elem);
	};
}

exports.getElements = function(options, element, recurse, limit){
	var funcs = Object.keys(options).map(function(key){
		var value = options[key];
		return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
	});

	return funcs.length === 0 ? [] : this.filter(
		funcs.reduce(combineFuncs),
		element, recurse, limit
	);
};

exports.getElementById = function(id, element, recurse){
	if(!Array.isArray(element)) element = [element];
	return this.findOne(getAttribCheck("id", id), element, recurse !== false);
};

exports.getElementsByTagName = function(name, element, recurse, limit){
	return this.filter(Checks.tag_name(name), element, recurse, limit);
};

exports.getElementsByTagType = function(type, element, recurse, limit){
	return this.filter(Checks.tag_type(type), element, recurse, limit);
};


/***/ }),
/* 967 */
/***/ (function(module, exports) {

// removeSubsets
// Given an array of nodes, remove any member that is contained by another.
exports.removeSubsets = function(nodes) {
	var idx = nodes.length, node, ancestor, replace;

	// Check if each node (or one of its ancestors) is already contained in the
	// array.
	while (--idx > -1) {
		node = ancestor = nodes[idx];

		// Temporarily remove the node under consideration
		nodes[idx] = null;
		replace = true;

		while (ancestor) {
			if (nodes.indexOf(ancestor) > -1) {
				replace = false;
				nodes.splice(idx, 1);
				break;
			}
			ancestor = ancestor.parent;
		}

		// If the node has been found to be unique, re-insert it.
		if (replace) {
			nodes[idx] = node;
		}
	}

	return nodes;
};

// Source: http://dom.spec.whatwg.org/#dom-node-comparedocumentposition
var POSITION = {
	DISCONNECTED: 1,
	PRECEDING: 2,
	FOLLOWING: 4,
	CONTAINS: 8,
	CONTAINED_BY: 16
};

// Compare the position of one node against another node in any other document.
// The return value is a bitmask with the following values:
//
// document order:
// > There is an ordering, document order, defined on all the nodes in the
// > document corresponding to the order in which the first character of the
// > XML representation of each node occurs in the XML representation of the
// > document after expansion of general entities. Thus, the document element
// > node will be the first node. Element nodes occur before their children.
// > Thus, document order orders element nodes in order of the occurrence of
// > their start-tag in the XML (after expansion of entities). The attribute
// > nodes of an element occur after the element and before its children. The
// > relative order of attribute nodes is implementation-dependent./
// Source:
// http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
//
// @argument {Node} nodaA The first node to use in the comparison
// @argument {Node} nodeB The second node to use in the comparison
//
// @return {Number} A bitmask describing the input nodes' relative position.
//         See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
//         a description of these values.
var comparePos = exports.compareDocumentPosition = function(nodeA, nodeB) {
	var aParents = [];
	var bParents = [];
	var current, sharedParent, siblings, aSibling, bSibling, idx;

	if (nodeA === nodeB) {
		return 0;
	}

	current = nodeA;
	while (current) {
		aParents.unshift(current);
		current = current.parent;
	}
	current = nodeB;
	while (current) {
		bParents.unshift(current);
		current = current.parent;
	}

	idx = 0;
	while (aParents[idx] === bParents[idx]) {
		idx++;
	}

	if (idx === 0) {
		return POSITION.DISCONNECTED;
	}

	sharedParent = aParents[idx - 1];
	siblings = sharedParent.children;
	aSibling = aParents[idx];
	bSibling = bParents[idx];

	if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
		if (sharedParent === nodeB) {
			return POSITION.FOLLOWING | POSITION.CONTAINED_BY;
		}
		return POSITION.FOLLOWING;
	} else {
		if (sharedParent === nodeA) {
			return POSITION.PRECEDING | POSITION.CONTAINS;
		}
		return POSITION.PRECEDING;
	}
};

// Sort an array of nodes based on their relative position in the document and
// remove any duplicate nodes. If the array contains nodes that do not belong
// to the same document, sort order is unspecified.
//
// @argument {Array} nodes Array of DOM nodes
//
// @returns {Array} collection of unique nodes, sorted in document order
exports.uniqueSort = function(nodes) {
	var idx = nodes.length, node, position;

	nodes = nodes.slice();

	while (--idx > -1) {
		node = nodes[idx];
		position = nodes.indexOf(node);
		if (position > -1 && position < idx) {
			nodes.splice(idx, 1);
		}
	}
	nodes.sort(function(a, b) {
		var relative = comparePos(a, b);
		if (relative & POSITION.PRECEDING) {
			return -1;
		} else if (relative & POSITION.FOLLOWING) {
			return 1;
		}
		return 0;
	});

	return nodes;
};


/***/ }),
/* 968 */
/***/ (function(module, exports, __nested_webpack_require_4626313__) {

module.exports = Stream;

var Parser = __nested_webpack_require_4626313__(461);

function Stream(options) {
    Parser.call(this, new Cbs(this), options);
}

__nested_webpack_require_4626313__(58)(Stream, Parser);

Stream.prototype.readable = true;

function Cbs(scope) {
    this.scope = scope;
}

var EVENTS = __nested_webpack_require_4626313__(148).EVENTS;

Object.keys(EVENTS).forEach(function(name) {
    if (EVENTS[name] === 0) {
        Cbs.prototype["on" + name] = function() {
            this.scope.emit(name);
        };
    } else if (EVENTS[name] === 1) {
        Cbs.prototype["on" + name] = function(a) {
            this.scope.emit(name, a);
        };
    } else if (EVENTS[name] === 2) {
        Cbs.prototype["on" + name] = function(a, b) {
            this.scope.emit(name, a, b);
        };
    } else {
        throw Error("wrong number of arguments!");
    }
});


/***/ }),
/* 969 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 970 */
/***/ (function(module, exports, __nested_webpack_require_4627306__) {

module.exports = ProxyHandler;

function ProxyHandler(cbs) {
    this._cbs = cbs || {};
}

var EVENTS = __nested_webpack_require_4627306__(148).EVENTS;
Object.keys(EVENTS).forEach(function(name) {
    if (EVENTS[name] === 0) {
        name = "on" + name;
        ProxyHandler.prototype[name] = function() {
            if (this._cbs[name]) this._cbs[name]();
        };
    } else if (EVENTS[name] === 1) {
        name = "on" + name;
        ProxyHandler.prototype[name] = function(a) {
            if (this._cbs[name]) this._cbs[name](a);
        };
    } else if (EVENTS[name] === 2) {
        name = "on" + name;
        ProxyHandler.prototype[name] = function(a, b) {
            if (this._cbs[name]) this._cbs[name](a, b);
        };
    } else {
        throw Error("wrong number of arguments");
    }
});


/***/ }),
/* 971 */
/***/ (function(module, exports, __nested_webpack_require_4628183__) {

module.exports = CollectingHandler;

function CollectingHandler(cbs) {
    this._cbs = cbs || {};
    this.events = [];
}

var EVENTS = __nested_webpack_require_4628183__(148).EVENTS;
Object.keys(EVENTS).forEach(function(name) {
    if (EVENTS[name] === 0) {
        name = "on" + name;
        CollectingHandler.prototype[name] = function() {
            this.events.push([name]);
            if (this._cbs[name]) this._cbs[name]();
        };
    } else if (EVENTS[name] === 1) {
        name = "on" + name;
        CollectingHandler.prototype[name] = function(a) {
            this.events.push([name, a]);
            if (this._cbs[name]) this._cbs[name](a);
        };
    } else if (EVENTS[name] === 2) {
        name = "on" + name;
        CollectingHandler.prototype[name] = function(a, b) {
            this.events.push([name, a, b]);
            if (this._cbs[name]) this._cbs[name](a, b);
        };
    } else {
        throw Error("wrong number of arguments");
    }
});

CollectingHandler.prototype.onreset = function() {
    this.events = [];
    if (this._cbs.onreset) this._cbs.onreset();
};

CollectingHandler.prototype.restart = function() {
    if (this._cbs.onreset) this._cbs.onreset();

    for (var i = 0, len = this.events.length; i < len; i++) {
        if (this._cbs[this.events[i][0]]) {
            var num = this.events[i].length;

            if (num === 1) {
                this._cbs[this.events[i][0]]();
            } else if (num === 2) {
                this._cbs[this.events[i][0]](this.events[i][1]);
            } else {
                this._cbs[this.events[i][0]](
                    this.events[i][1],
                    this.events[i][2]
                );
            }
        }
    }
};


/***/ }),
/* 972 */
/***/ (function(module, exports, __nested_webpack_require_4629982__) {

"use strict";


var Parser = __nested_webpack_require_4629982__(462),
    Serializer = __nested_webpack_require_4629982__(466);


// Shorthands
exports.parse = function parse(html, options) {
    var parser = new Parser(options);

    return parser.parse(html);
};

exports.parseFragment = function parseFragment(fragmentContext, html, options) {
    if (typeof fragmentContext === 'string') {
        options = html;
        html = fragmentContext;
        fragmentContext = null;
    }

    var parser = new Parser(options);

    return parser.parseFragment(html, fragmentContext);
};

exports.serialize = function (node, options) {
    var serializer = new Serializer(node, options);

    return serializer.serialize();
};


// Tree adapters
exports.treeAdapters = {
    default: __nested_webpack_require_4629982__(301),
    htmlparser2: __nested_webpack_require_4629982__(980)
};


// Streaming
exports.ParserStream = __nested_webpack_require_4629982__(467);
exports.PlainTextConversionStream = __nested_webpack_require_4629982__(992);
exports.SerializerStream = __nested_webpack_require_4629982__(993);
exports.SAXParser = __nested_webpack_require_4629982__(994);


/***/ }),
/* 973 */
/***/ (function(module, exports, __nested_webpack_require_4631110__) {

"use strict";


var UNICODE = __nested_webpack_require_4631110__(149);

//Aliases
var $ = UNICODE.CODE_POINTS;

//Utils

//OPTIMIZATION: these utility functions should not be moved out of this module. V8 Crankshaft will not inline
//this functions if they will be situated in another module due to context switch.
//Always perform inlining check before modifying this functions ('node --trace-inlining').
function isSurrogatePair(cp1, cp2) {
    return cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF;
}

function getSurrogatePairCodePoint(cp1, cp2) {
    return (cp1 - 0xD800) * 0x400 + 0x2400 + cp2;
}


//Const
var DEFAULT_BUFFER_WATERLINE = 1 << 16;


//Preprocessor
//NOTE: HTML input preprocessing
//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#preprocessing-the-input-stream)
var Preprocessor = module.exports = function () {
    this.html = null;

    this.pos = -1;
    this.lastGapPos = -1;
    this.lastCharPos = -1;

    this.gapStack = [];

    this.skipNextNewLine = false;

    this.lastChunkWritten = false;
    this.endOfChunkHit = false;
    this.bufferWaterline = DEFAULT_BUFFER_WATERLINE;
};

Preprocessor.prototype.dropParsedChunk = function () {
    if (this.pos > this.bufferWaterline) {
        this.lastCharPos -= this.pos;
        this.html = this.html.substring(this.pos);
        this.pos = 0;
        this.lastGapPos = -1;
        this.gapStack = [];
    }
};

Preprocessor.prototype._addGap = function () {
    this.gapStack.push(this.lastGapPos);
    this.lastGapPos = this.pos;
};

Preprocessor.prototype._processHighRangeCodePoint = function (cp) {
    //NOTE: try to peek a surrogate pair
    if (this.pos !== this.lastCharPos) {
        var nextCp = this.html.charCodeAt(this.pos + 1);

        if (isSurrogatePair(cp, nextCp)) {
            //NOTE: we have a surrogate pair. Peek pair character and recalculate code point.
            this.pos++;
            cp = getSurrogatePairCodePoint(cp, nextCp);

            //NOTE: add gap that should be avoided during retreat
            this._addGap();
        }
    }

    // NOTE: we've hit the end of chunk, stop processing at this point
    else if (!this.lastChunkWritten) {
        this.endOfChunkHit = true;
        return $.EOF;
    }

    return cp;
};

Preprocessor.prototype.write = function (chunk, isLastChunk) {
    if (this.html)
        this.html += chunk;

    else
        this.html = chunk;

    this.lastCharPos = this.html.length - 1;
    this.endOfChunkHit = false;
    this.lastChunkWritten = isLastChunk;
};

Preprocessor.prototype.insertHtmlAtCurrentPos = function (chunk) {
    this.html = this.html.substring(0, this.pos + 1) +
                chunk +
                this.html.substring(this.pos + 1, this.html.length);

    this.lastCharPos = this.html.length - 1;
    this.endOfChunkHit = false;
};


Preprocessor.prototype.advance = function () {
    this.pos++;

    if (this.pos > this.lastCharPos) {
        if (!this.lastChunkWritten)
            this.endOfChunkHit = true;

        return $.EOF;
    }

    var cp = this.html.charCodeAt(this.pos);

    //NOTE: any U+000A LINE FEED (LF) characters that immediately follow a U+000D CARRIAGE RETURN (CR) character
    //must be ignored.
    if (this.skipNextNewLine && cp === $.LINE_FEED) {
        this.skipNextNewLine = false;
        this._addGap();
        return this.advance();
    }

    //NOTE: all U+000D CARRIAGE RETURN (CR) characters must be converted to U+000A LINE FEED (LF) characters
    if (cp === $.CARRIAGE_RETURN) {
        this.skipNextNewLine = true;
        return $.LINE_FEED;
    }

    this.skipNextNewLine = false;

    //OPTIMIZATION: first perform check if the code point in the allowed range that covers most common
    //HTML input (e.g. ASCII codes) to avoid performance-cost operations for high-range code points.
    return cp >= 0xD800 ? this._processHighRangeCodePoint(cp) : cp;
};

Preprocessor.prototype.retreat = function () {
    if (this.pos === this.lastGapPos) {
        this.lastGapPos = this.gapStack.pop();
        this.pos--;
    }

    this.pos--;
};



/***/ }),
/* 974 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//NOTE: this file contains auto-generated array mapped radix tree that is used for the named entity references consumption
//(details: https://github.com/inikulin/parse5/tree/master/scripts/generate_named_entity_data/README.md)
module.exports = new Uint16Array([4,52,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,106,303,412,810,1432,1701,1796,1987,2114,2360,2420,2484,3170,3251,4140,4393,4575,4610,5106,5512,5728,6117,6274,6315,6345,6427,6516,7002,7910,8733,9323,9870,10170,10631,10893,11318,11386,11467,12773,13092,14474,14922,15448,15542,16419,17666,18166,18611,19004,19095,19298,19397,4,16,69,77,97,98,99,102,103,108,109,110,111,112,114,115,116,117,140,150,158,169,176,194,199,210,216,222,226,242,256,266,283,294,108,105,103,5,198,1,59,148,1,198,80,5,38,1,59,156,1,38,99,117,116,101,5,193,1,59,167,1,193,114,101,118,101,59,1,258,4,2,105,121,182,191,114,99,5,194,1,59,189,1,194,59,1,1040,114,59,3,55349,56580,114,97,118,101,5,192,1,59,208,1,192,112,104,97,59,1,913,97,99,114,59,1,256,100,59,1,10835,4,2,103,112,232,237,111,110,59,1,260,102,59,3,55349,56632,112,108,121,70,117,110,99,116,105,111,110,59,1,8289,105,110,103,5,197,1,59,264,1,197,4,2,99,115,272,277,114,59,3,55349,56476,105,103,110,59,1,8788,105,108,100,101,5,195,1,59,292,1,195,109,108,5,196,1,59,301,1,196,4,8,97,99,101,102,111,114,115,117,321,350,354,383,388,394,400,405,4,2,99,114,327,336,107,115,108,97,115,104,59,1,8726,4,2,118,119,342,345,59,1,10983,101,100,59,1,8966,121,59,1,1041,4,3,99,114,116,362,369,379,97,117,115,101,59,1,8757,110,111,117,108,108,105,115,59,1,8492,97,59,1,914,114,59,3,55349,56581,112,102,59,3,55349,56633,101,118,101,59,1,728,99,114,59,1,8492,109,112,101,113,59,1,8782,4,14,72,79,97,99,100,101,102,104,105,108,111,114,115,117,442,447,456,504,542,547,569,573,577,616,678,784,790,796,99,121,59,1,1063,80,89,5,169,1,59,454,1,169,4,3,99,112,121,464,470,497,117,116,101,59,1,262,4,2,59,105,476,478,1,8914,116,97,108,68,105,102,102,101,114,101,110,116,105,97,108,68,59,1,8517,108,101,121,115,59,1,8493,4,4,97,101,105,111,514,520,530,535,114,111,110,59,1,268,100,105,108,5,199,1,59,528,1,199,114,99,59,1,264,110,105,110,116,59,1,8752,111,116,59,1,266,4,2,100,110,553,560,105,108,108,97,59,1,184,116,101,114,68,111,116,59,1,183,114,59,1,8493,105,59,1,935,114,99,108,101,4,4,68,77,80,84,591,596,603,609,111,116,59,1,8857,105,110,117,115,59,1,8854,108,117,115,59,1,8853,105,109,101,115,59,1,8855,111,4,2,99,115,623,646,107,119,105,115,101,67,111,110,116,111,117,114,73,110,116,101,103,114,97,108,59,1,8754,101,67,117,114,108,121,4,2,68,81,658,671,111,117,98,108,101,81,117,111,116,101,59,1,8221,117,111,116,101,59,1,8217,4,4,108,110,112,117,688,701,736,753,111,110,4,2,59,101,696,698,1,8759,59,1,10868,4,3,103,105,116,709,717,722,114,117,101,110,116,59,1,8801,110,116,59,1,8751,111,117,114,73,110,116,101,103,114,97,108,59,1,8750,4,2,102,114,742,745,59,1,8450,111,100,117,99,116,59,1,8720,110,116,101,114,67,108,111,99,107,119,105,115,101,67,111,110,116,111,117,114,73,110,116,101,103,114,97,108,59,1,8755,111,115,115,59,1,10799,99,114,59,3,55349,56478,112,4,2,59,67,803,805,1,8915,97,112,59,1,8781,4,11,68,74,83,90,97,99,101,102,105,111,115,834,850,855,860,865,888,903,916,921,1011,1415,4,2,59,111,840,842,1,8517,116,114,97,104,100,59,1,10513,99,121,59,1,1026,99,121,59,1,1029,99,121,59,1,1039,4,3,103,114,115,873,879,883,103,101,114,59,1,8225,114,59,1,8609,104,118,59,1,10980,4,2,97,121,894,900,114,111,110,59,1,270,59,1,1044,108,4,2,59,116,910,912,1,8711,97,59,1,916,114,59,3,55349,56583,4,2,97,102,927,998,4,2,99,109,933,992,114,105,116,105,99,97,108,4,4,65,68,71,84,950,957,978,985,99,117,116,101,59,1,180,111,4,2,116,117,964,967,59,1,729,98,108,101,65,99,117,116,101,59,1,733,114,97,118,101,59,1,96,105,108,100,101,59,1,732,111,110,100,59,1,8900,102,101,114,101,110,116,105,97,108,68,59,1,8518,4,4,112,116,117,119,1021,1026,1048,1249,102,59,3,55349,56635,4,3,59,68,69,1034,1036,1041,1,168,111,116,59,1,8412,113,117,97,108,59,1,8784,98,108,101,4,6,67,68,76,82,85,86,1065,1082,1101,1189,1211,1236,111,110,116,111,117,114,73,110,116,101,103,114,97,108,59,1,8751,111,4,2,116,119,1089,1092,59,1,168,110,65,114,114,111,119,59,1,8659,4,2,101,111,1107,1141,102,116,4,3,65,82,84,1117,1124,1136,114,114,111,119,59,1,8656,105,103,104,116,65,114,114,111,119,59,1,8660,101,101,59,1,10980,110,103,4,2,76,82,1149,1177,101,102,116,4,2,65,82,1158,1165,114,114,111,119,59,1,10232,105,103,104,116,65,114,114,111,119,59,1,10234,105,103,104,116,65,114,114,111,119,59,1,10233,105,103,104,116,4,2,65,84,1199,1206,114,114,111,119,59,1,8658,101,101,59,1,8872,112,4,2,65,68,1218,1225,114,114,111,119,59,1,8657,111,119,110,65,114,114,111,119,59,1,8661,101,114,116,105,99,97,108,66,97,114,59,1,8741,110,4,6,65,66,76,82,84,97,1264,1292,1299,1352,1391,1408,114,114,111,119,4,3,59,66,85,1276,1278,1283,1,8595,97,114,59,1,10515,112,65,114,114,111,119,59,1,8693,114,101,118,101,59,1,785,101,102,116,4,3,82,84,86,1310,1323,1334,105,103,104,116,86,101,99,116,111,114,59,1,10576,101,101,86,101,99,116,111,114,59,1,10590,101,99,116,111,114,4,2,59,66,1345,1347,1,8637,97,114,59,1,10582,105,103,104,116,4,2,84,86,1362,1373,101,101,86,101,99,116,111,114,59,1,10591,101,99,116,111,114,4,2,59,66,1384,1386,1,8641,97,114,59,1,10583,101,101,4,2,59,65,1399,1401,1,8868,114,114,111,119,59,1,8615,114,114,111,119,59,1,8659,4,2,99,116,1421,1426,114,59,3,55349,56479,114,111,107,59,1,272,4,16,78,84,97,99,100,102,103,108,109,111,112,113,115,116,117,120,1466,1470,1478,1489,1515,1520,1525,1536,1544,1593,1609,1617,1650,1664,1668,1677,71,59,1,330,72,5,208,1,59,1476,1,208,99,117,116,101,5,201,1,59,1487,1,201,4,3,97,105,121,1497,1503,1512,114,111,110,59,1,282,114,99,5,202,1,59,1510,1,202,59,1,1069,111,116,59,1,278,114,59,3,55349,56584,114,97,118,101,5,200,1,59,1534,1,200,101,109,101,110,116,59,1,8712,4,2,97,112,1550,1555,99,114,59,1,274,116,121,4,2,83,86,1563,1576,109,97,108,108,83,113,117,97,114,101,59,1,9723,101,114,121,83,109,97,108,108,83,113,117,97,114,101,59,1,9643,4,2,103,112,1599,1604,111,110,59,1,280,102,59,3,55349,56636,115,105,108,111,110,59,1,917,117,4,2,97,105,1624,1640,108,4,2,59,84,1631,1633,1,10869,105,108,100,101,59,1,8770,108,105,98,114,105,117,109,59,1,8652,4,2,99,105,1656,1660,114,59,1,8496,109,59,1,10867,97,59,1,919,109,108,5,203,1,59,1675,1,203,4,2,105,112,1683,1689,115,116,115,59,1,8707,111,110,101,110,116,105,97,108,69,59,1,8519,4,5,99,102,105,111,115,1713,1717,1722,1762,1791,121,59,1,1060,114,59,3,55349,56585,108,108,101,100,4,2,83,86,1732,1745,109,97,108,108,83,113,117,97,114,101,59,1,9724,101,114,121,83,109,97,108,108,83,113,117,97,114,101,59,1,9642,4,3,112,114,117,1770,1775,1781,102,59,3,55349,56637,65,108,108,59,1,8704,114,105,101,114,116,114,102,59,1,8497,99,114,59,1,8497,4,12,74,84,97,98,99,100,102,103,111,114,115,116,1822,1827,1834,1848,1855,1877,1882,1887,1890,1896,1978,1984,99,121,59,1,1027,5,62,1,59,1832,1,62,109,109,97,4,2,59,100,1843,1845,1,915,59,1,988,114,101,118,101,59,1,286,4,3,101,105,121,1863,1869,1874,100,105,108,59,1,290,114,99,59,1,284,59,1,1043,111,116,59,1,288,114,59,3,55349,56586,59,1,8921,112,102,59,3,55349,56638,101,97,116,101,114,4,6,69,70,71,76,83,84,1915,1933,1944,1953,1959,1971,113,117,97,108,4,2,59,76,1925,1927,1,8805,101,115,115,59,1,8923,117,108,108,69,113,117,97,108,59,1,8807,114,101,97,116,101,114,59,1,10914,101,115,115,59,1,8823,108,97,110,116,69,113,117,97,108,59,1,10878,105,108,100,101,59,1,8819,99,114,59,3,55349,56482,59,1,8811,4,8,65,97,99,102,105,111,115,117,2005,2012,2026,2032,2036,2049,2073,2089,82,68,99,121,59,1,1066,4,2,99,116,2018,2023,101,107,59,1,711,59,1,94,105,114,99,59,1,292,114,59,1,8460,108,98,101,114,116,83,112,97,99,101,59,1,8459,4,2,112,114,2055,2059,102,59,1,8461,105,122,111,110,116,97,108,76,105,110,101,59,1,9472,4,2,99,116,2079,2083,114,59,1,8459,114,111,107,59,1,294,109,112,4,2,68,69,2097,2107,111,119,110,72,117,109,112,59,1,8782,113,117,97,108,59,1,8783,4,14,69,74,79,97,99,100,102,103,109,110,111,115,116,117,2144,2149,2155,2160,2171,2189,2194,2198,2209,2245,2307,2329,2334,2341,99,121,59,1,1045,108,105,103,59,1,306,99,121,59,1,1025,99,117,116,101,5,205,1,59,2169,1,205,4,2,105,121,2177,2186,114,99,5,206,1,59,2184,1,206,59,1,1048,111,116,59,1,304,114,59,1,8465,114,97,118,101,5,204,1,59,2207,1,204,4,3,59,97,112,2217,2219,2238,1,8465,4,2,99,103,2225,2229,114,59,1,298,105,110,97,114,121,73,59,1,8520,108,105,101,115,59,1,8658,4,2,116,118,2251,2281,4,2,59,101,2257,2259,1,8748,4,2,103,114,2265,2271,114,97,108,59,1,8747,115,101,99,116,105,111,110,59,1,8898,105,115,105,98,108,101,4,2,67,84,2293,2300,111,109,109,97,59,1,8291,105,109,101,115,59,1,8290,4,3,103,112,116,2315,2320,2325,111,110,59,1,302,102,59,3,55349,56640,97,59,1,921,99,114,59,1,8464,105,108,100,101,59,1,296,4,2,107,109,2347,2352,99,121,59,1,1030,108,5,207,1,59,2358,1,207,4,5,99,102,111,115,117,2372,2386,2391,2397,2414,4,2,105,121,2378,2383,114,99,59,1,308,59,1,1049,114,59,3,55349,56589,112,102,59,3,55349,56641,4,2,99,101,2403,2408,114,59,3,55349,56485,114,99,121,59,1,1032,107,99,121,59,1,1028,4,7,72,74,97,99,102,111,115,2436,2441,2446,2452,2467,2472,2478,99,121,59,1,1061,99,121,59,1,1036,112,112,97,59,1,922,4,2,101,121,2458,2464,100,105,108,59,1,310,59,1,1050,114,59,3,55349,56590,112,102,59,3,55349,56642,99,114,59,3,55349,56486,4,11,74,84,97,99,101,102,108,109,111,115,116,2508,2513,2520,2562,2585,2981,2986,3004,3011,3146,3167,99,121,59,1,1033,5,60,1,59,2518,1,60,4,5,99,109,110,112,114,2532,2538,2544,2548,2558,117,116,101,59,1,313,98,100,97,59,1,923,103,59,1,10218,108,97,99,101,116,114,102,59,1,8466,114,59,1,8606,4,3,97,101,121,2570,2576,2582,114,111,110,59,1,317,100,105,108,59,1,315,59,1,1051,4,2,102,115,2591,2907,116,4,10,65,67,68,70,82,84,85,86,97,114,2614,2663,2672,2728,2735,2760,2820,2870,2888,2895,4,2,110,114,2620,2633,103,108,101,66,114,97,99,107,101,116,59,1,10216,114,111,119,4,3,59,66,82,2644,2646,2651,1,8592,97,114,59,1,8676,105,103,104,116,65,114,114,111,119,59,1,8646,101,105,108,105,110,103,59,1,8968,111,4,2,117,119,2679,2692,98,108,101,66,114,97,99,107,101,116,59,1,10214,110,4,2,84,86,2699,2710,101,101,86,101,99,116,111,114,59,1,10593,101,99,116,111,114,4,2,59,66,2721,2723,1,8643,97,114,59,1,10585,108,111,111,114,59,1,8970,105,103,104,116,4,2,65,86,2745,2752,114,114,111,119,59,1,8596,101,99,116,111,114,59,1,10574,4,2,101,114,2766,2792,101,4,3,59,65,86,2775,2777,2784,1,8867,114,114,111,119,59,1,8612,101,99,116,111,114,59,1,10586,105,97,110,103,108,101,4,3,59,66,69,2806,2808,2813,1,8882,97,114,59,1,10703,113,117,97,108,59,1,8884,112,4,3,68,84,86,2829,2841,2852,111,119,110,86,101,99,116,111,114,59,1,10577,101,101,86,101,99,116,111,114,59,1,10592,101,99,116,111,114,4,2,59,66,2863,2865,1,8639,97,114,59,1,10584,101,99,116,111,114,4,2,59,66,2881,2883,1,8636,97,114,59,1,10578,114,114,111,119,59,1,8656,105,103,104,116,97,114,114,111,119,59,1,8660,115,4,6,69,70,71,76,83,84,2922,2936,2947,2956,2962,2974,113,117,97,108,71,114,101,97,116,101,114,59,1,8922,117,108,108,69,113,117,97,108,59,1,8806,114,101,97,116,101,114,59,1,8822,101,115,115,59,1,10913,108,97,110,116,69,113,117,97,108,59,1,10877,105,108,100,101,59,1,8818,114,59,3,55349,56591,4,2,59,101,2992,2994,1,8920,102,116,97,114,114,111,119,59,1,8666,105,100,111,116,59,1,319,4,3,110,112,119,3019,3110,3115,103,4,4,76,82,108,114,3030,3058,3070,3098,101,102,116,4,2,65,82,3039,3046,114,114,111,119,59,1,10229,105,103,104,116,65,114,114,111,119,59,1,10231,105,103,104,116,65,114,114,111,119,59,1,10230,101,102,116,4,2,97,114,3079,3086,114,114,111,119,59,1,10232,105,103,104,116,97,114,114,111,119,59,1,10234,105,103,104,116,97,114,114,111,119,59,1,10233,102,59,3,55349,56643,101,114,4,2,76,82,3123,3134,101,102,116,65,114,114,111,119,59,1,8601,105,103,104,116,65,114,114,111,119,59,1,8600,4,3,99,104,116,3154,3158,3161,114,59,1,8466,59,1,8624,114,111,107,59,1,321,59,1,8810,4,8,97,99,101,102,105,111,115,117,3188,3192,3196,3222,3227,3237,3243,3248,112,59,1,10501,121,59,1,1052,4,2,100,108,3202,3213,105,117,109,83,112,97,99,101,59,1,8287,108,105,110,116,114,102,59,1,8499,114,59,3,55349,56592,110,117,115,80,108,117,115,59,1,8723,112,102,59,3,55349,56644,99,114,59,1,8499,59,1,924,4,9,74,97,99,101,102,111,115,116,117,3271,3276,3283,3306,3422,3427,4120,4126,4137,99,121,59,1,1034,99,117,116,101,59,1,323,4,3,97,101,121,3291,3297,3303,114,111,110,59,1,327,100,105,108,59,1,325,59,1,1053,4,3,103,115,119,3314,3380,3415,97,116,105,118,101,4,3,77,84,86,3327,3340,3365,101,100,105,117,109,83,112,97,99,101,59,1,8203,104,105,4,2,99,110,3348,3357,107,83,112,97,99,101,59,1,8203,83,112,97,99,101,59,1,8203,101,114,121,84,104,105,110,83,112,97,99,101,59,1,8203,116,101,100,4,2,71,76,3389,3405,114,101,97,116,101,114,71,114,101,97,116,101,114,59,1,8811,101,115,115,76,101,115,115,59,1,8810,76,105,110,101,59,1,10,114,59,3,55349,56593,4,4,66,110,112,116,3437,3444,3460,3464,114,101,97,107,59,1,8288,66,114,101,97,107,105,110,103,83,112,97,99,101,59,1,160,102,59,1,8469,4,13,59,67,68,69,71,72,76,78,80,82,83,84,86,3492,3494,3517,3536,3578,3657,3685,3784,3823,3860,3915,4066,4107,1,10988,4,2,111,117,3500,3510,110,103,114,117,101,110,116,59,1,8802,112,67,97,112,59,1,8813,111,117,98,108,101,86,101,114,116,105,99,97,108,66,97,114,59,1,8742,4,3,108,113,120,3544,3552,3571,101,109,101,110,116,59,1,8713,117,97,108,4,2,59,84,3561,3563,1,8800,105,108,100,101,59,3,8770,824,105,115,116,115,59,1,8708,114,101,97,116,101,114,4,7,59,69,70,71,76,83,84,3600,3602,3609,3621,3631,3637,3650,1,8815,113,117,97,108,59,1,8817,117,108,108,69,113,117,97,108,59,3,8807,824,114,101,97,116,101,114,59,3,8811,824,101,115,115,59,1,8825,108,97,110,116,69,113,117,97,108,59,3,10878,824,105,108,100,101,59,1,8821,117,109,112,4,2,68,69,3666,3677,111,119,110,72,117,109,112,59,3,8782,824,113,117,97,108,59,3,8783,824,101,4,2,102,115,3692,3724,116,84,114,105,97,110,103,108,101,4,3,59,66,69,3709,3711,3717,1,8938,97,114,59,3,10703,824,113,117,97,108,59,1,8940,115,4,6,59,69,71,76,83,84,3739,3741,3748,3757,3764,3777,1,8814,113,117,97,108,59,1,8816,114,101,97,116,101,114,59,1,8824,101,115,115,59,3,8810,824,108,97,110,116,69,113,117,97,108,59,3,10877,824,105,108,100,101,59,1,8820,101,115,116,101,100,4,2,71,76,3795,3812,114,101,97,116,101,114,71,114,101,97,116,101,114,59,3,10914,824,101,115,115,76,101,115,115,59,3,10913,824,114,101,99,101,100,101,115,4,3,59,69,83,3838,3840,3848,1,8832,113,117,97,108,59,3,10927,824,108,97,110,116,69,113,117,97,108,59,1,8928,4,2,101,105,3866,3881,118,101,114,115,101,69,108,101,109,101,110,116,59,1,8716,103,104,116,84,114,105,97,110,103,108,101,4,3,59,66,69,3900,3902,3908,1,8939,97,114,59,3,10704,824,113,117,97,108,59,1,8941,4,2,113,117,3921,3973,117,97,114,101,83,117,4,2,98,112,3933,3952,115,101,116,4,2,59,69,3942,3945,3,8847,824,113,117,97,108,59,1,8930,101,114,115,101,116,4,2,59,69,3963,3966,3,8848,824,113,117,97,108,59,1,8931,4,3,98,99,112,3981,4000,4045,115,101,116,4,2,59,69,3990,3993,3,8834,8402,113,117,97,108,59,1,8840,99,101,101,100,115,4,4,59,69,83,84,4015,4017,4025,4037,1,8833,113,117,97,108,59,3,10928,824,108,97,110,116,69,113,117,97,108,59,1,8929,105,108,100,101,59,3,8831,824,101,114,115,101,116,4,2,59,69,4056,4059,3,8835,8402,113,117,97,108,59,1,8841,105,108,100,101,4,4,59,69,70,84,4080,4082,4089,4100,1,8769,113,117,97,108,59,1,8772,117,108,108,69,113,117,97,108,59,1,8775,105,108,100,101,59,1,8777,101,114,116,105,99,97,108,66,97,114,59,1,8740,99,114,59,3,55349,56489,105,108,100,101,5,209,1,59,4135,1,209,59,1,925,4,14,69,97,99,100,102,103,109,111,112,114,115,116,117,118,4170,4176,4187,4205,4212,4217,4228,4253,4259,4292,4295,4316,4337,4346,108,105,103,59,1,338,99,117,116,101,5,211,1,59,4185,1,211,4,2,105,121,4193,4202,114,99,5,212,1,59,4200,1,212,59,1,1054,98,108,97,99,59,1,336,114,59,3,55349,56594,114,97,118,101,5,210,1,59,4226,1,210,4,3,97,101,105,4236,4241,4246,99,114,59,1,332,103,97,59,1,937,99,114,111,110,59,1,927,112,102,59,3,55349,56646,101,110,67,117,114,108,121,4,2,68,81,4272,4285,111,117,98,108,101,81,117,111,116,101,59,1,8220,117,111,116,101,59,1,8216,59,1,10836,4,2,99,108,4301,4306,114,59,3,55349,56490,97,115,104,5,216,1,59,4314,1,216,105,4,2,108,109,4323,4332,100,101,5,213,1,59,4330,1,213,101,115,59,1,10807,109,108,5,214,1,59,4344,1,214,101,114,4,2,66,80,4354,4380,4,2,97,114,4360,4364,114,59,1,8254,97,99,4,2,101,107,4372,4375,59,1,9182,101,116,59,1,9140,97,114,101,110,116,104,101,115,105,115,59,1,9180,4,9,97,99,102,104,105,108,111,114,115,4413,4422,4426,4431,4435,4438,4448,4471,4561,114,116,105,97,108,68,59,1,8706,121,59,1,1055,114,59,3,55349,56595,105,59,1,934,59,1,928,117,115,77,105,110,117,115,59,1,177,4,2,105,112,4454,4467,110,99,97,114,101,112,108,97,110,101,59,1,8460,102,59,1,8473,4,4,59,101,105,111,4481,4483,4526,4531,1,10939,99,101,100,101,115,4,4,59,69,83,84,4498,4500,4507,4519,1,8826,113,117,97,108,59,1,10927,108,97,110,116,69,113,117,97,108,59,1,8828,105,108,100,101,59,1,8830,109,101,59,1,8243,4,2,100,112,4537,4543,117,99,116,59,1,8719,111,114,116,105,111,110,4,2,59,97,4555,4557,1,8759,108,59,1,8733,4,2,99,105,4567,4572,114,59,3,55349,56491,59,1,936,4,4,85,102,111,115,4585,4594,4599,4604,79,84,5,34,1,59,4592,1,34,114,59,3,55349,56596,112,102,59,1,8474,99,114,59,3,55349,56492,4,12,66,69,97,99,101,102,104,105,111,114,115,117,4636,4642,4650,4681,4704,4763,4767,4771,5047,5069,5081,5094,97,114,114,59,1,10512,71,5,174,1,59,4648,1,174,4,3,99,110,114,4658,4664,4668,117,116,101,59,1,340,103,59,1,10219,114,4,2,59,116,4675,4677,1,8608,108,59,1,10518,4,3,97,101,121,4689,4695,4701,114,111,110,59,1,344,100,105,108,59,1,342,59,1,1056,4,2,59,118,4710,4712,1,8476,101,114,115,101,4,2,69,85,4722,4748,4,2,108,113,4728,4736,101,109,101,110,116,59,1,8715,117,105,108,105,98,114,105,117,109,59,1,8651,112,69,113,117,105,108,105,98,114,105,117,109,59,1,10607,114,59,1,8476,111,59,1,929,103,104,116,4,8,65,67,68,70,84,85,86,97,4792,4840,4849,4905,4912,4972,5022,5040,4,2,110,114,4798,4811,103,108,101,66,114,97,99,107,101,116,59,1,10217,114,111,119,4,3,59,66,76,4822,4824,4829,1,8594,97,114,59,1,8677,101,102,116,65,114,114,111,119,59,1,8644,101,105,108,105,110,103,59,1,8969,111,4,2,117,119,4856,4869,98,108,101,66,114,97,99,107,101,116,59,1,10215,110,4,2,84,86,4876,4887,101,101,86,101,99,116,111,114,59,1,10589,101,99,116,111,114,4,2,59,66,4898,4900,1,8642,97,114,59,1,10581,108,111,111,114,59,1,8971,4,2,101,114,4918,4944,101,4,3,59,65,86,4927,4929,4936,1,8866,114,114,111,119,59,1,8614,101,99,116,111,114,59,1,10587,105,97,110,103,108,101,4,3,59,66,69,4958,4960,4965,1,8883,97,114,59,1,10704,113,117,97,108,59,1,8885,112,4,3,68,84,86,4981,4993,5004,111,119,110,86,101,99,116,111,114,59,1,10575,101,101,86,101,99,116,111,114,59,1,10588,101,99,116,111,114,4,2,59,66,5015,5017,1,8638,97,114,59,1,10580,101,99,116,111,114,4,2,59,66,5033,5035,1,8640,97,114,59,1,10579,114,114,111,119,59,1,8658,4,2,112,117,5053,5057,102,59,1,8477,110,100,73,109,112,108,105,101,115,59,1,10608,105,103,104,116,97,114,114,111,119,59,1,8667,4,2,99,104,5087,5091,114,59,1,8475,59,1,8625,108,101,68,101,108,97,121,101,100,59,1,10740,4,13,72,79,97,99,102,104,105,109,111,113,115,116,117,5134,5150,5157,5164,5198,5203,5259,5265,5277,5283,5374,5380,5385,4,2,67,99,5140,5146,72,99,121,59,1,1065,121,59,1,1064,70,84,99,121,59,1,1068,99,117,116,101,59,1,346,4,5,59,97,101,105,121,5176,5178,5184,5190,5195,1,10940,114,111,110,59,1,352,100,105,108,59,1,350,114,99,59,1,348,59,1,1057,114,59,3,55349,56598,111,114,116,4,4,68,76,82,85,5216,5227,5238,5250,111,119,110,65,114,114,111,119,59,1,8595,101,102,116,65,114,114,111,119,59,1,8592,105,103,104,116,65,114,114,111,119,59,1,8594,112,65,114,114,111,119,59,1,8593,103,109,97,59,1,931,97,108,108,67,105,114,99,108,101,59,1,8728,112,102,59,3,55349,56650,4,2,114,117,5289,5293,116,59,1,8730,97,114,101,4,4,59,73,83,85,5306,5308,5322,5367,1,9633,110,116,101,114,115,101,99,116,105,111,110,59,1,8851,117,4,2,98,112,5329,5347,115,101,116,4,2,59,69,5338,5340,1,8847,113,117,97,108,59,1,8849,101,114,115,101,116,4,2,59,69,5358,5360,1,8848,113,117,97,108,59,1,8850,110,105,111,110,59,1,8852,99,114,59,3,55349,56494,97,114,59,1,8902,4,4,98,99,109,112,5395,5420,5475,5478,4,2,59,115,5401,5403,1,8912,101,116,4,2,59,69,5411,5413,1,8912,113,117,97,108,59,1,8838,4,2,99,104,5426,5468,101,101,100,115,4,4,59,69,83,84,5440,5442,5449,5461,1,8827,113,117,97,108,59,1,10928,108,97,110,116,69,113,117,97,108,59,1,8829,105,108,100,101,59,1,8831,84,104,97,116,59,1,8715,59,1,8721,4,3,59,101,115,5486,5488,5507,1,8913,114,115,101,116,4,2,59,69,5498,5500,1,8835,113,117,97,108,59,1,8839,101,116,59,1,8913,4,11,72,82,83,97,99,102,104,105,111,114,115,5536,5546,5552,5567,5579,5602,5607,5655,5695,5701,5711,79,82,78,5,222,1,59,5544,1,222,65,68,69,59,1,8482,4,2,72,99,5558,5563,99,121,59,1,1035,121,59,1,1062,4,2,98,117,5573,5576,59,1,9,59,1,932,4,3,97,101,121,5587,5593,5599,114,111,110,59,1,356,100,105,108,59,1,354,59,1,1058,114,59,3,55349,56599,4,2,101,105,5613,5631,4,2,114,116,5619,5627,101,102,111,114,101,59,1,8756,97,59,1,920,4,2,99,110,5637,5647,107,83,112,97,99,101,59,3,8287,8202,83,112,97,99,101,59,1,8201,108,100,101,4,4,59,69,70,84,5668,5670,5677,5688,1,8764,113,117,97,108,59,1,8771,117,108,108,69,113,117,97,108,59,1,8773,105,108,100,101,59,1,8776,112,102,59,3,55349,56651,105,112,108,101,68,111,116,59,1,8411,4,2,99,116,5717,5722,114,59,3,55349,56495,114,111,107,59,1,358,4,14,97,98,99,100,102,103,109,110,111,112,114,115,116,117,5758,5789,5805,5823,5830,5835,5846,5852,5921,5937,6089,6095,6101,6108,4,2,99,114,5764,5774,117,116,101,5,218,1,59,5772,1,218,114,4,2,59,111,5781,5783,1,8607,99,105,114,59,1,10569,114,4,2,99,101,5796,5800,121,59,1,1038,118,101,59,1,364,4,2,105,121,5811,5820,114,99,5,219,1,59,5818,1,219,59,1,1059,98,108,97,99,59,1,368,114,59,3,55349,56600,114,97,118,101,5,217,1,59,5844,1,217,97,99,114,59,1,362,4,2,100,105,5858,5905,101,114,4,2,66,80,5866,5892,4,2,97,114,5872,5876,114,59,1,95,97,99,4,2,101,107,5884,5887,59,1,9183,101,116,59,1,9141,97,114,101,110,116,104,101,115,105,115,59,1,9181,111,110,4,2,59,80,5913,5915,1,8899,108,117,115,59,1,8846,4,2,103,112,5927,5932,111,110,59,1,370,102,59,3,55349,56652,4,8,65,68,69,84,97,100,112,115,5955,5985,5996,6009,6026,6033,6044,6075,114,114,111,119,4,3,59,66,68,5967,5969,5974,1,8593,97,114,59,1,10514,111,119,110,65,114,114,111,119,59,1,8645,111,119,110,65,114,114,111,119,59,1,8597,113,117,105,108,105,98,114,105,117,109,59,1,10606,101,101,4,2,59,65,6017,6019,1,8869,114,114,111,119,59,1,8613,114,114,111,119,59,1,8657,111,119,110,97,114,114,111,119,59,1,8661,101,114,4,2,76,82,6052,6063,101,102,116,65,114,114,111,119,59,1,8598,105,103,104,116,65,114,114,111,119,59,1,8599,105,4,2,59,108,6082,6084,1,978,111,110,59,1,933,105,110,103,59,1,366,99,114,59,3,55349,56496,105,108,100,101,59,1,360,109,108,5,220,1,59,6115,1,220,4,9,68,98,99,100,101,102,111,115,118,6137,6143,6148,6152,6166,6250,6255,6261,6267,97,115,104,59,1,8875,97,114,59,1,10987,121,59,1,1042,97,115,104,4,2,59,108,6161,6163,1,8873,59,1,10982,4,2,101,114,6172,6175,59,1,8897,4,3,98,116,121,6183,6188,6238,97,114,59,1,8214,4,2,59,105,6194,6196,1,8214,99,97,108,4,4,66,76,83,84,6209,6214,6220,6231,97,114,59,1,8739,105,110,101,59,1,124,101,112,97,114,97,116,111,114,59,1,10072,105,108,100,101,59,1,8768,84,104,105,110,83,112,97,99,101,59,1,8202,114,59,3,55349,56601,112,102,59,3,55349,56653,99,114,59,3,55349,56497,100,97,115,104,59,1,8874,4,5,99,101,102,111,115,6286,6292,6298,6303,6309,105,114,99,59,1,372,100,103,101,59,1,8896,114,59,3,55349,56602,112,102,59,3,55349,56654,99,114,59,3,55349,56498,4,4,102,105,111,115,6325,6330,6333,6339,114,59,3,55349,56603,59,1,926,112,102,59,3,55349,56655,99,114,59,3,55349,56499,4,9,65,73,85,97,99,102,111,115,117,6365,6370,6375,6380,6391,6405,6410,6416,6422,99,121,59,1,1071,99,121,59,1,1031,99,121,59,1,1070,99,117,116,101,5,221,1,59,6389,1,221,4,2,105,121,6397,6402,114,99,59,1,374,59,1,1067,114,59,3,55349,56604,112,102,59,3,55349,56656,99,114,59,3,55349,56500,109,108,59,1,376,4,8,72,97,99,100,101,102,111,115,6445,6450,6457,6472,6477,6501,6505,6510,99,121,59,1,1046,99,117,116,101,59,1,377,4,2,97,121,6463,6469,114,111,110,59,1,381,59,1,1047,111,116,59,1,379,4,2,114,116,6483,6497,111,87,105,100,116,104,83,112,97,99,101,59,1,8203,97,59,1,918,114,59,1,8488,112,102,59,1,8484,99,114,59,3,55349,56501,4,16,97,98,99,101,102,103,108,109,110,111,112,114,115,116,117,119,6550,6561,6568,6612,6622,6634,6645,6672,6699,6854,6870,6923,6933,6963,6974,6983,99,117,116,101,5,225,1,59,6559,1,225,114,101,118,101,59,1,259,4,6,59,69,100,105,117,121,6582,6584,6588,6591,6600,6609,1,8766,59,3,8766,819,59,1,8767,114,99,5,226,1,59,6598,1,226,116,101,5,180,1,59,6607,1,180,59,1,1072,108,105,103,5,230,1,59,6620,1,230,4,2,59,114,6628,6630,1,8289,59,3,55349,56606,114,97,118,101,5,224,1,59,6643,1,224,4,2,101,112,6651,6667,4,2,102,112,6657,6663,115,121,109,59,1,8501,104,59,1,8501,104,97,59,1,945,4,2,97,112,6678,6692,4,2,99,108,6684,6688,114,59,1,257,103,59,1,10815,5,38,1,59,6697,1,38,4,2,100,103,6705,6737,4,5,59,97,100,115,118,6717,6719,6724,6727,6734,1,8743,110,100,59,1,10837,59,1,10844,108,111,112,101,59,1,10840,59,1,10842,4,7,59,101,108,109,114,115,122,6753,6755,6758,6762,6814,6835,6848,1,8736,59,1,10660,101,59,1,8736,115,100,4,2,59,97,6770,6772,1,8737,4,8,97,98,99,100,101,102,103,104,6790,6793,6796,6799,6802,6805,6808,6811,59,1,10664,59,1,10665,59,1,10666,59,1,10667,59,1,10668,59,1,10669,59,1,10670,59,1,10671,116,4,2,59,118,6821,6823,1,8735,98,4,2,59,100,6830,6832,1,8894,59,1,10653,4,2,112,116,6841,6845,104,59,1,8738,59,1,197,97,114,114,59,1,9084,4,2,103,112,6860,6865,111,110,59,1,261,102,59,3,55349,56658,4,7,59,69,97,101,105,111,112,6886,6888,6891,6897,6900,6904,6908,1,8776,59,1,10864,99,105,114,59,1,10863,59,1,8778,100,59,1,8779,115,59,1,39,114,111,120,4,2,59,101,6917,6919,1,8776,113,59,1,8778,105,110,103,5,229,1,59,6931,1,229,4,3,99,116,121,6941,6946,6949,114,59,3,55349,56502,59,1,42,109,112,4,2,59,101,6957,6959,1,8776,113,59,1,8781,105,108,100,101,5,227,1,59,6972,1,227,109,108,5,228,1,59,6981,1,228,4,2,99,105,6989,6997,111,110,105,110,116,59,1,8755,110,116,59,1,10769,4,16,78,97,98,99,100,101,102,105,107,108,110,111,112,114,115,117,7036,7041,7119,7135,7149,7155,7219,7224,7347,7354,7463,7489,7786,7793,7814,7866,111,116,59,1,10989,4,2,99,114,7047,7094,107,4,4,99,101,112,115,7058,7064,7073,7080,111,110,103,59,1,8780,112,115,105,108,111,110,59,1,1014,114,105,109,101,59,1,8245,105,109,4,2,59,101,7088,7090,1,8765,113,59,1,8909,4,2,118,119,7100,7105,101,101,59,1,8893,101,100,4,2,59,103,7113,7115,1,8965,101,59,1,8965,114,107,4,2,59,116,7127,7129,1,9141,98,114,107,59,1,9142,4,2,111,121,7141,7146,110,103,59,1,8780,59,1,1073,113,117,111,59,1,8222,4,5,99,109,112,114,116,7167,7181,7188,7193,7199,97,117,115,4,2,59,101,7176,7178,1,8757,59,1,8757,112,116,121,118,59,1,10672,115,105,59,1,1014,110,111,117,59,1,8492,4,3,97,104,119,7207,7210,7213,59,1,946,59,1,8502,101,101,110,59,1,8812,114,59,3,55349,56607,103,4,7,99,111,115,116,117,118,119,7241,7262,7288,7305,7328,7335,7340,4,3,97,105,117,7249,7253,7258,112,59,1,8898,114,99,59,1,9711,112,59,1,8899,4,3,100,112,116,7270,7275,7281,111,116,59,1,10752,108,117,115,59,1,10753,105,109,101,115,59,1,10754,4,2,113,116,7294,7300,99,117,112,59,1,10758,97,114,59,1,9733,114,105,97,110,103,108,101,4,2,100,117,7318,7324,111,119,110,59,1,9661,112,59,1,9651,112,108,117,115,59,1,10756,101,101,59,1,8897,101,100,103,101,59,1,8896,97,114,111,119,59,1,10509,4,3,97,107,111,7362,7436,7458,4,2,99,110,7368,7432,107,4,3,108,115,116,7377,7386,7394,111,122,101,110,103,101,59,1,10731,113,117,97,114,101,59,1,9642,114,105,97,110,103,108,101,4,4,59,100,108,114,7411,7413,7419,7425,1,9652,111,119,110,59,1,9662,101,102,116,59,1,9666,105,103,104,116,59,1,9656,107,59,1,9251,4,2,49,51,7442,7454,4,2,50,52,7448,7451,59,1,9618,59,1,9617,52,59,1,9619,99,107,59,1,9608,4,2,101,111,7469,7485,4,2,59,113,7475,7478,3,61,8421,117,105,118,59,3,8801,8421,116,59,1,8976,4,4,112,116,119,120,7499,7504,7517,7523,102,59,3,55349,56659,4,2,59,116,7510,7512,1,8869,111,109,59,1,8869,116,105,101,59,1,8904,4,12,68,72,85,86,98,100,104,109,112,116,117,118,7549,7571,7597,7619,7655,7660,7682,7708,7715,7721,7728,7750,4,4,76,82,108,114,7559,7562,7565,7568,59,1,9559,59,1,9556,59,1,9558,59,1,9555,4,5,59,68,85,100,117,7583,7585,7588,7591,7594,1,9552,59,1,9574,59,1,9577,59,1,9572,59,1,9575,4,4,76,82,108,114,7607,7610,7613,7616,59,1,9565,59,1,9562,59,1,9564,59,1,9561,4,7,59,72,76,82,104,108,114,7635,7637,7640,7643,7646,7649,7652,1,9553,59,1,9580,59,1,9571,59,1,9568,59,1,9579,59,1,9570,59,1,9567,111,120,59,1,10697,4,4,76,82,108,114,7670,7673,7676,7679,59,1,9557,59,1,9554,59,1,9488,59,1,9484,4,5,59,68,85,100,117,7694,7696,7699,7702,7705,1,9472,59,1,9573,59,1,9576,59,1,9516,59,1,9524,105,110,117,115,59,1,8863,108,117,115,59,1,8862,105,109,101,115,59,1,8864,4,4,76,82,108,114,7738,7741,7744,7747,59,1,9563,59,1,9560,59,1,9496,59,1,9492,4,7,59,72,76,82,104,108,114,7766,7768,7771,7774,7777,7780,7783,1,9474,59,1,9578,59,1,9569,59,1,9566,59,1,9532,59,1,9508,59,1,9500,114,105,109,101,59,1,8245,4,2,101,118,7799,7804,118,101,59,1,728,98,97,114,5,166,1,59,7812,1,166,4,4,99,101,105,111,7824,7829,7834,7846,114,59,3,55349,56503,109,105,59,1,8271,109,4,2,59,101,7841,7843,1,8765,59,1,8909,108,4,3,59,98,104,7855,7857,7860,1,92,59,1,10693,115,117,98,59,1,10184,4,2,108,109,7872,7885,108,4,2,59,101,7879,7881,1,8226,116,59,1,8226,112,4,3,59,69,101,7894,7896,7899,1,8782,59,1,10926,4,2,59,113,7905,7907,1,8783,59,1,8783,4,15,97,99,100,101,102,104,105,108,111,114,115,116,117,119,121,7942,8021,8075,8080,8121,8126,8157,8279,8295,8430,8446,8485,8491,8707,8726,4,3,99,112,114,7950,7956,8007,117,116,101,59,1,263,4,6,59,97,98,99,100,115,7970,7972,7977,7984,7998,8003,1,8745,110,100,59,1,10820,114,99,117,112,59,1,10825,4,2,97,117,7990,7994,112,59,1,10827,112,59,1,10823,111,116,59,1,10816,59,3,8745,65024,4,2,101,111,8013,8017,116,59,1,8257,110,59,1,711,4,4,97,101,105,117,8031,8046,8056,8061,4,2,112,114,8037,8041,115,59,1,10829,111,110,59,1,269,100,105,108,5,231,1,59,8054,1,231,114,99,59,1,265,112,115,4,2,59,115,8069,8071,1,10828,109,59,1,10832,111,116,59,1,267,4,3,100,109,110,8088,8097,8104,105,108,5,184,1,59,8095,1,184,112,116,121,118,59,1,10674,116,5,162,2,59,101,8112,8114,1,162,114,100,111,116,59,1,183,114,59,3,55349,56608,4,3,99,101,105,8134,8138,8154,121,59,1,1095,99,107,4,2,59,109,8146,8148,1,10003,97,114,107,59,1,10003,59,1,967,114,4,7,59,69,99,101,102,109,115,8174,8176,8179,8258,8261,8268,8273,1,9675,59,1,10691,4,3,59,101,108,8187,8189,8193,1,710,113,59,1,8791,101,4,2,97,100,8200,8223,114,114,111,119,4,2,108,114,8210,8216,101,102,116,59,1,8634,105,103,104,116,59,1,8635,4,5,82,83,97,99,100,8235,8238,8241,8246,8252,59,1,174,59,1,9416,115,116,59,1,8859,105,114,99,59,1,8858,97,115,104,59,1,8861,59,1,8791,110,105,110,116,59,1,10768,105,100,59,1,10991,99,105,114,59,1,10690,117,98,115,4,2,59,117,8288,8290,1,9827,105,116,59,1,9827,4,4,108,109,110,112,8305,8326,8376,8400,111,110,4,2,59,101,8313,8315,1,58,4,2,59,113,8321,8323,1,8788,59,1,8788,4,2,109,112,8332,8344,97,4,2,59,116,8339,8341,1,44,59,1,64,4,3,59,102,108,8352,8354,8358,1,8705,110,59,1,8728,101,4,2,109,120,8365,8371,101,110,116,59,1,8705,101,115,59,1,8450,4,2,103,105,8382,8395,4,2,59,100,8388,8390,1,8773,111,116,59,1,10861,110,116,59,1,8750,4,3,102,114,121,8408,8412,8417,59,3,55349,56660,111,100,59,1,8720,5,169,2,59,115,8424,8426,1,169,114,59,1,8471,4,2,97,111,8436,8441,114,114,59,1,8629,115,115,59,1,10007,4,2,99,117,8452,8457,114,59,3,55349,56504,4,2,98,112,8463,8474,4,2,59,101,8469,8471,1,10959,59,1,10961,4,2,59,101,8480,8482,1,10960,59,1,10962,100,111,116,59,1,8943,4,7,100,101,108,112,114,118,119,8507,8522,8536,8550,8600,8697,8702,97,114,114,4,2,108,114,8516,8519,59,1,10552,59,1,10549,4,2,112,115,8528,8532,114,59,1,8926,99,59,1,8927,97,114,114,4,2,59,112,8545,8547,1,8630,59,1,10557,4,6,59,98,99,100,111,115,8564,8566,8573,8587,8592,8596,1,8746,114,99,97,112,59,1,10824,4,2,97,117,8579,8583,112,59,1,10822,112,59,1,10826,111,116,59,1,8845,114,59,1,10821,59,3,8746,65024,4,4,97,108,114,118,8610,8623,8663,8672,114,114,4,2,59,109,8618,8620,1,8631,59,1,10556,121,4,3,101,118,119,8632,8651,8656,113,4,2,112,115,8639,8645,114,101,99,59,1,8926,117,99,99,59,1,8927,101,101,59,1,8910,101,100,103,101,59,1,8911,101,110,5,164,1,59,8670,1,164,101,97,114,114,111,119,4,2,108,114,8684,8690,101,102,116,59,1,8630,105,103,104,116,59,1,8631,101,101,59,1,8910,101,100,59,1,8911,4,2,99,105,8713,8721,111,110,105,110,116,59,1,8754,110,116,59,1,8753,108,99,116,121,59,1,9005,4,19,65,72,97,98,99,100,101,102,104,105,106,108,111,114,115,116,117,119,122,8773,8778,8783,8821,8839,8854,8887,8914,8930,8944,9036,9041,9058,9197,9227,9258,9281,9297,9305,114,114,59,1,8659,97,114,59,1,10597,4,4,103,108,114,115,8793,8799,8805,8809,103,101,114,59,1,8224,101,116,104,59,1,8504,114,59,1,8595,104,4,2,59,118,8816,8818,1,8208,59,1,8867,4,2,107,108,8827,8834,97,114,111,119,59,1,10511,97,99,59,1,733,4,2,97,121,8845,8851,114,111,110,59,1,271,59,1,1076,4,3,59,97,111,8862,8864,8880,1,8518,4,2,103,114,8870,8876,103,101,114,59,1,8225,114,59,1,8650,116,115,101,113,59,1,10871,4,3,103,108,109,8895,8902,8907,5,176,1,59,8900,1,176,116,97,59,1,948,112,116,121,118,59,1,10673,4,2,105,114,8920,8926,115,104,116,59,1,10623,59,3,55349,56609,97,114,4,2,108,114,8938,8941,59,1,8643,59,1,8642,4,5,97,101,103,115,118,8956,8986,8989,8996,9001,109,4,3,59,111,115,8965,8967,8983,1,8900,110,100,4,2,59,115,8975,8977,1,8900,117,105,116,59,1,9830,59,1,9830,59,1,168,97,109,109,97,59,1,989,105,110,59,1,8946,4,3,59,105,111,9009,9011,9031,1,247,100,101,5,247,2,59,111,9020,9022,1,247,110,116,105,109,101,115,59,1,8903,110,120,59,1,8903,99,121,59,1,1106,99,4,2,111,114,9048,9053,114,110,59,1,8990,111,112,59,1,8973,4,5,108,112,116,117,119,9070,9076,9081,9130,9144,108,97,114,59,1,36,102,59,3,55349,56661,4,5,59,101,109,112,115,9093,9095,9109,9116,9122,1,729,113,4,2,59,100,9102,9104,1,8784,111,116,59,1,8785,105,110,117,115,59,1,8760,108,117,115,59,1,8724,113,117,97,114,101,59,1,8865,98,108,101,98,97,114,119,101,100,103,101,59,1,8966,110,4,3,97,100,104,9153,9160,9172,114,114,111,119,59,1,8595,111,119,110,97,114,114,111,119,115,59,1,8650,97,114,112,111,111,110,4,2,108,114,9184,9190,101,102,116,59,1,8643,105,103,104,116,59,1,8642,4,2,98,99,9203,9211,107,97,114,111,119,59,1,10512,4,2,111,114,9217,9222,114,110,59,1,8991,111,112,59,1,8972,4,3,99,111,116,9235,9248,9252,4,2,114,121,9241,9245,59,3,55349,56505,59,1,1109,108,59,1,10742,114,111,107,59,1,273,4,2,100,114,9264,9269,111,116,59,1,8945,105,4,2,59,102,9276,9278,1,9663,59,1,9662,4,2,97,104,9287,9292,114,114,59,1,8693,97,114,59,1,10607,97,110,103,108,101,59,1,10662,4,2,99,105,9311,9315,121,59,1,1119,103,114,97,114,114,59,1,10239,4,18,68,97,99,100,101,102,103,108,109,110,111,112,113,114,115,116,117,120,9361,9376,9398,9439,9444,9447,9462,9495,9531,9585,9598,9614,9659,9755,9771,9792,9808,9826,4,2,68,111,9367,9372,111,116,59,1,10871,116,59,1,8785,4,2,99,115,9382,9392,117,116,101,5,233,1,59,9390,1,233,116,101,114,59,1,10862,4,4,97,105,111,121,9408,9414,9430,9436,114,111,110,59,1,283,114,4,2,59,99,9421,9423,1,8790,5,234,1,59,9428,1,234,108,111,110,59,1,8789,59,1,1101,111,116,59,1,279,59,1,8519,4,2,68,114,9453,9458,111,116,59,1,8786,59,3,55349,56610,4,3,59,114,115,9470,9472,9482,1,10906,97,118,101,5,232,1,59,9480,1,232,4,2,59,100,9488,9490,1,10902,111,116,59,1,10904,4,4,59,105,108,115,9505,9507,9515,9518,1,10905,110,116,101,114,115,59,1,9191,59,1,8467,4,2,59,100,9524,9526,1,10901,111,116,59,1,10903,4,3,97,112,115,9539,9544,9564,99,114,59,1,275,116,121,4,3,59,115,118,9554,9556,9561,1,8709,101,116,59,1,8709,59,1,8709,112,4,2,49,59,9571,9583,4,2,51,52,9577,9580,59,1,8196,59,1,8197,1,8195,4,2,103,115,9591,9594,59,1,331,112,59,1,8194,4,2,103,112,9604,9609,111,110,59,1,281,102,59,3,55349,56662,4,3,97,108,115,9622,9635,9640,114,4,2,59,115,9629,9631,1,8917,108,59,1,10723,117,115,59,1,10865,105,4,3,59,108,118,9649,9651,9656,1,949,111,110,59,1,949,59,1,1013,4,4,99,115,117,118,9669,9686,9716,9747,4,2,105,111,9675,9680,114,99,59,1,8790,108,111,110,59,1,8789,4,2,105,108,9692,9696,109,59,1,8770,97,110,116,4,2,103,108,9705,9710,116,114,59,1,10902,101,115,115,59,1,10901,4,3,97,101,105,9724,9729,9734,108,115,59,1,61,115,116,59,1,8799,118,4,2,59,68,9741,9743,1,8801,68,59,1,10872,112,97,114,115,108,59,1,10725,4,2,68,97,9761,9766,111,116,59,1,8787,114,114,59,1,10609,4,3,99,100,105,9779,9783,9788,114,59,1,8495,111,116,59,1,8784,109,59,1,8770,4,2,97,104,9798,9801,59,1,951,5,240,1,59,9806,1,240,4,2,109,114,9814,9822,108,5,235,1,59,9820,1,235,111,59,1,8364,4,3,99,105,112,9834,9838,9843,108,59,1,33,115,116,59,1,8707,4,2,101,111,9849,9859,99,116,97,116,105,111,110,59,1,8496,110,101,110,116,105,97,108,101,59,1,8519,4,12,97,99,101,102,105,106,108,110,111,112,114,115,9896,9910,9914,9921,9954,9960,9967,9989,9994,10027,10036,10164,108,108,105,110,103,100,111,116,115,101,113,59,1,8786,121,59,1,1092,109,97,108,101,59,1,9792,4,3,105,108,114,9929,9935,9950,108,105,103,59,1,64259,4,2,105,108,9941,9945,103,59,1,64256,105,103,59,1,64260,59,3,55349,56611,108,105,103,59,1,64257,108,105,103,59,3,102,106,4,3,97,108,116,9975,9979,9984,116,59,1,9837,105,103,59,1,64258,110,115,59,1,9649,111,102,59,1,402,4,2,112,114,10000,10005,102,59,3,55349,56663,4,2,97,107,10011,10016,108,108,59,1,8704,4,2,59,118,10022,10024,1,8916,59,1,10969,97,114,116,105,110,116,59,1,10765,4,2,97,111,10042,10159,4,2,99,115,10048,10155,4,6,49,50,51,52,53,55,10062,10102,10114,10135,10139,10151,4,6,50,51,52,53,54,56,10076,10083,10086,10093,10096,10099,5,189,1,59,10081,1,189,59,1,8531,5,188,1,59,10091,1,188,59,1,8533,59,1,8537,59,1,8539,4,2,51,53,10108,10111,59,1,8532,59,1,8534,4,3,52,53,56,10122,10129,10132,5,190,1,59,10127,1,190,59,1,8535,59,1,8540,53,59,1,8536,4,2,54,56,10145,10148,59,1,8538,59,1,8541,56,59,1,8542,108,59,1,8260,119,110,59,1,8994,99,114,59,3,55349,56507,4,17,69,97,98,99,100,101,102,103,105,106,108,110,111,114,115,116,118,10206,10217,10247,10254,10268,10273,10358,10363,10374,10380,10385,10406,10458,10464,10470,10497,10610,4,2,59,108,10212,10214,1,8807,59,1,10892,4,3,99,109,112,10225,10231,10244,117,116,101,59,1,501,109,97,4,2,59,100,10239,10241,1,947,59,1,989,59,1,10886,114,101,118,101,59,1,287,4,2,105,121,10260,10265,114,99,59,1,285,59,1,1075,111,116,59,1,289,4,4,59,108,113,115,10283,10285,10288,10308,1,8805,59,1,8923,4,3,59,113,115,10296,10298,10301,1,8805,59,1,8807,108,97,110,116,59,1,10878,4,4,59,99,100,108,10318,10320,10324,10345,1,10878,99,59,1,10921,111,116,4,2,59,111,10332,10334,1,10880,4,2,59,108,10340,10342,1,10882,59,1,10884,4,2,59,101,10351,10354,3,8923,65024,115,59,1,10900,114,59,3,55349,56612,4,2,59,103,10369,10371,1,8811,59,1,8921,109,101,108,59,1,8503,99,121,59,1,1107,4,4,59,69,97,106,10395,10397,10400,10403,1,8823,59,1,10898,59,1,10917,59,1,10916,4,4,69,97,101,115,10416,10419,10434,10453,59,1,8809,112,4,2,59,112,10426,10428,1,10890,114,111,120,59,1,10890,4,2,59,113,10440,10442,1,10888,4,2,59,113,10448,10450,1,10888,59,1,8809,105,109,59,1,8935,112,102,59,3,55349,56664,97,118,101,59,1,96,4,2,99,105,10476,10480,114,59,1,8458,109,4,3,59,101,108,10489,10491,10494,1,8819,59,1,10894,59,1,10896,5,62,6,59,99,100,108,113,114,10512,10514,10527,10532,10538,10545,1,62,4,2,99,105,10520,10523,59,1,10919,114,59,1,10874,111,116,59,1,8919,80,97,114,59,1,10645,117,101,115,116,59,1,10876,4,5,97,100,101,108,115,10557,10574,10579,10599,10605,4,2,112,114,10563,10570,112,114,111,120,59,1,10886,114,59,1,10616,111,116,59,1,8919,113,4,2,108,113,10586,10592,101,115,115,59,1,8923,108,101,115,115,59,1,10892,101,115,115,59,1,8823,105,109,59,1,8819,4,2,101,110,10616,10626,114,116,110,101,113,113,59,3,8809,65024,69,59,3,8809,65024,4,10,65,97,98,99,101,102,107,111,115,121,10653,10658,10713,10718,10724,10760,10765,10786,10850,10875,114,114,59,1,8660,4,4,105,108,109,114,10668,10674,10678,10684,114,115,112,59,1,8202,102,59,1,189,105,108,116,59,1,8459,4,2,100,114,10690,10695,99,121,59,1,1098,4,3,59,99,119,10703,10705,10710,1,8596,105,114,59,1,10568,59,1,8621,97,114,59,1,8463,105,114,99,59,1,293,4,3,97,108,114,10732,10748,10754,114,116,115,4,2,59,117,10741,10743,1,9829,105,116,59,1,9829,108,105,112,59,1,8230,99,111,110,59,1,8889,114,59,3,55349,56613,115,4,2,101,119,10772,10779,97,114,111,119,59,1,10533,97,114,111,119,59,1,10534,4,5,97,109,111,112,114,10798,10803,10809,10839,10844,114,114,59,1,8703,116,104,116,59,1,8763,107,4,2,108,114,10816,10827,101,102,116,97,114,114,111,119,59,1,8617,105,103,104,116,97,114,114,111,119,59,1,8618,102,59,3,55349,56665,98,97,114,59,1,8213,4,3,99,108,116,10858,10863,10869,114,59,3,55349,56509,97,115,104,59,1,8463,114,111,107,59,1,295,4,2,98,112,10881,10887,117,108,108,59,1,8259,104,101,110,59,1,8208,4,15,97,99,101,102,103,105,106,109,110,111,112,113,115,116,117,10925,10936,10958,10977,10990,11001,11039,11045,11101,11192,11220,11226,11237,11285,11299,99,117,116,101,5,237,1,59,10934,1,237,4,3,59,105,121,10944,10946,10955,1,8291,114,99,5,238,1,59,10953,1,238,59,1,1080,4,2,99,120,10964,10968,121,59,1,1077,99,108,5,161,1,59,10975,1,161,4,2,102,114,10983,10986,59,1,8660,59,3,55349,56614,114,97,118,101,5,236,1,59,10999,1,236,4,4,59,105,110,111,11011,11013,11028,11034,1,8520,4,2,105,110,11019,11024,110,116,59,1,10764,116,59,1,8749,102,105,110,59,1,10716,116,97,59,1,8489,108,105,103,59,1,307,4,3,97,111,112,11053,11092,11096,4,3,99,103,116,11061,11065,11088,114,59,1,299,4,3,101,108,112,11073,11076,11082,59,1,8465,105,110,101,59,1,8464,97,114,116,59,1,8465,104,59,1,305,102,59,1,8887,101,100,59,1,437,4,5,59,99,102,111,116,11113,11115,11121,11136,11142,1,8712,97,114,101,59,1,8453,105,110,4,2,59,116,11129,11131,1,8734,105,101,59,1,10717,100,111,116,59,1,305,4,5,59,99,101,108,112,11154,11156,11161,11179,11186,1,8747,97,108,59,1,8890,4,2,103,114,11167,11173,101,114,115,59,1,8484,99,97,108,59,1,8890,97,114,104,107,59,1,10775,114,111,100,59,1,10812,4,4,99,103,112,116,11202,11206,11211,11216,121,59,1,1105,111,110,59,1,303,102,59,3,55349,56666,97,59,1,953,114,111,100,59,1,10812,117,101,115,116,5,191,1,59,11235,1,191,4,2,99,105,11243,11248,114,59,3,55349,56510,110,4,5,59,69,100,115,118,11261,11263,11266,11271,11282,1,8712,59,1,8953,111,116,59,1,8949,4,2,59,118,11277,11279,1,8948,59,1,8947,59,1,8712,4,2,59,105,11291,11293,1,8290,108,100,101,59,1,297,4,2,107,109,11305,11310,99,121,59,1,1110,108,5,239,1,59,11316,1,239,4,6,99,102,109,111,115,117,11332,11346,11351,11357,11363,11380,4,2,105,121,11338,11343,114,99,59,1,309,59,1,1081,114,59,3,55349,56615,97,116,104,59,1,567,112,102,59,3,55349,56667,4,2,99,101,11369,11374,114,59,3,55349,56511,114,99,121,59,1,1112,107,99,121,59,1,1108,4,8,97,99,102,103,104,106,111,115,11404,11418,11433,11438,11445,11450,11455,11461,112,112,97,4,2,59,118,11413,11415,1,954,59,1,1008,4,2,101,121,11424,11430,100,105,108,59,1,311,59,1,1082,114,59,3,55349,56616,114,101,101,110,59,1,312,99,121,59,1,1093,99,121,59,1,1116,112,102,59,3,55349,56668,99,114,59,3,55349,56512,4,23,65,66,69,72,97,98,99,100,101,102,103,104,106,108,109,110,111,112,114,115,116,117,118,11515,11538,11544,11555,11560,11721,11780,11818,11868,12136,12160,12171,12203,12208,12246,12275,12327,12509,12523,12569,12641,12732,12752,4,3,97,114,116,11523,11528,11532,114,114,59,1,8666,114,59,1,8656,97,105,108,59,1,10523,97,114,114,59,1,10510,4,2,59,103,11550,11552,1,8806,59,1,10891,97,114,59,1,10594,4,9,99,101,103,109,110,112,113,114,116,11580,11586,11594,11600,11606,11624,11627,11636,11694,117,116,101,59,1,314,109,112,116,121,118,59,1,10676,114,97,110,59,1,8466,98,100,97,59,1,955,103,4,3,59,100,108,11615,11617,11620,1,10216,59,1,10641,101,59,1,10216,59,1,10885,117,111,5,171,1,59,11634,1,171,114,4,8,59,98,102,104,108,112,115,116,11655,11657,11669,11673,11677,11681,11685,11690,1,8592,4,2,59,102,11663,11665,1,8676,115,59,1,10527,115,59,1,10525,107,59,1,8617,112,59,1,8619,108,59,1,10553,105,109,59,1,10611,108,59,1,8610,4,3,59,97,101,11702,11704,11709,1,10923,105,108,59,1,10521,4,2,59,115,11715,11717,1,10925,59,3,10925,65024,4,3,97,98,114,11729,11734,11739,114,114,59,1,10508,114,107,59,1,10098,4,2,97,107,11745,11758,99,4,2,101,107,11752,11755,59,1,123,59,1,91,4,2,101,115,11764,11767,59,1,10635,108,4,2,100,117,11774,11777,59,1,10639,59,1,10637,4,4,97,101,117,121,11790,11796,11811,11815,114,111,110,59,1,318,4,2,100,105,11802,11807,105,108,59,1,316,108,59,1,8968,98,59,1,123,59,1,1083,4,4,99,113,114,115,11828,11832,11845,11864,97,59,1,10550,117,111,4,2,59,114,11840,11842,1,8220,59,1,8222,4,2,100,117,11851,11857,104,97,114,59,1,10599,115,104,97,114,59,1,10571,104,59,1,8626,4,5,59,102,103,113,115,11880,11882,12008,12011,12031,1,8804,116,4,5,97,104,108,114,116,11895,11913,11935,11947,11996,114,114,111,119,4,2,59,116,11905,11907,1,8592,97,105,108,59,1,8610,97,114,112,111,111,110,4,2,100,117,11925,11931,111,119,110,59,1,8637,112,59,1,8636,101,102,116,97,114,114,111,119,115,59,1,8647,105,103,104,116,4,3,97,104,115,11959,11974,11984,114,114,111,119,4,2,59,115,11969,11971,1,8596,59,1,8646,97,114,112,111,111,110,115,59,1,8651,113,117,105,103,97,114,114,111,119,59,1,8621,104,114,101,101,116,105,109,101,115,59,1,8907,59,1,8922,4,3,59,113,115,12019,12021,12024,1,8804,59,1,8806,108,97,110,116,59,1,10877,4,5,59,99,100,103,115,12043,12045,12049,12070,12083,1,10877,99,59,1,10920,111,116,4,2,59,111,12057,12059,1,10879,4,2,59,114,12065,12067,1,10881,59,1,10883,4,2,59,101,12076,12079,3,8922,65024,115,59,1,10899,4,5,97,100,101,103,115,12095,12103,12108,12126,12131,112,112,114,111,120,59,1,10885,111,116,59,1,8918,113,4,2,103,113,12115,12120,116,114,59,1,8922,103,116,114,59,1,10891,116,114,59,1,8822,105,109,59,1,8818,4,3,105,108,114,12144,12150,12156,115,104,116,59,1,10620,111,111,114,59,1,8970,59,3,55349,56617,4,2,59,69,12166,12168,1,8822,59,1,10897,4,2,97,98,12177,12198,114,4,2,100,117,12184,12187,59,1,8637,4,2,59,108,12193,12195,1,8636,59,1,10602,108,107,59,1,9604,99,121,59,1,1113,4,5,59,97,99,104,116,12220,12222,12227,12235,12241,1,8810,114,114,59,1,8647,111,114,110,101,114,59,1,8990,97,114,100,59,1,10603,114,105,59,1,9722,4,2,105,111,12252,12258,100,111,116,59,1,320,117,115,116,4,2,59,97,12267,12269,1,9136,99,104,101,59,1,9136,4,4,69,97,101,115,12285,12288,12303,12322,59,1,8808,112,4,2,59,112,12295,12297,1,10889,114,111,120,59,1,10889,4,2,59,113,12309,12311,1,10887,4,2,59,113,12317,12319,1,10887,59,1,8808,105,109,59,1,8934,4,8,97,98,110,111,112,116,119,122,12345,12359,12364,12421,12446,12467,12474,12490,4,2,110,114,12351,12355,103,59,1,10220,114,59,1,8701,114,107,59,1,10214,103,4,3,108,109,114,12373,12401,12409,101,102,116,4,2,97,114,12382,12389,114,114,111,119,59,1,10229,105,103,104,116,97,114,114,111,119,59,1,10231,97,112,115,116,111,59,1,10236,105,103,104,116,97,114,114,111,119,59,1,10230,112,97,114,114,111,119,4,2,108,114,12433,12439,101,102,116,59,1,8619,105,103,104,116,59,1,8620,4,3,97,102,108,12454,12458,12462,114,59,1,10629,59,3,55349,56669,117,115,59,1,10797,105,109,101,115,59,1,10804,4,2,97,98,12480,12485,115,116,59,1,8727,97,114,59,1,95,4,3,59,101,102,12498,12500,12506,1,9674,110,103,101,59,1,9674,59,1,10731,97,114,4,2,59,108,12517,12519,1,40,116,59,1,10643,4,5,97,99,104,109,116,12535,12540,12548,12561,12564,114,114,59,1,8646,111,114,110,101,114,59,1,8991,97,114,4,2,59,100,12556,12558,1,8651,59,1,10605,59,1,8206,114,105,59,1,8895,4,6,97,99,104,105,113,116,12583,12589,12594,12597,12614,12635,113,117,111,59,1,8249,114,59,3,55349,56513,59,1,8624,109,4,3,59,101,103,12606,12608,12611,1,8818,59,1,10893,59,1,10895,4,2,98,117,12620,12623,59,1,91,111,4,2,59,114,12630,12632,1,8216,59,1,8218,114,111,107,59,1,322,5,60,8,59,99,100,104,105,108,113,114,12660,12662,12675,12680,12686,12692,12698,12705,1,60,4,2,99,105,12668,12671,59,1,10918,114,59,1,10873,111,116,59,1,8918,114,101,101,59,1,8907,109,101,115,59,1,8905,97,114,114,59,1,10614,117,101,115,116,59,1,10875,4,2,80,105,12711,12716,97,114,59,1,10646,4,3,59,101,102,12724,12726,12729,1,9667,59,1,8884,59,1,9666,114,4,2,100,117,12739,12746,115,104,97,114,59,1,10570,104,97,114,59,1,10598,4,2,101,110,12758,12768,114,116,110,101,113,113,59,3,8808,65024,69,59,3,8808,65024,4,14,68,97,99,100,101,102,104,105,108,110,111,112,115,117,12803,12809,12893,12908,12914,12928,12933,12937,13011,13025,13032,13049,13052,13069,68,111,116,59,1,8762,4,4,99,108,112,114,12819,12827,12849,12887,114,5,175,1,59,12825,1,175,4,2,101,116,12833,12836,59,1,9794,4,2,59,101,12842,12844,1,10016,115,101,59,1,10016,4,2,59,115,12855,12857,1,8614,116,111,4,4,59,100,108,117,12869,12871,12877,12883,1,8614,111,119,110,59,1,8615,101,102,116,59,1,8612,112,59,1,8613,107,101,114,59,1,9646,4,2,111,121,12899,12905,109,109,97,59,1,10793,59,1,1084,97,115,104,59,1,8212,97,115,117,114,101,100,97,110,103,108,101,59,1,8737,114,59,3,55349,56618,111,59,1,8487,4,3,99,100,110,12945,12954,12985,114,111,5,181,1,59,12952,1,181,4,4,59,97,99,100,12964,12966,12971,12976,1,8739,115,116,59,1,42,105,114,59,1,10992,111,116,5,183,1,59,12983,1,183,117,115,4,3,59,98,100,12995,12997,13000,1,8722,59,1,8863,4,2,59,117,13006,13008,1,8760,59,1,10794,4,2,99,100,13017,13021,112,59,1,10971,114,59,1,8230,112,108,117,115,59,1,8723,4,2,100,112,13038,13044,101,108,115,59,1,8871,102,59,3,55349,56670,59,1,8723,4,2,99,116,13058,13063,114,59,3,55349,56514,112,111,115,59,1,8766,4,3,59,108,109,13077,13079,13087,1,956,116,105,109,97,112,59,1,8888,97,112,59,1,8888,4,24,71,76,82,86,97,98,99,100,101,102,103,104,105,106,108,109,111,112,114,115,116,117,118,119,13142,13165,13217,13229,13247,13330,13359,13414,13420,13508,13513,13579,13602,13626,13631,13762,13767,13855,13936,13995,14214,14285,14312,14432,4,2,103,116,13148,13152,59,3,8921,824,4,2,59,118,13158,13161,3,8811,8402,59,3,8811,824,4,3,101,108,116,13173,13200,13204,102,116,4,2,97,114,13181,13188,114,114,111,119,59,1,8653,105,103,104,116,97,114,114,111,119,59,1,8654,59,3,8920,824,4,2,59,118,13210,13213,3,8810,8402,59,3,8810,824,105,103,104,116,97,114,114,111,119,59,1,8655,4,2,68,100,13235,13241,97,115,104,59,1,8879,97,115,104,59,1,8878,4,5,98,99,110,112,116,13259,13264,13270,13275,13308,108,97,59,1,8711,117,116,101,59,1,324,103,59,3,8736,8402,4,5,59,69,105,111,112,13287,13289,13293,13298,13302,1,8777,59,3,10864,824,100,59,3,8779,824,115,59,1,329,114,111,120,59,1,8777,117,114,4,2,59,97,13316,13318,1,9838,108,4,2,59,115,13325,13327,1,9838,59,1,8469,4,2,115,117,13336,13344,112,5,160,1,59,13342,1,160,109,112,4,2,59,101,13352,13355,3,8782,824,59,3,8783,824,4,5,97,101,111,117,121,13371,13385,13391,13407,13411,4,2,112,114,13377,13380,59,1,10819,111,110,59,1,328,100,105,108,59,1,326,110,103,4,2,59,100,13399,13401,1,8775,111,116,59,3,10861,824,112,59,1,10818,59,1,1085,97,115,104,59,1,8211,4,7,59,65,97,100,113,115,120,13436,13438,13443,13466,13472,13478,13494,1,8800,114,114,59,1,8663,114,4,2,104,114,13450,13454,107,59,1,10532,4,2,59,111,13460,13462,1,8599,119,59,1,8599,111,116,59,3,8784,824,117,105,118,59,1,8802,4,2,101,105,13484,13489,97,114,59,1,10536,109,59,3,8770,824,105,115,116,4,2,59,115,13503,13505,1,8708,59,1,8708,114,59,3,55349,56619,4,4,69,101,115,116,13523,13527,13563,13568,59,3,8807,824,4,3,59,113,115,13535,13537,13559,1,8817,4,3,59,113,115,13545,13547,13551,1,8817,59,3,8807,824,108,97,110,116,59,3,10878,824,59,3,10878,824,105,109,59,1,8821,4,2,59,114,13574,13576,1,8815,59,1,8815,4,3,65,97,112,13587,13592,13597,114,114,59,1,8654,114,114,59,1,8622,97,114,59,1,10994,4,3,59,115,118,13610,13612,13623,1,8715,4,2,59,100,13618,13620,1,8956,59,1,8954,59,1,8715,99,121,59,1,1114,4,7,65,69,97,100,101,115,116,13647,13652,13656,13661,13665,13737,13742,114,114,59,1,8653,59,3,8806,824,114,114,59,1,8602,114,59,1,8229,4,4,59,102,113,115,13675,13677,13703,13725,1,8816,116,4,2,97,114,13684,13691,114,114,111,119,59,1,8602,105,103,104,116,97,114,114,111,119,59,1,8622,4,3,59,113,115,13711,13713,13717,1,8816,59,3,8806,824,108,97,110,116,59,3,10877,824,4,2,59,115,13731,13734,3,10877,824,59,1,8814,105,109,59,1,8820,4,2,59,114,13748,13750,1,8814,105,4,2,59,101,13757,13759,1,8938,59,1,8940,105,100,59,1,8740,4,2,112,116,13773,13778,102,59,3,55349,56671,5,172,3,59,105,110,13787,13789,13829,1,172,110,4,4,59,69,100,118,13800,13802,13806,13812,1,8713,59,3,8953,824,111,116,59,3,8949,824,4,3,97,98,99,13820,13823,13826,59,1,8713,59,1,8951,59,1,8950,105,4,2,59,118,13836,13838,1,8716,4,3,97,98,99,13846,13849,13852,59,1,8716,59,1,8958,59,1,8957,4,3,97,111,114,13863,13892,13899,114,4,4,59,97,115,116,13874,13876,13883,13888,1,8742,108,108,101,108,59,1,8742,108,59,3,11005,8421,59,3,8706,824,108,105,110,116,59,1,10772,4,3,59,99,101,13907,13909,13914,1,8832,117,101,59,1,8928,4,2,59,99,13920,13923,3,10927,824,4,2,59,101,13929,13931,1,8832,113,59,3,10927,824,4,4,65,97,105,116,13946,13951,13971,13982,114,114,59,1,8655,114,114,4,3,59,99,119,13961,13963,13967,1,8603,59,3,10547,824,59,3,8605,824,103,104,116,97,114,114,111,119,59,1,8603,114,105,4,2,59,101,13990,13992,1,8939,59,1,8941,4,7,99,104,105,109,112,113,117,14011,14036,14060,14080,14085,14090,14106,4,4,59,99,101,114,14021,14023,14028,14032,1,8833,117,101,59,1,8929,59,3,10928,824,59,3,55349,56515,111,114,116,4,2,109,112,14045,14050,105,100,59,1,8740,97,114,97,108,108,101,108,59,1,8742,109,4,2,59,101,14067,14069,1,8769,4,2,59,113,14075,14077,1,8772,59,1,8772,105,100,59,1,8740,97,114,59,1,8742,115,117,4,2,98,112,14098,14102,101,59,1,8930,101,59,1,8931,4,3,98,99,112,14114,14157,14171,4,4,59,69,101,115,14124,14126,14130,14133,1,8836,59,3,10949,824,59,1,8840,101,116,4,2,59,101,14141,14144,3,8834,8402,113,4,2,59,113,14151,14153,1,8840,59,3,10949,824,99,4,2,59,101,14164,14166,1,8833,113,59,3,10928,824,4,4,59,69,101,115,14181,14183,14187,14190,1,8837,59,3,10950,824,59,1,8841,101,116,4,2,59,101,14198,14201,3,8835,8402,113,4,2,59,113,14208,14210,1,8841,59,3,10950,824,4,4,103,105,108,114,14224,14228,14238,14242,108,59,1,8825,108,100,101,5,241,1,59,14236,1,241,103,59,1,8824,105,97,110,103,108,101,4,2,108,114,14254,14269,101,102,116,4,2,59,101,14263,14265,1,8938,113,59,1,8940,105,103,104,116,4,2,59,101,14279,14281,1,8939,113,59,1,8941,4,2,59,109,14291,14293,1,957,4,3,59,101,115,14301,14303,14308,1,35,114,111,59,1,8470,112,59,1,8199,4,9,68,72,97,100,103,105,108,114,115,14332,14338,14344,14349,14355,14369,14376,14408,14426,97,115,104,59,1,8877,97,114,114,59,1,10500,112,59,3,8781,8402,97,115,104,59,1,8876,4,2,101,116,14361,14365,59,3,8805,8402,59,3,62,8402,110,102,105,110,59,1,10718,4,3,65,101,116,14384,14389,14393,114,114,59,1,10498,59,3,8804,8402,4,2,59,114,14399,14402,3,60,8402,105,101,59,3,8884,8402,4,2,65,116,14414,14419,114,114,59,1,10499,114,105,101,59,3,8885,8402,105,109,59,3,8764,8402,4,3,65,97,110,14440,14445,14468,114,114,59,1,8662,114,4,2,104,114,14452,14456,107,59,1,10531,4,2,59,111,14462,14464,1,8598,119,59,1,8598,101,97,114,59,1,10535,4,18,83,97,99,100,101,102,103,104,105,108,109,111,112,114,115,116,117,118,14512,14515,14535,14560,14597,14603,14618,14643,14657,14662,14701,14741,14747,14769,14851,14877,14907,14916,59,1,9416,4,2,99,115,14521,14531,117,116,101,5,243,1,59,14529,1,243,116,59,1,8859,4,2,105,121,14541,14557,114,4,2,59,99,14548,14550,1,8858,5,244,1,59,14555,1,244,59,1,1086,4,5,97,98,105,111,115,14572,14577,14583,14587,14591,115,104,59,1,8861,108,97,99,59,1,337,118,59,1,10808,116,59,1,8857,111,108,100,59,1,10684,108,105,103,59,1,339,4,2,99,114,14609,14614,105,114,59,1,10687,59,3,55349,56620,4,3,111,114,116,14626,14630,14640,110,59,1,731,97,118,101,5,242,1,59,14638,1,242,59,1,10689,4,2,98,109,14649,14654,97,114,59,1,10677,59,1,937,110,116,59,1,8750,4,4,97,99,105,116,14672,14677,14693,14698,114,114,59,1,8634,4,2,105,114,14683,14687,114,59,1,10686,111,115,115,59,1,10683,110,101,59,1,8254,59,1,10688,4,3,97,101,105,14709,14714,14719,99,114,59,1,333,103,97,59,1,969,4,3,99,100,110,14727,14733,14736,114,111,110,59,1,959,59,1,10678,117,115,59,1,8854,112,102,59,3,55349,56672,4,3,97,101,108,14755,14759,14764,114,59,1,10679,114,112,59,1,10681,117,115,59,1,8853,4,7,59,97,100,105,111,115,118,14785,14787,14792,14831,14837,14841,14848,1,8744,114,114,59,1,8635,4,4,59,101,102,109,14802,14804,14817,14824,1,10845,114,4,2,59,111,14811,14813,1,8500,102,59,1,8500,5,170,1,59,14822,1,170,5,186,1,59,14829,1,186,103,111,102,59,1,8886,114,59,1,10838,108,111,112,101,59,1,10839,59,1,10843,4,3,99,108,111,14859,14863,14873,114,59,1,8500,97,115,104,5,248,1,59,14871,1,248,108,59,1,8856,105,4,2,108,109,14884,14893,100,101,5,245,1,59,14891,1,245,101,115,4,2,59,97,14901,14903,1,8855,115,59,1,10806,109,108,5,246,1,59,14914,1,246,98,97,114,59,1,9021,4,12,97,99,101,102,104,105,108,109,111,114,115,117,14948,14992,14996,15033,15038,15068,15090,15189,15192,15222,15427,15441,114,4,4,59,97,115,116,14959,14961,14976,14989,1,8741,5,182,2,59,108,14968,14970,1,182,108,101,108,59,1,8741,4,2,105,108,14982,14986,109,59,1,10995,59,1,11005,59,1,8706,121,59,1,1087,114,4,5,99,105,109,112,116,15009,15014,15019,15024,15027,110,116,59,1,37,111,100,59,1,46,105,108,59,1,8240,59,1,8869,101,110,107,59,1,8241,114,59,3,55349,56621,4,3,105,109,111,15046,15057,15063,4,2,59,118,15052,15054,1,966,59,1,981,109,97,116,59,1,8499,110,101,59,1,9742,4,3,59,116,118,15076,15078,15087,1,960,99,104,102,111,114,107,59,1,8916,59,1,982,4,2,97,117,15096,15119,110,4,2,99,107,15103,15115,107,4,2,59,104,15110,15112,1,8463,59,1,8462,118,59,1,8463,115,4,9,59,97,98,99,100,101,109,115,116,15140,15142,15148,15151,15156,15168,15171,15179,15184,1,43,99,105,114,59,1,10787,59,1,8862,105,114,59,1,10786,4,2,111,117,15162,15165,59,1,8724,59,1,10789,59,1,10866,110,5,177,1,59,15177,1,177,105,109,59,1,10790,119,111,59,1,10791,59,1,177,4,3,105,112,117,15200,15208,15213,110,116,105,110,116,59,1,10773,102,59,3,55349,56673,110,100,5,163,1,59,15220,1,163,4,10,59,69,97,99,101,105,110,111,115,117,15244,15246,15249,15253,15258,15334,15347,15367,15416,15421,1,8826,59,1,10931,112,59,1,10935,117,101,59,1,8828,4,2,59,99,15264,15266,1,10927,4,6,59,97,99,101,110,115,15280,15282,15290,15299,15303,15329,1,8826,112,112,114,111,120,59,1,10935,117,114,108,121,101,113,59,1,8828,113,59,1,10927,4,3,97,101,115,15311,15319,15324,112,112,114,111,120,59,1,10937,113,113,59,1,10933,105,109,59,1,8936,105,109,59,1,8830,109,101,4,2,59,115,15342,15344,1,8242,59,1,8473,4,3,69,97,115,15355,15358,15362,59,1,10933,112,59,1,10937,105,109,59,1,8936,4,3,100,102,112,15375,15378,15404,59,1,8719,4,3,97,108,115,15386,15392,15398,108,97,114,59,1,9006,105,110,101,59,1,8978,117,114,102,59,1,8979,4,2,59,116,15410,15412,1,8733,111,59,1,8733,105,109,59,1,8830,114,101,108,59,1,8880,4,2,99,105,15433,15438,114,59,3,55349,56517,59,1,968,110,99,115,112,59,1,8200,4,6,102,105,111,112,115,117,15462,15467,15472,15478,15485,15491,114,59,3,55349,56622,110,116,59,1,10764,112,102,59,3,55349,56674,114,105,109,101,59,1,8279,99,114,59,3,55349,56518,4,3,97,101,111,15499,15520,15534,116,4,2,101,105,15506,15515,114,110,105,111,110,115,59,1,8461,110,116,59,1,10774,115,116,4,2,59,101,15528,15530,1,63,113,59,1,8799,116,5,34,1,59,15540,1,34,4,21,65,66,72,97,98,99,100,101,102,104,105,108,109,110,111,112,114,115,116,117,120,15586,15609,15615,15620,15796,15855,15893,15931,15977,16001,16039,16183,16204,16222,16228,16285,16312,16318,16363,16408,16416,4,3,97,114,116,15594,15599,15603,114,114,59,1,8667,114,59,1,8658,97,105,108,59,1,10524,97,114,114,59,1,10511,97,114,59,1,10596,4,7,99,100,101,110,113,114,116,15636,15651,15656,15664,15687,15696,15770,4,2,101,117,15642,15646,59,3,8765,817,116,101,59,1,341,105,99,59,1,8730,109,112,116,121,118,59,1,10675,103,4,4,59,100,101,108,15675,15677,15680,15683,1,10217,59,1,10642,59,1,10661,101,59,1,10217,117,111,5,187,1,59,15694,1,187,114,4,11,59,97,98,99,102,104,108,112,115,116,119,15721,15723,15727,15739,15742,15746,15750,15754,15758,15763,15767,1,8594,112,59,1,10613,4,2,59,102,15733,15735,1,8677,115,59,1,10528,59,1,10547,115,59,1,10526,107,59,1,8618,112,59,1,8620,108,59,1,10565,105,109,59,1,10612,108,59,1,8611,59,1,8605,4,2,97,105,15776,15781,105,108,59,1,10522,111,4,2,59,110,15788,15790,1,8758,97,108,115,59,1,8474,4,3,97,98,114,15804,15809,15814,114,114,59,1,10509,114,107,59,1,10099,4,2,97,107,15820,15833,99,4,2,101,107,15827,15830,59,1,125,59,1,93,4,2,101,115,15839,15842,59,1,10636,108,4,2,100,117,15849,15852,59,1,10638,59,1,10640,4,4,97,101,117,121,15865,15871,15886,15890,114,111,110,59,1,345,4,2,100,105,15877,15882,105,108,59,1,343,108,59,1,8969,98,59,1,125,59,1,1088,4,4,99,108,113,115,15903,15907,15914,15927,97,59,1,10551,100,104,97,114,59,1,10601,117,111,4,2,59,114,15922,15924,1,8221,59,1,8221,104,59,1,8627,4,3,97,99,103,15939,15966,15970,108,4,4,59,105,112,115,15950,15952,15957,15963,1,8476,110,101,59,1,8475,97,114,116,59,1,8476,59,1,8477,116,59,1,9645,5,174,1,59,15975,1,174,4,3,105,108,114,15985,15991,15997,115,104,116,59,1,10621,111,111,114,59,1,8971,59,3,55349,56623,4,2,97,111,16007,16028,114,4,2,100,117,16014,16017,59,1,8641,4,2,59,108,16023,16025,1,8640,59,1,10604,4,2,59,118,16034,16036,1,961,59,1,1009,4,3,103,110,115,16047,16167,16171,104,116,4,6,97,104,108,114,115,116,16063,16081,16103,16130,16143,16155,114,114,111,119,4,2,59,116,16073,16075,1,8594,97,105,108,59,1,8611,97,114,112,111,111,110,4,2,100,117,16093,16099,111,119,110,59,1,8641,112,59,1,8640,101,102,116,4,2,97,104,16112,16120,114,114,111,119,115,59,1,8644,97,114,112,111,111,110,115,59,1,8652,105,103,104,116,97,114,114,111,119,115,59,1,8649,113,117,105,103,97,114,114,111,119,59,1,8605,104,114,101,101,116,105,109,101,115,59,1,8908,103,59,1,730,105,110,103,100,111,116,115,101,113,59,1,8787,4,3,97,104,109,16191,16196,16201,114,114,59,1,8644,97,114,59,1,8652,59,1,8207,111,117,115,116,4,2,59,97,16214,16216,1,9137,99,104,101,59,1,9137,109,105,100,59,1,10990,4,4,97,98,112,116,16238,16252,16257,16278,4,2,110,114,16244,16248,103,59,1,10221,114,59,1,8702,114,107,59,1,10215,4,3,97,102,108,16265,16269,16273,114,59,1,10630,59,3,55349,56675,117,115,59,1,10798,105,109,101,115,59,1,10805,4,2,97,112,16291,16304,114,4,2,59,103,16298,16300,1,41,116,59,1,10644,111,108,105,110,116,59,1,10770,97,114,114,59,1,8649,4,4,97,99,104,113,16328,16334,16339,16342,113,117,111,59,1,8250,114,59,3,55349,56519,59,1,8625,4,2,98,117,16348,16351,59,1,93,111,4,2,59,114,16358,16360,1,8217,59,1,8217,4,3,104,105,114,16371,16377,16383,114,101,101,59,1,8908,109,101,115,59,1,8906,105,4,4,59,101,102,108,16394,16396,16399,16402,1,9657,59,1,8885,59,1,9656,116,114,105,59,1,10702,108,117,104,97,114,59,1,10600,59,1,8478,4,19,97,98,99,100,101,102,104,105,108,109,111,112,113,114,115,116,117,119,122,16459,16466,16472,16572,16590,16672,16687,16746,16844,16850,16924,16963,16988,17115,17121,17154,17206,17614,17656,99,117,116,101,59,1,347,113,117,111,59,1,8218,4,10,59,69,97,99,101,105,110,112,115,121,16494,16496,16499,16513,16518,16531,16536,16556,16564,16569,1,8827,59,1,10932,4,2,112,114,16505,16508,59,1,10936,111,110,59,1,353,117,101,59,1,8829,4,2,59,100,16524,16526,1,10928,105,108,59,1,351,114,99,59,1,349,4,3,69,97,115,16544,16547,16551,59,1,10934,112,59,1,10938,105,109,59,1,8937,111,108,105,110,116,59,1,10771,105,109,59,1,8831,59,1,1089,111,116,4,3,59,98,101,16582,16584,16587,1,8901,59,1,8865,59,1,10854,4,7,65,97,99,109,115,116,120,16606,16611,16634,16642,16646,16652,16668,114,114,59,1,8664,114,4,2,104,114,16618,16622,107,59,1,10533,4,2,59,111,16628,16630,1,8600,119,59,1,8600,116,5,167,1,59,16640,1,167,105,59,1,59,119,97,114,59,1,10537,109,4,2,105,110,16659,16665,110,117,115,59,1,8726,59,1,8726,116,59,1,10038,114,4,2,59,111,16679,16682,3,55349,56624,119,110,59,1,8994,4,4,97,99,111,121,16697,16702,16716,16739,114,112,59,1,9839,4,2,104,121,16708,16713,99,121,59,1,1097,59,1,1096,114,116,4,2,109,112,16724,16729,105,100,59,1,8739,97,114,97,108,108,101,108,59,1,8741,5,173,1,59,16744,1,173,4,2,103,109,16752,16770,109,97,4,3,59,102,118,16762,16764,16767,1,963,59,1,962,59,1,962,4,8,59,100,101,103,108,110,112,114,16788,16790,16795,16806,16817,16828,16832,16838,1,8764,111,116,59,1,10858,4,2,59,113,16801,16803,1,8771,59,1,8771,4,2,59,69,16812,16814,1,10910,59,1,10912,4,2,59,69,16823,16825,1,10909,59,1,10911,101,59,1,8774,108,117,115,59,1,10788,97,114,114,59,1,10610,97,114,114,59,1,8592,4,4,97,101,105,116,16860,16883,16891,16904,4,2,108,115,16866,16878,108,115,101,116,109,105,110,117,115,59,1,8726,104,112,59,1,10803,112,97,114,115,108,59,1,10724,4,2,100,108,16897,16900,59,1,8739,101,59,1,8995,4,2,59,101,16910,16912,1,10922,4,2,59,115,16918,16920,1,10924,59,3,10924,65024,4,3,102,108,112,16932,16938,16958,116,99,121,59,1,1100,4,2,59,98,16944,16946,1,47,4,2,59,97,16952,16954,1,10692,114,59,1,9023,102,59,3,55349,56676,97,4,2,100,114,16970,16985,101,115,4,2,59,117,16978,16980,1,9824,105,116,59,1,9824,59,1,8741,4,3,99,115,117,16996,17028,17089,4,2,97,117,17002,17015,112,4,2,59,115,17009,17011,1,8851,59,3,8851,65024,112,4,2,59,115,17022,17024,1,8852,59,3,8852,65024,117,4,2,98,112,17035,17062,4,3,59,101,115,17043,17045,17048,1,8847,59,1,8849,101,116,4,2,59,101,17056,17058,1,8847,113,59,1,8849,4,3,59,101,115,17070,17072,17075,1,8848,59,1,8850,101,116,4,2,59,101,17083,17085,1,8848,113,59,1,8850,4,3,59,97,102,17097,17099,17112,1,9633,114,4,2,101,102,17106,17109,59,1,9633,59,1,9642,59,1,9642,97,114,114,59,1,8594,4,4,99,101,109,116,17131,17136,17142,17148,114,59,3,55349,56520,116,109,110,59,1,8726,105,108,101,59,1,8995,97,114,102,59,1,8902,4,2,97,114,17160,17172,114,4,2,59,102,17167,17169,1,9734,59,1,9733,4,2,97,110,17178,17202,105,103,104,116,4,2,101,112,17188,17197,112,115,105,108,111,110,59,1,1013,104,105,59,1,981,115,59,1,175,4,5,98,99,109,110,112,17218,17351,17420,17423,17427,4,9,59,69,100,101,109,110,112,114,115,17238,17240,17243,17248,17261,17267,17279,17285,17291,1,8834,59,1,10949,111,116,59,1,10941,4,2,59,100,17254,17256,1,8838,111,116,59,1,10947,117,108,116,59,1,10945,4,2,69,101,17273,17276,59,1,10955,59,1,8842,108,117,115,59,1,10943,97,114,114,59,1,10617,4,3,101,105,117,17299,17335,17339,116,4,3,59,101,110,17308,17310,17322,1,8834,113,4,2,59,113,17317,17319,1,8838,59,1,10949,101,113,4,2,59,113,17330,17332,1,8842,59,1,10955,109,59,1,10951,4,2,98,112,17345,17348,59,1,10965,59,1,10963,99,4,6,59,97,99,101,110,115,17366,17368,17376,17385,17389,17415,1,8827,112,112,114,111,120,59,1,10936,117,114,108,121,101,113,59,1,8829,113,59,1,10928,4,3,97,101,115,17397,17405,17410,112,112,114,111,120,59,1,10938,113,113,59,1,10934,105,109,59,1,8937,105,109,59,1,8831,59,1,8721,103,59,1,9834,4,13,49,50,51,59,69,100,101,104,108,109,110,112,115,17455,17462,17469,17476,17478,17481,17496,17509,17524,17530,17536,17548,17554,5,185,1,59,17460,1,185,5,178,1,59,17467,1,178,5,179,1,59,17474,1,179,1,8835,59,1,10950,4,2,111,115,17487,17491,116,59,1,10942,117,98,59,1,10968,4,2,59,100,17502,17504,1,8839,111,116,59,1,10948,115,4,2,111,117,17516,17520,108,59,1,10185,98,59,1,10967,97,114,114,59,1,10619,117,108,116,59,1,10946,4,2,69,101,17542,17545,59,1,10956,59,1,8843,108,117,115,59,1,10944,4,3,101,105,117,17562,17598,17602,116,4,3,59,101,110,17571,17573,17585,1,8835,113,4,2,59,113,17580,17582,1,8839,59,1,10950,101,113,4,2,59,113,17593,17595,1,8843,59,1,10956,109,59,1,10952,4,2,98,112,17608,17611,59,1,10964,59,1,10966,4,3,65,97,110,17622,17627,17650,114,114,59,1,8665,114,4,2,104,114,17634,17638,107,59,1,10534,4,2,59,111,17644,17646,1,8601,119,59,1,8601,119,97,114,59,1,10538,108,105,103,5,223,1,59,17664,1,223,4,13,97,98,99,100,101,102,104,105,111,112,114,115,119,17694,17709,17714,17737,17742,17749,17754,17860,17905,17957,17964,18090,18122,4,2,114,117,17700,17706,103,101,116,59,1,8982,59,1,964,114,107,59,1,9140,4,3,97,101,121,17722,17728,17734,114,111,110,59,1,357,100,105,108,59,1,355,59,1,1090,111,116,59,1,8411,108,114,101,99,59,1,8981,114,59,3,55349,56625,4,4,101,105,107,111,17764,17805,17836,17851,4,2,114,116,17770,17786,101,4,2,52,102,17777,17780,59,1,8756,111,114,101,59,1,8756,97,4,3,59,115,118,17795,17797,17802,1,952,121,109,59,1,977,59,1,977,4,2,99,110,17811,17831,107,4,2,97,115,17818,17826,112,112,114,111,120,59,1,8776,105,109,59,1,8764,115,112,59,1,8201,4,2,97,115,17842,17846,112,59,1,8776,105,109,59,1,8764,114,110,5,254,1,59,17858,1,254,4,3,108,109,110,17868,17873,17901,100,101,59,1,732,101,115,5,215,3,59,98,100,17884,17886,17898,1,215,4,2,59,97,17892,17894,1,8864,114,59,1,10801,59,1,10800,116,59,1,8749,4,3,101,112,115,17913,17917,17953,97,59,1,10536,4,4,59,98,99,102,17927,17929,17934,17939,1,8868,111,116,59,1,9014,105,114,59,1,10993,4,2,59,111,17945,17948,3,55349,56677,114,107,59,1,10970,97,59,1,10537,114,105,109,101,59,1,8244,4,3,97,105,112,17972,17977,18082,100,101,59,1,8482,4,7,97,100,101,109,112,115,116,17993,18051,18056,18059,18066,18072,18076,110,103,108,101,4,5,59,100,108,113,114,18009,18011,18017,18032,18035,1,9653,111,119,110,59,1,9663,101,102,116,4,2,59,101,18026,18028,1,9667,113,59,1,8884,59,1,8796,105,103,104,116,4,2,59,101,18045,18047,1,9657,113,59,1,8885,111,116,59,1,9708,59,1,8796,105,110,117,115,59,1,10810,108,117,115,59,1,10809,98,59,1,10701,105,109,101,59,1,10811,101,122,105,117,109,59,1,9186,4,3,99,104,116,18098,18111,18116,4,2,114,121,18104,18108,59,3,55349,56521,59,1,1094,99,121,59,1,1115,114,111,107,59,1,359,4,2,105,111,18128,18133,120,116,59,1,8812,104,101,97,100,4,2,108,114,18143,18154,101,102,116,97,114,114,111,119,59,1,8606,105,103,104,116,97,114,114,111,119,59,1,8608,4,18,65,72,97,98,99,100,102,103,104,108,109,111,112,114,115,116,117,119,18204,18209,18214,18234,18250,18268,18292,18308,18319,18343,18379,18397,18413,18504,18547,18553,18584,18603,114,114,59,1,8657,97,114,59,1,10595,4,2,99,114,18220,18230,117,116,101,5,250,1,59,18228,1,250,114,59,1,8593,114,4,2,99,101,18241,18245,121,59,1,1118,118,101,59,1,365,4,2,105,121,18256,18265,114,99,5,251,1,59,18263,1,251,59,1,1091,4,3,97,98,104,18276,18281,18287,114,114,59,1,8645,108,97,99,59,1,369,97,114,59,1,10606,4,2,105,114,18298,18304,115,104,116,59,1,10622,59,3,55349,56626,114,97,118,101,5,249,1,59,18317,1,249,4,2,97,98,18325,18338,114,4,2,108,114,18332,18335,59,1,8639,59,1,8638,108,107,59,1,9600,4,2,99,116,18349,18374,4,2,111,114,18355,18369,114,110,4,2,59,101,18363,18365,1,8988,114,59,1,8988,111,112,59,1,8975,114,105,59,1,9720,4,2,97,108,18385,18390,99,114,59,1,363,5,168,1,59,18395,1,168,4,2,103,112,18403,18408,111,110,59,1,371,102,59,3,55349,56678,4,6,97,100,104,108,115,117,18427,18434,18445,18470,18475,18494,114,114,111,119,59,1,8593,111,119,110,97,114,114,111,119,59,1,8597,97,114,112,111,111,110,4,2,108,114,18457,18463,101,102,116,59,1,8639,105,103,104,116,59,1,8638,117,115,59,1,8846,105,4,3,59,104,108,18484,18486,18489,1,965,59,1,978,111,110,59,1,965,112,97,114,114,111,119,115,59,1,8648,4,3,99,105,116,18512,18537,18542,4,2,111,114,18518,18532,114,110,4,2,59,101,18526,18528,1,8989,114,59,1,8989,111,112,59,1,8974,110,103,59,1,367,114,105,59,1,9721,99,114,59,3,55349,56522,4,3,100,105,114,18561,18566,18572,111,116,59,1,8944,108,100,101,59,1,361,105,4,2,59,102,18579,18581,1,9653,59,1,9652,4,2,97,109,18590,18595,114,114,59,1,8648,108,5,252,1,59,18601,1,252,97,110,103,108,101,59,1,10663,4,15,65,66,68,97,99,100,101,102,108,110,111,112,114,115,122,18643,18648,18661,18667,18847,18851,18857,18904,18909,18915,18931,18937,18943,18949,18996,114,114,59,1,8661,97,114,4,2,59,118,18656,18658,1,10984,59,1,10985,97,115,104,59,1,8872,4,2,110,114,18673,18679,103,114,116,59,1,10652,4,7,101,107,110,112,114,115,116,18695,18704,18711,18720,18742,18754,18810,112,115,105,108,111,110,59,1,1013,97,112,112,97,59,1,1008,111,116,104,105,110,103,59,1,8709,4,3,104,105,114,18728,18732,18735,105,59,1,981,59,1,982,111,112,116,111,59,1,8733,4,2,59,104,18748,18750,1,8597,111,59,1,1009,4,2,105,117,18760,18766,103,109,97,59,1,962,4,2,98,112,18772,18791,115,101,116,110,101,113,4,2,59,113,18784,18787,3,8842,65024,59,3,10955,65024,115,101,116,110,101,113,4,2,59,113,18803,18806,3,8843,65024,59,3,10956,65024,4,2,104,114,18816,18822,101,116,97,59,1,977,105,97,110,103,108,101,4,2,108,114,18834,18840,101,102,116,59,1,8882,105,103,104,116,59,1,8883,121,59,1,1074,97,115,104,59,1,8866,4,3,101,108,114,18865,18884,18890,4,3,59,98,101,18873,18875,18880,1,8744,97,114,59,1,8891,113,59,1,8794,108,105,112,59,1,8942,4,2,98,116,18896,18901,97,114,59,1,124,59,1,124,114,59,3,55349,56627,116,114,105,59,1,8882,115,117,4,2,98,112,18923,18927,59,3,8834,8402,59,3,8835,8402,112,102,59,3,55349,56679,114,111,112,59,1,8733,116,114,105,59,1,8883,4,2,99,117,18955,18960,114,59,3,55349,56523,4,2,98,112,18966,18981,110,4,2,69,101,18973,18977,59,3,10955,65024,59,3,8842,65024,110,4,2,69,101,18988,18992,59,3,10956,65024,59,3,8843,65024,105,103,122,97,103,59,1,10650,4,7,99,101,102,111,112,114,115,19020,19026,19061,19066,19072,19075,19089,105,114,99,59,1,373,4,2,100,105,19032,19055,4,2,98,103,19038,19043,97,114,59,1,10847,101,4,2,59,113,19050,19052,1,8743,59,1,8793,101,114,112,59,1,8472,114,59,3,55349,56628,112,102,59,3,55349,56680,59,1,8472,4,2,59,101,19081,19083,1,8768,97,116,104,59,1,8768,99,114,59,3,55349,56524,4,14,99,100,102,104,105,108,109,110,111,114,115,117,118,119,19125,19146,19152,19157,19173,19176,19192,19197,19202,19236,19252,19269,19286,19291,4,3,97,105,117,19133,19137,19142,112,59,1,8898,114,99,59,1,9711,112,59,1,8899,116,114,105,59,1,9661,114,59,3,55349,56629,4,2,65,97,19163,19168,114,114,59,1,10234,114,114,59,1,10231,59,1,958,4,2,65,97,19182,19187,114,114,59,1,10232,114,114,59,1,10229,97,112,59,1,10236,105,115,59,1,8955,4,3,100,112,116,19210,19215,19230,111,116,59,1,10752,4,2,102,108,19221,19225,59,3,55349,56681,117,115,59,1,10753,105,109,101,59,1,10754,4,2,65,97,19242,19247,114,114,59,1,10233,114,114,59,1,10230,4,2,99,113,19258,19263,114,59,3,55349,56525,99,117,112,59,1,10758,4,2,112,116,19275,19281,108,117,115,59,1,10756,114,105,59,1,9651,101,101,59,1,8897,101,100,103,101,59,1,8896,4,8,97,99,101,102,105,111,115,117,19316,19335,19349,19357,19362,19367,19373,19379,99,4,2,117,121,19323,19332,116,101,5,253,1,59,19330,1,253,59,1,1103,4,2,105,121,19341,19346,114,99,59,1,375,59,1,1099,110,5,165,1,59,19355,1,165,114,59,3,55349,56630,99,121,59,1,1111,112,102,59,3,55349,56682,99,114,59,3,55349,56526,4,2,99,109,19385,19389,121,59,1,1102,108,5,255,1,59,19395,1,255,4,10,97,99,100,101,102,104,105,111,115,119,19419,19426,19441,19446,19462,19467,19472,19480,19486,19492,99,117,116,101,59,1,378,4,2,97,121,19432,19438,114,111,110,59,1,382,59,1,1079,111,116,59,1,380,4,2,101,116,19452,19458,116,114,102,59,1,8488,97,59,1,950,114,59,3,55349,56631,99,121,59,1,1078,103,114,97,114,114,59,1,8669,112,102,59,3,55349,56683,99,114,59,3,55349,56527,4,2,106,110,19498,19501,59,1,8205,106,59,1,8204]);

/***/ }),
/* 975 */
/***/ (function(module, exports, __nested_webpack_require_4709087__) {

"use strict";


var HTML = __nested_webpack_require_4709087__(64);

//Aliases
var $ = HTML.TAG_NAMES,
    NS = HTML.NAMESPACES;

//Element utils

//OPTIMIZATION: Integer comparisons are low-cost, so we can use very fast tag name length filters here.
//It's faster than using dictionary.
function isImpliedEndTagRequired(tn) {
    switch (tn.length) {
        case 1:
            return tn === $.P;

        case 2:
            return tn === $.RB || tn === $.RP || tn === $.RT || tn === $.DD || tn === $.DT || tn === $.LI;

        case 3:
            return tn === $.RTC;

        case 6:
            return tn === $.OPTION;

        case 8:
            return tn === $.OPTGROUP || tn === $.MENUITEM;
    }

    return false;
}

function isScopingElement(tn, ns) {
    switch (tn.length) {
        case 2:
            if (tn === $.TD || tn === $.TH)
                return ns === NS.HTML;

            else if (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS)
                return ns === NS.MATHML;

            break;

        case 4:
            if (tn === $.HTML)
                return ns === NS.HTML;

            else if (tn === $.DESC)
                return ns === NS.SVG;

            break;

        case 5:
            if (tn === $.TABLE)
                return ns === NS.HTML;

            else if (tn === $.MTEXT)
                return ns === NS.MATHML;

            else if (tn === $.TITLE)
                return ns === NS.SVG;

            break;

        case 6:
            return (tn === $.APPLET || tn === $.OBJECT) && ns === NS.HTML;

        case 7:
            return (tn === $.CAPTION || tn === $.MARQUEE) && ns === NS.HTML;

        case 8:
            return tn === $.TEMPLATE && ns === NS.HTML;

        case 13:
            return tn === $.FOREIGN_OBJECT && ns === NS.SVG;

        case 14:
            return tn === $.ANNOTATION_XML && ns === NS.MATHML;
    }

    return false;
}

//Stack of open elements
var OpenElementStack = module.exports = function (document, treeAdapter) {
    this.stackTop = -1;
    this.items = [];
    this.current = document;
    this.currentTagName = null;
    this.currentTmplContent = null;
    this.tmplCount = 0;
    this.treeAdapter = treeAdapter;
};

//Index of element
OpenElementStack.prototype._indexOf = function (element) {
    var idx = -1;

    for (var i = this.stackTop; i >= 0; i--) {
        if (this.items[i] === element) {
            idx = i;
            break;
        }
    }
    return idx;
};

//Update current element
OpenElementStack.prototype._isInTemplate = function () {
    return this.currentTagName === $.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML;
};

OpenElementStack.prototype._updateCurrentElement = function () {
    this.current = this.items[this.stackTop];
    this.currentTagName = this.current && this.treeAdapter.getTagName(this.current);

    this.currentTmplContent = this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : null;
};

//Mutations
OpenElementStack.prototype.push = function (element) {
    this.items[++this.stackTop] = element;
    this._updateCurrentElement();

    if (this._isInTemplate())
        this.tmplCount++;

};

OpenElementStack.prototype.pop = function () {
    this.stackTop--;

    if (this.tmplCount > 0 && this._isInTemplate())
        this.tmplCount--;

    this._updateCurrentElement();
};

OpenElementStack.prototype.replace = function (oldElement, newElement) {
    var idx = this._indexOf(oldElement);

    this.items[idx] = newElement;

    if (idx === this.stackTop)
        this._updateCurrentElement();
};

OpenElementStack.prototype.insertAfter = function (referenceElement, newElement) {
    var insertionIdx = this._indexOf(referenceElement) + 1;

    this.items.splice(insertionIdx, 0, newElement);

    if (insertionIdx === ++this.stackTop)
        this._updateCurrentElement();
};

OpenElementStack.prototype.popUntilTagNamePopped = function (tagName) {
    while (this.stackTop > -1) {
        var tn = this.currentTagName,
            ns = this.treeAdapter.getNamespaceURI(this.current);

        this.pop();

        if (tn === tagName && ns === NS.HTML)
            break;
    }
};

OpenElementStack.prototype.popUntilElementPopped = function (element) {
    while (this.stackTop > -1) {
        var poppedElement = this.current;

        this.pop();

        if (poppedElement === element)
            break;
    }
};

OpenElementStack.prototype.popUntilNumberedHeaderPopped = function () {
    while (this.stackTop > -1) {
        var tn = this.currentTagName,
            ns = this.treeAdapter.getNamespaceURI(this.current);

        this.pop();

        if (tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6 && ns === NS.HTML)
            break;
    }
};

OpenElementStack.prototype.popUntilTableCellPopped = function () {
    while (this.stackTop > -1) {
        var tn = this.currentTagName,
            ns = this.treeAdapter.getNamespaceURI(this.current);

        this.pop();

        if (tn === $.TD || tn === $.TH && ns === NS.HTML)
            break;
    }
};

OpenElementStack.prototype.popAllUpToHtmlElement = function () {
    //NOTE: here we assume that root <html> element is always first in the open element stack, so
    //we perform this fast stack clean up.
    this.stackTop = 0;
    this._updateCurrentElement();
};

OpenElementStack.prototype.clearBackToTableContext = function () {
    while (this.currentTagName !== $.TABLE &&
           this.currentTagName !== $.TEMPLATE &&
           this.currentTagName !== $.HTML ||
           this.treeAdapter.getNamespaceURI(this.current) !== NS.HTML)
        this.pop();
};

OpenElementStack.prototype.clearBackToTableBodyContext = function () {
    while (this.currentTagName !== $.TBODY &&
           this.currentTagName !== $.TFOOT &&
           this.currentTagName !== $.THEAD &&
           this.currentTagName !== $.TEMPLATE &&
           this.currentTagName !== $.HTML ||
           this.treeAdapter.getNamespaceURI(this.current) !== NS.HTML)
        this.pop();
};

OpenElementStack.prototype.clearBackToTableRowContext = function () {
    while (this.currentTagName !== $.TR &&
           this.currentTagName !== $.TEMPLATE &&
           this.currentTagName !== $.HTML ||
           this.treeAdapter.getNamespaceURI(this.current) !== NS.HTML)
        this.pop();
};

OpenElementStack.prototype.remove = function (element) {
    for (var i = this.stackTop; i >= 0; i--) {
        if (this.items[i] === element) {
            this.items.splice(i, 1);
            this.stackTop--;
            this._updateCurrentElement();
            break;
        }
    }
};

//Search
OpenElementStack.prototype.tryPeekProperlyNestedBodyElement = function () {
    //Properly nested <body> element (should be second element in stack).
    var element = this.items[1];

    return element && this.treeAdapter.getTagName(element) === $.BODY ? element : null;
};

OpenElementStack.prototype.contains = function (element) {
    return this._indexOf(element) > -1;
};

OpenElementStack.prototype.getCommonAncestor = function (element) {
    var elementIdx = this._indexOf(element);

    return --elementIdx >= 0 ? this.items[elementIdx] : null;
};

OpenElementStack.prototype.isRootHtmlElementCurrent = function () {
    return this.stackTop === 0 && this.currentTagName === $.HTML;
};

//Element in scope
OpenElementStack.prototype.hasInScope = function (tagName) {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if (tn === tagName && ns === NS.HTML)
            return true;

        if (isScopingElement(tn, ns))
            return false;
    }

    return true;
};

OpenElementStack.prototype.hasNumberedHeaderInScope = function () {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if ((tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6) && ns === NS.HTML)
            return true;

        if (isScopingElement(tn, ns))
            return false;
    }

    return true;
};

OpenElementStack.prototype.hasInListItemScope = function (tagName) {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if (tn === tagName && ns === NS.HTML)
            return true;

        if ((tn === $.UL || tn === $.OL) && ns === NS.HTML || isScopingElement(tn, ns))
            return false;
    }

    return true;
};

OpenElementStack.prototype.hasInButtonScope = function (tagName) {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if (tn === tagName && ns === NS.HTML)
            return true;

        if (tn === $.BUTTON && ns === NS.HTML || isScopingElement(tn, ns))
            return false;
    }

    return true;
};

OpenElementStack.prototype.hasInTableScope = function (tagName) {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if (ns !== NS.HTML)
            continue;

        if (tn === tagName)
            return true;

        if (tn === $.TABLE || tn === $.TEMPLATE || tn === $.HTML)
            return false;
    }

    return true;
};

OpenElementStack.prototype.hasTableBodyContextInTableScope = function () {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if (ns !== NS.HTML)
            continue;

        if (tn === $.TBODY || tn === $.THEAD || tn === $.TFOOT)
            return true;

        if (tn === $.TABLE || tn === $.HTML)
            return false;
    }

    return true;
};

OpenElementStack.prototype.hasInSelectScope = function (tagName) {
    for (var i = this.stackTop; i >= 0; i--) {
        var tn = this.treeAdapter.getTagName(this.items[i]),
            ns = this.treeAdapter.getNamespaceURI(this.items[i]);

        if (ns !== NS.HTML)
            continue;

        if (tn === tagName)
            return true;

        if (tn !== $.OPTION && tn !== $.OPTGROUP)
            return false;
    }

    return true;
};

//Implied end tags
OpenElementStack.prototype.generateImpliedEndTags = function () {
    while (isImpliedEndTagRequired(this.currentTagName))
        this.pop();
};

OpenElementStack.prototype.generateImpliedEndTagsWithExclusion = function (exclusionTagName) {
    while (isImpliedEndTagRequired(this.currentTagName) && this.currentTagName !== exclusionTagName)
        this.pop();
};


/***/ }),
/* 976 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


//Const
var NOAH_ARK_CAPACITY = 3;

//List of formatting elements
var FormattingElementList = module.exports = function (treeAdapter) {
    this.length = 0;
    this.entries = [];
    this.treeAdapter = treeAdapter;
    this.bookmark = null;
};

//Entry types
FormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY';
FormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY';

//Noah Ark's condition
//OPTIMIZATION: at first we try to find possible candidates for exclusion using
//lightweight heuristics without thorough attributes check.
FormattingElementList.prototype._getNoahArkConditionCandidates = function (newElement) {
    var candidates = [];

    if (this.length >= NOAH_ARK_CAPACITY) {
        var neAttrsLength = this.treeAdapter.getAttrList(newElement).length,
            neTagName = this.treeAdapter.getTagName(newElement),
            neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement);

        for (var i = this.length - 1; i >= 0; i--) {
            var entry = this.entries[i];

            if (entry.type === FormattingElementList.MARKER_ENTRY)
                break;

            var element = entry.element,
                elementAttrs = this.treeAdapter.getAttrList(element),
                isCandidate = this.treeAdapter.getTagName(element) === neTagName &&
                              this.treeAdapter.getNamespaceURI(element) === neNamespaceURI &&
                              elementAttrs.length === neAttrsLength;

            if (isCandidate)
                candidates.push({idx: i, attrs: elementAttrs});
        }
    }

    return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates;
};

FormattingElementList.prototype._ensureNoahArkCondition = function (newElement) {
    var candidates = this._getNoahArkConditionCandidates(newElement),
        cLength = candidates.length;

    if (cLength) {
        var neAttrs = this.treeAdapter.getAttrList(newElement),
            neAttrsLength = neAttrs.length,
            neAttrsMap = Object.create(null);

        //NOTE: build attrs map for the new element so we can perform fast lookups
        for (var i = 0; i < neAttrsLength; i++) {
            var neAttr = neAttrs[i];

            neAttrsMap[neAttr.name] = neAttr.value;
        }

        for (i = 0; i < neAttrsLength; i++) {
            for (var j = 0; j < cLength; j++) {
                var cAttr = candidates[j].attrs[i];

                if (neAttrsMap[cAttr.name] !== cAttr.value) {
                    candidates.splice(j, 1);
                    cLength--;
                }

                if (candidates.length < NOAH_ARK_CAPACITY)
                    return;
            }
        }

        //NOTE: remove bottommost candidates until Noah's Ark condition will not be met
        for (i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) {
            this.entries.splice(candidates[i].idx, 1);
            this.length--;
        }
    }
};

//Mutations
FormattingElementList.prototype.insertMarker = function () {
    this.entries.push({type: FormattingElementList.MARKER_ENTRY});
    this.length++;
};

FormattingElementList.prototype.pushElement = function (element, token) {
    this._ensureNoahArkCondition(element);

    this.entries.push({
        type: FormattingElementList.ELEMENT_ENTRY,
        element: element,
        token: token
    });

    this.length++;
};

FormattingElementList.prototype.insertElementAfterBookmark = function (element, token) {
    var bookmarkIdx = this.length - 1;

    for (; bookmarkIdx >= 0; bookmarkIdx--) {
        if (this.entries[bookmarkIdx] === this.bookmark)
            break;
    }

    this.entries.splice(bookmarkIdx + 1, 0, {
        type: FormattingElementList.ELEMENT_ENTRY,
        element: element,
        token: token
    });

    this.length++;
};

FormattingElementList.prototype.removeEntry = function (entry) {
    for (var i = this.length - 1; i >= 0; i--) {
        if (this.entries[i] === entry) {
            this.entries.splice(i, 1);
            this.length--;
            break;
        }
    }
};

FormattingElementList.prototype.clearToLastMarker = function () {
    while (this.length) {
        var entry = this.entries.pop();

        this.length--;

        if (entry.type === FormattingElementList.MARKER_ENTRY)
            break;
    }
};

//Search
FormattingElementList.prototype.getElementEntryInScopeWithTagName = function (tagName) {
    for (var i = this.length - 1; i >= 0; i--) {
        var entry = this.entries[i];

        if (entry.type === FormattingElementList.MARKER_ENTRY)
            return null;

        if (this.treeAdapter.getTagName(entry.element) === tagName)
            return entry;
    }

    return null;
};

FormattingElementList.prototype.getElementEntry = function (element) {
    for (var i = this.length - 1; i >= 0; i--) {
        var entry = this.entries[i];

        if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element)
            return entry;
    }

    return null;
};


/***/ }),
/* 977 */
/***/ (function(module, exports, __nested_webpack_require_4725213__) {

"use strict";


var Mixin = __nested_webpack_require_4725213__(201),
    Tokenizer = __nested_webpack_require_4725213__(124),
    LocationInfoTokenizerMixin = __nested_webpack_require_4725213__(463),
    PositionTrackingPreprocessorMixin = __nested_webpack_require_4725213__(464),
    LocationInfoOpenElementStackMixin = __nested_webpack_require_4725213__(979),
    HTML = __nested_webpack_require_4725213__(64),
    inherits = __nested_webpack_require_4725213__(71).inherits;


//Aliases
var $ = HTML.TAG_NAMES;

var LocationInfoParserMixin = module.exports = function (parser) {
    Mixin.call(this, parser);

    this.parser = parser;
    this.posTracker = null;
    this.lastStartTagToken = null;
    this.lastFosterParentingLocation = null;
    this.currentToken = null;
};

inherits(LocationInfoParserMixin, Mixin);


LocationInfoParserMixin.prototype._setStartLocation = function (element) {
    if (this.lastStartTagToken) {
        element.__location = Object.create(this.lastStartTagToken.location);
        element.__location.startTag = this.lastStartTagToken.location;
    }
    else
        element.__location = null;
};

LocationInfoParserMixin.prototype._setEndLocation = function (element, closingToken) {
    var loc = element.__location;

    if (loc) {
        if (closingToken.location) {
            var ctLoc = closingToken.location,
                tn = this.parser.treeAdapter.getTagName(element);

            // NOTE: For cases like <p> <p> </p> - First 'p' closes without a closing
            // tag and for cases like <td> <p> </td> - 'p' closes without a closing tag.
            var isClosingEndTag = closingToken.type === Tokenizer.END_TAG_TOKEN && tn === closingToken.tagName;

            if (isClosingEndTag) {
                loc.endTag = Object.create(ctLoc);
                loc.endOffset = ctLoc.endOffset;
            }

            else
                loc.endOffset = ctLoc.startOffset;
        }

        else if (closingToken.type === Tokenizer.EOF_TOKEN)
            loc.endOffset = this.posTracker.offset;
    }
};

LocationInfoParserMixin.prototype._getOverriddenMethods = function (mxn, orig) {
    return {
        _bootstrap: function (document, fragmentContext) {
            orig._bootstrap.call(this, document, fragmentContext);

            mxn.lastStartTagToken = null;
            mxn.lastFosterParentingLocation = null;
            mxn.currentToken = null;
            mxn.posTracker = new PositionTrackingPreprocessorMixin(this.tokenizer.preprocessor);

            new LocationInfoTokenizerMixin(this.tokenizer);

            new LocationInfoOpenElementStackMixin(this.openElements, {
                onItemPop: function (element) {
                    mxn._setEndLocation(element, mxn.currentToken);
                }
            });
        },

        _runParsingLoop: function (scriptHandler) {
            orig._runParsingLoop.call(this, scriptHandler);

            // NOTE: generate location info for elements
            // that remains on open element stack
            for (var i = this.openElements.stackTop; i >= 0; i--)
                mxn._setEndLocation(this.openElements.items[i], mxn.currentToken);
        },


        //Token processing
        _processTokenInForeignContent: function (token) {
            mxn.currentToken = token;
            orig._processTokenInForeignContent.call(this, token);
        },

        _processToken: function (token) {
            mxn.currentToken = token;
            orig._processToken.call(this, token);

            //NOTE: <body> and <html> are never popped from the stack, so we need to updated
            //their end location explicitly.
            var requireExplicitUpdate = token.type === Tokenizer.END_TAG_TOKEN &&
                                        (token.tagName === $.HTML ||
                                         token.tagName === $.BODY && this.openElements.hasInScope($.BODY));

            if (requireExplicitUpdate) {
                for (var i = this.openElements.stackTop; i >= 0; i--) {
                    var element = this.openElements.items[i];

                    if (this.treeAdapter.getTagName(element) === token.tagName) {
                        mxn._setEndLocation(element, token);
                        break;
                    }
                }
            }
        },


        //Doctype
        _setDocumentType: function (token) {
            orig._setDocumentType.call(this, token);

            var documentChildren = this.treeAdapter.getChildNodes(this.document),
                cnLength = documentChildren.length;

            for (var i = 0; i < cnLength; i++) {
                var node = documentChildren[i];

                if (this.treeAdapter.isDocumentTypeNode(node)) {
                    node.__location = token.location;
                    break;
                }
            }
        },


        //Elements
        _attachElementToTree: function (element) {
            //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods.
            //So we will use token location stored in this methods for the element.
            mxn._setStartLocation(element);
            mxn.lastStartTagToken = null;
            orig._attachElementToTree.call(this, element);
        },

        _appendElement: function (token, namespaceURI) {
            mxn.lastStartTagToken = token;
            orig._appendElement.call(this, token, namespaceURI);
        },

        _insertElement: function (token, namespaceURI) {
            mxn.lastStartTagToken = token;
            orig._insertElement.call(this, token, namespaceURI);
        },

        _insertTemplate: function (token) {
            mxn.lastStartTagToken = token;
            orig._insertTemplate.call(this, token);

            var tmplContent = this.treeAdapter.getTemplateContent(this.openElements.current);

            tmplContent.__location = null;
        },

        _insertFakeRootElement: function () {
            orig._insertFakeRootElement.call(this);
            this.openElements.current.__location = null;
        },

        //Comments
        _appendCommentNode: function (token, parent) {
            orig._appendCommentNode.call(this, token, parent);

            var children = this.treeAdapter.getChildNodes(parent),
                commentNode = children[children.length - 1];

            commentNode.__location = token.location;
        },

        //Text
        _findFosterParentingLocation: function () {
            //NOTE: store last foster parenting location, so we will be able to find inserted text
            //in case of foster parenting
            mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call(this);

            return mxn.lastFosterParentingLocation;
        },

        _insertCharacters: function (token) {
            orig._insertCharacters.call(this, token);

            var hasFosterParent = this._shouldFosterParentOnInsertion(),
                parent = hasFosterParent && mxn.lastFosterParentingLocation.parent ||
                         this.openElements.currentTmplContent ||
                         this.openElements.current,
                siblings = this.treeAdapter.getChildNodes(parent),
                textNodeIdx = hasFosterParent && mxn.lastFosterParentingLocation.beforeElement ?
                siblings.indexOf(mxn.lastFosterParentingLocation.beforeElement) - 1 :
                siblings.length - 1,
                textNode = siblings[textNodeIdx];

            //NOTE: if we have location assigned by another token, then just update end position
            if (textNode.__location)
                textNode.__location.endOffset = token.location.endOffset;

            else
                textNode.__location = token.location;
        }
    };
};



/***/ }),
/* 978 */
/***/ (function(module, exports) {

module.exports = function isBuffer(arg) {
  return arg && typeof arg === 'object'
    && typeof arg.copy === 'function'
    && typeof arg.fill === 'function'
    && typeof arg.readUInt8 === 'function';
}

/***/ }),
/* 979 */
/***/ (function(module, exports, __nested_webpack_require_4733275__) {

"use strict";


var Mixin = __nested_webpack_require_4733275__(201),
    inherits = __nested_webpack_require_4733275__(71).inherits;

var LocationInfoOpenElementStackMixin = module.exports = function (stack, options) {
    Mixin.call(this, stack);

    this.onItemPop = options.onItemPop;
};

inherits(LocationInfoOpenElementStackMixin, Mixin);

LocationInfoOpenElementStackMixin.prototype._getOverriddenMethods = function (mxn, orig) {
    return {
        pop: function () {
            mxn.onItemPop(this.current);
            orig.pop.call(this);
        },

        popAllUpToHtmlElement: function () {
            for (var i = this.stackTop; i > 0; i--)
                mxn.onItemPop(this.items[i]);

            orig.popAllUpToHtmlElement.call(this);
        },

        remove: function (element) {
            mxn.onItemPop(this.current);
            orig.remove.call(this, element);
        }
    };
};



/***/ }),
/* 980 */
/***/ (function(module, exports, __nested_webpack_require_4734238__) {

"use strict";


var doctype = __nested_webpack_require_4734238__(303),
    DOCUMENT_MODE = __nested_webpack_require_4734238__(64).DOCUMENT_MODE;


//Conversion tables for DOM Level1 structure emulation
var nodeTypes = {
    element: 1,
    text: 3,
    cdata: 4,
    comment: 8
};

var nodePropertyShorthands = {
    tagName: 'name',
    childNodes: 'children',
    parentNode: 'parent',
    previousSibling: 'prev',
    nextSibling: 'next',
    nodeValue: 'data'
};

//Node
var Node = function (props) {
    for (var key in props) {
        if (props.hasOwnProperty(key))
            this[key] = props[key];
    }
};

Node.prototype = {
    get firstChild() {
        var children = this.children;

        return children && children[0] || null;
    },

    get lastChild() {
        var children = this.children;

        return children && children[children.length - 1] || null;
    },

    get nodeType() {
        return nodeTypes[this.type] || nodeTypes.element;
    }
};

Object.keys(nodePropertyShorthands).forEach(function (key) {
    var shorthand = nodePropertyShorthands[key];

    Object.defineProperty(Node.prototype, key, {
        get: function () {
            return this[shorthand] || null;
        },
        set: function (val) {
            this[shorthand] = val;
            return val;
        }
    });
});


//Node construction
exports.createDocument = function () {
    return new Node({
        type: 'root',
        name: 'root',
        parent: null,
        prev: null,
        next: null,
        children: [],
        'x-mode': DOCUMENT_MODE.NO_QUIRKS
    });
};

exports.createDocumentFragment = function () {
    return new Node({
        type: 'root',
        name: 'root',
        parent: null,
        prev: null,
        next: null,
        children: []
    });
};

exports.createElement = function (tagName, namespaceURI, attrs) {
    var attribs = Object.create(null),
        attribsNamespace = Object.create(null),
        attribsPrefix = Object.create(null);

    for (var i = 0; i < attrs.length; i++) {
        var attrName = attrs[i].name;

        attribs[attrName] = attrs[i].value;
        attribsNamespace[attrName] = attrs[i].namespace;
        attribsPrefix[attrName] = attrs[i].prefix;
    }

    return new Node({
        type: tagName === 'script' || tagName === 'style' ? tagName : 'tag',
        name: tagName,
        namespace: namespaceURI,
        attribs: attribs,
        'x-attribsNamespace': attribsNamespace,
        'x-attribsPrefix': attribsPrefix,
        children: [],
        parent: null,
        prev: null,
        next: null
    });
};

exports.createCommentNode = function (data) {
    return new Node({
        type: 'comment',
        data: data,
        parent: null,
        prev: null,
        next: null
    });
};

var createTextNode = function (value) {
    return new Node({
        type: 'text',
        data: value,
        parent: null,
        prev: null,
        next: null
    });
};


//Tree mutation
var appendChild = exports.appendChild = function (parentNode, newNode) {
    var prev = parentNode.children[parentNode.children.length - 1];

    if (prev) {
        prev.next = newNode;
        newNode.prev = prev;
    }

    parentNode.children.push(newNode);
    newNode.parent = parentNode;
};

var insertBefore = exports.insertBefore = function (parentNode, newNode, referenceNode) {
    var insertionIdx = parentNode.children.indexOf(referenceNode),
        prev = referenceNode.prev;

    if (prev) {
        prev.next = newNode;
        newNode.prev = prev;
    }

    referenceNode.prev = newNode;
    newNode.next = referenceNode;

    parentNode.children.splice(insertionIdx, 0, newNode);
    newNode.parent = parentNode;
};

exports.setTemplateContent = function (templateElement, contentElement) {
    appendChild(templateElement, contentElement);
};

exports.getTemplateContent = function (templateElement) {
    return templateElement.children[0];
};

exports.setDocumentType = function (document, name, publicId, systemId) {
    var data = doctype.serializeContent(name, publicId, systemId),
        doctypeNode = null;

    for (var i = 0; i < document.children.length; i++) {
        if (document.children[i].type === 'directive' && document.children[i].name === '!doctype') {
            doctypeNode = document.children[i];
            break;
        }
    }

    if (doctypeNode) {
        doctypeNode.data = data;
        doctypeNode['x-name'] = name;
        doctypeNode['x-publicId'] = publicId;
        doctypeNode['x-systemId'] = systemId;
    }

    else {
        appendChild(document, new Node({
            type: 'directive',
            name: '!doctype',
            data: data,
            'x-name': name,
            'x-publicId': publicId,
            'x-systemId': systemId
        }));
    }

};

exports.setDocumentMode = function (document, mode) {
    document['x-mode'] = mode;
};

exports.getDocumentMode = function (document) {
    return document['x-mode'];
};

exports.detachNode = function (node) {
    if (node.parent) {
        var idx = node.parent.children.indexOf(node),
            prev = node.prev,
            next = node.next;

        node.prev = null;
        node.next = null;

        if (prev)
            prev.next = next;

        if (next)
            next.prev = prev;

        node.parent.children.splice(idx, 1);
        node.parent = null;
    }
};

exports.insertText = function (parentNode, text) {
    var lastChild = parentNode.children[parentNode.children.length - 1];

    if (lastChild && lastChild.type === 'text')
        lastChild.data += text;
    else
        appendChild(parentNode, createTextNode(text));
};

exports.insertTextBefore = function (parentNode, text, referenceNode) {
    var prevNode = parentNode.children[parentNode.children.indexOf(referenceNode) - 1];

    if (prevNode && prevNode.type === 'text')
        prevNode.data += text;
    else
        insertBefore(parentNode, createTextNode(text), referenceNode);
};

exports.adoptAttributes = function (recipient, attrs) {
    for (var i = 0; i < attrs.length; i++) {
        var attrName = attrs[i].name;

        if (typeof recipient.attribs[attrName] === 'undefined') {
            recipient.attribs[attrName] = attrs[i].value;
            recipient['x-attribsNamespace'][attrName] = attrs[i].namespace;
            recipient['x-attribsPrefix'][attrName] = attrs[i].prefix;
        }
    }
};


//Tree traversing
exports.getFirstChild = function (node) {
    return node.children[0];
};

exports.getChildNodes = function (node) {
    return node.children;
};

exports.getParentNode = function (node) {
    return node.parent;
};

exports.getAttrList = function (element) {
    var attrList = [];

    for (var name in element.attribs) {
        attrList.push({
            name: name,
            value: element.attribs[name],
            namespace: element['x-attribsNamespace'][name],
            prefix: element['x-attribsPrefix'][name]
        });
    }

    return attrList;
};


//Node data
exports.getTagName = function (element) {
    return element.name;
};

exports.getNamespaceURI = function (element) {
    return element.namespace;
};

exports.getTextNodeContent = function (textNode) {
    return textNode.data;
};

exports.getCommentNodeContent = function (commentNode) {
    return commentNode.data;
};

exports.getDocumentTypeNodeName = function (doctypeNode) {
    return doctypeNode['x-name'];
};

exports.getDocumentTypeNodePublicId = function (doctypeNode) {
    return doctypeNode['x-publicId'];
};

exports.getDocumentTypeNodeSystemId = function (doctypeNode) {
    return doctypeNode['x-systemId'];
};


//Node types
exports.isTextNode = function (node) {
    return node.type === 'text';
};

exports.isCommentNode = function (node) {
    return node.type === 'comment';
};

exports.isDocumentTypeNode = function (node) {
    return node.type === 'directive' && node.name === '!doctype';
};

exports.isElementNode = function (node) {
    return !!node.attribs;
};


/***/ }),
/* 981 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 982 */
/***/ (function(module, exports, __nested_webpack_require_4742389__) {

"use strict";


function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Buffer = __nested_webpack_require_4742389__(200).Buffer;
var util = __nested_webpack_require_4742389__(983);

function copyBuffer(src, target, offset) {
  src.copy(target, offset);
}

module.exports = function () {
  function BufferList() {
    _classCallCheck(this, BufferList);

    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  BufferList.prototype.push = function push(v) {
    var entry = { data: v, next: null };
    if (this.length > 0) this.tail.next = entry;else this.head = entry;
    this.tail = entry;
    ++this.length;
  };

  BufferList.prototype.unshift = function unshift(v) {
    var entry = { data: v, next: this.head };
    if (this.length === 0) this.tail = entry;
    this.head = entry;
    ++this.length;
  };

  BufferList.prototype.shift = function shift() {
    if (this.length === 0) return;
    var ret = this.head.data;
    if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
    --this.length;
    return ret;
  };

  BufferList.prototype.clear = function clear() {
    this.head = this.tail = null;
    this.length = 0;
  };

  BufferList.prototype.join = function join(s) {
    if (this.length === 0) return '';
    var p = this.head;
    var ret = '' + p.data;
    while (p = p.next) {
      ret += s + p.data;
    }return ret;
  };

  BufferList.prototype.concat = function concat(n) {
    if (this.length === 0) return Buffer.alloc(0);
    if (this.length === 1) return this.head.data;
    var ret = Buffer.allocUnsafe(n >>> 0);
    var p = this.head;
    var i = 0;
    while (p) {
      copyBuffer(p.data, ret, i);
      i += p.data.length;
      p = p.next;
    }
    return ret;
  };

  return BufferList;
}();

if (util && util.inspect && util.inspect.custom) {
  module.exports.prototype[util.inspect.custom] = function () {
    var obj = util.inspect({ length: this.length });
    return this.constructor.name + ' ' + obj;
  };
}

/***/ }),
/* 983 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 984 */
/***/ (function(module, exports, __nested_webpack_require_4744612__) {

/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
            (typeof self !== "undefined" && self) ||
            window;
var apply = Function.prototype.apply;

// DOM APIs, for completeness

exports.setTimeout = function() {
  return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
  return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
  if (timeout) {
    timeout.close();
  }
};

function Timeout(id, clearFn) {
  this._id = id;
  this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  this._clearFn.call(scope, this._id);
};

// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
};

exports.unenroll = function(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
};

exports._unrefActive = exports.active = function(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
};

// setimmediate attaches itself to the global object
__nested_webpack_require_4744612__(985);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto.  Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
                       (typeof global !== "undefined" && global.setImmediate) ||
                       (this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
                         (typeof global !== "undefined" && global.clearImmediate) ||
                         (this && this.clearImmediate);

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4744612__(27)))

/***/ }),
/* 985 */
/***/ (function(module, exports, __nested_webpack_require_4746826__) {

/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
    "use strict";

    if (global.setImmediate) {
        return;
    }

    var nextHandle = 1; // Spec says greater than zero
    var tasksByHandle = {};
    var currentlyRunningATask = false;
    var doc = global.document;
    var registerImmediate;

    function setImmediate(callback) {
      // Callback can either be a function or a string
      if (typeof callback !== "function") {
        callback = new Function("" + callback);
      }
      // Copy function arguments
      var args = new Array(arguments.length - 1);
      for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i + 1];
      }
      // Store and register the task
      var task = { callback: callback, args: args };
      tasksByHandle[nextHandle] = task;
      registerImmediate(nextHandle);
      return nextHandle++;
    }

    function clearImmediate(handle) {
        delete tasksByHandle[handle];
    }

    function run(task) {
        var callback = task.callback;
        var args = task.args;
        switch (args.length) {
        case 0:
            callback();
            break;
        case 1:
            callback(args[0]);
            break;
        case 2:
            callback(args[0], args[1]);
            break;
        case 3:
            callback(args[0], args[1], args[2]);
            break;
        default:
            callback.apply(undefined, args);
            break;
        }
    }

    function runIfPresent(handle) {
        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
        // So if we're currently running a task, we'll need to delay this invocation.
        if (currentlyRunningATask) {
            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
            // "too much recursion" error.
            setTimeout(runIfPresent, 0, handle);
        } else {
            var task = tasksByHandle[handle];
            if (task) {
                currentlyRunningATask = true;
                try {
                    run(task);
                } finally {
                    clearImmediate(handle);
                    currentlyRunningATask = false;
                }
            }
        }
    }

    function installNextTickImplementation() {
        registerImmediate = function(handle) {
            process.nextTick(function () { runIfPresent(handle); });
        };
    }

    function canUsePostMessage() {
        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
        // where `global.postMessage` means something completely different and can't be used for this purpose.
        if (global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function() {
                postMessageIsAsynchronous = false;
            };
            global.postMessage("", "*");
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous;
        }
    }

    function installPostMessageImplementation() {
        // Installs an event handler on `global` for the `message` event: see
        // * https://developer.mozilla.org/en/DOM/window.postMessage
        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

        var messagePrefix = "setImmediate$" + Math.random() + "$";
        var onGlobalMessage = function(event) {
            if (event.source === global &&
                typeof event.data === "string" &&
                event.data.indexOf(messagePrefix) === 0) {
                runIfPresent(+event.data.slice(messagePrefix.length));
            }
        };

        if (global.addEventListener) {
            global.addEventListener("message", onGlobalMessage, false);
        } else {
            global.attachEvent("onmessage", onGlobalMessage);
        }

        registerImmediate = function(handle) {
            global.postMessage(messagePrefix + handle, "*");
        };
    }

    function installMessageChannelImplementation() {
        var channel = new MessageChannel();
        channel.port1.onmessage = function(event) {
            var handle = event.data;
            runIfPresent(handle);
        };

        registerImmediate = function(handle) {
            channel.port2.postMessage(handle);
        };
    }

    function installReadyStateChangeImplementation() {
        var html = doc.documentElement;
        registerImmediate = function(handle) {
            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();

    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();

    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();

    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();

    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4746826__(27), __nested_webpack_require_4746826__(150)))

/***/ }),
/* 986 */
/***/ (function(module, exports, __nested_webpack_require_4753525__) {

/* WEBPACK VAR INJECTION */(function(global) {
/**
 * Module exports.
 */

module.exports = deprecate;

/**
 * Mark that a method should not be used.
 * Returns a modified function which warns once by default.
 *
 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
 *
 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
 * will throw an Error when invoked.
 *
 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
 * will invoke `console.trace()` instead of `console.error()`.
 *
 * @param {Function} fn - the function to deprecate
 * @param {String} msg - the string to print to the console when `fn` is invoked
 * @returns {Function} a new "deprecated" version of `fn`
 * @api public
 */

function deprecate (fn, msg) {
  if (config('noDeprecation')) {
    return fn;
  }

  var warned = false;
  function deprecated() {
    if (!warned) {
      if (config('throwDeprecation')) {
        throw new Error(msg);
      } else if (config('traceDeprecation')) {
        console.trace(msg);
      } else {
        console.warn(msg);
      }
      warned = true;
    }
    return fn.apply(this, arguments);
  }

  return deprecated;
}

/**
 * Checks `localStorage` for boolean values for the given `name`.
 *
 * @param {String} name
 * @returns {Boolean}
 * @api private
 */

function config (name) {
  // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  try {
    if (!global.localStorage) return false;
  } catch (_) {
    return false;
  }
  var val = global.localStorage[name];
  if (null == val) return false;
  return String(val).toLowerCase() === 'true';
}

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4753525__(27)))

/***/ }),
/* 987 */
/***/ (function(module, exports, __nested_webpack_require_4755330__) {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.



module.exports = PassThrough;

var Transform = __nested_webpack_require_4755330__(471);

/*<replacement>*/
var util = __nested_webpack_require_4755330__(151);
util.inherits = __nested_webpack_require_4755330__(58);
/*</replacement>*/

util.inherits(PassThrough, Transform);

function PassThrough(options) {
  if (!(this instanceof PassThrough)) return new PassThrough(options);

  Transform.call(this, options);
}

PassThrough.prototype._transform = function (chunk, encoding, cb) {
  cb(null, chunk);
};

/***/ }),
/* 988 */
/***/ (function(module, exports, __nested_webpack_require_4757147__) {

module.exports = __nested_webpack_require_4757147__(305);


/***/ }),
/* 989 */
/***/ (function(module, exports, __nested_webpack_require_4757269__) {

module.exports = __nested_webpack_require_4757269__(102);


/***/ }),
/* 990 */
/***/ (function(module, exports, __nested_webpack_require_4757391__) {

module.exports = __nested_webpack_require_4757391__(304).Transform


/***/ }),
/* 991 */
/***/ (function(module, exports, __nested_webpack_require_4757522__) {

module.exports = __nested_webpack_require_4757522__(304).PassThrough


/***/ }),
/* 992 */
/***/ (function(module, exports, __nested_webpack_require_4757655__) {

"use strict";


var ParserStream = __nested_webpack_require_4757655__(467),
    inherits = __nested_webpack_require_4757655__(71).inherits,
    $ = __nested_webpack_require_4757655__(64).TAG_NAMES;

var PlainTextConversionStream = module.exports = function (options) {
    ParserStream.call(this, options);

    // NOTE: see https://html.spec.whatwg.org/#read-text
    this.parser._insertFakeElement($.HTML);
    this.parser._insertFakeElement($.HEAD);
    this.parser.openElements.pop();
    this.parser._insertFakeElement($.BODY);
    this.parser._insertFakeElement($.PRE);
    this.parser.treeAdapter.insertText(this.parser.openElements.current, '\n');
    this.parser.switchToPlaintextParsing();
};

inherits(PlainTextConversionStream, ParserStream);


/***/ }),
/* 993 */
/***/ (function(module, exports, __nested_webpack_require_4758444__) {

"use strict";


var ReadableStream = __nested_webpack_require_4758444__(202).Readable,
    inherits = __nested_webpack_require_4758444__(71).inherits,
    Serializer = __nested_webpack_require_4758444__(466);

var SerializerStream = module.exports = function (node, options) {
    ReadableStream.call(this);

    this.serializer = new Serializer(node, options);

    Object.defineProperty(this.serializer, 'html', {
        //NOTE: To make `+=` concat operator work properly we define
        //getter which always returns empty string
        get: function () {
            return '';
        },
        set: this.push.bind(this)
    });
};

inherits(SerializerStream, ReadableStream);

//Readable stream implementation
SerializerStream.prototype._read = function () {
    this.serializer.serialize();
    this.push(null);
};


/***/ }),
/* 994 */
/***/ (function(module, exports, __nested_webpack_require_4759305__) {

"use strict";


var TransformStream = __nested_webpack_require_4759305__(202).Transform,
    DevNullStream = __nested_webpack_require_4759305__(995),
    inherits = __nested_webpack_require_4759305__(71).inherits,
    Tokenizer = __nested_webpack_require_4759305__(124),
    LocationInfoTokenizerMixin = __nested_webpack_require_4759305__(463),
    ParserFeedbackSimulator = __nested_webpack_require_4759305__(996),
    mergeOptions = __nested_webpack_require_4759305__(302);

var DEFAULT_OPTIONS = {
    locationInfo: false
};

var SAXParser = module.exports = function (options) {
    TransformStream.call(this);

    this.options = mergeOptions(DEFAULT_OPTIONS, options);

    this.tokenizer = new Tokenizer(options);

    if (this.options.locationInfo)
        new LocationInfoTokenizerMixin(this.tokenizer);

    this.parserFeedbackSimulator = new ParserFeedbackSimulator(this.tokenizer);

    this.pendingText = null;
    this.currentTokenLocation = void 0;

    this.lastChunkWritten = false;
    this.stopped = false;

    // NOTE: always pipe stream to the /dev/null stream to avoid
    // `highWaterMark` hit even if we don't have consumers.
    // (see: https://github.com/inikulin/parse5/issues/97#issuecomment-171940774)
    this.pipe(new DevNullStream());
};

inherits(SAXParser, TransformStream);

//TransformStream implementation
SAXParser.prototype._transform = function (chunk, encoding, callback) {
    if (!this.stopped) {
        this.tokenizer.write(chunk.toString('utf8'), this.lastChunkWritten);
        this._runParsingLoop();
    }

    this.push(chunk);

    callback();
};

SAXParser.prototype._flush = function (callback) {
    callback();
};

SAXParser.prototype.end = function (chunk, encoding, callback) {
    this.lastChunkWritten = true;
    TransformStream.prototype.end.call(this, chunk, encoding, callback);
};

SAXParser.prototype.stop = function () {
    this.stopped = true;
};

//Internals
SAXParser.prototype._runParsingLoop = function () {
    do {
        var token = this.parserFeedbackSimulator.getNextToken();

        if (token.type === Tokenizer.HIBERNATION_TOKEN)
            break;

        if (token.type === Tokenizer.CHARACTER_TOKEN ||
            token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN ||
            token.type === Tokenizer.NULL_CHARACTER_TOKEN) {

            if (this.options.locationInfo) {
                if (this.pendingText === null)
                    this.currentTokenLocation = token.location;

                else
                    this.currentTokenLocation.endOffset = token.location.endOffset;
            }

            this.pendingText = (this.pendingText || '') + token.chars;
        }

        else {
            this._emitPendingText();
            this._handleToken(token);
        }
    } while (!this.stopped && token.type !== Tokenizer.EOF_TOKEN);
};

SAXParser.prototype._handleToken = function (token) {
    if (this.options.locationInfo)
        this.currentTokenLocation = token.location;

    if (token.type === Tokenizer.START_TAG_TOKEN)
        this.emit('startTag', token.tagName, token.attrs, token.selfClosing, this.currentTokenLocation);

    else if (token.type === Tokenizer.END_TAG_TOKEN)
        this.emit('endTag', token.tagName, this.currentTokenLocation);

    else if (token.type === Tokenizer.COMMENT_TOKEN)
        this.emit('comment', token.data, this.currentTokenLocation);

    else if (token.type === Tokenizer.DOCTYPE_TOKEN)
        this.emit('doctype', token.name, token.publicId, token.systemId, this.currentTokenLocation);
};

SAXParser.prototype._emitPendingText = function () {
    if (this.pendingText !== null) {
        this.emit('text', this.pendingText, this.currentTokenLocation);
        this.pendingText = null;
    }
};


/***/ }),
/* 995 */
/***/ (function(module, exports, __nested_webpack_require_4763036__) {

"use strict";


var WritableStream = __nested_webpack_require_4763036__(202).Writable,
    util = __nested_webpack_require_4763036__(71);

var DevNullStream = module.exports = function () {
    WritableStream.call(this);
};

util.inherits(DevNullStream, WritableStream);

DevNullStream.prototype._write = function (chunk, encoding, cb) {
    cb();
};


/***/ }),
/* 996 */
/***/ (function(module, exports, __nested_webpack_require_4763436__) {

"use strict";


var Tokenizer = __nested_webpack_require_4763436__(124),
    foreignContent = __nested_webpack_require_4763436__(465),
    UNICODE = __nested_webpack_require_4763436__(149),
    HTML = __nested_webpack_require_4763436__(64);


//Aliases
var $ = HTML.TAG_NAMES,
    NS = HTML.NAMESPACES;


//ParserFeedbackSimulator
//Simulates adjustment of the Tokenizer which performed by standard parser during tree construction.
var ParserFeedbackSimulator = module.exports = function (tokenizer) {
    this.tokenizer = tokenizer;

    this.namespaceStack = [];
    this.namespaceStackTop = -1;
    this._enterNamespace(NS.HTML);
};

ParserFeedbackSimulator.prototype.getNextToken = function () {
    var token = this.tokenizer.getNextToken();

    if (token.type === Tokenizer.START_TAG_TOKEN)
        this._handleStartTagToken(token);

    else if (token.type === Tokenizer.END_TAG_TOKEN)
        this._handleEndTagToken(token);

    else if (token.type === Tokenizer.NULL_CHARACTER_TOKEN && this.inForeignContent) {
        token.type = Tokenizer.CHARACTER_TOKEN;
        token.chars = UNICODE.REPLACEMENT_CHARACTER;
    }

    else if (this.skipNextNewLine) {
        if (token.type !== Tokenizer.HIBERNATION_TOKEN)
            this.skipNextNewLine = false;

        if (token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN && token.chars[0] === '\n') {
            if (token.chars.length === 1)
                return this.getNextToken();

            token.chars = token.chars.substr(1);
        }
    }

    return token;
};

//Namespace stack mutations
ParserFeedbackSimulator.prototype._enterNamespace = function (namespace) {
    this.namespaceStackTop++;
    this.namespaceStack.push(namespace);

    this.inForeignContent = namespace !== NS.HTML;
    this.currentNamespace = namespace;
    this.tokenizer.allowCDATA = this.inForeignContent;
};

ParserFeedbackSimulator.prototype._leaveCurrentNamespace = function () {
    this.namespaceStackTop--;
    this.namespaceStack.pop();

    this.currentNamespace = this.namespaceStack[this.namespaceStackTop];
    this.inForeignContent = this.currentNamespace !== NS.HTML;
    this.tokenizer.allowCDATA = this.inForeignContent;
};

//Token handlers
ParserFeedbackSimulator.prototype._ensureTokenizerMode = function (tn) {
    if (tn === $.TEXTAREA || tn === $.TITLE)
        this.tokenizer.state = Tokenizer.MODE.RCDATA;

    else if (tn === $.PLAINTEXT)
        this.tokenizer.state = Tokenizer.MODE.PLAINTEXT;

    else if (tn === $.SCRIPT)
        this.tokenizer.state = Tokenizer.MODE.SCRIPT_DATA;

    else if (tn === $.STYLE || tn === $.IFRAME || tn === $.XMP ||
             tn === $.NOEMBED || tn === $.NOFRAMES || tn === $.NOSCRIPT)
        this.tokenizer.state = Tokenizer.MODE.RAWTEXT;
};

ParserFeedbackSimulator.prototype._handleStartTagToken = function (token) {
    var tn = token.tagName;

    if (tn === $.SVG)
        this._enterNamespace(NS.SVG);

    else if (tn === $.MATH)
        this._enterNamespace(NS.MATHML);

    if (this.inForeignContent) {
        if (foreignContent.causesExit(token)) {
            this._leaveCurrentNamespace();
            return;
        }

        var currentNs = this.currentNamespace;

        if (currentNs === NS.MATHML)
            foreignContent.adjustTokenMathMLAttrs(token);

        else if (currentNs === NS.SVG) {
            foreignContent.adjustTokenSVGTagName(token);
            foreignContent.adjustTokenSVGAttrs(token);
        }

        foreignContent.adjustTokenXMLAttrs(token);

        tn = token.tagName;

        if (!token.selfClosing && foreignContent.isIntegrationPoint(tn, currentNs, token.attrs))
            this._enterNamespace(NS.HTML);
    }

    else {
        if (tn === $.PRE || tn === $.TEXTAREA || tn === $.LISTING)
            this.skipNextNewLine = true;

        else if (tn === $.IMAGE)
            token.tagName = $.IMG;

        this._ensureTokenizerMode(tn);
    }
};

ParserFeedbackSimulator.prototype._handleEndTagToken = function (token) {
    var tn = token.tagName;

    if (!this.inForeignContent) {
        var previousNs = this.namespaceStack[this.namespaceStackTop - 1];

        if (previousNs === NS.SVG && foreignContent.SVG_TAG_NAMES_ADJUSTMENT_MAP[tn])
            tn = foreignContent.SVG_TAG_NAMES_ADJUSTMENT_MAP[tn];

        //NOTE: check for exit from integration point
        if (foreignContent.isIntegrationPoint(tn, previousNs, token.attrs))
            this._leaveCurrentNamespace();
    }

    else if (tn === $.SVG && this.currentNamespace === NS.SVG ||
             tn === $.MATH && this.currentNamespace === NS.MATHML)
        this._leaveCurrentNamespace();

    // NOTE: adjust end tag name as well for consistency
    if (this.currentNamespace === NS.SVG)
        foreignContent.adjustTokenSVGTagName(token);
};


/***/ }),
/* 997 */
/***/ (function(module, exports, __nested_webpack_require_4768250__) {

var baseSetData = __nested_webpack_require_4768250__(474),
    createBind = __nested_webpack_require_4768250__(998),
    createCurry = __nested_webpack_require_4768250__(999),
    createHybrid = __nested_webpack_require_4768250__(476),
    createPartial = __nested_webpack_require_4768250__(1016),
    getData = __nested_webpack_require_4768250__(480),
    mergeData = __nested_webpack_require_4768250__(1017),
    setData = __nested_webpack_require_4768250__(482),
    setWrapToString = __nested_webpack_require_4768250__(483),
    toInteger = __nested_webpack_require_4768250__(1018);

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_FLAG = 8,
    WRAP_CURRY_RIGHT_FLAG = 16,
    WRAP_PARTIAL_FLAG = 32,
    WRAP_PARTIAL_RIGHT_FLAG = 64;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;

/**
 * Creates a function that either curries or invokes `func` with optional
 * `this` binding and partially applied arguments.
 *
 * @private
 * @param {Function|string} func The function or method name to wrap.
 * @param {number} bitmask The bitmask flags.
 *    1 - `_.bind`
 *    2 - `_.bindKey`
 *    4 - `_.curry` or `_.curryRight` of a bound function
 *    8 - `_.curry`
 *   16 - `_.curryRight`
 *   32 - `_.partial`
 *   64 - `_.partialRight`
 *  128 - `_.rearg`
 *  256 - `_.ary`
 *  512 - `_.flip`
 * @param {*} [thisArg] The `this` binding of `func`.
 * @param {Array} [partials] The arguments to be partially applied.
 * @param {Array} [holders] The `partials` placeholder indexes.
 * @param {Array} [argPos] The argument positions of the new function.
 * @param {number} [ary] The arity cap of `func`.
 * @param {number} [arity] The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
  var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
  if (!isBindKey && typeof func != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  var length = partials ? partials.length : 0;
  if (!length) {
    bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
    partials = holders = undefined;
  }
  ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
  arity = arity === undefined ? arity : toInteger(arity);
  length -= holders ? holders.length : 0;

  if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
    var partialsRight = partials,
        holdersRight = holders;

    partials = holders = undefined;
  }
  var data = isBindKey ? undefined : getData(func);

  var newData = [
    func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
    argPos, ary, arity
  ];

  if (data) {
    mergeData(newData, data);
  }
  func = newData[0];
  bitmask = newData[1];
  thisArg = newData[2];
  partials = newData[3];
  holders = newData[4];
  arity = newData[9] = newData[9] === undefined
    ? (isBindKey ? 0 : func.length)
    : nativeMax(newData[9] - length, 0);

  if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
    bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
  }
  if (!bitmask || bitmask == WRAP_BIND_FLAG) {
    var result = createBind(func, bitmask, thisArg);
  } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
    result = createCurry(func, bitmask, arity);
  } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
    result = createPartial(func, bitmask, thisArg, partials);
  } else {
    result = createHybrid.apply(undefined, newData);
  }
  var setter = data ? baseSetData : setData;
  return setWrapToString(setter(result, newData), func, bitmask);
}

module.exports = createWrap;


/***/ }),
/* 998 */
/***/ (function(module, exports, __nested_webpack_require_4772043__) {

var createCtor = __nested_webpack_require_4772043__(205),
    root = __nested_webpack_require_4772043__(41);

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;

/**
 * Creates a function that wraps `func` to invoke it with the optional `this`
 * binding of `thisArg`.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} [thisArg] The `this` binding of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createBind(func, bitmask, thisArg) {
  var isBind = bitmask & WRAP_BIND_FLAG,
      Ctor = createCtor(func);

  function wrapper() {
    var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
    return fn.apply(isBind ? thisArg : this, arguments);
  }
  return wrapper;
}

module.exports = createBind;


/***/ }),
/* 999 */
/***/ (function(module, exports, __nested_webpack_require_4772980__) {

var apply = __nested_webpack_require_4772980__(292),
    createCtor = __nested_webpack_require_4772980__(205),
    createHybrid = __nested_webpack_require_4772980__(476),
    createRecurry = __nested_webpack_require_4772980__(479),
    getHolder = __nested_webpack_require_4772980__(309),
    replaceHolders = __nested_webpack_require_4772980__(206),
    root = __nested_webpack_require_4772980__(41);

/**
 * Creates a function that wraps `func` to enable currying.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {number} arity The arity of `func`.
 * @returns {Function} Returns the new wrapped function.
 */
function createCurry(func, bitmask, arity) {
  var Ctor = createCtor(func);

  function wrapper() {
    var length = arguments.length,
        args = Array(length),
        index = length,
        placeholder = getHolder(wrapper);

    while (index--) {
      args[index] = arguments[index];
    }
    var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
      ? []
      : replaceHolders(args, placeholder);

    length -= holders.length;
    if (length < arity) {
      return createRecurry(
        func, bitmask, createHybrid, wrapper.placeholder, undefined,
        args, holders, undefined, undefined, arity - length);
    }
    var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
    return apply(fn, this, args);
  }
  return wrapper;
}

module.exports = createCurry;


/***/ }),
/* 1000 */
/***/ (function(module, exports) {

/**
 * Gets the number of `placeholder` occurrences in `array`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} placeholder The placeholder to search for.
 * @returns {number} Returns the placeholder count.
 */
function countHolders(array, placeholder) {
  var length = array.length,
      result = 0;

  while (length--) {
    if (array[length] === placeholder) {
      ++result;
    }
  }
  return result;
}

module.exports = countHolders;


/***/ }),
/* 1001 */
/***/ (function(module, exports, __nested_webpack_require_4775037__) {

var LazyWrapper = __nested_webpack_require_4775037__(307),
    getData = __nested_webpack_require_4775037__(480),
    getFuncName = __nested_webpack_require_4775037__(1003),
    lodash = __nested_webpack_require_4775037__(1005);

/**
 * Checks if `func` has a lazy counterpart.
 *
 * @private
 * @param {Function} func The function to check.
 * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
 *  else `false`.
 */
function isLaziable(func) {
  var funcName = getFuncName(func),
      other = lodash[funcName];

  if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
    return false;
  }
  if (func === other) {
    return true;
  }
  var data = getData(other);
  return !!data && func === data[0];
}

module.exports = isLaziable;


/***/ }),
/* 1002 */
/***/ (function(module, exports) {

/**
 * This method returns `undefined`.
 *
 * @static
 * @memberOf _
 * @since 2.3.0
 * @category Util
 * @example
 *
 * _.times(2, _.noop);
 * // => [undefined, undefined]
 */
function noop() {
  // No operation performed.
}

module.exports = noop;


/***/ }),
/* 1003 */
/***/ (function(module, exports, __nested_webpack_require_4776139__) {

var realNames = __nested_webpack_require_4776139__(1004);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Gets the name of `func`.
 *
 * @private
 * @param {Function} func The function to query.
 * @returns {string} Returns the function name.
 */
function getFuncName(func) {
  var result = (func.name + ''),
      array = realNames[result],
      length = hasOwnProperty.call(realNames, result) ? array.length : 0;

  while (length--) {
    var data = array[length],
        otherFunc = data.func;
    if (otherFunc == null || otherFunc == func) {
      return data.name;
    }
  }
  return result;
}

module.exports = getFuncName;


/***/ }),
/* 1004 */
/***/ (function(module, exports) {

/** Used to lookup unminified function names. */
var realNames = {};

module.exports = realNames;


/***/ }),
/* 1005 */
/***/ (function(module, exports, __nested_webpack_require_4777134__) {

var LazyWrapper = __nested_webpack_require_4777134__(307),
    LodashWrapper = __nested_webpack_require_4777134__(481),
    baseLodash = __nested_webpack_require_4777134__(308),
    isArray = __nested_webpack_require_4777134__(31),
    isObjectLike = __nested_webpack_require_4777134__(56),
    wrapperClone = __nested_webpack_require_4777134__(1006);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Creates a `lodash` object which wraps `value` to enable implicit method
 * chain sequences. Methods that operate on and return arrays, collections,
 * and functions can be chained together. Methods that retrieve a single value
 * or may return a primitive value will automatically end the chain sequence
 * and return the unwrapped value. Otherwise, the value must be unwrapped
 * with `_#value`.
 *
 * Explicit chain sequences, which must be unwrapped with `_#value`, may be
 * enabled using `_.chain`.
 *
 * The execution of chained methods is lazy, that is, it's deferred until
 * `_#value` is implicitly or explicitly called.
 *
 * Lazy evaluation allows several methods to support shortcut fusion.
 * Shortcut fusion is an optimization to merge iteratee calls; this avoids
 * the creation of intermediate arrays and can greatly reduce the number of
 * iteratee executions. Sections of a chain sequence qualify for shortcut
 * fusion if the section is applied to an array and iteratees accept only
 * one argument. The heuristic for whether a section qualifies for shortcut
 * fusion is subject to change.
 *
 * Chaining is supported in custom builds as long as the `_#value` method is
 * directly or indirectly included in the build.
 *
 * In addition to lodash methods, wrappers have `Array` and `String` methods.
 *
 * The wrapper `Array` methods are:
 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
 *
 * The wrapper `String` methods are:
 * `replace` and `split`
 *
 * The wrapper methods that support shortcut fusion are:
 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
 *
 * The chainable wrapper methods are:
 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
 * `zipObject`, `zipObjectDeep`, and `zipWith`
 *
 * The wrapper methods that are **not** chainable by default are:
 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
 * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
 * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
 * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
 * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
 * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
 * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
 * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
 * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
 * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
 * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
 * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
 * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
 * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
 * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
 * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
 * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
 * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
 * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
 * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
 * `upperFirst`, `value`, and `words`
 *
 * @name _
 * @constructor
 * @category Seq
 * @param {*} value The value to wrap in a `lodash` instance.
 * @returns {Object} Returns the new `lodash` wrapper instance.
 * @example
 *
 * function square(n) {
 *   return n * n;
 * }
 *
 * var wrapped = _([1, 2, 3]);
 *
 * // Returns an unwrapped value.
 * wrapped.reduce(_.add);
 * // => 6
 *
 * // Returns a wrapped value.
 * var squares = wrapped.map(square);
 *
 * _.isArray(squares);
 * // => false
 *
 * _.isArray(squares.value());
 * // => true
 */
function lodash(value) {
  if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
    if (value instanceof LodashWrapper) {
      return value;
    }
    if (hasOwnProperty.call(value, '__wrapped__')) {
      return wrapperClone(value);
    }
  }
  return new LodashWrapper(value);
}

// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;

module.exports = lodash;


/***/ }),
/* 1006 */
/***/ (function(module, exports, __nested_webpack_require_4784152__) {

var LazyWrapper = __nested_webpack_require_4784152__(307),
    LodashWrapper = __nested_webpack_require_4784152__(481),
    copyArray = __nested_webpack_require_4784152__(196);

/**
 * Creates a clone of `wrapper`.
 *
 * @private
 * @param {Object} wrapper The wrapper to clone.
 * @returns {Object} Returns the cloned wrapper.
 */
function wrapperClone(wrapper) {
  if (wrapper instanceof LazyWrapper) {
    return wrapper.clone();
  }
  var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
  result.__actions__ = copyArray(wrapper.__actions__);
  result.__index__  = wrapper.__index__;
  result.__values__ = wrapper.__values__;
  return result;
}

module.exports = wrapperClone;


/***/ }),
/* 1007 */
/***/ (function(module, exports) {

/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
    reSplitDetails = /,? & /;

/**
 * Extracts wrapper details from the `source` body comment.
 *
 * @private
 * @param {string} source The source to inspect.
 * @returns {Array} Returns the wrapper details.
 */
function getWrapDetails(source) {
  var match = source.match(reWrapDetails);
  return match ? match[1].split(reSplitDetails) : [];
}

module.exports = getWrapDetails;


/***/ }),
/* 1008 */
/***/ (function(module, exports) {

/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;

/**
 * Inserts wrapper `details` in a comment at the top of the `source` body.
 *
 * @private
 * @param {string} source The source to modify.
 * @returns {Array} details The details to insert.
 * @returns {string} Returns the modified source.
 */
function insertWrapDetails(source, details) {
  var length = details.length;
  if (!length) {
    return source;
  }
  var lastIndex = length - 1;
  details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
  details = details.join(length > 2 ? ', ' : ' ');
  return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}

module.exports = insertWrapDetails;


/***/ }),
/* 1009 */
/***/ (function(module, exports, __nested_webpack_require_4786232__) {

var arrayEach = __nested_webpack_require_4786232__(286),
    arrayIncludes = __nested_webpack_require_4786232__(1010);

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_FLAG = 8,
    WRAP_CURRY_RIGHT_FLAG = 16,
    WRAP_PARTIAL_FLAG = 32,
    WRAP_PARTIAL_RIGHT_FLAG = 64,
    WRAP_ARY_FLAG = 128,
    WRAP_REARG_FLAG = 256,
    WRAP_FLIP_FLAG = 512;

/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
  ['ary', WRAP_ARY_FLAG],
  ['bind', WRAP_BIND_FLAG],
  ['bindKey', WRAP_BIND_KEY_FLAG],
  ['curry', WRAP_CURRY_FLAG],
  ['curryRight', WRAP_CURRY_RIGHT_FLAG],
  ['flip', WRAP_FLIP_FLAG],
  ['partial', WRAP_PARTIAL_FLAG],
  ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
  ['rearg', WRAP_REARG_FLAG]
];

/**
 * Updates wrapper `details` based on `bitmask` flags.
 *
 * @private
 * @returns {Array} details The details to modify.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @returns {Array} Returns `details`.
 */
function updateWrapDetails(details, bitmask) {
  arrayEach(wrapFlags, function(pair) {
    var value = '_.' + pair[0];
    if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
      details.push(value);
    }
  });
  return details.sort();
}

module.exports = updateWrapDetails;


/***/ }),
/* 1010 */
/***/ (function(module, exports, __nested_webpack_require_4787621__) {

var baseIndexOf = __nested_webpack_require_4787621__(1011);

/**
 * A specialized version of `_.includes` for arrays without support for
 * specifying an index to search from.
 *
 * @private
 * @param {Array} [array] The array to inspect.
 * @param {*} target The value to search for.
 * @returns {boolean} Returns `true` if `target` is found, else `false`.
 */
function arrayIncludes(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && baseIndexOf(array, value, 0) > -1;
}

module.exports = arrayIncludes;


/***/ }),
/* 1011 */
/***/ (function(module, exports, __nested_webpack_require_4788227__) {

var baseFindIndex = __nested_webpack_require_4788227__(1012),
    baseIsNaN = __nested_webpack_require_4788227__(1013),
    strictIndexOf = __nested_webpack_require_4788227__(1014);

/**
 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseIndexOf(array, value, fromIndex) {
  return value === value
    ? strictIndexOf(array, value, fromIndex)
    : baseFindIndex(array, baseIsNaN, fromIndex);
}

module.exports = baseIndexOf;


/***/ }),
/* 1012 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.findIndex` and `_.findLastIndex` without
 * support for iteratee shorthands.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {Function} predicate The function invoked per iteration.
 * @param {number} fromIndex The index to search from.
 * @param {boolean} [fromRight] Specify iterating from right to left.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function baseFindIndex(array, predicate, fromIndex, fromRight) {
  var length = array.length,
      index = fromIndex + (fromRight ? 1 : -1);

  while ((fromRight ? index-- : ++index < length)) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}

module.exports = baseFindIndex;


/***/ }),
/* 1013 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.isNaN` without support for number objects.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 */
function baseIsNaN(value) {
  return value !== value;
}

module.exports = baseIsNaN;


/***/ }),
/* 1014 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.indexOf` which performs strict equality
 * comparisons of values, i.e. `===`.
 *
 * @private
 * @param {Array} array The array to inspect.
 * @param {*} value The value to search for.
 * @param {number} fromIndex The index to search from.
 * @returns {number} Returns the index of the matched value, else `-1`.
 */
function strictIndexOf(array, value, fromIndex) {
  var index = fromIndex - 1,
      length = array.length;

  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}

module.exports = strictIndexOf;


/***/ }),
/* 1015 */
/***/ (function(module, exports, __nested_webpack_require_4790803__) {

var copyArray = __nested_webpack_require_4790803__(196),
    isIndex = __nested_webpack_require_4790803__(142);

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;

/**
 * Reorder `array` according to the specified indexes where the element at
 * the first index is assigned as the first element, the element at
 * the second index is assigned as the second element, and so on.
 *
 * @private
 * @param {Array} array The array to reorder.
 * @param {Array} indexes The arranged array indexes.
 * @returns {Array} Returns `array`.
 */
function reorder(array, indexes) {
  var arrLength = array.length,
      length = nativeMin(indexes.length, arrLength),
      oldArray = copyArray(array);

  while (length--) {
    var index = indexes[length];
    array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
  }
  return array;
}

module.exports = reorder;


/***/ }),
/* 1016 */
/***/ (function(module, exports, __nested_webpack_require_4791787__) {

var apply = __nested_webpack_require_4791787__(292),
    createCtor = __nested_webpack_require_4791787__(205),
    root = __nested_webpack_require_4791787__(41);

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;

/**
 * Creates a function that wraps `func` to invoke it with the `this` binding
 * of `thisArg` and `partials` prepended to the arguments it receives.
 *
 * @private
 * @param {Function} func The function to wrap.
 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
 * @param {*} thisArg The `this` binding of `func`.
 * @param {Array} partials The arguments to prepend to those provided to
 *  the new function.
 * @returns {Function} Returns the new wrapped function.
 */
function createPartial(func, bitmask, thisArg, partials) {
  var isBind = bitmask & WRAP_BIND_FLAG,
      Ctor = createCtor(func);

  function wrapper() {
    var argsIndex = -1,
        argsLength = arguments.length,
        leftIndex = -1,
        leftLength = partials.length,
        args = Array(leftLength + argsLength),
        fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;

    while (++leftIndex < leftLength) {
      args[leftIndex] = partials[leftIndex];
    }
    while (argsLength--) {
      args[leftIndex++] = arguments[++argsIndex];
    }
    return apply(fn, isBind ? thisArg : this, args);
  }
  return wrapper;
}

module.exports = createPartial;


/***/ }),
/* 1017 */
/***/ (function(module, exports, __nested_webpack_require_4793259__) {

var composeArgs = __nested_webpack_require_4793259__(477),
    composeArgsRight = __nested_webpack_require_4793259__(478),
    replaceHolders = __nested_webpack_require_4793259__(206);

/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';

/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
    WRAP_BIND_KEY_FLAG = 2,
    WRAP_CURRY_BOUND_FLAG = 4,
    WRAP_CURRY_FLAG = 8,
    WRAP_ARY_FLAG = 128,
    WRAP_REARG_FLAG = 256;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;

/**
 * Merges the function metadata of `source` into `data`.
 *
 * Merging metadata reduces the number of wrappers used to invoke a function.
 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
 * may be applied regardless of execution order. Methods like `_.ary` and
 * `_.rearg` modify function arguments, making the order in which they are
 * executed important, preventing the merging of metadata. However, we make
 * an exception for a safe combined case where curried functions have `_.ary`
 * and or `_.rearg` applied.
 *
 * @private
 * @param {Array} data The destination metadata.
 * @param {Array} source The source metadata.
 * @returns {Array} Returns `data`.
 */
function mergeData(data, source) {
  var bitmask = data[1],
      srcBitmask = source[1],
      newBitmask = bitmask | srcBitmask,
      isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);

  var isCombo =
    ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
    ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
    ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));

  // Exit early if metadata can't be merged.
  if (!(isCommon || isCombo)) {
    return data;
  }
  // Use source `thisArg` if available.
  if (srcBitmask & WRAP_BIND_FLAG) {
    data[2] = source[2];
    // Set when currying a bound function.
    newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
  }
  // Compose partial arguments.
  var value = source[3];
  if (value) {
    var partials = data[3];
    data[3] = partials ? composeArgs(partials, value, source[4]) : value;
    data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
  }
  // Compose partial right arguments.
  value = source[5];
  if (value) {
    partials = data[5];
    data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
    data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
  }
  // Use source `argPos` if available.
  value = source[7];
  if (value) {
    data[7] = value;
  }
  // Use source `ary` if it's smaller.
  if (srcBitmask & WRAP_ARY_FLAG) {
    data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
  }
  // Use source `arity` if one is not provided.
  if (data[9] == null) {
    data[9] = source[9];
  }
  // Use source `func` and merge bitmasks.
  data[0] = source[0];
  data[1] = newBitmask;

  return data;
}

module.exports = mergeData;


/***/ }),
/* 1018 */
/***/ (function(module, exports, __nested_webpack_require_4796463__) {

var toFinite = __nested_webpack_require_4796463__(1019);

/**
 * Converts `value` to an integer.
 *
 * **Note:** This method is loosely based on
 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted integer.
 * @example
 *
 * _.toInteger(3.2);
 * // => 3
 *
 * _.toInteger(Number.MIN_VALUE);
 * // => 0
 *
 * _.toInteger(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toInteger('3.2');
 * // => 3
 */
function toInteger(value) {
  var result = toFinite(value),
      remainder = result % 1;

  return result === result ? (remainder ? result - remainder : result) : 0;
}

module.exports = toInteger;


/***/ }),
/* 1019 */
/***/ (function(module, exports, __nested_webpack_require_4797307__) {

var toNumber = __nested_webpack_require_4797307__(436);

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_INTEGER = 1.7976931348623157e+308;

/**
 * Converts `value` to a finite number.
 *
 * @static
 * @memberOf _
 * @since 4.12.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {number} Returns the converted number.
 * @example
 *
 * _.toFinite(3.2);
 * // => 3.2
 *
 * _.toFinite(Number.MIN_VALUE);
 * // => 5e-324
 *
 * _.toFinite(Infinity);
 * // => 1.7976931348623157e+308
 *
 * _.toFinite('3.2');
 * // => 3.2
 */
function toFinite(value) {
  if (!value) {
    return value === 0 ? value : 0;
  }
  value = toNumber(value);
  if (value === INFINITY || value === -INFINITY) {
    var sign = (value < 0 ? -1 : 1);
    return sign * MAX_INTEGER;
  }
  return value === value ? value : 0;
}

module.exports = toFinite;


/***/ }),
/* 1020 */
/***/ (function(module, exports, __nested_webpack_require_4798258__) {

var $ = __nested_webpack_require_4798258__(310),
    utils = __nested_webpack_require_4798258__(152),
    isTag = utils.isTag,
    domEach = utils.domEach,
    hasOwn = Object.prototype.hasOwnProperty,
    camelCase = utils.camelCase,
    cssCase = utils.cssCase,
    rspace = /\s+/,
    dataAttrPrefix = 'data-',
    _ = {
      forEach: __nested_webpack_require_4798258__(147),
      extend: __nested_webpack_require_4798258__(473),
      some: __nested_webpack_require_4798258__(1028)
    },

  // Lookup table for coercing string data-* attributes to their corresponding
  // JavaScript primitives
  primitives = {
    null: null,
    true: true,
    false: false
  },

  // Attributes that are booleans
  rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
  // Matches strings that look like JSON objects or arrays
  rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;


var getAttr = function(elem, name) {
  if (!elem || !isTag(elem)) return;

  if (!elem.attribs) {
    elem.attribs = {};
  }

  // Return the entire attribs object if no attribute specified
  if (!name) {
    return elem.attribs;
  }

  if (hasOwn.call(elem.attribs, name)) {
    // Get the (decoded) attribute
    return rboolean.test(name) ? name : elem.attribs[name];
  }

  // Mimic the DOM and return text content as value for `option's`
  if (elem.name === 'option' && name === 'value') {
    return $.text(elem.children);
  }

  // Mimic DOM with default value for radios/checkboxes
  if (elem.name === 'input' &&
      (elem.attribs.type === 'radio' || elem.attribs.type === 'checkbox') &&
      name === 'value') {
    return 'on';
  }
};

var setAttr = function(el, name, value) {

  if (value === null) {
    removeAttribute(el, name);
  } else {
    el.attribs[name] = value+'';
  }
};

exports.attr = function(name, value) {
  // Set the value (with attr map support)
  if (typeof name === 'object' || value !== undefined) {
    if (typeof value === 'function') {
      return domEach(this, function(i, el) {
        setAttr(el, name, value.call(el, i, el.attribs[name]));
      });
    }
    return domEach(this, function(i, el) {
      if (!isTag(el)) return;

      if (typeof name === 'object') {
        _.forEach(name, function(objValue, objName) {
          setAttr(el, objName, objValue);
        });
      } else {
        setAttr(el, name, value);
      }
    });
  }

  return getAttr(this[0], name);
};

var getProp = function (el, name) {
  if (!el || !isTag(el)) return;

  return hasOwn.call(el, name)
      ? el[name]
      : rboolean.test(name)
          ? getAttr(el, name) !== undefined
          : getAttr(el, name);
};

var setProp = function (el, name, value) {
  el[name] = rboolean.test(name) ? !!value : value;
};

exports.prop = function (name, value) {
  var i = 0,
      property;

  if (typeof name === 'string' && value === undefined) {

    switch (name) {
      case 'style':
        property = this.css();

        _.forEach(property, function (v, p) {
          property[i++] = p;
        });

        property.length = i;

        break;
      case 'tagName':
      case 'nodeName':
        property = this[0].name.toUpperCase();
        break;
      default:
        property = getProp(this[0], name);
    }

    return property;
  }

  if (typeof name === 'object' || value !== undefined) {

    if (typeof value === 'function') {
      return domEach(this, function(j, el) {
        setProp(el, name, value.call(el, j, getProp(el, name)));
      });
    }

    return domEach(this, function(__, el) {
      if (!isTag(el)) return;

      if (typeof name === 'object') {

        _.forEach(name, function(val, key) {
          setProp(el, key, val);
        });

      } else {
        setProp(el, name, value);
      }
    });

  }
};

var setData = function(el, name, value) {
  if (!el.data) {
    el.data = {};
  }

  if (typeof name === 'object') return _.extend(el.data, name);
  if (typeof name === 'string' && value !== undefined) {
    el.data[name] = value;
  }
};

// Read the specified attribute from the equivalent HTML5 `data-*` attribute,
// and (if present) cache the value in the node's internal data store. If no
// attribute name is specified, read *all* HTML5 `data-*` attributes in this
// manner.
var readData = function(el, name) {
  var readAll = arguments.length === 1;
  var domNames, domName, jsNames, jsName, value, idx, length;

  if (readAll) {
    domNames = Object.keys(el.attribs).filter(function(attrName) {
      return attrName.slice(0, dataAttrPrefix.length) === dataAttrPrefix;
    });
    jsNames = domNames.map(function(_domName) {
      return camelCase(_domName.slice(dataAttrPrefix.length));
    });
  } else {
    domNames = [dataAttrPrefix + cssCase(name)];
    jsNames = [name];
  }

  for (idx = 0, length = domNames.length; idx < length; ++idx) {
    domName = domNames[idx];
    jsName = jsNames[idx];
    if (hasOwn.call(el.attribs, domName)) {
      value = el.attribs[domName];

      if (hasOwn.call(primitives, value)) {
        value = primitives[value];
      } else if (value === String(Number(value))) {
        value = Number(value);
      } else if (rbrace.test(value)) {
        try {
          value = JSON.parse(value);
        } catch(e){ }
      }

      el.data[jsName] = value;
    }
  }

  return readAll ? el.data : value;
};

exports.data = function(name, value) {
  var elem = this[0];

  if (!elem || !isTag(elem)) return;

  if (!elem.data) {
    elem.data = {};
  }

  // Return the entire data object if no data specified
  if (!name) {
    return readData(elem);
  }

  // Set the value (with attr map support)
  if (typeof name === 'object' || value !== undefined) {
    domEach(this, function(i, el) {
      setData(el, name, value);
    });
    return this;
  } else if (hasOwn.call(elem.data, name)) {
    return elem.data[name];
  }

  return readData(elem, name);
};

/**
 * Get the value of an element
 */

exports.val = function(value) {
  var querying = arguments.length === 0,
      element = this[0];

  if(!element) return;

  switch (element.name) {
    case 'textarea':
      return this.text(value);
    case 'input':
      switch (this.attr('type')) {
        case 'radio':
          if (querying) {
            return this.attr('value');
          } else {
            this.attr('value', value);
            return this;
          }
          break;
        default:
          return this.attr('value', value);
      }
      return;
    case 'select':
      var option = this.find('option:selected'),
          returnValue;
      if (option === undefined) return undefined;
      if (!querying) {
        if (!hasOwn.call(this.attr(), 'multiple') && typeof value == 'object') {
          return this;
        }
        if (typeof value != 'object') {
          value = [value];
        }
        this.find('option').removeAttr('selected');
        for (var i = 0; i < value.length; i++) {
          this.find('option[value="' + value[i] + '"]').attr('selected', '');
        }
        return this;
      }
      returnValue = option.attr('value');
      if (hasOwn.call(this.attr(), 'multiple')) {
        returnValue = [];
        domEach(option, function(__, el) {
          returnValue.push(getAttr(el, 'value'));
        });
      }
      return returnValue;
    case 'option':
      if (!querying) {
        this.attr('value', value);
        return this;
      }
      return this.attr('value');
  }
};

/**
 * Remove an attribute
 */

var removeAttribute = function(elem, name) {
  if (!elem.attribs || !hasOwn.call(elem.attribs, name))
    return;

  delete elem.attribs[name];
};


exports.removeAttr = function(name) {
  domEach(this, function(i, elem) {
    removeAttribute(elem, name);
  });

  return this;
};

exports.hasClass = function(className) {
  return _.some(this, function(elem) {
    var attrs = elem.attribs,
        clazz = attrs && attrs['class'],
        idx = -1,
        end;

    if (clazz && className.length) {
      while ((idx = clazz.indexOf(className, idx+1)) > -1) {
        end = idx + className.length;

        if ((idx === 0 || rspace.test(clazz[idx-1]))
            && (end === clazz.length || rspace.test(clazz[end]))) {
          return true;
        }
      }
    }
  });
};

exports.addClass = function(value) {
  // Support functions
  if (typeof value === 'function') {
    return domEach(this, function(i, el) {
      var className = el.attribs['class'] || '';
      exports.addClass.call([el], value.call(el, i, className));
    });
  }

  // Return if no value or not a string or function
  if (!value || typeof value !== 'string') return this;

  var classNames = value.split(rspace),
      numElements = this.length;


  for (var i = 0; i < numElements; i++) {
    // If selected element isn't a tag, move on
    if (!isTag(this[i])) continue;

    // If we don't already have classes
    var className = getAttr(this[i], 'class'),
        numClasses,
        setClass;

    if (!className) {
      setAttr(this[i], 'class', classNames.join(' ').trim());
    } else {
      setClass = ' ' + className + ' ';
      numClasses = classNames.length;

      // Check if class already exists
      for (var j = 0; j < numClasses; j++) {
        var appendClass = classNames[j] + ' ';
        if (setClass.indexOf(' ' + appendClass) < 0)
          setClass += appendClass;
      }

      setAttr(this[i], 'class', setClass.trim());
    }
  }

  return this;
};

var splitClass = function(className) {
  return className ? className.trim().split(rspace) : [];
};

exports.removeClass = function(value) {
  var classes,
      numClasses,
      removeAll;

  // Handle if value is a function
  if (typeof value === 'function') {
    return domEach(this, function(i, el) {
      exports.removeClass.call(
        [el], value.call(el, i, el.attribs['class'] || '')
      );
    });
  }

  classes = splitClass(value);
  numClasses = classes.length;
  removeAll = arguments.length === 0;

  return domEach(this, function(i, el) {
    if (!isTag(el)) return;

    if (removeAll) {
      // Short circuit the remove all case as this is the nice one
      el.attribs.class = '';
    } else {
      var elClasses = splitClass(el.attribs.class),
          index,
          changed;

      for (var j = 0; j < numClasses; j++) {
        index = elClasses.indexOf(classes[j]);

        if (index >= 0) {
          elClasses.splice(index, 1);
          changed = true;

          // We have to do another pass to ensure that there are not duplicate
          // classes listed
          j--;
        }
      }
      if (changed) {
        el.attribs.class = elClasses.join(' ');
      }
    }
  });
};

exports.toggleClass = function(value, stateVal) {
  // Support functions
  if (typeof value === 'function') {
    return domEach(this, function(i, el) {
      exports.toggleClass.call(
        [el],
        value.call(el, i, el.attribs['class'] || '', stateVal),
        stateVal
      );
    });
  }

  // Return if no value or not a string or function
  if (!value || typeof value !== 'string') return this;

  var classNames = value.split(rspace),
    numClasses = classNames.length,
    state = typeof stateVal === 'boolean' ? stateVal ? 1 : -1 : 0,
    numElements = this.length,
    elementClasses,
    index;

  for (var i = 0; i < numElements; i++) {
    // If selected element isn't a tag, move on
    if (!isTag(this[i])) continue;

    elementClasses = splitClass(this[i].attribs.class);

    // Check if class already exists
    for (var j = 0; j < numClasses; j++) {
      // Check if the class name is currently defined
      index = elementClasses.indexOf(classNames[j]);

      // Add if stateValue === true or we are toggling and there is no value
      if (state >= 0 && index < 0) {
        elementClasses.push(classNames[j]);
      } else if (state <= 0 && index >= 0) {
        // Otherwise remove but only if the item exists
        elementClasses.splice(index, 1);
      }
    }

    this[i].attribs.class = elementClasses.join(' ');
  }

  return this;
};

exports.is = function (selector) {
  if (selector) {
    return this.filter(selector).length > 0;
  }
  return false;
};


/***/ }),
/* 1021 */
/***/ (function(module, exports, __nested_webpack_require_4810497__) {

var parse = __nested_webpack_require_4810497__(1022),
    compile = __nested_webpack_require_4810497__(1023);

module.exports = function nthCheck(formula){
	return compile(parse(formula));
};

module.exports.parse = parse;
module.exports.compile = compile;

/***/ }),
/* 1022 */
/***/ (function(module, exports) {

module.exports = parse;

//following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo

//[ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
var re_nthElement = /^([+\-]?\d*n)?\s*(?:([+\-]?)\s*(\d+))?$/;

/*
	parses a nth-check formula, returns an array of two numbers
*/
function parse(formula){
	formula = formula.trim().toLowerCase();

	if(formula === "even"){
		return [2, 0];
	} else if(formula === "odd"){
		return [2, 1];
	} else {
		var parsed = formula.match(re_nthElement);

		if(!parsed){
			throw new SyntaxError("n-th rule couldn't be parsed ('" + formula + "')");
		}

		var a;

		if(parsed[1]){
			a = parseInt(parsed[1], 10);
			if(isNaN(a)){
				if(parsed[1].charAt(0) === "-") a = -1;
				else a = 1;
			}
		} else a = 0;

		return [
			a,
			parsed[3] ? parseInt((parsed[2] || "") + parsed[3], 10) : 0
		];
	}
}


/***/ }),
/* 1023 */
/***/ (function(module, exports, __nested_webpack_require_4811701__) {

module.exports = compile;

var BaseFuncs = __nested_webpack_require_4811701__(153),
    trueFunc  = BaseFuncs.trueFunc,
    falseFunc = BaseFuncs.falseFunc;

/*
	returns a function that checks if an elements index matches the given rule
	highly optimized to return the fastest solution
*/
function compile(parsed){
	var a = parsed[0],
	    b = parsed[1] - 1;

	//when b <= 0, a*n won't be possible for any matches when a < 0
	//besides, the specification says that no element is matched when a and b are 0
	if(b < 0 && a <= 0) return falseFunc;

	//when a is in the range -1..1, it matches any element (so only b is checked)
	if(a ===-1) return function(pos){ return pos <= b; };
	if(a === 0) return function(pos){ return pos === b; };
	//when b <= 0 and a === 1, they match any element
	if(a === 1) return b < 0 ? trueFunc : function(pos){ return pos >= b; };

	//when a > 0, modulo can be used to check if there is a match
	var bMod = b % a;
	if(bMod < 0) bMod += a;

	if(a > 1){
		return function(pos){
			return pos >= b && pos % a === bMod;
		};
	}

	a *= -1; //make `a` positive

	return function(pos){
		return pos <= b && pos % a === bMod;
	};
}

/***/ }),
/* 1024 */
/***/ (function(module, exports, __nested_webpack_require_4812919__) {

/*
	compiles a selector to an executable function
*/

module.exports = compile;
module.exports.compileUnsafe = compileUnsafe;
module.exports.compileToken = compileToken;

var parse       = __nested_webpack_require_4812919__(1025),
    DomUtils    = __nested_webpack_require_4812919__(101),
    isTag       = DomUtils.isTag,
    Rules       = __nested_webpack_require_4812919__(1026),
    sortRules   = __nested_webpack_require_4812919__(1027),
    BaseFuncs   = __nested_webpack_require_4812919__(153),
    trueFunc    = BaseFuncs.trueFunc,
    falseFunc   = BaseFuncs.falseFunc,
    procedure   = __nested_webpack_require_4812919__(487);

function compile(selector, options, context){
	var next = compileUnsafe(selector, options, context);
	return wrap(next);
}

function wrap(next){
	return function base(elem){
		return isTag(elem) && next(elem);
	};
}

function compileUnsafe(selector, options, context){
	var token = parse(selector, options);
	return compileToken(token, options, context);
}

function includesScopePseudo(t){
    return t.type === "pseudo" && (
        t.name === "scope" || (
            Array.isArray(t.data) &&
            t.data.some(function(data){
                return data.some(includesScopePseudo);
            })
        )
    );
}

var DESCENDANT_TOKEN = {type: "descendant"},
    SCOPE_TOKEN = {type: "pseudo", name: "scope"},
    PLACEHOLDER_ELEMENT = {},
    getParent = DomUtils.getParent;

//CSS 4 Spec (Draft): 3.3.1. Absolutizing a Scope-relative Selector
//http://www.w3.org/TR/selectors4/#absolutizing
function absolutize(token, context){
    //TODO better check if context is document
    var hasContext = !!context && !!context.length && context.every(function(e){
        return e === PLACEHOLDER_ELEMENT || !!getParent(e);
    });


    token.forEach(function(t){
        if(t.length > 0 && isTraversal(t[0]) && t[0].type !== "descendant"){
            //don't return in else branch
        } else if(hasContext && !includesScopePseudo(t)){
            t.unshift(DESCENDANT_TOKEN);
        } else {
            return;
        }

        t.unshift(SCOPE_TOKEN);
    });
}

function compileToken(token, options, context){
    token = token.filter(function(t){ return t.length > 0; });

	token.forEach(sortRules);

	var isArrayContext = Array.isArray(context);

    context = (options && options.context) || context;

    if(context && !isArrayContext) context = [context];

    absolutize(token, context);

	return token
		.map(function(rules){ return compileRules(rules, options, context, isArrayContext); })
		.reduce(reduceRules, falseFunc);
}

function isTraversal(t){
	return procedure[t.type] < 0;
}

function compileRules(rules, options, context, isArrayContext){
	var acceptSelf = (isArrayContext && rules[0].name === "scope" && rules[1].type === "descendant");
	return rules.reduce(function(func, rule, index){
		if(func === falseFunc) return func;
		return Rules[rule.type](func, rule, options, context, acceptSelf && index === 1);
	}, options && options.rootFunc || trueFunc);
}

function reduceRules(a, b){
	if(b === falseFunc || a === trueFunc){
		return a;
	}
	if(a === falseFunc || b === trueFunc){
		return b;
	}

	return function combine(elem){
		return a(elem) || b(elem);
	};
}

//:not, :has and :matches have to compile selectors
//doing this in lib/pseudos.js would lead to circular dependencies,
//so we add them here

var Pseudos     = __nested_webpack_require_4812919__(311),
    filters     = Pseudos.filters,
    existsOne   = DomUtils.existsOne,
    isTag       = DomUtils.isTag,
    getChildren = DomUtils.getChildren;


function containsTraversal(t){
	return t.some(isTraversal);
}

filters.not = function(next, token, options, context){
	var opts = {
	    	xmlMode: !!(options && options.xmlMode),
	    	strict: !!(options && options.strict)
	    };

	if(opts.strict){
		if(token.length > 1 || token.some(containsTraversal)){
			throw new SyntaxError("complex selectors in :not aren't allowed in strict mode");
		}
	}

    var func = compileToken(token, opts, context);

	if(func === falseFunc) return next;
	if(func === trueFunc)  return falseFunc;

	return function(elem){
		return !func(elem) && next(elem);
	};
};

filters.has = function(next, token, options){
	var opts = {
		xmlMode: !!(options && options.xmlMode),
		strict: !!(options && options.strict)
	};

    //FIXME: Uses an array as a pointer to the current element (side effects)
    var context = token.some(containsTraversal) ? [PLACEHOLDER_ELEMENT] : null;

	var func = compileToken(token, opts, context);

	if(func === falseFunc) return falseFunc;
	if(func === trueFunc)  return function(elem){
			return getChildren(elem).some(isTag) && next(elem);
		};

	func = wrap(func);

    if(context){
        return function has(elem){
		return next(elem) && (
                (context[0] = elem), existsOne(func, getChildren(elem))
            );
	};
    }

    return function has(elem){
		return next(elem) && existsOne(func, getChildren(elem));
	};
};

filters.matches = function(next, token, options, context){
	var opts = {
		xmlMode: !!(options && options.xmlMode),
		strict: !!(options && options.strict),
		rootFunc: next
	};

	return compileToken(token, opts, context);
};


/***/ }),
/* 1025 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = parse;

var re_name = /^(?:\\.|[\w\-\u00b0-\uFFFF])+/,
    re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig,
    //modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
    re_attr = /^\s*((?:\\.|[\w\u00b0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])([^]*?)\3|(#?(?:\\.|[\w\u00b0-\uFFFF\-])*)|)|)\s*(i)?\]/;

var actionTypes = {
	__proto__: null,
	"undefined": "exists",
	"":  "equals",
	"~": "element",
	"^": "start",
	"$": "end",
	"*": "any",
	"!": "not",
	"|": "hyphen"
};

var simpleSelectors = {
	__proto__: null,
	">": "child",
	"<": "parent",
	"~": "sibling",
	"+": "adjacent"
};

var attribSelectors = {
	__proto__: null,
	"#": ["id", "equals"],
	".": ["class", "element"]
};

//pseudos, whose data-property is parsed as well
var unpackPseudos = {
	__proto__: null,
	"has": true,
	"not": true,
	"matches": true
};

var stripQuotesFromPseudos = {
	__proto__: null,
	"contains": true,
	"icontains": true
};

var quotes = {
	__proto__: null,
	"\"": true,
	"'": true
};

//unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139
function funescape( _, escaped, escapedWhitespace ) {
	var high = "0x" + escaped - 0x10000;
	// NaN means non-codepoint
	// Support: Firefox
	// Workaround erroneous numeric interpretation of +"0x"
	return high !== high || escapedWhitespace ?
		escaped :
		// BMP codepoint
		high < 0 ?
			String.fromCharCode( high + 0x10000 ) :
			// Supplemental Plane codepoint (surrogate pair)
			String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
}

function unescapeCSS(str){
	return str.replace(re_escape, funescape);
}

function isWhitespace(c){
	return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}

function parse(selector, options){
	var subselects = [];

	selector = parseSelector(subselects, selector + "", options);

	if(selector !== ""){
		throw new SyntaxError("Unmatched selector: " + selector);
	}

	return subselects;
}

function parseSelector(subselects, selector, options){
	var tokens = [],
		sawWS = false,
		data, firstChar, name, quot;

	function getName(){
		var sub = selector.match(re_name)[0];
		selector = selector.substr(sub.length);
		return unescapeCSS(sub);
	}

	function stripWhitespace(start){
		while(isWhitespace(selector.charAt(start))) start++;
		selector = selector.substr(start);
	}

	function isEscaped(pos) {
		var slashCount = 0;

		while (selector.charAt(--pos) === "\\") slashCount++;
		return (slashCount & 1) === 1;
	}

	stripWhitespace(0);

	while(selector !== ""){
		firstChar = selector.charAt(0);

		if(isWhitespace(firstChar)){
			sawWS = true;
			stripWhitespace(1);
		} else if(firstChar in simpleSelectors){
			tokens.push({type: simpleSelectors[firstChar]});
			sawWS = false;

			stripWhitespace(1);
		} else if(firstChar === ","){
			if(tokens.length === 0){
				throw new SyntaxError("empty sub-selector");
			}
			subselects.push(tokens);
			tokens = [];
			sawWS = false;
			stripWhitespace(1);
		} else {
			if(sawWS){
				if(tokens.length > 0){
					tokens.push({type: "descendant"});
				}
				sawWS = false;
			}

			if(firstChar === "*"){
				selector = selector.substr(1);
				tokens.push({type: "universal"});
			} else if(firstChar in attribSelectors){
				selector = selector.substr(1);
				tokens.push({
					type: "attribute",
					name: attribSelectors[firstChar][0],
					action: attribSelectors[firstChar][1],
					value: getName(),
					ignoreCase: false
				});
			} else if(firstChar === "["){
				selector = selector.substr(1);
				data = selector.match(re_attr);
				if(!data){
					throw new SyntaxError("Malformed attribute selector: " + selector);
				}
				selector = selector.substr(data[0].length);
				name = unescapeCSS(data[1]);

				if(
					!options || (
						"lowerCaseAttributeNames" in options ?
							options.lowerCaseAttributeNames :
							!options.xmlMode
					)
				){
					name = name.toLowerCase();
				}

				tokens.push({
					type: "attribute",
					name: name,
					action: actionTypes[data[2]],
					value: unescapeCSS(data[4] || data[5] || ""),
					ignoreCase: !!data[6]
				});

			} else if(firstChar === ":"){
				if(selector.charAt(1) === ":"){
					selector = selector.substr(2);
					tokens.push({type: "pseudo-element", name: getName().toLowerCase()});
					continue;
				}

				selector = selector.substr(1);

				name = getName().toLowerCase();
				data = null;

				if(selector.charAt(0) === "("){
					if(name in unpackPseudos){
						quot = selector.charAt(1);
						var quoted = quot in quotes;

						selector = selector.substr(quoted + 1);

						data = [];
						selector = parseSelector(data, selector, options);

						if(quoted){
							if(selector.charAt(0) !== quot){
								throw new SyntaxError("unmatched quotes in :" + name);
							} else {
								selector = selector.substr(1);
							}
						}

						if(selector.charAt(0) !== ")"){
							throw new SyntaxError("missing closing parenthesis in :" + name + " " + selector);
						}

						selector = selector.substr(1);
					} else {
						var pos = 1, counter = 1;

						for(; counter > 0 && pos < selector.length; pos++){
							if(selector.charAt(pos) === "(" && !isEscaped(pos)) counter++;
							else if(selector.charAt(pos) === ")" && !isEscaped(pos)) counter--;
						}

						if(counter){
							throw new SyntaxError("parenthesis not matched");
						}

						data = selector.substr(1, pos - 2);
						selector = selector.substr(pos);

						if(name in stripQuotesFromPseudos){
							quot = data.charAt(0);

							if(quot === data.slice(-1) && quot in quotes){
								data = data.slice(1, -1);
							}

							data = unescapeCSS(data);
						}
					}
				}

				tokens.push({type: "pseudo", name: name, data: data});
			} else if(re_name.test(selector)){
				name = getName();

				if(!options || ("lowerCaseTags" in options ? options.lowerCaseTags : !options.xmlMode)){
					name = name.toLowerCase();
				}

				tokens.push({type: "tag", name: name});
			} else {
				if(tokens.length && tokens[tokens.length - 1].type === "descendant"){
					tokens.pop();
				}
				addToken(subselects, tokens);
				return selector;
			}
		}
	}

	addToken(subselects, tokens);

	return selector;
}

function addToken(subselects, tokens){
	if(subselects.length > 0 && tokens.length === 0){
		throw new SyntaxError("empty sub-selector");
	}

	subselects.push(tokens);
}


/***/ }),
/* 1026 */
/***/ (function(module, exports, __nested_webpack_require_4824596__) {

var DomUtils    = __nested_webpack_require_4824596__(101),
    isTag       = DomUtils.isTag,
    getParent   = DomUtils.getParent,
    getChildren = DomUtils.getChildren,
    getSiblings = DomUtils.getSiblings,
    getName     = DomUtils.getName;

/*
	all available rules
*/
module.exports = {
	__proto__: null,

	attribute: __nested_webpack_require_4824596__(486).compile,
	pseudo: __nested_webpack_require_4824596__(311).compile,

	//tags
	tag: function(next, data){
		var name = data.name;
		return function tag(elem){
			return getName(elem) === name && next(elem);
		};
	},

	//traversal
	descendant: function(next, rule, options, context, acceptSelf){
		return function descendant(elem){

			if (acceptSelf && next(elem)) return true;

			var found = false;

			while(!found && (elem = getParent(elem))){
				found = next(elem);
			}

			return found;
		};
	},
	parent: function(next, data, options){
		if(options && options.strict) throw SyntaxError("Parent selector isn't part of CSS3");

		return function parent(elem){
			return getChildren(elem).some(test);
		};

		function test(elem){
			return isTag(elem) && next(elem);
		}
	},
	child: function(next){
		return function child(elem){
			var parent = getParent(elem);
			return !!parent && next(parent);
		};
	},
	sibling: function(next){
		return function sibling(elem){
			var siblings = getSiblings(elem);

			for(var i = 0; i < siblings.length; i++){
				if(isTag(siblings[i])){
					if(siblings[i] === elem) break;
					if(next(siblings[i])) return true;
				}
			}

			return false;
		};
	},
	adjacent: function(next){
		return function adjacent(elem){
			var siblings = getSiblings(elem),
			    lastElement;

			for(var i = 0; i < siblings.length; i++){
				if(isTag(siblings[i])){
					if(siblings[i] === elem) break;
					lastElement = siblings[i];
				}
			}

			return !!lastElement && next(lastElement);
		};
	},
	universal: function(next){
		return next;
	}
};

/***/ }),
/* 1027 */
/***/ (function(module, exports, __nested_webpack_require_4826568__) {

module.exports = sortByProcedure;

/*
	sort the parts of the passed selector,
	as there is potential for optimization
	(some types of selectors are faster than others)
*/

var procedure = __nested_webpack_require_4826568__(487);

var attributes = {
	__proto__: null,
	exists: 10,
	equals: 8,
	not: 7,
	start: 6,
	end: 6,
	any: 5,
	hyphen: 4,
	element: 4
};

function sortByProcedure(arr){
	var procs = arr.map(getProcedure);
	for(var i = 1; i < arr.length; i++){
		var procNew = procs[i];

		if(procNew < 0) continue;

		for(var j = i - 1; j >= 0 && procNew < procs[j]; j--){
			var token = arr[j + 1];
			arr[j + 1] = arr[j];
			arr[j] = token;
			procs[j + 1] = procs[j];
			procs[j] = procNew;
		}
	}
}

function getProcedure(token){
	var proc = procedure[token.type];

	if(proc === procedure.attribute){
		proc = attributes[token.action];

		if(proc === attributes.equals && token.name === "id"){
			//prefer ID selectors (eg. #ID)
			proc = 9;
		}

		if(token.ignoreCase){
			//ignoreCase adds some overhead, prefer "normal" token
			//this is a binary operation, to ensure it's still an int
			proc >>= 1;
		}
	} else if(proc === procedure.pseudo){
		if(!token.data){
			proc = 3;
		} else if(token.name === "has" || token.name === "contains"){
			proc = 0; //expensive in any case
		} else if(token.name === "matches" || token.name === "not"){
			proc = 0;
			for(var i = 0; i < token.data.length; i++){
				//TODO better handling of complex selectors
				if(token.data[i].length !== 1) continue;
				var cur = getProcedure(token.data[i][0]);
				//avoid executing :has or :contains
				if(cur === 0){
					proc = 0;
					break;
				}
				if(cur > proc) proc = cur;
			}
			if(token.data.length > 1 && proc > 0) proc -= 1;
		} else {
			proc = 1;
		}
	}
	return proc;
}


/***/ }),
/* 1028 */
/***/ (function(module, exports, __nested_webpack_require_4828410__) {

var arraySome = __nested_webpack_require_4828410__(417),
    baseIteratee = __nested_webpack_require_4828410__(144),
    baseSome = __nested_webpack_require_4828410__(1029),
    isArray = __nested_webpack_require_4828410__(31),
    isIterateeCall = __nested_webpack_require_4828410__(294);

/**
 * Checks if `predicate` returns truthy for **any** element of `collection`.
 * Iteration is stopped once `predicate` returns truthy. The predicate is
 * invoked with three arguments: (value, index|key, collection).
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 * @example
 *
 * _.some([null, 0, 'yes', false], Boolean);
 * // => true
 *
 * var users = [
 *   { 'user': 'barney', 'active': true },
 *   { 'user': 'fred',   'active': false }
 * ];
 *
 * // The `_.matches` iteratee shorthand.
 * _.some(users, { 'user': 'barney', 'active': false });
 * // => false
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.some(users, ['active', false]);
 * // => true
 *
 * // The `_.property` iteratee shorthand.
 * _.some(users, 'active');
 * // => true
 */
function some(collection, predicate, guard) {
  var func = isArray(collection) ? arraySome : baseSome;
  if (guard && isIterateeCall(collection, predicate, guard)) {
    predicate = undefined;
  }
  return func(collection, baseIteratee(predicate, 3));
}

module.exports = some;


/***/ }),
/* 1029 */
/***/ (function(module, exports, __nested_webpack_require_4830099__) {

var baseEach = __nested_webpack_require_4830099__(146);

/**
 * The base implementation of `_.some` without support for iteratee shorthands.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} predicate The function invoked per iteration.
 * @returns {boolean} Returns `true` if any element passes the predicate check,
 *  else `false`.
 */
function baseSome(collection, predicate) {
  var result;

  baseEach(collection, function(value, index, collection) {
    result = predicate(value, index, collection);
    return !result;
  });
  return !!result;
}

module.exports = baseSome;


/***/ }),
/* 1030 */
/***/ (function(module, exports, __nested_webpack_require_4830800__) {

var select = __nested_webpack_require_4830800__(485),
    utils = __nested_webpack_require_4830800__(152),
    domEach = utils.domEach,
    uniqueSort = __nested_webpack_require_4830800__(148).DomUtils.uniqueSort,
    isTag = utils.isTag,
    _ = {
      bind: __nested_webpack_require_4830800__(306),
      forEach: __nested_webpack_require_4830800__(147),
      reject: __nested_webpack_require_4830800__(1031),
      filter: __nested_webpack_require_4830800__(1033),
      reduce: __nested_webpack_require_4830800__(1034)
    };

exports.find = function(selectorOrHaystack) {
  var elems = _.reduce(this, function(memo, elem) {
    return memo.concat(_.filter(elem.children, isTag));
  }, []);
  var contains = this.constructor.contains;
  var haystack;

  if (selectorOrHaystack && typeof selectorOrHaystack !== 'string') {
    if (selectorOrHaystack.cheerio) {
      haystack = selectorOrHaystack.get();
    } else {
      haystack = [selectorOrHaystack];
    }

    return this._make(haystack.filter(function(elem) {
      var idx, len;
      for (idx = 0, len = this.length; idx < len; ++idx) {
        if (contains(this[idx], elem)) {
          return true;
        }
      }
    }, this));
  }

  var options = {__proto__: this.options, context: this.toArray()};

  return this._make(select(selectorOrHaystack, elems, options));
};

// Get the parent of each element in the current set of matched elements,
// optionally filtered by a selector.
exports.parent = function(selector) {
  var set = [];

  domEach(this, function(idx, elem) {
    var parentElem = elem.parent;
    if (parentElem && set.indexOf(parentElem) < 0) {
      set.push(parentElem);
    }
  });

  if (arguments.length) {
    set = exports.filter.call(set, selector, this);
  }

  return this._make(set);
};

exports.parents = function(selector) {
  var parentNodes = [];

  // When multiple DOM elements are in the original set, the resulting set will
  // be in *reverse* order of the original elements as well, with duplicates
  // removed.
  this.get().reverse().forEach(function(elem) {
    traverseParents(this, elem.parent, selector, Infinity)
      .forEach(function(node) {
        if (parentNodes.indexOf(node) === -1) {
          parentNodes.push(node);
        }
      }
    );
  }, this);

  return this._make(parentNodes);
};

exports.parentsUntil = function(selector, filter) {
  var parentNodes = [], untilNode, untilNodes;

  if (typeof selector === 'string') {
    untilNode = select(selector, this.parents().toArray(), this.options)[0];
  } else if (selector && selector.cheerio) {
    untilNodes = selector.toArray();
  } else if (selector) {
    untilNode = selector;
  }

  // When multiple DOM elements are in the original set, the resulting set will
  // be in *reverse* order of the original elements as well, with duplicates
  // removed.

  this.toArray().reverse().forEach(function(elem) {
    while ((elem = elem.parent)) {
      if ((untilNode && elem !== untilNode) ||
        (untilNodes && untilNodes.indexOf(elem) === -1) ||
        (!untilNode && !untilNodes)) {
        if (isTag(elem) && parentNodes.indexOf(elem) === -1) { parentNodes.push(elem); }
      } else {
        break;
      }
    }
  }, this);

  return this._make(filter ? select(filter, parentNodes, this.options) : parentNodes);
};

// For each element in the set, get the first element that matches the selector
// by testing the element itself and traversing up through its ancestors in the
// DOM tree.
exports.closest = function(selector) {
  var set = [];

  if (!selector) {
    return this._make(set);
  }

  domEach(this, function(idx, elem) {
    var closestElem = traverseParents(this, elem, selector, 1)[0];

    // Do not add duplicate elements to the set
    if (closestElem && set.indexOf(closestElem) < 0) {
      set.push(closestElem);
    }
  }.bind(this));

  return this._make(set);
};

exports.next = function(selector) {
  if (!this[0]) { return this; }
  var elems = [];

  _.forEach(this, function(elem) {
    while ((elem = elem.next)) {
      if (isTag(elem)) {
        elems.push(elem);
        return;
      }
    }
  });

  return selector ?
    exports.filter.call(elems, selector, this) :
    this._make(elems);
};

exports.nextAll = function(selector) {
  if (!this[0]) { return this; }
  var elems = [];

  _.forEach(this, function(elem) {
    while ((elem = elem.next)) {
      if (isTag(elem) && elems.indexOf(elem) === -1) {
        elems.push(elem);
      }
    }
  });

  return selector ?
    exports.filter.call(elems, selector, this) :
    this._make(elems);
};

exports.nextUntil = function(selector, filterSelector) {
  if (!this[0]) { return this; }
  var elems = [], untilNode, untilNodes;

  if (typeof selector === 'string') {
    untilNode = select(selector, this.nextAll().get(), this.options)[0];
  } else if (selector && selector.cheerio) {
    untilNodes = selector.get();
  } else if (selector) {
    untilNode = selector;
  }

  _.forEach(this, function(elem) {
    while ((elem = elem.next)) {
      if ((untilNode && elem !== untilNode) ||
        (untilNodes && untilNodes.indexOf(elem) === -1) ||
        (!untilNode && !untilNodes)) {
        if (isTag(elem) && elems.indexOf(elem) === -1) {
          elems.push(elem);
        }
      } else {
        break;
      }
    }
  });

  return filterSelector ?
    exports.filter.call(elems, filterSelector, this) :
    this._make(elems);
};

exports.prev = function(selector) {
  if (!this[0]) { return this; }
  var elems = [];

  _.forEach(this, function(elem) {
    while ((elem = elem.prev)) {
      if (isTag(elem)) {
        elems.push(elem);
        return;
      }
    }
  });

  return selector ?
    exports.filter.call(elems, selector, this) :
    this._make(elems);
};

exports.prevAll = function(selector) {
  if (!this[0]) { return this; }
  var elems = [];

  _.forEach(this, function(elem) {
    while ((elem = elem.prev)) {
      if (isTag(elem) && elems.indexOf(elem) === -1) {
        elems.push(elem);
      }
    }
  });

  return selector ?
    exports.filter.call(elems, selector, this) :
    this._make(elems);
};

exports.prevUntil = function(selector, filterSelector) {
  if (!this[0]) { return this; }
  var elems = [], untilNode, untilNodes;

  if (typeof selector === 'string') {
    untilNode = select(selector, this.prevAll().get(), this.options)[0];
  } else if (selector && selector.cheerio) {
    untilNodes = selector.get();
  } else if (selector) {
    untilNode = selector;
  }

  _.forEach(this, function(elem) {
    while ((elem = elem.prev)) {
      if ((untilNode && elem !== untilNode) ||
        (untilNodes && untilNodes.indexOf(elem) === -1) ||
        (!untilNode && !untilNodes)) {
        if (isTag(elem) && elems.indexOf(elem) === -1) {
          elems.push(elem);
        }
      } else {
        break;
      }
    }
  });

  return filterSelector ?
    exports.filter.call(elems, filterSelector, this) :
    this._make(elems);
};

exports.siblings = function(selector) {
  var parent = this.parent();

  var elems = _.filter(
    parent ? parent.children() : this.siblingsAndMe(),
    _.bind(function(elem) { return isTag(elem) && !this.is(elem); }, this)
  );

  if (selector !== undefined) {
    return exports.filter.call(elems, selector, this);
  } else {
    return this._make(elems);
  }
};

exports.children = function(selector) {

  var elems = _.reduce(this, function(memo, elem) {
    return memo.concat(_.filter(elem.children, isTag));
  }, []);

  if (selector === undefined) return this._make(elems);

  return exports.filter.call(elems, selector, this);
};

exports.contents = function() {
  return this._make(_.reduce(this, function(all, elem) {
    all.push.apply(all, elem.children);
    return all;
  }, []));
};

exports.each = function(fn) {
  var i = 0, len = this.length;
  while (i < len && fn.call(this[i], i, this[i]) !== false) ++i;
  return this;
};

exports.map = function(fn) {
  return this._make(_.reduce(this, function(memo, el, i) {
    var val = fn.call(el, i, el);
    return val == null ? memo : memo.concat(val);
  }, []));
};

var makeFilterMethod = function(filterFn) {
  return function(match, container) {
    var testFn;
    container = container || this;

    if (typeof match === 'string') {
      testFn = select.compile(match, container.options);
    } else if (typeof match === 'function') {
      testFn = function(el, i) {
        return match.call(el, i, el);
      };
    } else if (match.cheerio) {
      testFn = match.is.bind(match);
    } else {
      testFn = function(el) {
        return match === el;
      };
    }

    return container._make(filterFn(this, testFn));
  };
};

exports.filter = makeFilterMethod(_.filter);
exports.not = makeFilterMethod(_.reject);

exports.has = function(selectorOrHaystack) {
  var that = this;
  return exports.filter.call(this, function() {
    return that._make(this).find(selectorOrHaystack).length > 0;
  });
};

exports.first = function() {
  return this.length > 1 ? this._make(this[0]) : this;
};

exports.last = function() {
  return this.length > 1 ? this._make(this[this.length - 1]) : this;
};

// Reduce the set of matched elements to the one at the specified index.
exports.eq = function(i) {
  i = +i;

  // Use the first identity optimization if possible
  if (i === 0 && this.length <= 1) return this;

  if (i < 0) i = this.length + i;
  return this[i] ? this._make(this[i]) : this._make([]);
};

// Retrieve the DOM elements matched by the jQuery object.
exports.get = function(i) {
  if (i == null) {
    return Array.prototype.slice.call(this);
  } else {
    return this[i < 0 ? (this.length + i) : i];
  }
};

// Search for a given element from among the matched elements.
exports.index = function(selectorOrNeedle) {
  var $haystack, needle;

  if (arguments.length === 0) {
    $haystack = this.parent().children();
    needle = this[0];
  } else if (typeof selectorOrNeedle === 'string') {
    $haystack = this._make(selectorOrNeedle);
    needle = this[0];
  } else {
    $haystack = this;
    needle = selectorOrNeedle.cheerio ? selectorOrNeedle[0] : selectorOrNeedle;
  }

  return $haystack.get().indexOf(needle);
};

exports.slice = function() {
  return this._make([].slice.apply(this, arguments));
};

function traverseParents(self, elem, selector, limit) {
  var elems = [];
  while (elem && elems.length < limit) {
    if (!selector || exports.filter.call([elem], selector, self).length) {
      elems.push(elem);
    }
    elem = elem.parent;
  }
  return elems;
}

// End the most recent filtering operation in the current chain and return the
// set of matched elements to its previous state.
exports.end = function() {
  return this.prevObject || this._make([]);
};

exports.add = function(other, context) {
  var selection = this._make(other, context);
  var contents = uniqueSort(selection.get().concat(this.get()));

  for (var i = 0; i < contents.length; ++i) {
    selection[i] = contents[i];
  }
  selection.length = contents.length;

  return selection;
};

// Add the previous set of elements on the stack to the current set, optionally
// filtered by a selector.
exports.addBack = function(selector) {
  return this.add(
    arguments.length ? this.prevObject.filter(selector) : this.prevObject
  );
};


/***/ }),
/* 1031 */
/***/ (function(module, exports, __nested_webpack_require_4842043__) {

var arrayFilter = __nested_webpack_require_4842043__(283),
    baseFilter = __nested_webpack_require_4842043__(488),
    baseIteratee = __nested_webpack_require_4842043__(144),
    isArray = __nested_webpack_require_4842043__(31),
    negate = __nested_webpack_require_4842043__(1032);

/**
 * The opposite of `_.filter`; this method returns the elements of `collection`
 * that `predicate` does **not** return truthy for.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 * @see _.filter
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': false },
 *   { 'user': 'fred',   'age': 40, 'active': true }
 * ];
 *
 * _.reject(users, function(o) { return !o.active; });
 * // => objects for ['fred']
 *
 * // The `_.matches` iteratee shorthand.
 * _.reject(users, { 'age': 40, 'active': true });
 * // => objects for ['barney']
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.reject(users, ['active', false]);
 * // => objects for ['fred']
 *
 * // The `_.property` iteratee shorthand.
 * _.reject(users, 'active');
 * // => objects for ['barney']
 */
function reject(collection, predicate) {
  var func = isArray(collection) ? arrayFilter : baseFilter;
  return func(collection, negate(baseIteratee(predicate, 3)));
}

module.exports = reject;


/***/ }),
/* 1032 */
/***/ (function(module, exports) {

/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';

/**
 * Creates a function that negates the result of the predicate `func`. The
 * `func` predicate is invoked with the `this` binding and arguments of the
 * created function.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Function
 * @param {Function} predicate The predicate to negate.
 * @returns {Function} Returns the new negated function.
 * @example
 *
 * function isEven(n) {
 *   return n % 2 == 0;
 * }
 *
 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
 * // => [1, 3, 5]
 */
function negate(predicate) {
  if (typeof predicate != 'function') {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  return function() {
    var args = arguments;
    switch (args.length) {
      case 0: return !predicate.call(this);
      case 1: return !predicate.call(this, args[0]);
      case 2: return !predicate.call(this, args[0], args[1]);
      case 3: return !predicate.call(this, args[0], args[1], args[2]);
    }
    return !predicate.apply(this, args);
  };
}

module.exports = negate;


/***/ }),
/* 1033 */
/***/ (function(module, exports, __nested_webpack_require_4844684__) {

var arrayFilter = __nested_webpack_require_4844684__(283),
    baseFilter = __nested_webpack_require_4844684__(488),
    baseIteratee = __nested_webpack_require_4844684__(144),
    isArray = __nested_webpack_require_4844684__(31);

/**
 * Iterates over elements of `collection`, returning an array of all elements
 * `predicate` returns truthy for. The predicate is invoked with three
 * arguments: (value, index|key, collection).
 *
 * **Note:** Unlike `_.remove`, this method returns a new array.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [predicate=_.identity] The function invoked per iteration.
 * @returns {Array} Returns the new filtered array.
 * @see _.reject
 * @example
 *
 * var users = [
 *   { 'user': 'barney', 'age': 36, 'active': true },
 *   { 'user': 'fred',   'age': 40, 'active': false }
 * ];
 *
 * _.filter(users, function(o) { return !o.active; });
 * // => objects for ['fred']
 *
 * // The `_.matches` iteratee shorthand.
 * _.filter(users, { 'age': 36, 'active': true });
 * // => objects for ['barney']
 *
 * // The `_.matchesProperty` iteratee shorthand.
 * _.filter(users, ['active', false]);
 * // => objects for ['fred']
 *
 * // The `_.property` iteratee shorthand.
 * _.filter(users, 'active');
 * // => objects for ['barney']
 */
function filter(collection, predicate) {
  var func = isArray(collection) ? arrayFilter : baseFilter;
  return func(collection, baseIteratee(predicate, 3));
}

module.exports = filter;


/***/ }),
/* 1034 */
/***/ (function(module, exports, __nested_webpack_require_4846270__) {

var arrayReduce = __nested_webpack_require_4846270__(1035),
    baseEach = __nested_webpack_require_4846270__(146),
    baseIteratee = __nested_webpack_require_4846270__(144),
    baseReduce = __nested_webpack_require_4846270__(1036),
    isArray = __nested_webpack_require_4846270__(31);

/**
 * Reduces `collection` to a value which is the accumulated result of running
 * each element in `collection` thru `iteratee`, where each successive
 * invocation is supplied the return value of the previous. If `accumulator`
 * is not given, the first element of `collection` is used as the initial
 * value. The iteratee is invoked with four arguments:
 * (accumulator, value, index|key, collection).
 *
 * Many lodash methods are guarded to work as iteratees for methods like
 * `_.reduce`, `_.reduceRight`, and `_.transform`.
 *
 * The guarded methods are:
 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
 * and `sortBy`
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @returns {*} Returns the accumulated value.
 * @see _.reduceRight
 * @example
 *
 * _.reduce([1, 2], function(sum, n) {
 *   return sum + n;
 * }, 0);
 * // => 3
 *
 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
 *   (result[value] || (result[value] = [])).push(key);
 *   return result;
 * }, {});
 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
 */
function reduce(collection, iteratee, accumulator) {
  var func = isArray(collection) ? arrayReduce : baseReduce,
      initAccum = arguments.length < 3;

  return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}

module.exports = reduce;


/***/ }),
/* 1035 */
/***/ (function(module, exports) {

/**
 * A specialized version of `_.reduce` for arrays without support for
 * iteratee shorthands.
 *
 * @private
 * @param {Array} [array] The array to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} [accumulator] The initial value.
 * @param {boolean} [initAccum] Specify using the first element of `array` as
 *  the initial value.
 * @returns {*} Returns the accumulated value.
 */
function arrayReduce(array, iteratee, accumulator, initAccum) {
  var index = -1,
      length = array == null ? 0 : array.length;

  if (initAccum && length) {
    accumulator = array[++index];
  }
  while (++index < length) {
    accumulator = iteratee(accumulator, array[index], index, array);
  }
  return accumulator;
}

module.exports = arrayReduce;


/***/ }),
/* 1036 */
/***/ (function(module, exports) {

/**
 * The base implementation of `_.reduce` and `_.reduceRight`, without support
 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
 *
 * @private
 * @param {Array|Object} collection The collection to iterate over.
 * @param {Function} iteratee The function invoked per iteration.
 * @param {*} accumulator The initial value.
 * @param {boolean} initAccum Specify using the first or last element of
 *  `collection` as the initial value.
 * @param {Function} eachFunc The function to iterate over `collection`.
 * @returns {*} Returns the accumulated value.
 */
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
  eachFunc(collection, function(value, index, collection) {
    accumulator = initAccum
      ? (initAccum = false, value)
      : iteratee(accumulator, value, index, collection);
  });
  return accumulator;
}

module.exports = baseReduce;


/***/ }),
/* 1037 */
/***/ (function(module, exports, __nested_webpack_require_4849974__) {

var parse = __nested_webpack_require_4849974__(198),
    $ = __nested_webpack_require_4849974__(310),
    updateDOM = parse.update,
    evaluate = parse.evaluate,
    utils = __nested_webpack_require_4849974__(152),
    domEach = utils.domEach,
    cloneDom = utils.cloneDom,
    isHtml = utils.isHtml,
    slice = Array.prototype.slice,
    _ = {
      flatten: __nested_webpack_require_4849974__(489),
      bind: __nested_webpack_require_4849974__(306),
      forEach: __nested_webpack_require_4849974__(147)
    };

// Create an array of nodes, recursing into arrays and parsing strings if
// necessary
exports._makeDomArray = function makeDomArray(elem, clone) {
  if (elem == null) {
    return [];
  } else if (elem.cheerio) {
    return clone ? cloneDom(elem.get(), elem.options) : elem.get();
  } else if (Array.isArray(elem)) {
    return _.flatten(elem.map(function(el) {
      return this._makeDomArray(el, clone);
    }, this));
  } else if (typeof elem === 'string') {
    return evaluate(elem, this.options, false);
  } else {
    return clone ? cloneDom([elem]) : [elem];
  }
};

var _insert = function(concatenator) {
  return function() {
    var elems = slice.call(arguments),
        lastIdx = this.length - 1;

    return domEach(this, function(i, el) {
      var dom, domSrc;

      if (typeof elems[0] === 'function') {
        domSrc = elems[0].call(el, i, $.html(el.children));
      } else {
        domSrc = elems;
      }

      dom = this._makeDomArray(domSrc, i < lastIdx);
      concatenator(dom, el.children, el);
    });
  };
};

/*
 * Modify an array in-place, removing some number of elements and adding new
 * elements directly following them.
 *
 * @param {Array} array Target array to splice.
 * @param {Number} spliceIdx Index at which to begin changing the array.
 * @param {Number} spliceCount Number of elements to remove from the array.
 * @param {Array} newElems Elements to insert into the array.
 *
 * @api private
 */
var uniqueSplice = function(array, spliceIdx, spliceCount, newElems, parent) {
  var spliceArgs = [spliceIdx, spliceCount].concat(newElems),
      prev = array[spliceIdx - 1] || null,
      next = array[spliceIdx] || null;
  var idx, len, prevIdx, node, oldParent;

  // Before splicing in new elements, ensure they do not already appear in the
  // current array.
  for (idx = 0, len = newElems.length; idx < len; ++idx) {
    node = newElems[idx];
    oldParent = node.parent || node.root;
    prevIdx = oldParent && oldParent.children.indexOf(newElems[idx]);

    if (oldParent && prevIdx > -1) {
      oldParent.children.splice(prevIdx, 1);
      if (parent === oldParent && spliceIdx > prevIdx) {
        spliceArgs[0]--;
      }
    }

    node.root = null;
    node.parent = parent;

    if (node.prev) {
      node.prev.next = node.next || null;
    }

    if (node.next) {
      node.next.prev = node.prev || null;
    }

    node.prev = newElems[idx - 1] || prev;
    node.next = newElems[idx + 1] || next;
  }

  if (prev) {
    prev.next = newElems[0];
  }
  if (next) {
    next.prev = newElems[newElems.length - 1];
  }
  return array.splice.apply(array, spliceArgs);
};

exports.appendTo = function(target) {
  if (!target.cheerio) {
    target = this.constructor.call(this.constructor, target, null, this._originalRoot);
  }

  target.append(this);

  return this;
};

exports.prependTo = function(target) {
  if (!target.cheerio) {
    target = this.constructor.call(this.constructor, target, null, this._originalRoot);
  }

  target.prepend(this);

  return this;
};

exports.append = _insert(function(dom, children, parent) {
  uniqueSplice(children, children.length, 0, dom, parent);
});

exports.prepend = _insert(function(dom, children, parent) {
  uniqueSplice(children, 0, 0, dom, parent);
});

exports.wrap = function(wrapper) {
  var wrapperFn = typeof wrapper === 'function' && wrapper,
      lastIdx = this.length - 1;

  _.forEach(this, _.bind(function(el, i) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        wrapperDom, elInsertLocation, j, index;

    if (!parent) {
      return;
    }

    if (wrapperFn) {
      wrapper = wrapperFn.call(el, i);
    }

    if (typeof wrapper === 'string' && !isHtml(wrapper)) {
      wrapper = this.parents().last().find(wrapper).clone();
    }

    wrapperDom = this._makeDomArray(wrapper, i < lastIdx).slice(0, 1);
    elInsertLocation = wrapperDom[0];
    // Find the deepest child. Only consider the first tag child of each node
    // (ignore text); stop if no children are found.
    j = 0;

    while (elInsertLocation && elInsertLocation.children) {
      if (j >= elInsertLocation.children.length) {
        break;
      }

      if (elInsertLocation.children[j].type === 'tag') {
        elInsertLocation = elInsertLocation.children[j];
        j=0;
      } else {
        j++;
      }
    }
    index = siblings.indexOf(el);

    updateDOM([el], elInsertLocation);
    // The previous operation removed the current element from the `siblings`
    // array, so the `dom` array can be inserted without removing any
    // additional elements.
    uniqueSplice(siblings, index, 0, wrapperDom, parent);
  }, this));

  return this;
};

exports.after = function() {
  var elems = slice.call(arguments),
      lastIdx = this.length - 1;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root;
    if (!parent) {
      return;
    }

    var siblings = parent.children,
        index = siblings.indexOf(el),
        domSrc, dom;

    // If not found, move on
    if (index < 0) return;

    if (typeof elems[0] === 'function') {
      domSrc = elems[0].call(el, i, $.html(el.children));
    } else {
      domSrc = elems;
    }
    dom = this._makeDomArray(domSrc, i < lastIdx);

    // Add element after `this` element
    uniqueSplice(siblings, index + 1, 0, dom, parent);
  });

  return this;
};

exports.insertAfter = function(target) {
  var clones = [],
      self = this;
  if (typeof target === 'string') {
    target = this.constructor.call(this.constructor, target, null, this._originalRoot);
  }
  target = this._makeDomArray(target);
  self.remove();
  domEach(target, function(i, el) {
    var clonedSelf = self._makeDomArray(self.clone());
    var parent = el.parent || el.root;
    if (!parent) {
      return;
    }

    var siblings = parent.children,
        index = siblings.indexOf(el);

    // If not found, move on
    if (index < 0) return;

    // Add cloned `this` element(s) after target element
    uniqueSplice(siblings, index + 1, 0, clonedSelf, parent);
    clones.push(clonedSelf);
  });
  return this.constructor.call(this.constructor, this._makeDomArray(clones));
};

exports.before = function() {
  var elems = slice.call(arguments),
      lastIdx = this.length - 1;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root;
    if (!parent) {
      return;
    }

    var siblings = parent.children,
        index = siblings.indexOf(el),
        domSrc, dom;

    // If not found, move on
    if (index < 0) return;

    if (typeof elems[0] === 'function') {
      domSrc = elems[0].call(el, i, $.html(el.children));
    } else {
      domSrc = elems;
    }

    dom = this._makeDomArray(domSrc, i < lastIdx);

    // Add element before `el` element
    uniqueSplice(siblings, index, 0, dom, parent);
  });

  return this;
};

exports.insertBefore = function(target) {
  var clones = [],
      self = this;
  if (typeof target === 'string') {
    target = this.constructor.call(this.constructor, target, null, this._originalRoot);
  }
  target = this._makeDomArray(target);
  self.remove();
  domEach(target, function(i, el) {
    var clonedSelf = self._makeDomArray(self.clone());
    var parent = el.parent || el.root;
    if (!parent) {
      return;
    }

    var siblings = parent.children,
        index = siblings.indexOf(el);

    // If not found, move on
    if (index < 0) return;

    // Add cloned `this` element(s) after target element
    uniqueSplice(siblings, index, 0, clonedSelf, parent);
    clones.push(clonedSelf);
  });
  return this.constructor.call(this.constructor, this._makeDomArray(clones));
};

/*
  remove([selector])
*/
exports.remove = function(selector) {
  var elems = this;

  // Filter if we have selector
  if (selector)
    elems = elems.filter(selector);

  domEach(elems, function(i, el) {
    var parent = el.parent || el.root;
    if (!parent) {
      return;
    }

    var siblings = parent.children,
        index = siblings.indexOf(el);

    if (index < 0) return;

    siblings.splice(index, 1);
    if (el.prev) {
      el.prev.next = el.next;
    }
    if (el.next) {
      el.next.prev = el.prev;
    }
    el.prev = el.next = el.parent = el.root = null;
  });

  return this;
};

exports.replaceWith = function(content) {
  var self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root;
    if (!parent) {
      return;
    }

    var siblings = parent.children,
        dom = self._makeDomArray(typeof content === 'function' ? content.call(el, i, el) : content),
        index;

    // In the case that `dom` contains nodes that already exist in other
    // structures, ensure those nodes are properly removed.
    updateDOM(dom, null);

    index = siblings.indexOf(el);

    // Completely remove old element
    uniqueSplice(siblings, index, 1, dom, parent);
    el.parent = el.prev = el.next = el.root = null;
  });

  return this;
};

exports.empty = function() {
  domEach(this, function(i, el) {
    _.forEach(el.children, function(child) {
      child.next = child.prev = child.parent = null;
    });

    el.children.length = 0;
  });
  return this;
};

/**
 * Set/Get the HTML
 */
exports.html = function(str) {
  if (str === undefined) {
    if (!this[0] || !this[0].children) return null;
    return $.html(this[0].children, this.options);
  }

  var opts = this.options;

  domEach(this, function(i, el) {
    _.forEach(el.children, function(child) {
      child.next = child.prev = child.parent = null;
    });

    var content = str.cheerio ? str.clone().get() : evaluate('' + str, opts, false);

    updateDOM(content, el);
  });

  return this;
};

exports.toString = function() {
  return $.html(this, this.options);
};

exports.text = function(str) {
  // If `str` is undefined, act as a "getter"
  if (str === undefined) {
    return $.text(this);
  } else if (typeof str === 'function') {
    // Function support
    return domEach(this, function(i, el) {
      var $el = [el];
      return exports.text.call($el, str.call(el, i, $.text($el)));
    });
  }

  // Append text node to each selected elements
  domEach(this, function(i, el) {
    _.forEach(el.children, function(child) {
      child.next = child.prev = child.parent = null;
    });

    var elem = {
      data: '' + str,
      type: 'text',
      parent: el,
      prev: null,
      next: null,
      children: []
    };

    updateDOM(elem, el);
  });

  return this;
};

exports.clone = function() {
  return this._make(cloneDom(this.get(), this.options));
};


/***/ }),
/* 1038 */
/***/ (function(module, exports, __nested_webpack_require_4861035__) {

var arrayPush = __nested_webpack_require_4861035__(281),
    isFlattenable = __nested_webpack_require_4861035__(1039);

/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;

  predicate || (predicate = isFlattenable);
  result || (result = []);

  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}

module.exports = baseFlatten;


/***/ }),
/* 1039 */
/***/ (function(module, exports, __nested_webpack_require_4862315__) {

var Symbol = __nested_webpack_require_4862315__(118),
    isArguments = __nested_webpack_require_4862315__(184),
    isArray = __nested_webpack_require_4862315__(31);

/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;

/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable(value) {
  return isArray(value) || isArguments(value) ||
    !!(spreadableSymbol && value && value[spreadableSymbol]);
}

module.exports = isFlattenable;


/***/ }),
/* 1040 */
/***/ (function(module, exports, __nested_webpack_require_4863010__) {

var domEach = __nested_webpack_require_4863010__(152).domEach,
    _ = {
      pick: __nested_webpack_require_4863010__(1041),
    };

var toString = Object.prototype.toString;

/**
 * Set / Get css.
 *
 * @param {String|Object} prop
 * @param {String} val
 * @return {self}
 * @api public
 */

exports.css = function(prop, val) {
  if (arguments.length === 2 ||
    // When `prop` is a "plain" object
    (toString.call(prop) === '[object Object]')) {
    return domEach(this, function(idx, el) {
      setCss(el, prop, val, idx);
    });
  } else {
    return getCss(this[0], prop);
  }
};

/**
 * Set styles of all elements.
 *
 * @param {String|Object} prop
 * @param {String} val
 * @param {Number} idx - optional index within the selection
 * @return {self}
 * @api private
 */

function setCss(el, prop, val, idx) {
  if ('string' == typeof prop) {
    var styles = getCss(el);
    if (typeof val === 'function') {
      val = val.call(el, idx, styles[prop]);
    }

    if (val === '') {
      delete styles[prop];
    } else if (val != null) {
      styles[prop] = val;
    }

    el.attribs.style = stringify(styles);
  } else if ('object' == typeof prop) {
    Object.keys(prop).forEach(function(k){
      setCss(el, k, prop[k]);
    });
  }
}

/**
 * Get parsed styles of the first element.
 *
 * @param {String} prop
 * @return {Object}
 * @api private
 */

function getCss(el, prop) {
  var styles = parse(el.attribs.style);
  if (typeof prop === 'string') {
    return styles[prop];
  } else if (Array.isArray(prop)) {
    return _.pick(styles, prop);
  } else {
    return styles;
  }
}

/**
 * Stringify `obj` to styles.
 *
 * @param {Object} obj
 * @return {Object}
 * @api private
 */

function stringify(obj) {
  return Object.keys(obj || {})
    .reduce(function(str, prop){
      return str += ''
        + (str ? ' ' : '')
        + prop
        + ': '
        + obj[prop]
        + ';';
    }, '');
}

/**
 * Parse `styles`.
 *
 * @param {String} styles
 * @return {Object}
 * @api private
 */

function parse(styles) {
  styles = (styles || '').trim();

  if (!styles) return {};

  return styles
    .split(';')
    .reduce(function(obj, str){
      var n = str.indexOf(':');
      // skip if there is no :, or if it is the first/last character
      if (n < 1 || n === str.length-1) return obj;
      obj[str.slice(0,n).trim()] = str.slice(n+1).trim();
      return obj;
    }, {});
}


/***/ }),
/* 1041 */
/***/ (function(module, exports, __nested_webpack_require_4865472__) {

var basePick = __nested_webpack_require_4865472__(1042),
    flatRest = __nested_webpack_require_4865472__(1045);

/**
 * Creates an object composed of the picked `object` properties.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The source object.
 * @param {...(string|string[])} [paths] The property paths to pick.
 * @returns {Object} Returns the new object.
 * @example
 *
 * var object = { 'a': 1, 'b': '2', 'c': 3 };
 *
 * _.pick(object, ['a', 'c']);
 * // => { 'a': 1, 'c': 3 }
 */
var pick = flatRest(function(object, paths) {
  return object == null ? {} : basePick(object, paths);
});

module.exports = pick;


/***/ }),
/* 1042 */
/***/ (function(module, exports, __nested_webpack_require_4866187__) {

var basePickBy = __nested_webpack_require_4866187__(1043),
    hasIn = __nested_webpack_require_4866187__(425);

/**
 * The base implementation of `_.pick` without support for individual
 * property identifiers.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @returns {Object} Returns the new object.
 */
function basePick(object, paths) {
  return basePickBy(object, paths, function(value, path) {
    return hasIn(object, path);
  });
}

module.exports = basePick;


/***/ }),
/* 1043 */
/***/ (function(module, exports, __nested_webpack_require_4866775__) {

var baseGet = __nested_webpack_require_4866775__(284),
    baseSet = __nested_webpack_require_4866775__(1044),
    castPath = __nested_webpack_require_4866775__(193);

/**
 * The base implementation of  `_.pickBy` without support for iteratee shorthands.
 *
 * @private
 * @param {Object} object The source object.
 * @param {string[]} paths The property paths to pick.
 * @param {Function} predicate The function invoked per property.
 * @returns {Object} Returns the new object.
 */
function basePickBy(object, paths, predicate) {
  var index = -1,
      length = paths.length,
      result = {};

  while (++index < length) {
    var path = paths[index],
        value = baseGet(object, path);

    if (predicate(value, path)) {
      baseSet(result, castPath(path, object), value);
    }
  }
  return result;
}

module.exports = basePickBy;


/***/ }),
/* 1044 */
/***/ (function(module, exports, __nested_webpack_require_4867655__) {

var assignValue = __nested_webpack_require_4867655__(195),
    castPath = __nested_webpack_require_4867655__(193),
    isIndex = __nested_webpack_require_4867655__(142),
    isObject = __nested_webpack_require_4867655__(45),
    toKey = __nested_webpack_require_4867655__(145);

/**
 * The base implementation of `_.set`.
 *
 * @private
 * @param {Object} object The object to modify.
 * @param {Array|string} path The path of the property to set.
 * @param {*} value The value to set.
 * @param {Function} [customizer] The function to customize path creation.
 * @returns {Object} Returns `object`.
 */
function baseSet(object, path, value, customizer) {
  if (!isObject(object)) {
    return object;
  }
  path = castPath(path, object);

  var index = -1,
      length = path.length,
      lastIndex = length - 1,
      nested = object;

  while (nested != null && ++index < length) {
    var key = toKey(path[index]),
        newValue = value;

    if (index != lastIndex) {
      var objValue = nested[key];
      newValue = customizer ? customizer(objValue, key, nested) : undefined;
      if (newValue === undefined) {
        newValue = isObject(objValue)
          ? objValue
          : (isIndex(path[index + 1]) ? [] : {});
      }
    }
    assignValue(nested, key, newValue);
    nested = nested[key];
  }
  return object;
}

module.exports = baseSet;


/***/ }),
/* 1045 */
/***/ (function(module, exports, __nested_webpack_require_4869024__) {

var flatten = __nested_webpack_require_4869024__(489),
    overRest = __nested_webpack_require_4869024__(433),
    setToString = __nested_webpack_require_4869024__(293);

/**
 * A specialized version of `baseRest` which flattens the rest array.
 *
 * @private
 * @param {Function} func The function to apply a rest parameter to.
 * @returns {Function} Returns the new function.
 */
function flatRest(func) {
  return setToString(overRest(func, undefined, flatten), func + '');
}

module.exports = flatRest;


/***/ }),
/* 1046 */
/***/ (function(module, exports, __nested_webpack_require_4869566__) {

// https://github.com/jquery/jquery/blob/2.1.3/src/manipulation/var/rcheckableType.js
// https://github.com/jquery/jquery/blob/2.1.3/src/serialize.js
var submittableSelector = 'input,select,textarea,keygen',
    r20 = /%20/g,
    rCRLF = /\r?\n/g,
    _ = {
      map: __nested_webpack_require_4869566__(70)
    };

exports.serialize = function() {
  // Convert form elements into name/value objects
  var arr = this.serializeArray();

  // Serialize each element into a key/value string
  var retArr = _.map(arr, function(data) {
    return encodeURIComponent(data.name) + '=' + encodeURIComponent(data.value);
  });

  // Return the resulting serialization
  return retArr.join('&').replace(r20, '+');
};

exports.serializeArray = function() {
  // Resolve all form elements from either forms or collections of form elements
  var Cheerio = this.constructor;
  return this.map(function() {
      var elem = this;
      var $elem = Cheerio(elem);
      if (elem.name === 'form') {
        return $elem.find(submittableSelector).toArray();
      } else {
        return $elem.filter(submittableSelector).toArray();
      }
    }).filter(
        // Verify elements have a name (`attr.name`) and are not disabled (`:disabled`)
        '[name!=""]:not(:disabled)'
        // and cannot be clicked (`[type=submit]`) or are used in `x-www-form-urlencoded` (`[type=file]`)
        + ':not(:submit, :button, :image, :reset, :file)'
        // and are either checked/don't have a checkable state
        + ':matches([checked], :not(:checkbox, :radio))'
    // Convert each of the elements to its value(s)
    ).map(function(i, elem) {
      var $elem = Cheerio(elem);
      var name = $elem.attr('name');
      var value = $elem.val();

      // If there is no value set (e.g. `undefined`, `null`), then default value to empty
      if (value == null) {
        value = '';
      }

      // If we have an array of values (e.g. `<select multiple>`), return an array of key/value pairs
      if (Array.isArray(value)) {
        return _.map(value, function(val) {
          // We trim replace any line endings (e.g. `\r` or `\r\n` with `\r\n`) to guarantee consistency across platforms
          //   These can occur inside of `<textarea>'s`
          return {name: name, value: val.replace( rCRLF, '\r\n' )};
        });
      // Otherwise (e.g. `<input type="text">`, return only one key/value pair
      } else {
        return {name: name, value: value.replace( rCRLF, '\r\n' )};
      }
    // Convert our result to an array
    }).get();
};


/***/ }),
/* 1047 */
/***/ (function(module) {

module.exports = {"name":"cheerio","version":"1.0.0-rc.3","description":"Tiny, fast, and elegant implementation of core jQuery designed specifically for the server","author":"Matt Mueller <mattmuelle@gmail.com> (mat.io)","license":"MIT","keywords":["htmlparser","jquery","selector","scraper","parser","html"],"repository":{"type":"git","url":"git://github.com/cheeriojs/cheerio.git"},"main":"./index.js","files":["index.js","lib"],"engines":{"node":">= 0.6"},"dependencies":{"css-select":"~1.2.0","dom-serializer":"~0.1.1","entities":"~1.1.1","htmlparser2":"^3.9.1","lodash":"^4.15.0","parse5":"^3.0.1"},"devDependencies":{"benchmark":"^2.1.0","coveralls":"^2.11.9","expect.js":"~0.3.1","istanbul":"^0.4.3","jquery":"^3.0.0","jsdom":"^9.2.1","jshint":"^2.9.2","mocha":"^3.1.2","xyz":"~1.1.0"},"scripts":{"test":"make test"},"_resolved":"https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.3.tgz","_integrity":"sha512-0td5ijfUPuubwLUu0OBoe98gZj8C/AA+RW3v67GPlGOrvxWjZmBXiBCRU+I8VEiNyJzjth40POfHiz2RB3gImA==","_from":"cheerio@1.0.0-rc.3"};

/***/ }),
/* 1048 */
/***/ (function(module, exports, __nested_webpack_require_4873259__) {

"use strict";


var bind = __nested_webpack_require_4873259__(53);

var ES2016 = __nested_webpack_require_4873259__(491);
var assign = __nested_webpack_require_4873259__(312);
var forEach = __nested_webpack_require_4873259__(1057);

var GetIntrinsic = __nested_webpack_require_4873259__(207);

var $TypeError = GetIntrinsic('%TypeError%');
var $isEnumerable = bind.call(Function.call, GetIntrinsic('%ObjectPrototype%').propertyIsEnumerable);
var $pushApply = bind.call(Function.apply, GetIntrinsic('%ArrayPrototype%').push);

var ES2017 = assign(assign({}, ES2016), {
	ToIndex: function ToIndex(value) {
		if (typeof value === 'undefined') {
			return 0;
		}
		var integerIndex = this.ToInteger(value);
		if (integerIndex < 0) {
			throw new RangeError('index must be >= 0');
		}
		var index = this.ToLength(integerIndex);
		if (!this.SameValueZero(integerIndex, index)) {
			throw new RangeError('index must be >= 0 and < 2 ** 53 - 1');
		}
		return index;
	},

	// https://www.ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties
	EnumerableOwnProperties: function EnumerableOwnProperties(O, kind) {
		var keys = ES2016.EnumerableOwnNames(O);
		if (kind === 'key') {
			return keys;
		}
		if (kind === 'value' || kind === 'key+value') {
			var results = [];
			forEach(keys, function (key) {
				if ($isEnumerable(O, key)) {
					$pushApply(results, [
						kind === 'value' ? O[key] : [key, O[key]]
					]);
				}
			});
			return results;
		}
		throw new $TypeError('Assertion failed: "kind" is not "key", "value", or "key+value": ' + kind);
	}
});

delete ES2017.EnumerableOwnNames; // replaced with EnumerableOwnProperties

module.exports = ES2017;


/***/ }),
/* 1049 */
/***/ (function(module, exports, __nested_webpack_require_4874931__) {

"use strict";


var has = __nested_webpack_require_4874931__(59);
var toPrimitive = __nested_webpack_require_4874931__(1050);
var keys = __nested_webpack_require_4874931__(295);

var GetIntrinsic = __nested_webpack_require_4874931__(207);

var $TypeError = GetIntrinsic('%TypeError%');
var $SyntaxError = GetIntrinsic('%SyntaxError%');
var $Array = GetIntrinsic('%Array%');
var $String = GetIntrinsic('%String%');
var $Object = GetIntrinsic('%Object%');
var $Number = GetIntrinsic('%Number%');
var $Symbol = GetIntrinsic('%Symbol%', true);
var $RegExp = GetIntrinsic('%RegExp%');

var hasSymbols = !!$Symbol;

var assertRecord = __nested_webpack_require_4874931__(493);
var $isNaN = __nested_webpack_require_4874931__(494);
var $isFinite = __nested_webpack_require_4874931__(495);
var MAX_SAFE_INTEGER = $Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;

var assign = __nested_webpack_require_4874931__(312);
var sign = __nested_webpack_require_4874931__(496);
var mod = __nested_webpack_require_4874931__(497);
var isPrimitive = __nested_webpack_require_4874931__(1055);
var parseInteger = parseInt;
var bind = __nested_webpack_require_4874931__(53);
var arraySlice = bind.call(Function.call, $Array.prototype.slice);
var strSlice = bind.call(Function.call, $String.prototype.slice);
var isBinary = bind.call(Function.call, $RegExp.prototype.test, /^0b[01]+$/i);
var isOctal = bind.call(Function.call, $RegExp.prototype.test, /^0o[0-7]+$/i);
var regexExec = bind.call(Function.call, $RegExp.prototype.exec);
var nonWS = ['\u0085', '\u200b', '\ufffe'].join('');
var nonWSregex = new $RegExp('[' + nonWS + ']', 'g');
var hasNonWS = bind.call(Function.call, $RegExp.prototype.test, nonWSregex);
var invalidHexLiteral = /^[-+]0x[0-9a-f]+$/i;
var isInvalidHexLiteral = bind.call(Function.call, $RegExp.prototype.test, invalidHexLiteral);
var $charCodeAt = bind.call(Function.call, $String.prototype.charCodeAt);

var toStr = bind.call(Function.call, Object.prototype.toString);

var $NumberValueOf = bind.call(Function.call, GetIntrinsic('%NumberPrototype%').valueOf);
var $BooleanValueOf = bind.call(Function.call, GetIntrinsic('%BooleanPrototype%').valueOf);
var $StringValueOf = bind.call(Function.call, GetIntrinsic('%StringPrototype%').valueOf);
var $DateValueOf = bind.call(Function.call, GetIntrinsic('%DatePrototype%').valueOf);

var $floor = Math.floor;
var $abs = Math.abs;

var $ObjectCreate = Object.create;
var $gOPD = $Object.getOwnPropertyDescriptor;

var $isExtensible = $Object.isExtensible;

var $defineProperty = $Object.defineProperty;

// whitespace from: http://es5.github.io/#x15.5.4.20
// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
var ws = [
	'\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
	'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
	'\u2029\uFEFF'
].join('');
var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
var replace = bind.call(Function.call, $String.prototype.replace);
var trim = function (value) {
	return replace(value, trimRegex, '');
};

var ES5 = __nested_webpack_require_4874931__(498);

var hasRegExpMatcher = __nested_webpack_require_4874931__(499);

// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-abstract-operations
var ES6 = assign(assign({}, ES5), {

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args
	Call: function Call(F, V) {
		var args = arguments.length > 2 ? arguments[2] : [];
		if (!this.IsCallable(F)) {
			throw new $TypeError(F + ' is not a function');
		}
		return F.apply(V, args);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toprimitive
	ToPrimitive: toPrimitive,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toboolean
	// ToBoolean: ES5.ToBoolean,

	// https://ecma-international.org/ecma-262/6.0/#sec-tonumber
	ToNumber: function ToNumber(argument) {
		var value = isPrimitive(argument) ? argument : toPrimitive(argument, $Number);
		if (typeof value === 'symbol') {
			throw new $TypeError('Cannot convert a Symbol value to a number');
		}
		if (typeof value === 'string') {
			if (isBinary(value)) {
				return this.ToNumber(parseInteger(strSlice(value, 2), 2));
			} else if (isOctal(value)) {
				return this.ToNumber(parseInteger(strSlice(value, 2), 8));
			} else if (hasNonWS(value) || isInvalidHexLiteral(value)) {
				return NaN;
			} else {
				var trimmed = trim(value);
				if (trimmed !== value) {
					return this.ToNumber(trimmed);
				}
			}
		}
		return $Number(value);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tointeger
	// ToInteger: ES5.ToNumber,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint32
	// ToInt32: ES5.ToInt32,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint32
	// ToUint32: ES5.ToUint32,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint16
	ToInt16: function ToInt16(argument) {
		var int16bit = this.ToUint16(argument);
		return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit;
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint16
	// ToUint16: ES5.ToUint16,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint8
	ToInt8: function ToInt8(argument) {
		var int8bit = this.ToUint8(argument);
		return int8bit >= 0x80 ? int8bit - 0x100 : int8bit;
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8
	ToUint8: function ToUint8(argument) {
		var number = this.ToNumber(argument);
		if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
		var posInt = sign(number) * $floor($abs(number));
		return mod(posInt, 0x100);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8clamp
	ToUint8Clamp: function ToUint8Clamp(argument) {
		var number = this.ToNumber(argument);
		if ($isNaN(number) || number <= 0) { return 0; }
		if (number >= 0xFF) { return 0xFF; }
		var f = $floor(argument);
		if (f + 0.5 < number) { return f + 1; }
		if (number < f + 0.5) { return f; }
		if (f % 2 !== 0) { return f + 1; }
		return f;
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring
	ToString: function ToString(argument) {
		if (typeof argument === 'symbol') {
			throw new $TypeError('Cannot convert a Symbol value to a string');
		}
		return $String(argument);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toobject
	ToObject: function ToObject(value) {
		this.RequireObjectCoercible(value);
		return $Object(value);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey
	ToPropertyKey: function ToPropertyKey(argument) {
		var key = this.ToPrimitive(argument, $String);
		return typeof key === 'symbol' ? key : this.ToString(key);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
	ToLength: function ToLength(argument) {
		var len = this.ToInteger(argument);
		if (len <= 0) { return 0; } // includes converting -0 to +0
		if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; }
		return len;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring
	CanonicalNumericIndexString: function CanonicalNumericIndexString(argument) {
		if (toStr(argument) !== '[object String]') {
			throw new $TypeError('must be a string');
		}
		if (argument === '-0') { return -0; }
		var n = this.ToNumber(argument);
		if (this.SameValue(this.ToString(n), argument)) { return n; }
		return void 0;
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-requireobjectcoercible
	RequireObjectCoercible: ES5.CheckObjectCoercible,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray
	IsArray: $Array.isArray || function IsArray(argument) {
		return toStr(argument) === '[object Array]';
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iscallable
	// IsCallable: ES5.IsCallable,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor
	IsConstructor: function IsConstructor(argument) {
		return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument`
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isextensible-o
	IsExtensible: Object.preventExtensions
		? function IsExtensible(obj) {
			if (isPrimitive(obj)) {
				return false;
			}
			return $isExtensible(obj);
		}
		: function isExtensible(obj) { return true; }, // eslint-disable-line no-unused-vars

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isinteger
	IsInteger: function IsInteger(argument) {
		if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) {
			return false;
		}
		var abs = $abs(argument);
		return $floor(abs) === abs;
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ispropertykey
	IsPropertyKey: function IsPropertyKey(argument) {
		return typeof argument === 'string' || typeof argument === 'symbol';
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-isregexp
	IsRegExp: function IsRegExp(argument) {
		if (!argument || typeof argument !== 'object') {
			return false;
		}
		if (hasSymbols) {
			var isRegExp = argument[$Symbol.match];
			if (typeof isRegExp !== 'undefined') {
				return ES5.ToBoolean(isRegExp);
			}
		}
		return hasRegExpMatcher(argument);
	},

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevalue
	// SameValue: ES5.SameValue,

	// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero
	SameValueZero: function SameValueZero(x, y) {
		return (x === y) || ($isNaN(x) && $isNaN(y));
	},

	/**
	 * 7.3.2 GetV (V, P)
	 * 1. Assert: IsPropertyKey(P) is true.
	 * 2. Let O be ToObject(V).
	 * 3. ReturnIfAbrupt(O).
	 * 4. Return O.[[Get]](P, V).
	 */
	GetV: function GetV(V, P) {
		// 7.3.2.1
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}

		// 7.3.2.2-3
		var O = this.ToObject(V);

		// 7.3.2.4
		return O[P];
	},

	/**
	 * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod
	 * 1. Assert: IsPropertyKey(P) is true.
	 * 2. Let func be GetV(O, P).
	 * 3. ReturnIfAbrupt(func).
	 * 4. If func is either undefined or null, return undefined.
	 * 5. If IsCallable(func) is false, throw a TypeError exception.
	 * 6. Return func.
	 */
	GetMethod: function GetMethod(O, P) {
		// 7.3.9.1
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}

		// 7.3.9.2
		var func = this.GetV(O, P);

		// 7.3.9.4
		if (func == null) {
			return void 0;
		}

		// 7.3.9.5
		if (!this.IsCallable(func)) {
			throw new $TypeError(P + 'is not a function');
		}

		// 7.3.9.6
		return func;
	},

	/**
	 * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p
	 * 1. Assert: Type(O) is Object.
	 * 2. Assert: IsPropertyKey(P) is true.
	 * 3. Return O.[[Get]](P, O).
	 */
	Get: function Get(O, P) {
		// 7.3.1.1
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}
		// 7.3.1.2
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}
		// 7.3.1.3
		return O[P];
	},

	Type: function Type(x) {
		if (typeof x === 'symbol') {
			return 'Symbol';
		}
		return ES5.Type(x);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor
	SpeciesConstructor: function SpeciesConstructor(O, defaultConstructor) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}
		var C = O.constructor;
		if (typeof C === 'undefined') {
			return defaultConstructor;
		}
		if (this.Type(C) !== 'Object') {
			throw new $TypeError('O.constructor is not an Object');
		}
		var S = hasSymbols && $Symbol.species ? C[$Symbol.species] : void 0;
		if (S == null) {
			return defaultConstructor;
		}
		if (this.IsConstructor(S)) {
			return S;
		}
		throw new $TypeError('no constructor found');
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor
	CompletePropertyDescriptor: function CompletePropertyDescriptor(Desc) {
		assertRecord(this, 'Property Descriptor', 'Desc', Desc);

		if (this.IsGenericDescriptor(Desc) || this.IsDataDescriptor(Desc)) {
			if (!has(Desc, '[[Value]]')) {
				Desc['[[Value]]'] = void 0;
			}
			if (!has(Desc, '[[Writable]]')) {
				Desc['[[Writable]]'] = false;
			}
		} else {
			if (!has(Desc, '[[Get]]')) {
				Desc['[[Get]]'] = void 0;
			}
			if (!has(Desc, '[[Set]]')) {
				Desc['[[Set]]'] = void 0;
			}
		}
		if (!has(Desc, '[[Enumerable]]')) {
			Desc['[[Enumerable]]'] = false;
		}
		if (!has(Desc, '[[Configurable]]')) {
			Desc['[[Configurable]]'] = false;
		}
		return Desc;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw
	Set: function Set(O, P, V, Throw) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('O must be an Object');
		}
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('P must be a Property Key');
		}
		if (this.Type(Throw) !== 'Boolean') {
			throw new $TypeError('Throw must be a Boolean');
		}
		if (Throw) {
			O[P] = V;
			return true;
		} else {
			try {
				O[P] = V;
			} catch (e) {
				return false;
			}
		}
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty
	HasOwnProperty: function HasOwnProperty(O, P) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('O must be an Object');
		}
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('P must be a Property Key');
		}
		return has(O, P);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-hasproperty
	HasProperty: function HasProperty(O, P) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('O must be an Object');
		}
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('P must be a Property Key');
		}
		return P in O;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable
	IsConcatSpreadable: function IsConcatSpreadable(O) {
		if (this.Type(O) !== 'Object') {
			return false;
		}
		if (hasSymbols && typeof $Symbol.isConcatSpreadable === 'symbol') {
			var spreadable = this.Get(O, Symbol.isConcatSpreadable);
			if (typeof spreadable !== 'undefined') {
				return this.ToBoolean(spreadable);
			}
		}
		return this.IsArray(O);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-invoke
	Invoke: function Invoke(O, P) {
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('P must be a Property Key');
		}
		var argumentsList = arraySlice(arguments, 2);
		var func = this.GetV(O, P);
		return this.Call(func, O, argumentsList);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-getiterator
	GetIterator: function GetIterator(obj, method) {
		if (!hasSymbols) {
			throw new SyntaxError('ES.GetIterator depends on native iterator support.');
		}

		var actualMethod = method;
		if (arguments.length < 2) {
			actualMethod = this.GetMethod(obj, $Symbol.iterator);
		}
		var iterator = this.Call(actualMethod, obj);
		if (this.Type(iterator) !== 'Object') {
			throw new $TypeError('iterator must return an object');
		}

		return iterator;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-iteratornext
	IteratorNext: function IteratorNext(iterator, value) {
		var result = this.Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]);
		if (this.Type(result) !== 'Object') {
			throw new $TypeError('iterator next must return an object');
		}
		return result;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete
	IteratorComplete: function IteratorComplete(iterResult) {
		if (this.Type(iterResult) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(iterResult) is not Object');
		}
		return this.ToBoolean(this.Get(iterResult, 'done'));
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue
	IteratorValue: function IteratorValue(iterResult) {
		if (this.Type(iterResult) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(iterResult) is not Object');
		}
		return this.Get(iterResult, 'value');
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep
	IteratorStep: function IteratorStep(iterator) {
		var result = this.IteratorNext(iterator);
		var done = this.IteratorComplete(result);
		return done === true ? false : result;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose
	IteratorClose: function IteratorClose(iterator, completion) {
		if (this.Type(iterator) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(iterator) is not Object');
		}
		if (!this.IsCallable(completion)) {
			throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record');
		}
		var completionThunk = completion;

		var iteratorReturn = this.GetMethod(iterator, 'return');

		if (typeof iteratorReturn === 'undefined') {
			return completionThunk();
		}

		var completionRecord;
		try {
			var innerResult = this.Call(iteratorReturn, iterator, []);
		} catch (e) {
			// if we hit here, then "e" is the innerResult completion that needs re-throwing

			// if the completion is of type "throw", this will throw.
			completionRecord = completionThunk();
			completionThunk = null; // ensure it's not called twice.

			// if not, then return the innerResult completion
			throw e;
		}
		completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does
		completionThunk = null; // ensure it's not called twice.

		if (this.Type(innerResult) !== 'Object') {
			throw new $TypeError('iterator .return must return an object');
		}

		return completionRecord;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject
	CreateIterResultObject: function CreateIterResultObject(value, done) {
		if (this.Type(done) !== 'Boolean') {
			throw new $TypeError('Assertion failed: Type(done) is not Boolean');
		}
		return {
			value: value,
			done: done
		};
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-regexpexec
	RegExpExec: function RegExpExec(R, S) {
		if (this.Type(R) !== 'Object') {
			throw new $TypeError('R must be an Object');
		}
		if (this.Type(S) !== 'String') {
			throw new $TypeError('S must be a String');
		}
		var exec = this.Get(R, 'exec');
		if (this.IsCallable(exec)) {
			var result = this.Call(exec, R, [S]);
			if (result === null || this.Type(result) === 'Object') {
				return result;
			}
			throw new $TypeError('"exec" method must return `null` or an Object');
		}
		return regexExec(R, S);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate
	ArraySpeciesCreate: function ArraySpeciesCreate(originalArray, length) {
		if (!this.IsInteger(length) || length < 0) {
			throw new $TypeError('Assertion failed: length must be an integer >= 0');
		}
		var len = length === 0 ? 0 : length;
		var C;
		var isArray = this.IsArray(originalArray);
		if (isArray) {
			C = this.Get(originalArray, 'constructor');
			// TODO: figure out how to make a cross-realm normal Array, a same-realm Array
			// if (this.IsConstructor(C)) {
			// 	if C is another realm's Array, C = undefined
			// 	Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ?
			// }
			if (this.Type(C) === 'Object' && hasSymbols && $Symbol.species) {
				C = this.Get(C, $Symbol.species);
				if (C === null) {
					C = void 0;
				}
			}
		}
		if (typeof C === 'undefined') {
			return $Array(len);
		}
		if (!this.IsConstructor(C)) {
			throw new $TypeError('C must be a constructor');
		}
		return new C(len); // this.Construct(C, len);
	},

	CreateDataProperty: function CreateDataProperty(O, P, V) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}
		var oldDesc = $gOPD(O, P);
		var extensible = oldDesc || (typeof $isExtensible !== 'function' || $isExtensible(O));
		var immutable = oldDesc && (!oldDesc.writable || !oldDesc.configurable);
		if (immutable || !extensible) {
			return false;
		}
		var newDesc = {
			configurable: true,
			enumerable: true,
			value: V,
			writable: true
		};
		$defineProperty(O, P, newDesc);
		return true;
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow
	CreateDataPropertyOrThrow: function CreateDataPropertyOrThrow(O, P, V) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}
		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}
		var success = this.CreateDataProperty(O, P, V);
		if (!success) {
			throw new $TypeError('unable to create data property');
		}
		return success;
	},

	// https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate
	ObjectCreate: function ObjectCreate(proto, internalSlotsList) {
		if (proto !== null && this.Type(proto) !== 'Object') {
			throw new $TypeError('Assertion failed: proto must be null or an object');
		}
		var slots = arguments.length < 2 ? [] : internalSlotsList;
		if (slots.length > 0) {
			throw new $SyntaxError('es-abstract does not yet support internal slots');
		}

		if (proto === null && !$ObjectCreate) {
			throw new $SyntaxError('native Object.create support is required to create null objects');
		}

		return $ObjectCreate(proto);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex
	AdvanceStringIndex: function AdvanceStringIndex(S, index, unicode) {
		if (this.Type(S) !== 'String') {
			throw new $TypeError('S must be a String');
		}
		if (!this.IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) {
			throw new $TypeError('Assertion failed: length must be an integer >= 0 and <= 2**53');
		}
		if (this.Type(unicode) !== 'Boolean') {
			throw new $TypeError('Assertion failed: unicode must be a Boolean');
		}
		if (!unicode) {
			return index + 1;
		}
		var length = S.length;
		if ((index + 1) >= length) {
			return index + 1;
		}

		var first = $charCodeAt(S, index);
		if (first < 0xD800 || first > 0xDBFF) {
			return index + 1;
		}

		var second = $charCodeAt(S, index + 1);
		if (second < 0xDC00 || second > 0xDFFF) {
			return index + 1;
		}

		return index + 2;
	},

	// https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty
	CreateMethodProperty: function CreateMethodProperty(O, P, V) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}

		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}

		var newDesc = {
			configurable: true,
			enumerable: false,
			value: V,
			writable: true
		};
		return !!$defineProperty(O, P, newDesc);
	},

	// https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow
	DefinePropertyOrThrow: function DefinePropertyOrThrow(O, P, desc) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}

		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}

		return !!$defineProperty(O, P, desc);
	},

	// https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow
	DeletePropertyOrThrow: function DeletePropertyOrThrow(O, P) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}

		if (!this.IsPropertyKey(P)) {
			throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true');
		}

		var success = delete O[P];
		if (!success) {
			throw new TypeError('Attempt to delete property failed.');
		}
		return success;
	},

	// https://www.ecma-international.org/ecma-262/6.0/#sec-enumerableownnames
	EnumerableOwnNames: function EnumerableOwnNames(O) {
		if (this.Type(O) !== 'Object') {
			throw new $TypeError('Assertion failed: Type(O) is not Object');
		}

		return keys(O);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object
	thisNumberValue: function thisNumberValue(value) {
		if (this.Type(value) === 'Number') {
			return value;
		}

		return $NumberValueOf(value);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object
	thisBooleanValue: function thisBooleanValue(value) {
		if (this.Type(value) === 'Boolean') {
			return value;
		}

		return $BooleanValueOf(value);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object
	thisStringValue: function thisStringValue(value) {
		if (this.Type(value) === 'String') {
			return value;
		}

		return $StringValueOf(value);
	},

	// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object
	thisTimeValue: function thisTimeValue(value) {
		return $DateValueOf(value);
	}
});

delete ES6.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible

module.exports = ES6;


/***/ }),
/* 1050 */
/***/ (function(module, exports, __nested_webpack_require_4899832__) {

"use strict";


module.exports = __nested_webpack_require_4899832__(1051);


/***/ }),
/* 1051 */
/***/ (function(module, exports, __nested_webpack_require_4899972__) {

"use strict";


var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';

var isPrimitive = __nested_webpack_require_4899972__(492);
var isCallable = __nested_webpack_require_4899972__(155);
var isDate = __nested_webpack_require_4899972__(1052);
var isSymbol = __nested_webpack_require_4899972__(1053);

var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
	if (typeof O === 'undefined' || O === null) {
		throw new TypeError('Cannot call method on ' + O);
	}
	if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) {
		throw new TypeError('hint must be "string" or "number"');
	}
	var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
	var method, result, i;
	for (i = 0; i < methodNames.length; ++i) {
		method = O[methodNames[i]];
		if (isCallable(method)) {
			result = method.call(O);
			if (isPrimitive(result)) {
				return result;
			}
		}
	}
	throw new TypeError('No default value');
};

var GetMethod = function GetMethod(O, P) {
	var func = O[P];
	if (func !== null && typeof func !== 'undefined') {
		if (!isCallable(func)) {
			throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
		}
		return func;
	}
	return void 0;
};

// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
module.exports = function ToPrimitive(input) {
	if (isPrimitive(input)) {
		return input;
	}
	var hint = 'default';
	if (arguments.length > 1) {
		if (arguments[1] === String) {
			hint = 'string';
		} else if (arguments[1] === Number) {
			hint = 'number';
		}
	}

	var exoticToPrim;
	if (hasSymbols) {
		if (Symbol.toPrimitive) {
			exoticToPrim = GetMethod(input, Symbol.toPrimitive);
		} else if (isSymbol(input)) {
			exoticToPrim = Symbol.prototype.valueOf;
		}
	}
	if (typeof exoticToPrim !== 'undefined') {
		var result = exoticToPrim.call(input, hint);
		if (isPrimitive(result)) {
			return result;
		}
		throw new TypeError('unable to convert exotic object to primitive');
	}
	if (hint === 'default' && (isDate(input) || isSymbol(input))) {
		hint = 'string';
	}
	return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
};


/***/ }),
/* 1052 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateObject(value) {
	try {
		getDay.call(value);
		return true;
	} catch (e) {
		return false;
	}
};

var toStr = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isDateObject(value) {
	if (typeof value !== 'object' || value === null) { return false; }
	return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass;
};


/***/ }),
/* 1053 */
/***/ (function(module, exports, __nested_webpack_require_4902823__) {

"use strict";


var toStr = Object.prototype.toString;
var hasSymbols = __nested_webpack_require_4902823__(1054)();

if (hasSymbols) {
	var symToStr = Symbol.prototype.toString;
	var symStringRegex = /^Symbol\(.*\)$/;
	var isSymbolObject = function isRealSymbolObject(value) {
		if (typeof value.valueOf() !== 'symbol') {
			return false;
		}
		return symStringRegex.test(symToStr.call(value));
	};

	module.exports = function isSymbol(value) {
		if (typeof value === 'symbol') {
			return true;
		}
		if (toStr.call(value) !== '[object Symbol]') {
			return false;
		}
		try {
			return isSymbolObject(value);
		} catch (e) {
			return false;
		}
	};
} else {

	module.exports = function isSymbol(value) {
		// this environment does not support Symbols.
		return   false && 0;
	};
}


/***/ }),
/* 1054 */
/***/ (function(module, exports, __nested_webpack_require_4903675__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var origSymbol = global.Symbol;
var hasSymbolSham = __nested_webpack_require_4903675__(452);

module.exports = function hasNativeSymbols() {
	if (typeof origSymbol !== 'function') { return false; }
	if (typeof Symbol !== 'function') { return false; }
	if (typeof origSymbol('foo') !== 'symbol') { return false; }
	if (typeof Symbol('bar') !== 'symbol') { return false; }

	return hasSymbolSham();
};

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4903675__(27)))

/***/ }),
/* 1055 */
/***/ (function(module, exports) {

module.exports = function isPrimitive(value) {
	return value === null || (typeof value !== 'function' && typeof value !== 'object');
};


/***/ }),
/* 1056 */
/***/ (function(module, exports, __nested_webpack_require_4904463__) {

"use strict";


var toStr = Object.prototype.toString;

var isPrimitive = __nested_webpack_require_4904463__(492);

var isCallable = __nested_webpack_require_4904463__(155);

// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
var ES5internalSlots = {
	'[[DefaultValue]]': function (O) {
		var actualHint;
		if (arguments.length > 1) {
			actualHint = arguments[1];
		} else {
			actualHint = toStr.call(O) === '[object Date]' ? String : Number;
		}

		if (actualHint === String || actualHint === Number) {
			var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
			var value, i;
			for (i = 0; i < methods.length; ++i) {
				if (isCallable(O[methods[i]])) {
					value = O[methods[i]]();
					if (isPrimitive(value)) {
						return value;
					}
				}
			}
			throw new TypeError('No default value');
		}
		throw new TypeError('invalid [[DefaultValue]] hint supplied');
	}
};

// http://ecma-international.org/ecma-262/5.1/#sec-9.1
module.exports = function ToPrimitive(input) {
	if (isPrimitive(input)) {
		return input;
	}
	if (arguments.length > 1) {
		return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
	}
	return ES5internalSlots['[[DefaultValue]]'](input);
};


/***/ }),
/* 1057 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


module.exports = function forEach(array, callback) {
	for (var i = 0; i < array.length; i += 1) {
		callback(array[i], i, array);
	}
};


/***/ }),
/* 1058 */
/***/ (function(module, exports, __nested_webpack_require_4905969__) {

"use strict";


var define = __nested_webpack_require_4905969__(52);
var getPolyfill = __nested_webpack_require_4905969__(500);

module.exports = function shimFlat() {
	var polyfill = getPolyfill();
	define(
		Array.prototype,
		{ flat: polyfill },
		{ flat: function () { return Array.prototype.flat !== polyfill; } }
	);
	return polyfill;
};


/***/ }),
/* 1059 */
/***/ (function(module, exports, __nested_webpack_require_4906363__) {

"use strict";


var getPolyfill = __nested_webpack_require_4906363__(505);
var define = __nested_webpack_require_4906363__(52);

module.exports = function shimEntries() {
	var polyfill = getPolyfill();
	define(Object, { entries: polyfill }, {
		entries: function testEntries() {
			return Object.entries !== polyfill;
		}
	});
	return polyfill;
};


/***/ }),
/* 1060 */
/***/ (function(module, exports, __nested_webpack_require_4906761__) {

"use strict";


var supportsDescriptors = __nested_webpack_require_4906761__(52).supportsDescriptors;
var functionsHaveNames = __nested_webpack_require_4906761__(507);
var getPolyfill = __nested_webpack_require_4906761__(508);
var defineProperty = Object.defineProperty;
var TypeErr = TypeError;

module.exports = function shimName() {
	var polyfill = getPolyfill();
	if (functionsHaveNames) {
		return polyfill;
	}
	if (!supportsDescriptors) {
		throw new TypeErr('Shimming Function.prototype.name support requires ES5 property descriptor support.');
	}
	var functionProto = Function.prototype;
	defineProperty(functionProto, 'name', {
		configurable: true,
		enumerable: false,
		get: function () {
			var name = polyfill.call(this);
			if (this !== functionProto) {
				defineProperty(this, 'name', {
					configurable: true,
					enumerable: false,
					value: name,
					writable: false
				});
			}
			return name;
		}
	});
	return polyfill;
};


/***/ }),
/* 1061 */
/***/ (function(module, exports, __nested_webpack_require_4907747__) {

"use strict";


var bind = __nested_webpack_require_4907747__(53);
var define = __nested_webpack_require_4907747__(52);

var implementation = __nested_webpack_require_4907747__(509);
var getPolyfill = __nested_webpack_require_4907747__(510);
var shim = __nested_webpack_require_4907747__(1062);

var boundTrim = bind.call(Function.call, getPolyfill());

define(boundTrim, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = boundTrim;


/***/ }),
/* 1062 */
/***/ (function(module, exports, __nested_webpack_require_4908231__) {

"use strict";


var define = __nested_webpack_require_4908231__(52);
var getPolyfill = __nested_webpack_require_4908231__(510);

module.exports = function shimStringTrim() {
	var polyfill = getPolyfill();
	define(String.prototype, { trim: polyfill }, { trim: function () { return String.prototype.trim !== polyfill; } });
	return polyfill;
};


/***/ }),
/* 1063 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


Object.defineProperty(exports, '__esModule', {
  value: true
});
/**
 * Check if an object is contained within another object.
 *
 * Returns `true` if:
 * - all enumerable keys of *subset* are also enumerable in *superset*, and
 * - every value assigned to an enumerable key of *subset* strictly equals
 *   the value assigned to the same key of *superset* – or is a subset of it.
 *
 * @param  {Object}  superset
 * @param  {Object}  subset
 *
 * @returns  {Boolean}
 *
 * @module    is-subset
 * @function  default
 * @alias     isSubset
 */
var isSubset = (function (_isSubset) {
  function isSubset(_x, _x2) {
    return _isSubset.apply(this, arguments);
  }

  isSubset.toString = function () {
    return _isSubset.toString();
  };

  return isSubset;
})(function (superset, subset) {
  if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false;

  return Object.keys(subset).every(function (key) {
    if (!superset.propertyIsEnumerable(key)) return false;

    var subsetItem = subset[key];
    var supersetItem = superset[key];
    if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false;

    return true;
  });
});

exports['default'] = isSubset;
module.exports = exports['default'];

/***/ }),
/* 1064 */
/***/ (function(module, exports, __nested_webpack_require_4910059__) {

/* WEBPACK VAR INJECTION */(function(global) {/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;

/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';

/** Used to match HTML entities and HTML characters. */
var reUnescapedHtml = /[&<>"'`]/g,
    reHasUnescapedHtml = RegExp(reUnescapedHtml.source);

/** Used to map characters to HTML entities. */
var htmlEscapes = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '`': '&#96;'
};

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

/**
 * The base implementation of `_.propertyOf` without support for deep paths.
 *
 * @private
 * @param {Object} object The object to query.
 * @returns {Function} Returns the new accessor function.
 */
function basePropertyOf(object) {
  return function(key) {
    return object == null ? undefined : object[key];
  };
}

/**
 * Used by `_.escape` to convert characters to HTML entities.
 *
 * @private
 * @param {string} chr The matched character to escape.
 * @returns {string} Returns the escaped character.
 */
var escapeHtmlChar = basePropertyOf(htmlEscapes);

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Built-in value references. */
var Symbol = root.Symbol;

/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
    symbolToString = symbolProto ? symbolProto.toString : undefined;

/**
 * The base implementation of `_.toString` which doesn't convert nullish
 * values to empty strings.
 *
 * @private
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 */
function baseToString(value) {
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value == 'string') {
    return value;
  }
  if (isSymbol(value)) {
    return symbolToString ? symbolToString.call(value) : '';
  }
  var result = (value + '');
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

/**
 * Checks if `value` is classified as a `Symbol` primitive or object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
 * @example
 *
 * _.isSymbol(Symbol.iterator);
 * // => true
 *
 * _.isSymbol('abc');
 * // => false
 */
function isSymbol(value) {
  return typeof value == 'symbol' ||
    (isObjectLike(value) && objectToString.call(value) == symbolTag);
}

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {string} Returns the string.
 * @example
 *
 * _.toString(null);
 * // => ''
 *
 * _.toString(-0);
 * // => '-0'
 *
 * _.toString([1, 2, 3]);
 * // => '1,2,3'
 */
function toString(value) {
  return value == null ? '' : baseToString(value);
}

/**
 * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to
 * their corresponding HTML entities.
 *
 * **Note:** No other characters are escaped. To escape additional
 * characters use a third-party library like [_he_](https://mths.be/he).
 *
 * Though the ">" character is escaped for symmetry, characters like
 * ">" and "/" don't need escaping in HTML and have no special meaning
 * unless they're part of a tag or unquoted attribute value. See
 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
 * (under "semi-related fun fact") for more details.
 *
 * Backticks are escaped because in IE < 9, they can break out of
 * attribute values or HTML comments. See [#59](https://html5sec.org/#59),
 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
 * [#133](https://html5sec.org/#133) of the
 * [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.
 *
 * When working with HTML you should always
 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
 * XSS vectors.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category String
 * @param {string} [string=''] The string to escape.
 * @returns {string} Returns the escaped string.
 * @example
 *
 * _.escape('fred, barney, & pebbles');
 * // => 'fred, barney, &amp; pebbles'
 */
function escape(string) {
  string = toString(string);
  return (string && reHasUnescapedHtml.test(string))
    ? string.replace(reUnescapedHtml, escapeHtmlChar)
    : string;
}

module.exports = escape;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4910059__(27)))

/***/ }),
/* 1065 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var strValue = String.prototype.valueOf;
var tryStringObject = function tryStringObject(value) {
	try {
		strValue.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var strClass = '[object String]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isString(value) {
	if (typeof value === 'string') { return true; }
	if (typeof value !== 'object') { return false; }
	return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass;
};


/***/ }),
/* 1066 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var numToStr = Number.prototype.toString;
var tryNumberObject = function tryNumberObject(value) {
	try {
		numToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var numClass = '[object Number]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isNumberObject(value) {
	if (typeof value === 'number') { return true; }
	if (typeof value !== 'object') { return false; }
	return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass;
};


/***/ }),
/* 1067 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var boolToStr = Boolean.prototype.toString;

var tryBooleanObject = function tryBooleanObject(value) {
	try {
		boolToStr.call(value);
		return true;
	} catch (e) {
		return false;
	}
};
var toStr = Object.prototype.toString;
var boolClass = '[object Boolean]';
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';

module.exports = function isBoolean(value) {
	if (typeof value === 'boolean') { return true; }
	if (typeof value !== 'object') { return false; }
	return hasToStringTag ? tryBooleanObject(value) : toStr.call(value) === boolClass;
};


/***/ }),
/* 1068 */
/***/ (function(module, exports, __nested_webpack_require_4918283__) {

var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;

var inspectCustom = __nested_webpack_require_4918283__(1069).custom;
var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null;

module.exports = function inspect_ (obj, opts, depth, seen) {
    if (!opts) opts = {};

    if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
        throw new TypeError('option "quoteStyle" must be "single" or "double"');
    }

    if (typeof obj === 'undefined') {
        return 'undefined';
    }
    if (obj === null) {
        return 'null';
    }
    if (typeof obj === 'boolean') {
        return obj ? 'true' : 'false';
    }

    if (typeof obj === 'string') {
        return inspectString(obj, opts);
    }
    if (typeof obj === 'number') {
      if (obj === 0) {
        return Infinity / obj > 0 ? '0' : '-0';
      }
      return String(obj);
    }
    if (typeof obj === 'bigint') {
      return String(obj) + 'n';
    }

    var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
    if (typeof depth === 'undefined') depth = 0;
    if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
        return '[Object]';
    }

    if (typeof seen === 'undefined') seen = [];
    else if (indexOf(seen, obj) >= 0) {
        return '[Circular]';
    }

    function inspect (value, from) {
        if (from) {
            seen = seen.slice();
            seen.push(from);
        }
        return inspect_(value, opts, depth + 1, seen);
    }

    if (typeof obj === 'function') {
        var name = nameOf(obj);
        return '[Function' + (name ? ': ' + name : '') + ']';
    }
    if (isSymbol(obj)) {
        var symString = Symbol.prototype.toString.call(obj);
        return typeof obj === 'object' ? markBoxed(symString) : symString;
    }
    if (isElement(obj)) {
        var s = '<' + String(obj.nodeName).toLowerCase();
        var attrs = obj.attributes || [];
        for (var i = 0; i < attrs.length; i++) {
            s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
        }
        s += '>';
        if (obj.childNodes && obj.childNodes.length) s += '...';
        s += '</' + String(obj.nodeName).toLowerCase() + '>';
        return s;
    }
    if (isArray(obj)) {
        if (obj.length === 0) return '[]';
        return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]';
    }
    if (isError(obj)) {
        var parts = arrObjKeys(obj, inspect);
        if (parts.length === 0) return '[' + String(obj) + ']';
        return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }';
    }
    if (typeof obj === 'object') {
        if (inspectSymbol && typeof obj[inspectSymbol] === 'function') {
            return obj[inspectSymbol]();
        } else if (typeof obj.inspect === 'function') {
            return obj.inspect();
        }
    }
    if (isMap(obj)) {
        var parts = [];
        mapForEach.call(obj, function (value, key) {
            parts.push(inspect(key, obj) + ' => ' + inspect(value, obj));
        });
        return collectionOf('Map', mapSize.call(obj), parts);
    }
    if (isSet(obj)) {
        var parts = [];
        setForEach.call(obj, function (value ) {
            parts.push(inspect(value, obj));
        });
        return collectionOf('Set', setSize.call(obj), parts);
    }
    if (isNumber(obj)) {
        return markBoxed(inspect(Number(obj)));
    }
    if (isBigInt(obj)) {
        return markBoxed(inspect(bigIntValueOf.call(obj)));
    }
    if (isBoolean(obj)) {
        return markBoxed(booleanValueOf.call(obj));
    }
    if (isString(obj)) {
        return markBoxed(inspect(String(obj)));
    }
    if (!isDate(obj) && !isRegExp(obj)) {
        var xs = arrObjKeys(obj, inspect);
        if (xs.length === 0) return '{}';
        return '{ ' + xs.join(', ') + ' }';
    }
    return String(obj);
};

function wrapQuotes (s, defaultStyle, opts) {
    var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
    return quoteChar + s + quoteChar;
}

function quote (s) {
    return String(s).replace(/"/g, '&quot;');
}

function isArray (obj) { return toStr(obj) === '[object Array]'; }
function isDate (obj) { return toStr(obj) === '[object Date]'; }
function isRegExp (obj) { return toStr(obj) === '[object RegExp]'; }
function isError (obj) { return toStr(obj) === '[object Error]'; }
function isSymbol (obj) { return toStr(obj) === '[object Symbol]'; }
function isString (obj) { return toStr(obj) === '[object String]'; }
function isNumber (obj) { return toStr(obj) === '[object Number]'; }
function isBigInt (obj) { return toStr(obj) === '[object BigInt]'; }
function isBoolean (obj) { return toStr(obj) === '[object Boolean]'; }

var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has (obj, key) {
    return hasOwn.call(obj, key);
}

function toStr (obj) {
    return objectToString.call(obj);
}

function nameOf (f) {
    if (f.name) return f.name;
    var m = String(f).match(/^function\s*([\w$]+)/);
    if (m) return m[1];
}

function indexOf (xs, x) {
    if (xs.indexOf) return xs.indexOf(x);
    for (var i = 0, l = xs.length; i < l; i++) {
        if (xs[i] === x) return i;
    }
    return -1;
}

function isMap (x) {
    if (!mapSize) {
        return false;
    }
    try {
        mapSize.call(x);
        try {
            setSize.call(x);
        } catch (s) {
            return true;
        }
        return x instanceof Map; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isSet (x) {
    if (!setSize) {
        return false;
    }
    try {
        setSize.call(x);
        try {
            mapSize.call(x);
        } catch (m) {
            return true;
        }
        return x instanceof Set; // core-js workaround, pre-v2.5.0
    } catch (e) {}
    return false;
}

function isElement (x) {
    if (!x || typeof x !== 'object') return false;
    if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
        return true;
    }
    return typeof x.nodeName === 'string'
        && typeof x.getAttribute === 'function'
    ;
}

function inspectString (str, opts) {
    var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
    return wrapQuotes(s, 'single', opts);
}

function lowbyte (c) {
    var n = c.charCodeAt(0);
    var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
    if (x) return '\\' + x;
    return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}

function markBoxed (str) {
    return 'Object(' + str + ')';
}

function collectionOf (type, size, entries) {
    return type + ' (' + size + ') {' + entries.join(', ') + '}';
}

function arrObjKeys (obj, inspect) {
    var isArr = isArray(obj);
    var xs = [];
    if (isArr) {
        xs.length = obj.length;
        for (var i = 0; i < obj.length; i++) {
            xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
        }
    }
    for (var key in obj) {
        if (!has(obj, key)) continue;
        if (isArr && String(Number(key)) === key && key < obj.length) continue;
        if (/[^\w$]/.test(key)) {
            xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
        } else {
            xs.push(key + ': ' + inspect(obj[key], obj));
        }
    }
    return xs;
}


/***/ }),
/* 1069 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 1070 */
/***/ (function(module, exports, __nested_webpack_require_4926608__) {

"use strict";


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

var _createGenerator = __nested_webpack_require_4926608__(1071);

var _createGenerator2 = _interopRequireDefault(_createGenerator);

var _createParser = __nested_webpack_require_4926608__(1072);

var _createParser2 = _interopRequireDefault(_createParser);

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

// @flow

exports.createGenerator = _createGenerator2.default;
exports.createParser = _createParser2.default;
//# sourceMappingURL=index.js.map

/***/ }),
/* 1071 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


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

/*:: import type {
  CombinatorTokenType,
  SelectorTokenType
} from './types';*/


var escapeValue = function escapeValue(value /*: string*/) /*: string*/ {
  return JSON.stringify(value);
};

var renderSelector = function renderSelector(selectorToken /*: SelectorTokenType*/) {
  var tokens = selectorToken.body;
  var parts = [];

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = tokens[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var token = _step.value;

      var part = void 0;

      if (token.type === 'universalSelector') {
        part = '*';
      } else if (token.type === 'typeSelector') {
        part = token.name;
      } else if (token.type === 'idSelector') {
        part = '#' + token.name;
      } else if (token.type === 'classSelector') {
        part = '.' + token.name;
      } else if (token.type === 'attributePresenceSelector') {
        part = '[' + token.name + ']';
      } else if (token.type === 'attributeValueSelector') {
        part = '[' + token.name + token.operator + escapeValue(token.value) + ']';
      } else if (token.type === 'pseudoClassSelector') {
        part = ':' + token.name;

        if (token.parameters.length) {
          part += '(' + token.parameters.map(escapeValue).join(', ') + ')';
        }
      } else if (token.type === 'pseudoElementSelector') {
        part = '::' + token.name;
      } else {
        throw new Error('Unknown token.');
      }

      parts.push(part);
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  return parts.join('');
};

exports.default = function () {
  var generate = function generate(tokens /*: Array<SelectorTokenType | CombinatorTokenType>*/) /*: string*/ {
    /**
     * @todo Think of a better name. This array contains selectors or combinators.
     */
    var sequences /*: Array<string>*/ = [];

    var _iteratorNormalCompletion2 = true;
    var _didIteratorError2 = false;
    var _iteratorError2 = undefined;

    try {
      for (var _iterator2 = tokens[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
        var token = _step2.value;

        if (token.type === 'selector') {
          sequences.push(renderSelector(token));
        } else if (token.type === 'descendantCombinator') {
          sequences.push(' ');
        } else if (token.type === 'childCombinator') {
          sequences.push(' > ');
        } else if (token.type === 'adjacentSiblingCombinator') {
          sequences.push(' + ');
        } else if (token.type === 'generalSiblingCombinator') {
          sequences.push(' ~ ');
        } else {
          throw new Error('Unknown token.');
        }
      }
    } catch (err) {
      _didIteratorError2 = true;
      _iteratorError2 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion2 && _iterator2.return) {
          _iterator2.return();
        }
      } finally {
        if (_didIteratorError2) {
          throw _iteratorError2;
        }
      }
    }

    return sequences.join('');
  };

  return {
    generate: generate
  };
};
//# sourceMappingURL=createGenerator.js.map

/***/ }),
/* 1072 */
/***/ (function(module, exports, __nested_webpack_require_4931022__) {

"use strict";


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

var _nearley = __nested_webpack_require_4931022__(1073);

var _grammar = __nested_webpack_require_4931022__(1074);

var _grammar2 = _interopRequireDefault(_grammar);

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

/*:: import type {
  CombinatorTokenType,
  SelectorTokenType
} from './types';*/ // @flow

exports.default = function () {
  var parse = function parse(selector /*: string*/) /*: Array<SelectorTokenType | CombinatorTokenType>*/ {
    var parser = new _nearley.Parser(_grammar2.default.ParserRules, _grammar2.default.ParserStart);

    var results = parser.feed(selector).results;

    if (results.length === 0) {
      throw new Error('Found no parsings.');
    }

    if (results.length > 1) {
      throw new Error('Ambiguous results.');
    }

    return results[0];
  };

  return {
    parse: parse
  };
};
//# sourceMappingURL=createParser.js.map

/***/ }),
/* 1073 */
/***/ (function(module, exports, __webpack_require__) {

(function(root, factory) {
    if (  true && module.exports) {
        module.exports = factory();
    } else {
        root.nearley = factory();
    }
}(this, function() {

    function Rule(name, symbols, postprocess) {
        this.id = ++Rule.highestId;
        this.name = name;
        this.symbols = symbols;        // a list of literal | regex class | nonterminal
        this.postprocess = postprocess;
        return this;
    }
    Rule.highestId = 0;

    Rule.prototype.toString = function(withCursorAt) {
        function stringifySymbolSequence (e) {
            return e.literal ? JSON.stringify(e.literal) :
                   e.type ? '%' + e.type : e.toString();
        }
        var symbolSequence = (typeof withCursorAt === "undefined")
                             ? this.symbols.map(stringifySymbolSequence).join(' ')
                             : (   this.symbols.slice(0, withCursorAt).map(stringifySymbolSequence).join(' ')
                                 + " ● "
                                 + this.symbols.slice(withCursorAt).map(stringifySymbolSequence).join(' ')     );
        return this.name + " → " + symbolSequence;
    }


    // a State is a rule at a position from a given starting point in the input stream (reference)
    function State(rule, dot, reference, wantedBy) {
        this.rule = rule;
        this.dot = dot;
        this.reference = reference;
        this.data = [];
        this.wantedBy = wantedBy;
        this.isComplete = this.dot === rule.symbols.length;
    }

    State.prototype.toString = function() {
        return "{" + this.rule.toString(this.dot) + "}, from: " + (this.reference || 0);
    };

    State.prototype.nextState = function(child) {
        var state = new State(this.rule, this.dot + 1, this.reference, this.wantedBy);
        state.left = this;
        state.right = child;
        if (state.isComplete) {
            state.data = state.build();
        }
        return state;
    };

    State.prototype.build = function() {
        var children = [];
        var node = this;
        do {
            children.push(node.right.data);
            node = node.left;
        } while (node.left);
        children.reverse();
        return children;
    };

    State.prototype.finish = function() {
        if (this.rule.postprocess) {
            this.data = this.rule.postprocess(this.data, this.reference, Parser.fail);
        }
    };


    function Column(grammar, index) {
        this.grammar = grammar;
        this.index = index;
        this.states = [];
        this.wants = {}; // states indexed by the non-terminal they expect
        this.scannable = []; // list of states that expect a token
        this.completed = {}; // states that are nullable
    }


    Column.prototype.process = function(nextColumn) {
        var states = this.states;
        var wants = this.wants;
        var completed = this.completed;

        for (var w = 0; w < states.length; w++) { // nb. we push() during iteration
            var state = states[w];

            if (state.isComplete) {
                state.finish();
                if (state.data !== Parser.fail) {
                    // complete
                    var wantedBy = state.wantedBy;
                    for (var i = wantedBy.length; i--; ) { // this line is hot
                        var left = wantedBy[i];
                        this.complete(left, state);
                    }

                    // special-case nullables
                    if (state.reference === this.index) {
                        // make sure future predictors of this rule get completed.
                        var exp = state.rule.name;
                        (this.completed[exp] = this.completed[exp] || []).push(state);
                    }
                }

            } else {
                // queue scannable states
                var exp = state.rule.symbols[state.dot];
                if (typeof exp !== 'string') {
                    this.scannable.push(state);
                    continue;
                }

                // predict
                if (wants[exp]) {
                    wants[exp].push(state);

                    if (completed.hasOwnProperty(exp)) {
                        var nulls = completed[exp];
                        for (var i = 0; i < nulls.length; i++) {
                            var right = nulls[i];
                            this.complete(state, right);
                        }
                    }
                } else {
                    wants[exp] = [state];
                    this.predict(exp);
                }
            }
        }
    }

    Column.prototype.predict = function(exp) {
        var rules = this.grammar.byName[exp] || [];

        for (var i = 0; i < rules.length; i++) {
            var r = rules[i];
            var wantedBy = this.wants[exp];
            var s = new State(r, 0, this.index, wantedBy);
            this.states.push(s);
        }
    }

    Column.prototype.complete = function(left, right) {
        var copy = left.nextState(right);
        this.states.push(copy);
    }


    function Grammar(rules, start) {
        this.rules = rules;
        this.start = start || this.rules[0].name;
        var byName = this.byName = {};
        this.rules.forEach(function(rule) {
            if (!byName.hasOwnProperty(rule.name)) {
                byName[rule.name] = [];
            }
            byName[rule.name].push(rule);
        });
    }

    // So we can allow passing (rules, start) directly to Parser for backwards compatibility
    Grammar.fromCompiled = function(rules, start) {
        var lexer = rules.Lexer;
        if (rules.ParserStart) {
          start = rules.ParserStart;
          rules = rules.ParserRules;
        }
        var rules = rules.map(function (r) { return (new Rule(r.name, r.symbols, r.postprocess)); });
        var g = new Grammar(rules, start);
        g.lexer = lexer; // nb. storing lexer on Grammar is iffy, but unavoidable
        return g;
    }


    function StreamLexer() {
      this.reset("");
    }

    StreamLexer.prototype.reset = function(data, state) {
        this.buffer = data;
        this.index = 0;
        this.line = state ? state.line : 1;
        this.lastLineBreak = state ? -state.col : 0;
    }

    StreamLexer.prototype.next = function() {
        if (this.index < this.buffer.length) {
            var ch = this.buffer[this.index++];
            if (ch === '\n') {
              this.line += 1;
              this.lastLineBreak = this.index;
            }
            return {value: ch};
        }
    }

    StreamLexer.prototype.save = function() {
      return {
        line: this.line,
        col: this.index - this.lastLineBreak,
      }
    }

    StreamLexer.prototype.formatError = function(token, message) {
        // nb. this gets called after consuming the offending token,
        // so the culprit is index-1
        var buffer = this.buffer;
        if (typeof buffer === 'string') {
            var nextLineBreak = buffer.indexOf('\n', this.index);
            if (nextLineBreak === -1) nextLineBreak = buffer.length;
            var line = buffer.substring(this.lastLineBreak, nextLineBreak)
            var col = this.index - this.lastLineBreak;
            message += " at line " + this.line + " col " + col + ":\n\n";
            message += "  " + line + "\n"
            message += "  " + Array(col).join(" ") + "^"
            return message;
        } else {
            return message + " at index " + (this.index - 1);
        }
    }


    function Parser(rules, start, options) {
        if (rules instanceof Grammar) {
            var grammar = rules;
            var options = start;
        } else {
            var grammar = Grammar.fromCompiled(rules, start);
        }
        this.grammar = grammar;

        // Read options
        this.options = {
            keepHistory: false,
            lexer: grammar.lexer || new StreamLexer,
        };
        for (var key in (options || {})) {
            this.options[key] = options[key];
        }

        // Setup lexer
        this.lexer = this.options.lexer;
        this.lexerState = undefined;

        // Setup a table
        var column = new Column(grammar, 0);
        var table = this.table = [column];

        // I could be expecting anything.
        column.wants[grammar.start] = [];
        column.predict(grammar.start);
        // TODO what if start rule is nullable?
        column.process();
        this.current = 0; // token index
    }

    // create a reserved token for indicating a parse fail
    Parser.fail = {};

    Parser.prototype.feed = function(chunk) {
        var lexer = this.lexer;
        lexer.reset(chunk, this.lexerState);

        var token;
        while (token = lexer.next()) {
            // We add new states to table[current+1]
            var column = this.table[this.current];

            // GC unused states
            if (!this.options.keepHistory) {
                delete this.table[this.current - 1];
            }

            var n = this.current + 1;
            var nextColumn = new Column(this.grammar, n);
            this.table.push(nextColumn);

            // Advance all tokens that expect the symbol
            var literal = token.text !== undefined ? token.text : token.value;
            var value = lexer.constructor === StreamLexer ? token.value : token;
            var scannable = column.scannable;
            for (var w = scannable.length; w--; ) {
                var state = scannable[w];
                var expect = state.rule.symbols[state.dot];
                // Try to consume the token
                // either regex or literal
                if (expect.test ? expect.test(value) :
                    expect.type ? expect.type === token.type
                                : expect.literal === literal) {
                    // Add it
                    var next = state.nextState({data: value, token: token, isToken: true, reference: n - 1});
                    nextColumn.states.push(next);
                }
            }

            // Next, for each of the rules, we either
            // (a) complete it, and try to see if the reference row expected that
            //     rule
            // (b) predict the next nonterminal it expects by adding that
            //     nonterminal's start state
            // To prevent duplication, we also keep track of rules we have already
            // added

            nextColumn.process();

            // If needed, throw an error:
            if (nextColumn.states.length === 0) {
                // No states at all! This is not good.
                var message = this.lexer.formatError(token, "invalid syntax") + "\n";
                message += "Unexpected " + (token.type ? token.type + " token: " : "");
                message += JSON.stringify(token.value !== undefined ? token.value : token) + "\n";
                var err = new Error(message);
                err.offset = this.current;
                err.token = token;
                throw err;
            }

            // maybe save lexer state
            if (this.options.keepHistory) {
              column.lexerState = lexer.save()
            }

            this.current++;
        }
        if (column) {
          this.lexerState = lexer.save()
        }

        // Incrementally keep track of results
        this.results = this.finish();

        // Allow chaining, for whatever it's worth
        return this;
    };

    Parser.prototype.save = function() {
        var column = this.table[this.current];
        column.lexerState = this.lexerState;
        return column;
    };

    Parser.prototype.restore = function(column) {
        var index = column.index;
        this.current = index;
        this.table[index] = column;
        this.table.splice(index + 1);
        this.lexerState = column.lexerState;

        // Incrementally keep track of results
        this.results = this.finish();
    };

    // nb. deprecated: use save/restore instead!
    Parser.prototype.rewind = function(index) {
        if (!this.options.keepHistory) {
            throw new Error('set option `keepHistory` to enable rewinding')
        }
        // nb. recall column (table) indicies fall between token indicies.
        //        col 0   --   token 0   --   col 1
        this.restore(this.table[index]);
    };

    Parser.prototype.finish = function() {
        // Return the possible parsings
        var considerations = [];
        var start = this.grammar.start;
        var column = this.table[this.table.length - 1]
        column.states.forEach(function (t) {
            if (t.rule.name === start
                    && t.dot === t.rule.symbols.length
                    && t.reference === 0
                    && t.data !== Parser.fail) {
                considerations.push(t);
            }
        });
        return considerations.map(function(c) {return c.data; });
    };

    return {
        Parser: Parser,
        Grammar: Grammar,
        Rule: Rule,
    };

}));


/***/ }),
/* 1074 */
/***/ (function(module, exports, __nested_webpack_require_4945273__) {

"use strict";


// Generated automatically by nearley
// http://github.com/Hardmath123/nearley
(function () {
  function id(x) {
    return x[0];
  }

  var flattenDeep = __nested_webpack_require_4945273__(1075);
  var appendItem = function appendItem(a, b) {
    return function (d) {
      return d[a].concat([d[b]]);
    };
  };
  var appendItemChar = function appendItemChar(a, b) {
    return function (d) {
      return d[a].concat(d[b]);
    };
  };

  var flatten = function flatten(d) {
    d = d.filter(function (r) {
      return r !== null;
    });
    return flattenDeep(d);
  };

  var combinatorMap = {
    ' ': 'descendantCombinator',
    '+': 'adjacentSiblingCombinator',
    '>': 'childCombinator',
    '~': 'generalSiblingCombinator'
  };

  var concatUsingCombinator = function concatUsingCombinator(d) {
    return (Array.isArray(d[0]) ? d[0] : [d[0]]).concat({
      type: combinatorMap[d[2]]
    }).concat(d[4]);
  };

  var parseAsNumber = function parseAsNumber(d, i, reject) {
    var joined = flattenDeep(d).join('');
    var parsed = parseFloat(joined);
    if (isNaN(parsed)) {
      return reject;
    }
    return parsed;
  };

  var parseAsBoolean = function parseAsBoolean(d, i, reject) {
    if (d[0] === 'true') return true;
    if (d[0] === 'false') return false;
    return reject;
  };

  var parseFalsyPrimitive = function parseFalsyPrimitive(d, i, reject) {
    if (d[0] === 'NaN') return NaN;
    if (d[0] === 'undefined') return undefined;
    if (d[0] === 'null') return null;
    return reject;
  };
  var grammar = {
    Lexer: undefined,
    ParserRules: [{ "name": "combinator", "symbols": ["selector"] }, { "name": "combinator", "symbols": ["combinator", "_", /[>+~ ]/, "_", "selector"], "postprocess": concatUsingCombinator }, { "name": "selector", "symbols": ["selectorBody"], "postprocess": function postprocess(d) {
        return { type: 'selector', body: d[0] };
      } }, { "name": "selectorBody$ebnf$1", "symbols": ["typeSelector"], "postprocess": id }, { "name": "selectorBody$ebnf$1", "symbols": [], "postprocess": function postprocess(d) {
        return null;
      } }, { "name": "selectorBody$ebnf$2", "symbols": [] }, { "name": "selectorBody$ebnf$2", "symbols": ["selectorBody$ebnf$2", "simpleSelector"], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "selectorBody", "symbols": ["selectorBody$ebnf$1", "selectorBody$ebnf$2"], "postprocess": function postprocess(d, i, reject) {
        var selectors = flatten(d);if (!selectors.length) return reject;return selectors;
      } }, { "name": "selectorBody$ebnf$3", "symbols": [] }, { "name": "selectorBody$ebnf$3", "symbols": ["selectorBody$ebnf$3", "simpleSelector"], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "selectorBody", "symbols": ["universalSelector", "selectorBody$ebnf$3"], "postprocess": flatten }, { "name": "simpleSelector", "symbols": ["idSelector"] }, { "name": "simpleSelector", "symbols": ["classSelector"] }, { "name": "simpleSelector", "symbols": ["attributeValueSelector"] }, { "name": "simpleSelector", "symbols": ["attributePresenceSelector"] }, { "name": "simpleSelector", "symbols": ["pseudoClassSelector"] }, { "name": "simpleSelector", "symbols": ["pseudoElementSelector"] }, { "name": "typeSelector", "symbols": ["attributeName"], "postprocess": function postprocess(d) {
        return { type: 'typeSelector', name: d[0] };
      } }, { "name": "className$ebnf$1", "symbols": [{ "literal": "-" }], "postprocess": id }, { "name": "className$ebnf$1", "symbols": [], "postprocess": function postprocess(d) {
        return null;
      } }, { "name": "className$ebnf$2", "symbols": [] }, { "name": "className$ebnf$2", "symbols": ["className$ebnf$2", /[_a-zA-Z0-9-]/], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "className", "symbols": ["className$ebnf$1", /[_a-zA-Z]/, "className$ebnf$2"], "postprocess": function postprocess(d) {
        return (d[0] || '') + d[1] + d[2].join('');
      } }, { "name": "attributeName$ebnf$1", "symbols": [] }, { "name": "attributeName$ebnf$1", "symbols": ["attributeName$ebnf$1", /[_a-zA-Z()0-9-]/], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "attributeName", "symbols": [/[_a-z()A-Z]/, "attributeName$ebnf$1"], "postprocess": function postprocess(d) {
        return d[0] + d[1].join('');
      } }, { "name": "classSelector", "symbols": [{ "literal": "." }, "className"], "postprocess": function postprocess(d) {
        return { type: 'classSelector', name: d[1] };
      } }, { "name": "idSelector", "symbols": [{ "literal": "#" }, "attributeName"], "postprocess": function postprocess(d) {
        return { type: 'idSelector', name: d[1] };
      } }, { "name": "universalSelector", "symbols": [{ "literal": "*" }], "postprocess": function postprocess(d) {
        return { type: 'universalSelector' };
      } }, { "name": "attributePresenceSelector", "symbols": [{ "literal": "[" }, "attributeName", { "literal": "]" }], "postprocess": function postprocess(d) {
        return { type: 'attributePresenceSelector', name: d[1] };
      } }, { "name": "attributeOperator", "symbols": [{ "literal": "=" }] }, { "name": "attributeOperator$string$1", "symbols": [{ "literal": "~" }, { "literal": "=" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "attributeOperator", "symbols": ["attributeOperator$string$1"] }, { "name": "attributeOperator$string$2", "symbols": [{ "literal": "|" }, { "literal": "=" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "attributeOperator", "symbols": ["attributeOperator$string$2"] }, { "name": "attributeOperator$string$3", "symbols": [{ "literal": "^" }, { "literal": "=" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "attributeOperator", "symbols": ["attributeOperator$string$3"] }, { "name": "attributeOperator$string$4", "symbols": [{ "literal": "$" }, { "literal": "=" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "attributeOperator", "symbols": ["attributeOperator$string$4"] }, { "name": "attributeOperator$string$5", "symbols": [{ "literal": "*" }, { "literal": "=" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "attributeOperator", "symbols": ["attributeOperator$string$5"] }, { "name": "attributeValueSelector", "symbols": [{ "literal": "[" }, "attributeName", "attributeOperator", "attributeValue", { "literal": "]" }], "postprocess": function postprocess(d) {
        return {
          type: 'attributeValueSelector',
          name: d[1],
          value: d[3],
          operator: d[2][0]
        };
      }
    }, { "name": "attributeValue", "symbols": ["falsyPrimitiveStrings"], "postprocess": id }, { "name": "attributeValue", "symbols": ["numericValue"], "postprocess": id }, { "name": "attributeValue", "symbols": ["sqstring"], "postprocess": id }, { "name": "attributeValue", "symbols": ["dqstring"], "postprocess": id }, { "name": "falsyPrimitiveStrings$string$1", "symbols": [{ "literal": "f" }, { "literal": "a" }, { "literal": "l" }, { "literal": "s" }, { "literal": "e" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "falsyPrimitiveStrings", "symbols": ["falsyPrimitiveStrings$string$1"], "postprocess": parseAsBoolean }, { "name": "falsyPrimitiveStrings$string$2", "symbols": [{ "literal": "t" }, { "literal": "r" }, { "literal": "u" }, { "literal": "e" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "falsyPrimitiveStrings", "symbols": ["falsyPrimitiveStrings$string$2"], "postprocess": parseAsBoolean }, { "name": "falsyPrimitiveStrings$string$3", "symbols": [{ "literal": "N" }, { "literal": "a" }, { "literal": "N" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "falsyPrimitiveStrings", "symbols": ["falsyPrimitiveStrings$string$3"], "postprocess": parseFalsyPrimitive }, { "name": "falsyPrimitiveStrings$string$4", "symbols": [{ "literal": "n" }, { "literal": "u" }, { "literal": "l" }, { "literal": "l" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "falsyPrimitiveStrings", "symbols": ["falsyPrimitiveStrings$string$4"], "postprocess": parseFalsyPrimitive }, { "name": "falsyPrimitiveStrings$string$5", "symbols": [{ "literal": "u" }, { "literal": "n" }, { "literal": "d" }, { "literal": "e" }, { "literal": "f" }, { "literal": "i" }, { "literal": "n" }, { "literal": "e" }, { "literal": "d" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "falsyPrimitiveStrings", "symbols": ["falsyPrimitiveStrings$string$5"], "postprocess": parseFalsyPrimitive }, { "name": "numericValue", "symbols": ["int", { "literal": "." }, "int"], "postprocess": parseAsNumber }, { "name": "numericValue", "symbols": [{ "literal": "+" }, "int", { "literal": "." }, "int"], "postprocess": parseAsNumber }, { "name": "numericValue", "symbols": [{ "literal": "-" }, "int", { "literal": "." }, "int"], "postprocess": parseAsNumber }, { "name": "numericValue", "symbols": [{ "literal": "-" }, "int"], "postprocess": parseAsNumber }, { "name": "numericValue", "symbols": ["int"], "postprocess": parseAsNumber }, { "name": "numericValue", "symbols": [{ "literal": "+" }, "int"], "postprocess": parseAsNumber }, { "name": "numericValue$string$1", "symbols": [{ "literal": "I" }, { "literal": "n" }, { "literal": "f" }, { "literal": "i" }, { "literal": "n" }, { "literal": "i" }, { "literal": "t" }, { "literal": "y" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "numericValue", "symbols": ["numericValue$string$1"], "postprocess": parseAsNumber }, { "name": "numericValue$string$2", "symbols": [{ "literal": "+" }, { "literal": "I" }, { "literal": "n" }, { "literal": "f" }, { "literal": "i" }, { "literal": "n" }, { "literal": "i" }, { "literal": "t" }, { "literal": "y" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "numericValue", "symbols": ["numericValue$string$2"], "postprocess": parseAsNumber }, { "name": "numericValue$string$3", "symbols": [{ "literal": "-" }, { "literal": "I" }, { "literal": "n" }, { "literal": "f" }, { "literal": "i" }, { "literal": "n" }, { "literal": "i" }, { "literal": "t" }, { "literal": "y" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "numericValue", "symbols": ["numericValue$string$3"], "postprocess": parseAsNumber }, { "name": "int$ebnf$1", "symbols": [/[0-9]/] }, { "name": "int$ebnf$1", "symbols": ["int$ebnf$1", /[0-9]/], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "int", "symbols": ["int$ebnf$1"] }, { "name": "classParameters", "symbols": [] }, { "name": "classParameters", "symbols": ["classParameter"] }, { "name": "classParameters", "symbols": ["classParameters", { "literal": "," }, "_", "classParameter"], "postprocess": appendItem(0, 3) }, { "name": "classParameter$ebnf$1", "symbols": [/[^()"', ]/] }, { "name": "classParameter$ebnf$1", "symbols": ["classParameter$ebnf$1", /[^()"', ]/], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "classParameter", "symbols": ["classParameter$ebnf$1"], "postprocess": function postprocess(d) {
        return d[0].join('');
      } }, { "name": "classParameter", "symbols": ["sqstring"], "postprocess": id }, { "name": "classParameter", "symbols": ["dqstring"], "postprocess": id }, { "name": "pseudoElementSelector$string$1", "symbols": [{ "literal": ":" }, { "literal": ":" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "pseudoElementSelector", "symbols": ["pseudoElementSelector$string$1", "pseudoClassSelectorName"], "postprocess": function postprocess(d) {
        return { type: 'pseudoElementSelector', name: d[1] };
      } }, { "name": "pseudoClassSelector", "symbols": [{ "literal": ":" }, "pseudoClassSelectorName"], "postprocess": function postprocess(d) {
        return { type: 'pseudoClassSelector', name: d[1] };
      } }, { "name": "pseudoClassSelector", "symbols": [{ "literal": ":" }, "pseudoClassSelectorName", { "literal": "(" }, "classParameters", { "literal": ")" }], "postprocess": function postprocess(d) {
        return { type: 'pseudoClassSelector', name: d[1], parameters: d[3] };
      } }, { "name": "pseudoClassSelectorName$ebnf$1", "symbols": [/[a-zA-Z0-9-_]/] }, { "name": "pseudoClassSelectorName$ebnf$1", "symbols": ["pseudoClassSelectorName$ebnf$1", /[a-zA-Z0-9-_]/], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "pseudoClassSelectorName", "symbols": [/[a-zA-Z]/, "pseudoClassSelectorName$ebnf$1"], "postprocess": function postprocess(d) {
        return d[0] + d[1].join('');
      } }, { "name": "dqstring$ebnf$1", "symbols": [] }, { "name": "dqstring$ebnf$1", "symbols": ["dqstring$ebnf$1", "dstrchar"], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "dqstring", "symbols": [{ "literal": "\"" }, "dqstring$ebnf$1", { "literal": "\"" }], "postprocess": function postprocess(d) {
        return d[1].join('');
      } }, { "name": "dstrchar", "symbols": [/[^"]/], "postprocess": id }, { "name": "dstrchar$string$1", "symbols": [{ "literal": "\\" }, { "literal": "\"" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "dstrchar", "symbols": ["dstrchar$string$1"], "postprocess": function postprocess(d) {
        return '"';
      } }, { "name": "sqstring$ebnf$1", "symbols": [] }, { "name": "sqstring$ebnf$1", "symbols": ["sqstring$ebnf$1", "sstrchar"], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "sqstring", "symbols": [{ "literal": "'" }, "sqstring$ebnf$1", { "literal": "'" }], "postprocess": function postprocess(d) {
        return d[1].join('');
      } }, { "name": "sstrchar", "symbols": [/[^']/], "postprocess": id }, { "name": "sstrchar$string$1", "symbols": [{ "literal": "\\" }, { "literal": "'" }], "postprocess": function joiner(d) {
        return d.join('');
      } }, { "name": "sstrchar", "symbols": ["sstrchar$string$1"], "postprocess": function postprocess(d) {
        return '\'';
      } }, { "name": "_$ebnf$1", "symbols": [] }, { "name": "_$ebnf$1", "symbols": ["_$ebnf$1", /[ ]/], "postprocess": function arrpush(d) {
        return d[0].concat([d[1]]);
      } }, { "name": "_", "symbols": ["_$ebnf$1"], "postprocess": function postprocess(d) {
        return null;
      } }],
    ParserStart: "combinator"
  };
  if (  true && typeof module.exports !== 'undefined') {
    module.exports = grammar;
  } else {
    window.grammar = grammar;
  }
})();
//# sourceMappingURL=grammar.js.map

/***/ }),
/* 1075 */
/***/ (function(module, exports, __nested_webpack_require_4960352__) {

/* WEBPACK VAR INJECTION */(function(global) {/**
 * lodash (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
 * Released under MIT license <https://lodash.com/license>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 */

/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
    MAX_SAFE_INTEGER = 9007199254740991;

/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
    funcTag = '[object Function]',
    genTag = '[object GeneratorFunction]';

/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;

/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();

/**
 * Appends the elements of `values` to `array`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to append.
 * @returns {Array} Returns `array`.
 */
function arrayPush(array, values) {
  var index = -1,
      length = values.length,
      offset = array.length;

  while (++index < length) {
    array[offset + index] = values[index];
  }
  return array;
}

/** Used for built-in method references. */
var objectProto = Object.prototype;

/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;

/**
 * Used to resolve the
 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/** Built-in value references. */
var Symbol = root.Symbol,
    propertyIsEnumerable = objectProto.propertyIsEnumerable,
    spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;

/**
 * The base implementation of `_.flatten` with support for restricting flattening.
 *
 * @private
 * @param {Array} array The array to flatten.
 * @param {number} depth The maximum recursion depth.
 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
 * @param {Array} [result=[]] The initial result value.
 * @returns {Array} Returns the new flattened array.
 */
function baseFlatten(array, depth, predicate, isStrict, result) {
  var index = -1,
      length = array.length;

  predicate || (predicate = isFlattenable);
  result || (result = []);

  while (++index < length) {
    var value = array[index];
    if (depth > 0 && predicate(value)) {
      if (depth > 1) {
        // Recursively flatten arrays (susceptible to call stack limits).
        baseFlatten(value, depth - 1, predicate, isStrict, result);
      } else {
        arrayPush(result, value);
      }
    } else if (!isStrict) {
      result[result.length] = value;
    }
  }
  return result;
}

/**
 * Checks if `value` is a flattenable `arguments` object or array.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
 */
function isFlattenable(value) {
  return isArray(value) || isArguments(value) ||
    !!(spreadableSymbol && value && value[spreadableSymbol]);
}

/**
 * Recursively flattens `array`.
 *
 * @static
 * @memberOf _
 * @since 3.0.0
 * @category Array
 * @param {Array} array The array to flatten.
 * @returns {Array} Returns the new flattened array.
 * @example
 *
 * _.flattenDeep([1, [2, [3, [4]], 5]]);
 * // => [1, 2, 3, 4, 5]
 */
function flattenDeep(array) {
  var length = array ? array.length : 0;
  return length ? baseFlatten(array, INFINITY) : [];
}

/**
 * Checks if `value` is likely an `arguments` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
 *  else `false`.
 * @example
 *
 * _.isArguments(function() { return arguments; }());
 * // => true
 *
 * _.isArguments([1, 2, 3]);
 * // => false
 */
function isArguments(value) {
  // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
    (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}

/**
 * Checks if `value` is classified as an `Array` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
 * @example
 *
 * _.isArray([1, 2, 3]);
 * // => true
 *
 * _.isArray(document.body.children);
 * // => false
 *
 * _.isArray('abc');
 * // => false
 *
 * _.isArray(_.noop);
 * // => false
 */
var isArray = Array.isArray;

/**
 * Checks if `value` is array-like. A value is considered array-like if it's
 * not a function and has a `value.length` that's an integer greater than or
 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
 * @example
 *
 * _.isArrayLike([1, 2, 3]);
 * // => true
 *
 * _.isArrayLike(document.body.children);
 * // => true
 *
 * _.isArrayLike('abc');
 * // => true
 *
 * _.isArrayLike(_.noop);
 * // => false
 */
function isArrayLike(value) {
  return value != null && isLength(value.length) && !isFunction(value);
}

/**
 * This method is like `_.isArrayLike` except that it also checks if `value`
 * is an object.
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an array-like object,
 *  else `false`.
 * @example
 *
 * _.isArrayLikeObject([1, 2, 3]);
 * // => true
 *
 * _.isArrayLikeObject(document.body.children);
 * // => true
 *
 * _.isArrayLikeObject('abc');
 * // => false
 *
 * _.isArrayLikeObject(_.noop);
 * // => false
 */
function isArrayLikeObject(value) {
  return isObjectLike(value) && isArrayLike(value);
}

/**
 * Checks if `value` is classified as a `Function` object.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
 * @example
 *
 * _.isFunction(_);
 * // => true
 *
 * _.isFunction(/abc/);
 * // => false
 */
function isFunction(value) {
  // The use of `Object#toString` avoids issues with the `typeof` operator
  // in Safari 8-9 which returns 'object' for typed array and other constructors.
  var tag = isObject(value) ? objectToString.call(value) : '';
  return tag == funcTag || tag == genTag;
}

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This method is loosely based on
 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 * @example
 *
 * _.isLength(3);
 * // => true
 *
 * _.isLength(Number.MIN_VALUE);
 * // => false
 *
 * _.isLength(Infinity);
 * // => false
 *
 * _.isLength('3');
 * // => false
 */
function isLength(value) {
  return typeof value == 'number' &&
    value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

/**
 * Checks if `value` is the
 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
 * @example
 *
 * _.isObject({});
 * // => true
 *
 * _.isObject([1, 2, 3]);
 * // => true
 *
 * _.isObject(_.noop);
 * // => true
 *
 * _.isObject(null);
 * // => false
 */
function isObject(value) {
  var type = typeof value;
  return !!value && (type == 'object' || type == 'function');
}

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

module.exports = flattenDeep;

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4960352__(27)))

/***/ }),
/* 1076 */
/***/ (function(module, exports, __nested_webpack_require_4969469__) {

"use strict";


var define = __nested_webpack_require_4969469__(52);

var implementation = __nested_webpack_require_4969469__(515);
var getPolyfill = __nested_webpack_require_4969469__(516);
var shim = __nested_webpack_require_4969469__(1077);

var polyfill = getPolyfill();

define(polyfill, {
	getPolyfill: getPolyfill,
	implementation: implementation,
	shim: shim
});

module.exports = polyfill;


/***/ }),
/* 1077 */
/***/ (function(module, exports, __nested_webpack_require_4969888__) {

"use strict";


var getPolyfill = __nested_webpack_require_4969888__(516);
var define = __nested_webpack_require_4969888__(52);

module.exports = function shimValues() {
	var polyfill = getPolyfill();
	define(Object, { values: polyfill }, {
		values: function testValues() {
			return Object.values !== polyfill;
		}
	});
	return polyfill;
};


/***/ }),
/* 1078 */
/***/ (function(module, exports, __nested_webpack_require_4970281__) {

"use strict";


var filter = __nested_webpack_require_4970281__(1079);
var getData = __nested_webpack_require_4970281__(1080);

module.exports = function byConstructor(constructor) {
	if (!constructor) {
		return [];
	}

	var data = getData();
	if (constructor === data.unknown) {
		return [];
	}
	if (constructor === data.all) {
		return data.elements;
	}
	return filter(data.elements, function (item) {
		return item.constructor === constructor;
	});
};


/***/ }),
/* 1079 */
/***/ (function(module, exports) {


/**
 * Array#filter.
 *
 * @param {Array} arr
 * @param {Function} fn
 * @param {Object=} self
 * @return {Array}
 * @throw TypeError
 */

module.exports = function (arr, fn, self) {
  if (arr.filter) return arr.filter(fn, self);
  if (void 0 === arr || null === arr) throw new TypeError;
  if ('function' != typeof fn) throw new TypeError;
  var ret = [];
  for (var i = 0; i < arr.length; i++) {
    if (!hasOwn.call(arr, i)) continue;
    var val = arr[i];
    if (fn.call(self, val, i, arr)) ret.push(val);
  }
  return ret;
};

var hasOwn = Object.prototype.hasOwnProperty;


/***/ }),
/* 1080 */
/***/ (function(module, exports, __nested_webpack_require_4971426__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var map = function (arr, mapper) {
	var mapped = [];
	for (var i = 0; i < arr.length; i += 1) {
		mapped.push(mapper(arr[i], i));
	}
	return mapped;
};

var expecteds = [
	['HTMLElement', 'article'],
	['HTMLElement', 'section'],
	['HTMLBaseFontElement', 'basefont'],
	['HTMLPhraseElement', 'cite'],
	['HTMLElement', 'noscript'],
	['HTMLBGSoundElement', 'bgsound'],
	['HTMLPhraseElement', 'blink'],
	['HTMLElement', 'multicol'],
	['HTMLNextIdElement', 'nextid'],
	['HTMLElement', 'rb'],
	['HTMLElement', 'spacer'],
	['HTMLAnchorElement', 'a'],
	// ['HTMLAppletElement', 'applet'], // commented out due to IE 11 java update popup
	['HTMLAreaElement', 'area'],
	['HTMLAudioElement', 'audio'],
	['HTMLBaseElement', 'base'],
	['HTMLBodyElement', 'body'],
	['HTMLBRElement', 'br'],
	['HTMLButtonElement', 'button'],
	['HTMLCanvasElement', 'canvas'],
	['HTMLContentElement', 'content'],
	['HTMLDataElement', 'data'],
	['HTMLDataListElement', 'datalist'],
	['HTMLDialogElement', 'dialog'],
	['HTMLDirectoryElement', 'dir'],
	['HTMLDivElement', 'div'],
	['HTMLDListElement', 'dl'],
	['HTMLEmbedElement', 'embed'],
	['HTMLFieldSetElement', 'fieldset'],
	['HTMLFontElement', 'font'],
	['HTMLFormElement', 'form'],
	['HTMLFrameElement', 'frame'],
	['HTMLFrameSetElement', 'frameset'],
	['HTMLHeadElement', 'head'],
	['HTMLHeadingElement', 'h1'],
	['HTMLHeadingElement', 'h2'],
	['HTMLHeadingElement', 'h3'],
	['HTMLHeadingElement', 'h4'],
	['HTMLHeadingElement', 'h5'],
	['HTMLHeadingElement', 'h6'],
	['HTMLHtmlElement', 'html'],
	['HTMLHRElement', 'hr'],
	['HTMLIFrameElement', 'iframe'],
	['HTMLImageElement', 'img'],
	['HTMLInputElement', 'input'],
	['HTMLIsIndexElement', 'index'], // in HTML5, this is HTMLUnknownElement
	['HTMLKeygenElement', 'keygen', 'HTMLBlockElement'],
	['HTMLLabelElement', 'label'],
	['HTMLLegendElement', 'legend'],
	['HTMLLIElement', 'li'],
	['HTMLLinkElement', 'link'],
	['HTMLMapElement', 'map'],
	['HTMLMarqueeElement', 'marquee'],
	['HTMLMenuElement', 'menu'],
	['HTMLMetaElement', 'meta'],
	['HTMLMeterElement', 'meter'],
	['HTMLModElement', 'del'],
	['HTMLModElement', 'ins'],
	['HTMLObjectElement', 'object'],
	['HTMLOListElement', 'ol'],
	['HTMLOptGroupElement', 'optgroup'],
	['HTMLOptionElement', 'option'],
	['HTMLOutputElement', 'output'],
	['HTMLParagraphElement', 'p'],
	['HTMLParamElement', 'param'],
	['HTMLPictureElement', 'picture'],
	['HTMLPreElement', 'pre'],
	['HTMLProgressElement', 'progress'],
	['HTMLQuoteElement', 'q'],
	['HTMLQuoteElement', 'blockquote', 'HTMLBlockElement'],
	['HTMLScriptElement', 'script'],
	['HTMLPictureElement', 'picture'],
	['HTMLSelectElement', 'select'],
	['HTMLShadowElement', 'shadow'],
	['HTMLSourceElement', 'source'],
	['HTMLSpanElement', 'span'],
	['HTMLStyleElement', 'style'],
	['HTMLTableElement', 'table'],
	['HTMLTableCaptionElement', 'caption'],
	['HTMLTableCellElement', 'td', 'HTMLTableDataCellElement'],
	['HTMLTableCellElement', 'th', 'HTMLTableHeaderCellElement'],
	['HTMLTableRowElement', 'tr'],
	['HTMLTableColElement', 'col'],
	['HTMLTableColElement', 'colgroup'],
	['HTMLTableSectionElement', 'tbody'],
	['HTMLTableSectionElement', 'thead'],
	['HTMLTableSectionElement', 'tfoot'],
	['HTMLTemplateElement', 'template'],
	['HTMLTextAreaElement', 'textarea'],
	['HTMLTimeElement', 'time'],
	['HTMLTitleElement', 'title'],
	['HTMLTrackElement', 'track'],
	['HTMLUListElement', 'ul'],
	['HTMLVideoElement', 'video']
];

// eslint-disable-next-line consistent-return, max-params
var getConstructor = function getTagConstructor(tag, constructor, unknown) {
	if (typeof document !== 'undefined' && typeof document.createElement === 'function') {
		var actual = document.createElement(tag).constructor;
		if (actual !== unknown) {
			return actual;
		}
	}
};

module.exports = function getData() {
	var unknown = global.HTMLUnknownElement;
	return {
		all: global.HTMLElement,
		elements: map(expecteds, function (expected) {
			var constructorName = expected[0];
			var tag = expected[1];
			var alternate = expected[2];
			var constructor = global[constructorName];
			var altConstructor = alternate && global[alternate];

			return {
				constructor: getConstructor(tag, altConstructor || constructor, unknown),
				constructorName: altConstructor ? alternate : constructorName,
				expectedConstructor: altConstructor || constructor,
				tag: tag
			};
		}),
		unknown: unknown
	};
};

/* WEBPACK VAR INJECTION */}.call(this, __nested_webpack_require_4971426__(27)))

/***/ }),
/* 1081 */
/***/ (function(module, exports, __nested_webpack_require_4976007__) {

"use strict";


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

var _ReactWrapper = __nested_webpack_require_4976007__(449);

var _ReactWrapper2 = _interopRequireDefault(_ReactWrapper);

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

/**
 * Mounts and renders a react component into the document and provides a testing wrapper around it.
 *
 * @param node
 * @returns {ReactWrapper}
 */
function mount(node, options) {
  return new _ReactWrapper2['default'](node, null, options);
}

/***/ }),
/* 1082 */
/***/ (function(module, exports, __nested_webpack_require_4976651__) {

"use strict";


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

var _ShallowWrapper = __nested_webpack_require_4976651__(517);

var _ShallowWrapper2 = _interopRequireDefault(_ShallowWrapper);

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

/**
 * Shallow renders a react component and provides a testing wrapper around it.
 *
 * @param node
 * @returns {ShallowWrapper}
 */
function shallow(node, options) {
  return new _ShallowWrapper2['default'](node, null, options);
}

/***/ }),
/* 1083 */
/***/ (function(module, exports, __nested_webpack_require_4977288__) {

"use strict";


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

var _object = __nested_webpack_require_4977288__(122);

var _object2 = _interopRequireDefault(_object);

var _cheerio = __nested_webpack_require_4977288__(296);

var _cheerio2 = _interopRequireDefault(_cheerio);

var _getAdapter = __nested_webpack_require_4977288__(103);

var _getAdapter2 = _interopRequireDefault(_getAdapter);

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

/**
 * Renders a react component into static HTML and provides a cheerio wrapper around it. This is
 * somewhat asymmetric with `mount` and `shallow`, which don't use any external libraries, but
 * Cheerio's API is pretty close to what we actually want and has a significant amount of utility
 * that would be recreating the wheel if we didn't use it.
 *
 * I think there are a lot of good use cases to use `render` instead of `shallow` or `mount`, and
 * thus I'd like to keep this API in here even though it's not really "ours".
 *
 * @param node
 * @param options
 * @returns {Cheerio}
 */

function render(node) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  var adapter = (0, _getAdapter2['default'])(options);
  var renderer = adapter.createRenderer((0, _object2['default'])({ mode: 'string' }, options));
  var html = renderer.render(node, options.context);
  return _cheerio2['default'].load('')(html);
}

/***/ }),
/* 1084 */
/***/ (function(module, exports, __nested_webpack_require_4978821__) {

"use strict";


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

var _classCallCheck2 = __nested_webpack_require_4978821__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_4978821__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

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

var DomEvent = function () {
  function DomEvent(pubSub) {
    (0, _classCallCheck3["default"])(this, DomEvent);

    /**
     * Supported event handlers.
     *
     * @type {object}
     */
    this.customEventHandlers = {};

    /**
     * Stack of elements with registered event listeners.
     *
     * @type {object}
     */
    this.registeredEls = {};
    this.pubSub = pubSub;
  }

  /**
   * Get event handler.
   *
   * @param {string} eventName - Name of the event.
   * @return {function} Either a custom or generic event handler.
   */


  (0, _createClass3["default"])(DomEvent, [{
    key: "getEventHandler",
    value: function () {
      function getEventHandler(eventName) {
        var _this = this;

        if (this.customEventHandlers[eventName]) {
          return this.customEventHandlers[eventName];
        }
        return function (event) {
          return _this.pubSub.publish(eventName, event);
        };
      }

      return getEventHandler;
    }()

    /**
     * Unregister an event listener.
     *
     * @param {string} event - Name of the event to stop listening from.
     * @param {object} element - DOM element which we listened to.
     */

  }, {
    key: "unregister",
    value: function () {
      function unregister(event, element) {
        if (!this.registeredEls[event] && this.registeredEls[event] !== element) return;

        this.registeredEls[event].removeEventListener(event, this.registeredEls[event].__handler__);

        this.registeredEls[event] = undefined;
        delete this.registeredEls[event];
      }

      return unregister;
    }()

    /**
     * Register an event listener.
     *
     * @param {string} event - Name of the event to listen to.
     * @param {object} newElement - DOM element which to listen to.
     */

  }, {
    key: "register",
    value: function () {
      function register(event, newElement) {
        var useCapture = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

        if (!newElement || this.registeredEls[event] === newElement) {
          return;
        }

        if (this.registeredEls[event]) {
          this.unregister(this.registeredEls[event]);
        }

        this.registeredEls[event] = newElement;
        this.registeredEls[event].__handler__ = this.getEventHandler(event);
        this.registeredEls[event].addEventListener(event, this.registeredEls[event].__handler__, {
          capture: useCapture,
          passive: false
        });
      }

      return register;
    }()
  }]);
  return DomEvent;
}();

/**
 * Public API.
 *
 * @type {object}
 */


var domEvent = function domEvent(pubSub) {
  return new DomEvent(pubSub);
};

exports["default"] = domEvent;

/***/ }),
/* 1085 */
/***/ (function(module, exports, __nested_webpack_require_4982024__) {

"use strict";


Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.trackInfo = exports.tileDataToPixData = exports.calculateTilesFromResolution = exports.calculateTileWidth = exports.calculateTiles = exports.calculateZoomLevel = exports.calculateResolution = exports.calculateZoomLevelFromResolutions = exports.fetchTilesDebounced = exports.getTileProxyAuthHeader = exports.setTileProxyAuthHeader = exports.authHeader = exports.requestsInFlight = undefined;

var _regenerator = __nested_webpack_require_4982024__(246);

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = __nested_webpack_require_4982024__(247);

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _getIterator2 = __nested_webpack_require_4982024__(17);

var _getIterator3 = _interopRequireDefault(_getIterator2);

var _promise = __nested_webpack_require_4982024__(62);

var _promise2 = _interopRequireDefault(_promise);

var _keys = __nested_webpack_require_4982024__(18);

var _keys2 = _interopRequireDefault(_keys);

/**
 * Send a JSON request and mark it so that we can tell how many are in flight
 *
 * @param url: URL to fetch
 * @param callback: Callback to execute with content from fetch
 */
var json = function () {
  var _ref = (0, _asyncToGenerator3['default'])( /*#__PURE__*/_regenerator2['default'].mark(function () {
    function _callee(url, callback, pubSub) {
      return _regenerator2['default'].wrap(function () {
        function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!(url.indexOf('hg19') >= 0)) {
                  _context.next = 3;
                  break;
                }

                _context.next = 3;
                return sleep(1);

              case 3:
                return _context.abrupt('return', fetchEither(url, callback, 'json', pubSub));

              case 4:
              case 'end':
                return _context.stop();
            }
          }
        }

        return _callee$;
      }(), _callee, this);
    }

    return _callee;
  }()));

  return function () {
    function json(_x, _x2, _x3) {
      return _ref.apply(this, arguments);
    }

    return json;
  }();
}();

/**
 * Request a tilesetInfo for a track
 *
 * @param {string} server: The server where the data resides
 * @param {string} tilesetUid: The identifier for the dataset
 * @param {func} doneCb: A callback that gets called when the data is retrieved
 * @param {func} errorCb: A callback that gets called when there is an error
 */


exports.fetchMultiRequestTiles = fetchMultiRequestTiles;
exports.calculateTileAndPosInTile = calculateTileAndPosInTile;

var _d3Array = __nested_webpack_require_4982024__(8);

var _slugid = __nested_webpack_require_4982024__(26);

var _slugid2 = _interopRequireDefault(_slugid);

var _worker = __nested_webpack_require_4982024__(182);

var _utils = __nested_webpack_require_4982024__(10);

var _configs = __nested_webpack_require_4982024__(11);

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

var MAX_FETCH_TILES = 15;

/*
const str = document.currentScript.src
const pathName = str.substring(0, str.lastIndexOf("/"));
const workerPath = `${pathName}/worker.js`;

const setPixPool = new Pool(1);

setPixPool.run(function(params, done) {
  try {
    const array = new Float32Array(params.data);
    const pixData = worker.workerSetPix(
      params.size,
      array,
      params.valueScaleType,
      params.valueScaleDomain,
      params.pseudocount,
      params.colorScale,
    );

    done.transfer({
      pixData: pixData
    }, [pixData.buffer]);
  } catch (err) {
    console.log('err:', err);
  }
}, [workerPath]);


const fetchTilesPool = new Pool(10);
fetchTilesPool.run(function(params, done) {
  try {
    worker.workerGetTiles(params.outUrl, params.server, params.theseTileIds,
    params.authHeader, done);
    // done.transfer({
    // pixData: pixData
    // }, [pixData.buffer]);
  } catch (err) {
    console.log('err:', err);
  }
}, [workerPath]);
*/

// Config
var sessionId = _slugid2['default'].nice();
var requestsInFlight = exports.requestsInFlight = 0; // eslint-disable-line import/no-mutable-exports
var authHeader = exports.authHeader = null; // eslint-disable-line import/no-mutable-exports

var throttleAndDebounce = function throttleAndDebounce(func, interval, finalWait) {
  var timeout = void 0;
  var bundledRequest = [];
  var requestMapper = {};
  var blockedCalls = 0;

  var bundleRequests = function bundleRequests(request) {
    var requestId = requestMapper[request.id];

    if (requestId && bundledRequest[requestId]) {
      bundledRequest[requestId].ids = bundledRequest[requestId].ids.concat(request.ids);
    } else {
      requestMapper[request.id] = bundledRequest.length;
      bundledRequest.push(request);
    }
  };

  var reset = function reset() {
    timeout = null;
    bundledRequest = [];
    requestMapper = {};
  };

  // In a normal situation we would just call `func(...args)` but since we
  // modify the first argument and always trigger `reset()` afterwards I created
  // this helper function to avoid code duplication. Think of this function
  // as the actual function call that is being throttled and debounced.
  var callFunc = function callFunc(request) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }

    func.apply(undefined, [{
      sessionId: sessionId,
      requests: bundledRequest
    }].concat(args));
    reset();
  };

  var debounced = function debounced(request) {
    for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }

    var later = function later() {
      // Since we throttle and debounce we should check whether there were
      // actually multiple attempts to call this function after the most recent
      // throttled call. If there were no more calls we don't have to call
      // the function again.
      if (blockedCalls > 0) {
        callFunc.apply(undefined, [request].concat(args));
        blockedCalls = 0;
      }
    };

    clearTimeout(timeout);
    timeout = setTimeout(later, finalWait);
  };

  debounced.cancel = function () {
    clearTimeout(timeout);
    reset();
  };

  debounced.immediate = function () {
    func({
      sessionId: sessionId,
      requests: bundledRequest
    });
  };

  var wait = false;
  var throttled = function throttled(request) {
    for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
      args[_key3 - 1] = arguments[_key3];
    }

    bundleRequests(request);

    if (!wait) {
      callFunc.apply(undefined, [request].concat(args));
      debounced.apply(undefined, [request].concat(args));
      wait = true;
      blockedCalls = 0;
      setTimeout(function () {
        wait = false;
      }, interval);
    } else {
      blockedCalls++;
    }
  };

  return throttled;
};

var setTileProxyAuthHeader = exports.setTileProxyAuthHeader = function setTileProxyAuthHeader(newHeader) {
  exports.authHeader = authHeader = newHeader;
};

var getTileProxyAuthHeader = exports.getTileProxyAuthHeader = function getTileProxyAuthHeader() {
  return authHeader;
};

// Fritz: is this function used anywhere?
function fetchMultiRequestTiles(req, pubSub) {
  var requests = req.requests;

  var fetchPromises = [];

  var requestsByServer = {};
  var requestBodyByServer = {};

  // We're converting the array of IDs into an object in order to filter out duplicated requests.
  // In case different instances request the same data it won't be loaded twice.
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = (0, _getIterator3['default'])(requests), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var request = _step.value;

      if (!requestsByServer[request.server]) {
        requestsByServer[request.server] = {};
        requestBodyByServer[request.server] = [];
      }
      var _iteratorNormalCompletion7 = true;
      var _didIteratorError7 = false;
      var _iteratorError7 = undefined;

      try {
        for (var _iterator7 = (0, _getIterator3['default'])(request.ids), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
          var id = _step7.value;

          requestsByServer[request.server][id] = true;

          if (request.options) {
            (function () {
              var firstSepIndex = id.indexOf('.');
              var tilesetUuid = id.substring(0, firstSepIndex);
              var tileId = id.substring(firstSepIndex + 1);
              var tilesetObject = requestBodyByServer[request.server].find(function (t) {
                return t.tilesetUid === tilesetUuid;
              });
              if (tilesetObject) {
                tilesetObject.tileIds.push(tileId);
              } else {
                requestBodyByServer[request.server].push({
                  tilesetUid: tilesetUuid,
                  tileIds: [tileId],
                  options: request.options
                });
              }
            })();
          }
        }
      } catch (err) {
        _didIteratorError7 = true;
        _iteratorError7 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion7 && _iterator7['return']) {
            _iterator7['return']();
          }
        } finally {
          if (_didIteratorError7) {
            throw _iteratorError7;
          }
        }
      }
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator['return']) {
        _iterator['return']();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  var servers = (0, _keys2['default'])(requestsByServer);

  var _loop = function _loop(server) {
    var ids = (0, _keys2['default'])(requestsByServer[server]);
    // console.log('ids:', ids);

    var requestBody = requestBodyByServer[server];

    // if we request too many tiles, then the URL can get too long and fail
    // so we'll break up the requests into smaller subsets

    var _loop2 = function _loop2(i) {
      var theseTileIds = ids.slice(i, i + Math.min(ids.length - i, MAX_FETCH_TILES));

      var renderParams = theseTileIds.map(function (x) {
        return 'd=' + String(x);
      }).join('&');
      var outUrl = String(server) + '/tiles/?' + String(renderParams) + '&s=' + String(sessionId);

      /* eslint-disable no-loop-func */
      /* eslint-disable no-unused-vars */
      var p = new _promise2['default'](function (resolve, reject) {
        pubSub.publish('requestSent', outUrl);
        var params = {};

        params.outUrl = outUrl;
        params.server = server;
        params.theseTileIds = theseTileIds;
        params.authHeader = authHeader;

        (0, _worker.workerGetTiles)(params.outUrl, params.server, params.theseTileIds, params.authHeader, resolve, requestBody);

        /*
        fetchTilesPool.send(params)
          .promise()
          .then(ret => {
            resolve(ret);
          });
        */
        pubSub.publish('requestReceived', outUrl);
      });

      fetchPromises.push(p);
    };

    for (var i = 0; i < ids.length; i += MAX_FETCH_TILES) {
      _loop2(i);
    }
  };

  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = (0, _getIterator3['default'])(servers), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      var server = _step2.value;

      _loop(server);
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2['return']) {
        _iterator2['return']();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }

  _promise2['default'].all(fetchPromises).then(function (datas) {
    var tiles = {};

    // merge back all the tile requests
    var _iteratorNormalCompletion3 = true;
    var _didIteratorError3 = false;
    var _iteratorError3 = undefined;

    try {
      for (var _iterator3 = (0, _getIterator3['default'])(datas), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
        var data = _step3.value;

        var tileIds = (0, _keys2['default'])(data);

        var _iteratorNormalCompletion5 = true;
        var _didIteratorError5 = false;
        var _iteratorError5 = undefined;

        try {
          for (var _iterator5 = (0, _getIterator3['default'])(tileIds), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
            var tileId = _step5.value;

            tiles[String(data[tileId].server) + '/' + String(tileId)] = data[tileId];
          }
        } catch (err) {
          _didIteratorError5 = true;
          _iteratorError5 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion5 && _iterator5['return']) {
              _iterator5['return']();
            }
          } finally {
            if (_didIteratorError5) {
              throw _iteratorError5;
            }
          }
        }
      }

      // trigger the callback for every request
    } catch (err) {
      _didIteratorError3 = true;
      _iteratorError3 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion3 && _iterator3['return']) {
          _iterator3['return']();
        }
      } finally {
        if (_didIteratorError3) {
          throw _iteratorError3;
        }
      }
    }

    var _iteratorNormalCompletion4 = true;
    var _didIteratorError4 = false;
    var _iteratorError4 = undefined;

    try {
      for (var _iterator4 = (0, _getIterator3['default'])(requests), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
        var _request = _step4.value;

        var reqDate = {};
        var server = _request.server;

        // pull together the data per request

        var _iteratorNormalCompletion6 = true;
        var _didIteratorError6 = false;
        var _iteratorError6 = undefined;

        try {
          for (var _iterator6 = (0, _getIterator3['default'])(_request.ids), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
            var id = _step6.value;

            reqDate[id] = tiles[String(server) + '/' + String(id)];
          }
        } catch (err) {
          _didIteratorError6 = true;
          _iteratorError6 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion6 && _iterator6['return']) {
              _iterator6['return']();
            }
          } finally {
            if (_didIteratorError6) {
              throw _iteratorError6;
            }
          }
        }

        _request.done(reqDate);
      }
    } catch (err) {
      _didIteratorError4 = true;
      _iteratorError4 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion4 && _iterator4['return']) {
          _iterator4['return']();
        }
      } finally {
        if (_didIteratorError4) {
          throw _iteratorError4;
        }
      }
    }
  });
}

/**
 * Retrieve a set of tiles from the server
 *
 * Plenty of room for optimization and caching here.
 *
 * @param server: A string with the server's url (e.g. "http://127.0.0.1")
 * @param tileIds: The ids of the tiles to fetch (e.g. asdf-sdfs-sdfs.0.0.0)
 */
var fetchTilesDebounced = exports.fetchTilesDebounced = throttleAndDebounce(fetchMultiRequestTiles, _configs.TILE_FETCH_DEBOUNCE, _configs.TILE_FETCH_DEBOUNCE);

/**
 * Calculate the zoom level from a list of available resolutions
 */
var calculateZoomLevelFromResolutions = exports.calculateZoomLevelFromResolutions = function calculateZoomLevelFromResolutions(resolutions, scale) {
  var sortedResolutions = resolutions.map(function (x) {
    return +x;
  }).sort(function (a, b) {
    return b - a;
  });

  var trackWidth = scale.range()[1] - scale.range()[0];

  var binsDisplayed = sortedResolutions.map(function (r) {
    return (scale.domain()[1] - scale.domain()[0]) / r;
  });
  var binsPerPixel = binsDisplayed.map(function (b) {
    return b / trackWidth;
  });

  // we're going to show the highest resolution that requires more than one
  // pixel per bin
  var displayableBinsPerPixel = binsPerPixel.filter(function (b) {
    return b < 1;
  });

  if (displayableBinsPerPixel.length === 0) return 0;

  return binsPerPixel.indexOf(displayableBinsPerPixel[displayableBinsPerPixel.length - 1]);
};

var calculateResolution = exports.calculateResolution = function calculateResolution(tilesetInfo, zoomLevel) {
  if (tilesetInfo.resolutions) {
    var sortedResolutions = tilesetInfo.resolutions.map(function (x) {
      return +x;
    }).sort(function (a, b) {
      return b - a;
    });
    var _resolution = sortedResolutions[zoomLevel];

    return _resolution;
  }

  var maxWidth = tilesetInfo.max_width;
  var binsPerDimension = +tilesetInfo.bins_per_dimension;
  var resolution = maxWidth / (Math.pow(2, zoomLevel) * binsPerDimension);

  return resolution;
};

/**
 * Calculate the current zoom level.
 */
var calculateZoomLevel = exports.calculateZoomLevel = function calculateZoomLevel(scale, minX, maxX, binsPerTile) {
  var rangeWidth = scale.range()[1] - scale.range()[0];

  var zoomScale = Math.max((maxX - minX) / (scale.domain()[1] - scale.domain()[0]), 1);

  var viewResolution = 384;
  // const viewResolution = 2048;

  // fun fact: the number 384 is halfway between 256 and 512
  var addedZoom = Math.max(0, Math.ceil(Math.log(rangeWidth / viewResolution) / Math.LN2));
  var zoomLevel = Math.round(Math.log(zoomScale) / Math.LN2) + addedZoom;

  var binsPerTileCorrection = 0;

  if (binsPerTile) {
    binsPerTileCorrection = Math.floor(Math.log(256) / Math.log(2) - Math.log(binsPerTile) / Math.log(2));
  }

  zoomLevel += binsPerTileCorrection;

  return zoomLevel;
};

/**
 * Calculate the element within this tile containing the given
 * position.
 *
 * Returns the tile position and position within the tile for
 * the given element.
 *
 * @param {object} tilesetInfo: The information about this tileset
 * @param {Number} maxDim: The maximum width of the dataset (only used for
 *        tilesets without resolutions)
 * @param {Number} dataStartPos: The position where the data begins
 * @param {int} zoomLevel: The current zoomLevel
 * @param {Number} position: The position (in absolute coordinates) to caculate
 *                 the tile and position in tile for
 */
function calculateTileAndPosInTile(tilesetInfo, maxDim, dataStartPos, zoomLevel, position) {
  var tileWidth = null;
  var PIXELS_PER_TILE = tilesetInfo.bins_per_dimension || 256;

  if (tilesetInfo.resolutions) {
    tileWidth = tilesetInfo.resolutions[zoomLevel] * PIXELS_PER_TILE;
  } else {
    tileWidth = maxDim / Math.pow(2, zoomLevel);
  }

  var tilePos = Math.floor((position - dataStartPos) / tileWidth);
  var posInTile = Math.floor(PIXELS_PER_TILE * (position - tilePos * tileWidth) / tileWidth);

  return [tilePos, posInTile];
}

/**
 * Calculate the tiles that should be visible get a data domain
 * and a tileset info
 *
 * All the parameters except the first should be present in the
 * tileset_info returned by the server.
 *
 * @param zoomLevel: The zoom level at which to find the tiles (can be
 *   calculated using this.calcaulteZoomLevel, but needs to synchronized across
 *   both x and y scales so should be calculated externally)
 * @param scale: A d3 scale mapping data domain to visible values
 * @param minX: The minimum possible value in the dataset
 * @param maxX: The maximum possible value in the dataset
 * @param maxZoom: The maximum zoom value in this dataset
 * @param maxDim: The largest dimension of the tileset (e.g., width or height)
 *   (roughlty equal to 2 ** maxZoom * tileSize * tileResolution)
 */
var calculateTiles = exports.calculateTiles = function calculateTiles(zoomLevel, scale, minX, maxX, maxZoom, maxDim) {
  var zoomLevelFinal = Math.min(zoomLevel, maxZoom);

  // the ski areas are positioned according to their
  // cumulative widths, which means the tiles need to also
  // be calculated according to cumulative width

  var tileWidth = maxDim / Math.pow(2, zoomLevelFinal);
  // console.log('maxDim:', maxDim);

  var epsilon = 0.0000001;

  /*
  console.log('minX:', minX, 'zoomLevel:', zoomLevel);
  console.log('domain:', scale.domain(), scale.domain()[0] - minX,
  ((scale.domain()[0] - minX) / tileWidth))
  */

  return (0, _d3Array.range)(Math.max(0, Math.floor((scale.domain()[0] - minX) / tileWidth)), Math.min(Math.pow(2, zoomLevelFinal), Math.ceil((scale.domain()[1] - minX - epsilon) / tileWidth)));
};

var calculateTileWidth = exports.calculateTileWidth = function calculateTileWidth(tilesetInfo, zoomLevel, binsPerTile) {
  if (tilesetInfo.resolutions) {
    var sortedResolutions = tilesetInfo.resolutions.map(function (x) {
      return +x;
    }).sort(function (a, b) {
      return b - a;
    });
    return sortedResolutions[zoomLevel] * binsPerTile;
  }
  return tilesetInfo.max_width / Math.pow(2, zoomLevel);
};

/**
 * Calculate the tiles that sould be visisble given the resolution and
 * the minX and maxX values for the region
 *
 * @param resolution: The number of base pairs per bin
 * @param scale: The scale to use to calculate the currently visible tiles
 * @param minX: The minimum x position of the tileset
 * @param maxX: The maximum x position of the tileset
 */
var calculateTilesFromResolution = exports.calculateTilesFromResolution = function calculateTilesFromResolution(resolution, scale, minX, maxX, pixelsPerTile) {
  var epsilon = 0.0000001;
  var PIXELS_PER_TILE = pixelsPerTile || 256;
  var tileWidth = resolution * PIXELS_PER_TILE;
  var MAX_TILES = 20;
  // console.log('PIXELS_PER_TILE:', PIXELS_PER_TILE);

  if (!maxX) {
    maxX = Number.MAX_VALUE; // eslint-disable-line no-param-reassign
  }

  var lowerBound = Math.max(0, Math.floor((scale.domain()[0] - minX) / tileWidth));
  var upperBound = Math.ceil(Math.min(maxX, scale.domain()[1] - minX - epsilon) / tileWidth);
  var tileRange = (0, _d3Array.range)(lowerBound, upperBound);

  if (tileRange.length > MAX_TILES) {
    // too many tiles visible in this range
    console.warn('Too many visible tiles: ' + String(tileRange.length) + ' truncating to ' + MAX_TILES);
    tileRange = tileRange.slice(0, MAX_TILES);
  }
  // console.log('tileRange:', tileRange);

  return tileRange;
};

/**
 * Render 2D tile data. Convert the raw values to an array of
 * color values
 *
 * @param finished: A callback to let the caller know that the worker thread
 *   has converted tileData to pixData
 * @param minVisibleValue: The minimum visible value (used for setting the color
 *   scale)
 * @param maxVisibleValue: The maximum visible value
 * @param valueScaleType: Either 'log' or 'linear'
 * @param valueScaleDomain: The domain of the scale (the range is always [254,0])
 * @param colorScale: a 255 x 4 rgba array used as a color scale
 * @param synchronous: Render this tile synchronously or pass it on to the threadpool (which doesn't exist yet).
 * @param ignoreUpperRight: If this is a tile along the diagonal and there will
 * be mirrored tiles present ignore the upper right values
 * @param ignoreLowerLeft: If this is a tile along the diagonal and there will be
 * mirrored tiles present ignore the lower left values
 * @param {array} zeroValueColor: The color to use for rendering zero data values, [r, g, b, a].
 * @param {object} selectedRowsOptions Rendering options when using a `selectRows` track option.
 */
var tileDataToPixData = exports.tileDataToPixData = function tileDataToPixData(tile, valueScaleType, valueScaleDomain, pseudocount, colorScale, finished, ignoreUpperRight, ignoreLowerLeft, zeroValueColor, selectedRowsOptions) {
  var tileData = tile.tileData;


  if (!tileData.dense) {
    // if we didn't get any data from the server, don't do anything
    finished(null);
    return;
  }

  if (tile.mirrored &&
  // Data is already copied over
  !tile.isMirrored && tile.tileData.tilePos.length > 0 && tile.tileData.tilePos[0] === tile.tileData.tilePos[1]) {
    // Copy the data before mutating it in case the same data is used elsewhere.
    // During throttling/debouncing tile requests we also merge the requests so
    // the very same tile data might be used by different tracks.
    tile.tileData.dense = tile.tileData.dense.slice();

    // if a center tile is mirrored, we'll just add its transpose
    var tileWidth = Math.floor(Math.sqrt(tile.tileData.dense.length));
    for (var row = 0; row < tileWidth; row++) {
      for (var col = row + 1; col < tileWidth; col++) {
        tile.tileData.dense[row * tileWidth + col] = tile.tileData.dense[col * tileWidth + row];
      }
    }
    if (ignoreLowerLeft) {
      for (var _row = 0; _row < tileWidth; _row++) {
        for (var _col = 0; _col < _row; _col++) {
          tile.tileData.dense[_row * tileWidth + _col] = NaN;
        }
      }
    }
    tile.isMirrored = true;
  }

  // console.log('tile', tile);
  // clone the tileData so that the original array doesn't get neutered
  // when being passed to the worker script
  // const newTileData = tileData.dense;

  // comment this and uncomment the code afterwards to enable threading
  var pixData = (0, _worker.workerSetPix)(tileData.dense.length, tileData.dense, valueScaleType, valueScaleDomain, pseudocount, colorScale, ignoreUpperRight, ignoreLowerLeft, tile.tileData.shape, zeroValueColor, selectedRowsOptions);

  finished({ pixData: pixData });

  // const newTileData = new Float32Array(tileData.dense.length);
  // newTileData.set(tileData.dense);
  /*
  var params = {
    size: newTileData.length,
    data: newTileData,
    valueScaleType: valueScaleType,
    valueScaleDomain: valueScaleDomain,
    pseudocount: pseudocount,
    colorScale: colorScale
  };
   setPixPool.send(params, [ newTileData.buffer ])
    .promise()
    .then(returned => {
      finished(returned);
    })
    .catch(reason => {
      finished(null);
    });
  ;
  */
};

function fetchEither(url, callback, textOrJson, pubSub) {
  exports.requestsInFlight = requestsInFlight += 1;
  pubSub.publish('requestSent', url);

  var mime = null;
  if (textOrJson === 'text') {
    mime = null;
  } else if (textOrJson === 'json') {
    mime = 'application/json';
  } else {
    throw new Error('fetch either "text" or "json", not "' + textOrJson + '"');
  }
  var headers = {};

  if (mime) {
    headers['Content-Type'] = mime;
  }
  if (authHeader) {
    headers.Authorization = authHeader;
  }
  return fetch(url, { credentials: 'same-origin', headers: headers }).then(function (rep) {
    if (!rep.ok) {
      throw Error(rep.statusText);
    }

    return rep[textOrJson]();
  }).then(function (content) {
    callback(undefined, content);
    return content;
  })['catch'](function (error) {
    console.error('Could not fetch ' + String(url), error);
    callback(error, undefined);
    return error;
  })['finally'](function () {
    pubSub.publish('requestReceived', url);
    exports.requestsInFlight = requestsInFlight -= 1;
  });
}

/**
 * Send a text request and mark it so that we can tell how many are in flight
 *
 * @param url: URL to fetch
 * @param callback: Callback to execute with content from fetch
 */
function text(url, callback, pubSub) {
  return fetchEither(url, callback, 'text', pubSub);
}

function sleep(ms) {
  return new _promise2['default'](function (resolve) {
    return setTimeout(resolve, ms);
  });
}var trackInfo = exports.trackInfo = function trackInfo(server, tilesetUid, doneCb, errorCb, pubSub) {
  var url = String((0, _utils.trimTrailingSlash)(server)) + '/tileset_info/?d=' + String(tilesetUid) + '&s=' + String(sessionId);
  pubSub.publish('requestSent', url);
  // TODO: Is this used?
  json(url, function (error, data) {
    // eslint-disable-line
    pubSub.publish('requestReceived', url);
    if (error) {
      // console.log('error:', error);
      // don't do anything
      // no tileset info just means we can't do anything with this file...
      if (errorCb) {
        errorCb('Error retrieving tilesetInfo from: ' + String(server));
      } else {
        console.warn('Error retrieving: ', url);
      }
    } else {
      // console.log('got data', data);
      doneCb(data);
    }
  }, pubSub);
};

var api = {
  calculateResolution: calculateResolution,
  calculateTileAndPosInTile: calculateTileAndPosInTile,
  calculateTiles: calculateTiles,
  calculateTilesFromResolution: calculateTilesFromResolution,
  calculateTileWidth: calculateTileWidth,
  calculateZoomLevel: calculateZoomLevel,
  calculateZoomLevelFromResolutions: calculateZoomLevelFromResolutions,
  fetchTilesDebounced: fetchTilesDebounced,
  json: json,
  text: text,
  tileDataToPixData: tileDataToPixData,
  trackInfo: trackInfo
};

exports['default'] = api;

/***/ }),
/* 1086 */
/***/ (function(module, exports, __nested_webpack_require_5011530__) {

"use strict";


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

var _getPrototypeOf = __nested_webpack_require_5011530__(5);

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = __nested_webpack_require_5011530__(3);

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = __nested_webpack_require_5011530__(4);

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = __nested_webpack_require_5011530__(6);

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = __nested_webpack_require_5011530__(7);

var _inherits3 = _interopRequireDefault(_inherits2);

var _slicedToArray2 = __nested_webpack_require_5011530__(19);

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _propTypes = __nested_webpack_require_5011530__(2);

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = __nested_webpack_require_5011530__(1);

var _react2 = _interopRequireDefault(_react);

var _hglib = __nested_webpack_require_5011530__(317);

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

/**
 * A barebones implementation of a HiGlass view used to display a 2d track.
 * Multiple layers can be used by specifying a `combined` track in `trackConfig`.
 *
 * Defaults to having no label and no colorbar.
 *
 * If the aspect ratio defined by the parameter bounds doesn't match the aspect
 * ration of the enclosing element, the x bounds will be respected and the y
 * y coordinates will be truncated.
 *
 * @param {element|HTMLElement} The element to attach the viewer to
 * @param {[xMin, xMax, yMin, yMax]|Array} The bounds of the track
 * @param {trackConfig: Object} The standard HiGlass track definition type
 * @returns {Object} A {id, hgApi} object
 */
var trackViewer = exports.trackViewer = function trackViewer(element, _ref, trackConfig) {
  var _ref2 = (0, _slicedToArray3['default'])(_ref, 4),
      xMin = _ref2[0],
      xMax = _ref2[1],
      yMin = _ref2[2],
      yMax = _ref2[3];

  if (!trackConfig.options.colorbarPosition) {
    trackConfig.options.colorbarPosition = 'hidden';
  }
  if (!trackConfig.options.labelPosition) {
    trackConfig.options.labelPosition = 'hidden';
  }
  var id = 'arbitary-id';
  var viewConfig = {
    editable: false,
    zoomFixed: false,
    views: [{
      uid: id,
      initialXDomain: [xMin, xMax],
      initialYDomain: [yMin, yMax],
      tracks: {
        center: [trackConfig]
      },
      layout: {
        w: 12,
        h: 12,
        x: 0,
        y: 0,
        moved: false,
        'static': false
      }
    }]
  };
  var hgApi = (0, _hglib.viewer)(element, viewConfig, { sizeMode: 'bounded' });
  return { id: id, hgApi: hgApi };
};

/**
 * React component wrapper around trackViewer.
 * Accepts x, y, width, and height props, in addition to trackConfig,
 * so HiGlass can be used to provide background imagery for Deck.gl.
 */

var HiGlassTrackComponent = function (_React$Component) {
  (0, _inherits3['default'])(HiGlassTrackComponent, _React$Component);

  function HiGlassTrackComponent(props) {
    (0, _classCallCheck3['default'])(this, HiGlassTrackComponent);

    var _this = (0, _possibleConstructorReturn3['default'])(this, (HiGlassTrackComponent.__proto__ || (0, _getPrototypeOf2['default'])(HiGlassTrackComponent)).call(this, props));

    _this.id = 'id-' + String(Math.random());
    return _this;
  }

  (0, _createClass3['default'])(HiGlassTrackComponent, [{
    key: 'componentDidMount',
    value: function () {
      function componentDidMount() {
        this.initTrackViewer();
      }

      return componentDidMount;
    }()
  }, {
    key: 'shouldComponentUpdate',
    value: function () {
      function shouldComponentUpdate(nextProps) {
        // For now, never re-render the component: Just re-zoom.
        var x = nextProps.x,
            y = nextProps.y,
            width = nextProps.width,
            height = nextProps.height;

        this.zoomTo(x, y, width, height);
        return false;
      }

      return shouldComponentUpdate;
    }()
  }, {
    key: 'initTrackViewer',
    value: function () {
      function initTrackViewer() {
        var _props = this.props,
            trackConfig = _props.trackConfig,
            x = _props.x,
            y = _props.y,
            width = _props.width,
            height = _props.height;

        var element = document.getElementById(this.id);

        var _trackViewer = trackViewer(element, [x, x + width, y, y + height], trackConfig),
            id = _trackViewer.id,
            hgApi = _trackViewer.hgApi;

        this.viewUid = id;
        this.viewer = hgApi;
      }

      return initTrackViewer;
    }()

    /**
     * Zoom to a particular position.
     *
     * @param  {Number}  x       Left side of viewport
     * @param  {Number}  y       Top side of viewport
     * @param  {Number}  width   Width of viewport
     * @param  {Number}  height  Height of viewport
     */

  }, {
    key: 'zoomTo',
    value: function () {
      function zoomTo(x, y, width, height) {
        this.viewer.zoomTo(this.viewUid, x, x + width, y, y + height);
      }

      return zoomTo;
    }()
  }, {
    key: 'render',
    value: function () {
      function render() {
        return _react2['default'].createElement('div', { id: this.id, style: { height: '100%', width: '100%' } });
      }

      return render;
    }()
  }]);
  return HiGlassTrackComponent;
}(_react2['default'].Component);

exports['default'] = HiGlassTrackComponent;


HiGlassTrackComponent.propTypes = {
  trackConfig: _propTypes2['default'].object,
  width: _propTypes2['default'].number,
  height: _propTypes2['default'].number,
  x: _propTypes2['default'].number,
  y: _propTypes2['default'].number
};

/***/ }),
/* 1087 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_5017397__) {

"use strict";
__nested_webpack_require_5017397__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-geo/src/adder.js
// Adds floating point numbers with twice the normal precision.
// Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and
// Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3)
// 305–363 (1997).
// Code adapted from GeographicLib by Charles F. F. Karney,
// http://geographiclib.sourceforge.net/

/* harmony default export */ var adder = (function() {
  return new Adder;
});

function Adder() {
  this.reset();
}

Adder.prototype = {
  constructor: Adder,
  reset: function() {
    this.s = // rounded value
    this.t = 0; // exact error
  },
  add: function(y) {
    add(temp, y, this.t);
    add(this, temp.s, this.s);
    if (this.s) this.t += temp.t;
    else this.s = temp.t;
  },
  valueOf: function() {
    return this.s;
  }
};

var temp = new Adder;

function add(adder, a, b) {
  var x = adder.s = a + b,
      bv = x - a,
      av = x - bv;
  adder.t = (a - av) + (b - bv);
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/math.js
var epsilon = 1e-6;
var epsilon2 = 1e-12;
var pi = Math.PI;
var halfPi = pi / 2;
var quarterPi = pi / 4;
var tau = pi * 2;

var degrees = 180 / pi;
var radians = pi / 180;

var abs = Math.abs;
var atan = Math.atan;
var atan2 = Math.atan2;
var cos = Math.cos;
var ceil = Math.ceil;
var exp = Math.exp;
var floor = Math.floor;
var log = Math.log;
var pow = Math.pow;
var sin = Math.sin;
var math_sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };
var sqrt = Math.sqrt;
var tan = Math.tan;

function acos(x) {
  return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
}

function asin(x) {
  return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);
}

function haversin(x) {
  return (x = sin(x / 2)) * x;
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/noop.js
function noop() {}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/stream.js
function streamGeometry(geometry, stream) {
  if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
    streamGeometryType[geometry.type](geometry, stream);
  }
}

var streamObjectType = {
  Feature: function(object, stream) {
    streamGeometry(object.geometry, stream);
  },
  FeatureCollection: function(object, stream) {
    var features = object.features, i = -1, n = features.length;
    while (++i < n) streamGeometry(features[i].geometry, stream);
  }
};

var streamGeometryType = {
  Sphere: function(object, stream) {
    stream.sphere();
  },
  Point: function(object, stream) {
    object = object.coordinates;
    stream.point(object[0], object[1], object[2]);
  },
  MultiPoint: function(object, stream) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);
  },
  LineString: function(object, stream) {
    streamLine(object.coordinates, stream, 0);
  },
  MultiLineString: function(object, stream) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) streamLine(coordinates[i], stream, 0);
  },
  Polygon: function(object, stream) {
    streamPolygon(object.coordinates, stream);
  },
  MultiPolygon: function(object, stream) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) streamPolygon(coordinates[i], stream);
  },
  GeometryCollection: function(object, stream) {
    var geometries = object.geometries, i = -1, n = geometries.length;
    while (++i < n) streamGeometry(geometries[i], stream);
  }
};

function streamLine(coordinates, stream, closed) {
  var i = -1, n = coordinates.length - closed, coordinate;
  stream.lineStart();
  while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
  stream.lineEnd();
}

function streamPolygon(coordinates, stream) {
  var i = -1, n = coordinates.length;
  stream.polygonStart();
  while (++i < n) streamLine(coordinates[i], stream, 1);
  stream.polygonEnd();
}

/* harmony default export */ var src_stream = (function(object, stream) {
  if (object && streamObjectType.hasOwnProperty(object.type)) {
    streamObjectType[object.type](object, stream);
  } else {
    streamGeometry(object, stream);
  }
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/area.js





var areaRingSum = adder();

var areaSum = adder(),
    area_lambda00,
    phi00,
    area_lambda0,
    area_cosPhi0,
    area_sinPhi0;

var areaStream = {
  point: noop,
  lineStart: noop,
  lineEnd: noop,
  polygonStart: function() {
    areaRingSum.reset();
    areaStream.lineStart = areaRingStart;
    areaStream.lineEnd = areaRingEnd;
  },
  polygonEnd: function() {
    var areaRing = +areaRingSum;
    areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);
    this.lineStart = this.lineEnd = this.point = noop;
  },
  sphere: function() {
    areaSum.add(tau);
  }
};

function areaRingStart() {
  areaStream.point = areaPointFirst;
}

function areaRingEnd() {
  areaPoint(area_lambda00, phi00);
}

function areaPointFirst(lambda, phi) {
  areaStream.point = areaPoint;
  area_lambda00 = lambda, phi00 = phi;
  lambda *= radians, phi *= radians;
  area_lambda0 = lambda, area_cosPhi0 = cos(phi = phi / 2 + quarterPi), area_sinPhi0 = sin(phi);
}

function areaPoint(lambda, phi) {
  lambda *= radians, phi *= radians;
  phi = phi / 2 + quarterPi; // half the angular distance from south pole

  // Spherical excess E for a spherical triangle with vertices: south pole,
  // previous point, current point.  Uses a formula derived from Cagnoli’s
  // theorem.  See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).
  var dLambda = lambda - area_lambda0,
      sdLambda = dLambda >= 0 ? 1 : -1,
      adLambda = sdLambda * dLambda,
      cosPhi = cos(phi),
      sinPhi = sin(phi),
      k = area_sinPhi0 * sinPhi,
      u = area_cosPhi0 * cosPhi + k * cos(adLambda),
      v = k * sdLambda * sin(adLambda);
  areaRingSum.add(atan2(v, u));

  // Advance the previous points.
  area_lambda0 = lambda, area_cosPhi0 = cosPhi, area_sinPhi0 = sinPhi;
}

/* harmony default export */ var src_area = (function(object) {
  areaSum.reset();
  src_stream(object, areaStream);
  return areaSum * 2;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/cartesian.js


function cartesian_spherical(cartesian) {
  return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];
}

function cartesian_cartesian(spherical) {
  var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);
  return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
}

function cartesianDot(a, b) {
  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}

function cartesianCross(a, b) {
  return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
}

// TODO return a
function cartesianAddInPlace(a, b) {
  a[0] += b[0], a[1] += b[1], a[2] += b[2];
}

function cartesianScale(vector, k) {
  return [vector[0] * k, vector[1] * k, vector[2] * k];
}

// TODO return d
function cartesianNormalizeInPlace(d) {
  var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
  d[0] /= l, d[1] /= l, d[2] /= l;
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/bounds.js






var bounds_lambda0, bounds_phi0, bounds_lambda1, bounds_phi1, // bounds
    bounds_lambda2, // previous lambda-coordinate
    bounds_lambda00, bounds_phi00, // first point
    bounds_p0, // previous 3D point
    deltaSum = adder(),
    ranges,
    range;

var boundsStream = {
  point: boundsPoint,
  lineStart: boundsLineStart,
  lineEnd: boundsLineEnd,
  polygonStart: function() {
    boundsStream.point = boundsRingPoint;
    boundsStream.lineStart = boundsRingStart;
    boundsStream.lineEnd = boundsRingEnd;
    deltaSum.reset();
    areaStream.polygonStart();
  },
  polygonEnd: function() {
    areaStream.polygonEnd();
    boundsStream.point = boundsPoint;
    boundsStream.lineStart = boundsLineStart;
    boundsStream.lineEnd = boundsLineEnd;
    if (areaRingSum < 0) bounds_lambda0 = -(bounds_lambda1 = 180), bounds_phi0 = -(bounds_phi1 = 90);
    else if (deltaSum > epsilon) bounds_phi1 = 90;
    else if (deltaSum < -epsilon) bounds_phi0 = -90;
    range[0] = bounds_lambda0, range[1] = bounds_lambda1;
  }
};

function boundsPoint(lambda, phi) {
  ranges.push(range = [bounds_lambda0 = lambda, bounds_lambda1 = lambda]);
  if (phi < bounds_phi0) bounds_phi0 = phi;
  if (phi > bounds_phi1) bounds_phi1 = phi;
}

function bounds_linePoint(lambda, phi) {
  var p = cartesian_cartesian([lambda * radians, phi * radians]);
  if (bounds_p0) {
    var normal = cartesianCross(bounds_p0, p),
        equatorial = [normal[1], -normal[0], 0],
        inflection = cartesianCross(equatorial, normal);
    cartesianNormalizeInPlace(inflection);
    inflection = cartesian_spherical(inflection);
    var delta = lambda - bounds_lambda2,
        sign = delta > 0 ? 1 : -1,
        lambdai = inflection[0] * degrees * sign,
        phii,
        antimeridian = abs(delta) > 180;
    if (antimeridian ^ (sign * bounds_lambda2 < lambdai && lambdai < sign * lambda)) {
      phii = inflection[1] * degrees;
      if (phii > bounds_phi1) bounds_phi1 = phii;
    } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * bounds_lambda2 < lambdai && lambdai < sign * lambda)) {
      phii = -inflection[1] * degrees;
      if (phii < bounds_phi0) bounds_phi0 = phii;
    } else {
      if (phi < bounds_phi0) bounds_phi0 = phi;
      if (phi > bounds_phi1) bounds_phi1 = phi;
    }
    if (antimeridian) {
      if (lambda < bounds_lambda2) {
        if (bounds_angle(bounds_lambda0, lambda) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda1 = lambda;
      } else {
        if (bounds_angle(lambda, bounds_lambda1) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda0 = lambda;
      }
    } else {
      if (bounds_lambda1 >= bounds_lambda0) {
        if (lambda < bounds_lambda0) bounds_lambda0 = lambda;
        if (lambda > bounds_lambda1) bounds_lambda1 = lambda;
      } else {
        if (lambda > bounds_lambda2) {
          if (bounds_angle(bounds_lambda0, lambda) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda1 = lambda;
        } else {
          if (bounds_angle(lambda, bounds_lambda1) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda0 = lambda;
        }
      }
    }
  } else {
    ranges.push(range = [bounds_lambda0 = lambda, bounds_lambda1 = lambda]);
  }
  if (phi < bounds_phi0) bounds_phi0 = phi;
  if (phi > bounds_phi1) bounds_phi1 = phi;
  bounds_p0 = p, bounds_lambda2 = lambda;
}

function boundsLineStart() {
  boundsStream.point = bounds_linePoint;
}

function boundsLineEnd() {
  range[0] = bounds_lambda0, range[1] = bounds_lambda1;
  boundsStream.point = boundsPoint;
  bounds_p0 = null;
}

function boundsRingPoint(lambda, phi) {
  if (bounds_p0) {
    var delta = lambda - bounds_lambda2;
    deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
  } else {
    bounds_lambda00 = lambda, bounds_phi00 = phi;
  }
  areaStream.point(lambda, phi);
  bounds_linePoint(lambda, phi);
}

function boundsRingStart() {
  areaStream.lineStart();
}

function boundsRingEnd() {
  boundsRingPoint(bounds_lambda00, bounds_phi00);
  areaStream.lineEnd();
  if (abs(deltaSum) > epsilon) bounds_lambda0 = -(bounds_lambda1 = 180);
  range[0] = bounds_lambda0, range[1] = bounds_lambda1;
  bounds_p0 = null;
}

// Finds the left-right distance between two longitudes.
// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want
// the distance between ±180° to be 360°.
function bounds_angle(lambda0, lambda1) {
  return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;
}

function rangeCompare(a, b) {
  return a[0] - b[0];
}

function rangeContains(range, x) {
  return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
}

/* harmony default export */ var bounds = (function(feature) {
  var i, n, a, b, merged, deltaMax, delta;

  bounds_phi1 = bounds_lambda1 = -(bounds_lambda0 = bounds_phi0 = Infinity);
  ranges = [];
  src_stream(feature, boundsStream);

  // First, sort ranges by their minimum longitudes.
  if (n = ranges.length) {
    ranges.sort(rangeCompare);

    // Then, merge any ranges that overlap.
    for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {
      b = ranges[i];
      if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {
        if (bounds_angle(a[0], b[1]) > bounds_angle(a[0], a[1])) a[1] = b[1];
        if (bounds_angle(b[0], a[1]) > bounds_angle(a[0], a[1])) a[0] = b[0];
      } else {
        merged.push(a = b);
      }
    }

    // Finally, find the largest gap between the merged ranges.
    // The final bounding box will be the inverse of this gap.
    for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {
      b = merged[i];
      if ((delta = bounds_angle(a[1], b[0])) > deltaMax) deltaMax = delta, bounds_lambda0 = b[0], bounds_lambda1 = a[1];
    }
  }

  ranges = range = null;

  return bounds_lambda0 === Infinity || bounds_phi0 === Infinity
      ? [[NaN, NaN], [NaN, NaN]]
      : [[bounds_lambda0, bounds_phi0], [bounds_lambda1, bounds_phi1]];
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/centroid.js




var W0, W1,
    centroid_X0, centroid_Y0, Z0,
    centroid_X1, centroid_Y1, Z1,
    X2, Y2, Z2,
    centroid_lambda00, centroid_phi00, // first point
    centroid_x0, centroid_y0, z0; // previous point

var centroidStream = {
  sphere: noop,
  point: centroidPoint,
  lineStart: centroidLineStart,
  lineEnd: centroidLineEnd,
  polygonStart: function() {
    centroidStream.lineStart = centroidRingStart;
    centroidStream.lineEnd = centroidRingEnd;
  },
  polygonEnd: function() {
    centroidStream.lineStart = centroidLineStart;
    centroidStream.lineEnd = centroidLineEnd;
  }
};

// Arithmetic mean of Cartesian vectors.
function centroidPoint(lambda, phi) {
  lambda *= radians, phi *= radians;
  var cosPhi = cos(phi);
  centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));
}

function centroidPointCartesian(x, y, z) {
  ++W0;
  centroid_X0 += (x - centroid_X0) / W0;
  centroid_Y0 += (y - centroid_Y0) / W0;
  Z0 += (z - Z0) / W0;
}

function centroidLineStart() {
  centroidStream.point = centroidLinePointFirst;
}

function centroidLinePointFirst(lambda, phi) {
  lambda *= radians, phi *= radians;
  var cosPhi = cos(phi);
  centroid_x0 = cosPhi * cos(lambda);
  centroid_y0 = cosPhi * sin(lambda);
  z0 = sin(phi);
  centroidStream.point = centroidLinePoint;
  centroidPointCartesian(centroid_x0, centroid_y0, z0);
}

function centroidLinePoint(lambda, phi) {
  lambda *= radians, phi *= radians;
  var cosPhi = cos(phi),
      x = cosPhi * cos(lambda),
      y = cosPhi * sin(lambda),
      z = sin(phi),
      w = atan2(sqrt((w = centroid_y0 * z - z0 * y) * w + (w = z0 * x - centroid_x0 * z) * w + (w = centroid_x0 * y - centroid_y0 * x) * w), centroid_x0 * x + centroid_y0 * y + z0 * z);
  W1 += w;
  centroid_X1 += w * (centroid_x0 + (centroid_x0 = x));
  centroid_Y1 += w * (centroid_y0 + (centroid_y0 = y));
  Z1 += w * (z0 + (z0 = z));
  centroidPointCartesian(centroid_x0, centroid_y0, z0);
}

function centroidLineEnd() {
  centroidStream.point = centroidPoint;
}

// See J. E. Brock, The Inertia Tensor for a Spherical Triangle,
// J. Applied Mechanics 42, 239 (1975).
function centroidRingStart() {
  centroidStream.point = centroidRingPointFirst;
}

function centroidRingEnd() {
  centroidRingPoint(centroid_lambda00, centroid_phi00);
  centroidStream.point = centroidPoint;
}

function centroidRingPointFirst(lambda, phi) {
  centroid_lambda00 = lambda, centroid_phi00 = phi;
  lambda *= radians, phi *= radians;
  centroidStream.point = centroidRingPoint;
  var cosPhi = cos(phi);
  centroid_x0 = cosPhi * cos(lambda);
  centroid_y0 = cosPhi * sin(lambda);
  z0 = sin(phi);
  centroidPointCartesian(centroid_x0, centroid_y0, z0);
}

function centroidRingPoint(lambda, phi) {
  lambda *= radians, phi *= radians;
  var cosPhi = cos(phi),
      x = cosPhi * cos(lambda),
      y = cosPhi * sin(lambda),
      z = sin(phi),
      cx = centroid_y0 * z - z0 * y,
      cy = z0 * x - centroid_x0 * z,
      cz = centroid_x0 * y - centroid_y0 * x,
      m = sqrt(cx * cx + cy * cy + cz * cz),
      w = asin(m), // line weight = angle
      v = m && -w / m; // area weight multiplier
  X2 += v * cx;
  Y2 += v * cy;
  Z2 += v * cz;
  W1 += w;
  centroid_X1 += w * (centroid_x0 + (centroid_x0 = x));
  centroid_Y1 += w * (centroid_y0 + (centroid_y0 = y));
  Z1 += w * (z0 + (z0 = z));
  centroidPointCartesian(centroid_x0, centroid_y0, z0);
}

/* harmony default export */ var centroid = (function(object) {
  W0 = W1 =
  centroid_X0 = centroid_Y0 = Z0 =
  centroid_X1 = centroid_Y1 = Z1 =
  X2 = Y2 = Z2 = 0;
  src_stream(object, centroidStream);

  var x = X2,
      y = Y2,
      z = Z2,
      m = x * x + y * y + z * z;

  // If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.
  if (m < epsilon2) {
    x = centroid_X1, y = centroid_Y1, z = Z1;
    // If the feature has zero length, fall back to arithmetic mean of point vectors.
    if (W1 < epsilon) x = centroid_X0, y = centroid_Y0, z = Z0;
    m = x * x + y * y + z * z;
    // If the feature still has an undefined ccentroid, then return.
    if (m < epsilon2) return [NaN, NaN];
  }

  return [atan2(y, x) * degrees, asin(z / sqrt(m)) * degrees];
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/constant.js
/* harmony default export */ var constant = (function(x) {
  return function() {
    return x;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/compose.js
/* harmony default export */ var compose = (function(a, b) {

  function compose(x, y) {
    return x = a(x, y), b(x[0], x[1]);
  }

  if (a.invert && b.invert) compose.invert = function(x, y) {
    return x = b.invert(x, y), x && a.invert(x[0], x[1]);
  };

  return compose;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/rotation.js



function rotationIdentity(lambda, phi) {
  return [abs(lambda) > pi ? lambda + Math.round(-lambda / tau) * tau : lambda, phi];
}

rotationIdentity.invert = rotationIdentity;

function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
  return (deltaLambda %= tau) ? (deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma))
    : rotationLambda(deltaLambda))
    : (deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma)
    : rotationIdentity);
}

function forwardRotationLambda(deltaLambda) {
  return function(lambda, phi) {
    return lambda += deltaLambda, [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];
  };
}

function rotationLambda(deltaLambda) {
  var rotation = forwardRotationLambda(deltaLambda);
  rotation.invert = forwardRotationLambda(-deltaLambda);
  return rotation;
}

function rotationPhiGamma(deltaPhi, deltaGamma) {
  var cosDeltaPhi = cos(deltaPhi),
      sinDeltaPhi = sin(deltaPhi),
      cosDeltaGamma = cos(deltaGamma),
      sinDeltaGamma = sin(deltaGamma);

  function rotation(lambda, phi) {
    var cosPhi = cos(phi),
        x = cos(lambda) * cosPhi,
        y = sin(lambda) * cosPhi,
        z = sin(phi),
        k = z * cosDeltaPhi + x * sinDeltaPhi;
    return [
      atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),
      asin(k * cosDeltaGamma + y * sinDeltaGamma)
    ];
  }

  rotation.invert = function(lambda, phi) {
    var cosPhi = cos(phi),
        x = cos(lambda) * cosPhi,
        y = sin(lambda) * cosPhi,
        z = sin(phi),
        k = z * cosDeltaGamma - y * sinDeltaGamma;
    return [
      atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),
      asin(k * cosDeltaPhi - x * sinDeltaPhi)
    ];
  };

  return rotation;
}

/* harmony default export */ var src_rotation = (function(rotate) {
  rotate = rotateRadians(rotate[0] * radians, rotate[1] * radians, rotate.length > 2 ? rotate[2] * radians : 0);

  function forward(coordinates) {
    coordinates = rotate(coordinates[0] * radians, coordinates[1] * radians);
    return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;
  }

  forward.invert = function(coordinates) {
    coordinates = rotate.invert(coordinates[0] * radians, coordinates[1] * radians);
    return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;
  };

  return forward;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/circle.js





// Generates a circle centered at [0°, 0°], with a given radius and precision.
function circleStream(stream, radius, delta, direction, t0, t1) {
  if (!delta) return;
  var cosRadius = cos(radius),
      sinRadius = sin(radius),
      step = direction * delta;
  if (t0 == null) {
    t0 = radius + direction * tau;
    t1 = radius - step / 2;
  } else {
    t0 = circleRadius(cosRadius, t0);
    t1 = circleRadius(cosRadius, t1);
    if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * tau;
  }
  for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {
    point = cartesian_spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);
    stream.point(point[0], point[1]);
  }
}

// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].
function circleRadius(cosRadius, point) {
  point = cartesian_cartesian(point), point[0] -= cosRadius;
  cartesianNormalizeInPlace(point);
  var radius = acos(-point[1]);
  return ((-point[2] < 0 ? -radius : radius) + tau - epsilon) % tau;
}

/* harmony default export */ var src_circle = (function() {
  var center = constant([0, 0]),
      radius = constant(90),
      precision = constant(6),
      ring,
      rotate,
      stream = {point: point};

  function point(x, y) {
    ring.push(x = rotate(x, y));
    x[0] *= degrees, x[1] *= degrees;
  }

  function circle() {
    var c = center.apply(this, arguments),
        r = radius.apply(this, arguments) * radians,
        p = precision.apply(this, arguments) * radians;
    ring = [];
    rotate = rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;
    circleStream(stream, r, p, 1);
    c = {type: "Polygon", coordinates: [ring]};
    ring = rotate = null;
    return c;
  }

  circle.center = function(_) {
    return arguments.length ? (center = typeof _ === "function" ? _ : constant([+_[0], +_[1]]), circle) : center;
  };

  circle.radius = function(_) {
    return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), circle) : radius;
  };

  circle.precision = function(_) {
    return arguments.length ? (precision = typeof _ === "function" ? _ : constant(+_), circle) : precision;
  };

  return circle;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/buffer.js


/* harmony default export */ var buffer = (function() {
  var lines = [],
      line;
  return {
    point: function(x, y) {
      line.push([x, y]);
    },
    lineStart: function() {
      lines.push(line = []);
    },
    lineEnd: noop,
    rejoin: function() {
      if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
    },
    result: function() {
      var result = lines;
      lines = [];
      line = null;
      return result;
    }
  };
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/pointEqual.js


/* harmony default export */ var pointEqual = (function(a, b) {
  return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/rejoin.js


function Intersection(point, points, other, entry) {
  this.x = point;
  this.z = points;
  this.o = other; // another intersection
  this.e = entry; // is an entry?
  this.v = false; // visited
  this.n = this.p = null; // next & previous
}

// A generalized polygon clipping algorithm: given a polygon that has been cut
// into its visible line segments, and rejoins the segments by interpolating
// along the clip edge.
/* harmony default export */ var rejoin = (function(segments, compareIntersection, startInside, interpolate, stream) {
  var subject = [],
      clip = [],
      i,
      n;

  segments.forEach(function(segment) {
    if ((n = segment.length - 1) <= 0) return;
    var n, p0 = segment[0], p1 = segment[n], x;

    // If the first and last points of a segment are coincident, then treat as a
    // closed ring. TODO if all rings are closed, then the winding order of the
    // exterior ring should be checked.
    if (pointEqual(p0, p1)) {
      stream.lineStart();
      for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);
      stream.lineEnd();
      return;
    }

    subject.push(x = new Intersection(p0, segment, null, true));
    clip.push(x.o = new Intersection(p0, null, x, false));
    subject.push(x = new Intersection(p1, segment, null, false));
    clip.push(x.o = new Intersection(p1, null, x, true));
  });

  if (!subject.length) return;

  clip.sort(compareIntersection);
  rejoin_link(subject);
  rejoin_link(clip);

  for (i = 0, n = clip.length; i < n; ++i) {
    clip[i].e = startInside = !startInside;
  }

  var start = subject[0],
      points,
      point;

  while (1) {
    // Find first unvisited intersection.
    var current = start,
        isSubject = true;
    while (current.v) if ((current = current.n) === start) return;
    points = current.z;
    stream.lineStart();
    do {
      current.v = current.o.v = true;
      if (current.e) {
        if (isSubject) {
          for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);
        } else {
          interpolate(current.x, current.n.x, 1, stream);
        }
        current = current.n;
      } else {
        if (isSubject) {
          points = current.p.z;
          for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);
        } else {
          interpolate(current.x, current.p.x, -1, stream);
        }
        current = current.p;
      }
      current = current.o;
      points = current.z;
      isSubject = !isSubject;
    } while (!current.v);
    stream.lineEnd();
  }
});

function rejoin_link(array) {
  if (!(n = array.length)) return;
  var n,
      i = 0,
      a = array[0],
      b;
  while (++i < n) {
    a.n = b = array[i];
    b.p = a;
    a = b;
  }
  a.n = b = array[0];
  b.p = a;
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/polygonContains.js




var sum = adder();

/* harmony default export */ var polygonContains = (function(polygon, point) {
  var lambda = point[0],
      phi = point[1],
      sinPhi = sin(phi),
      normal = [sin(lambda), -cos(lambda), 0],
      angle = 0,
      winding = 0;

  sum.reset();

  if (sinPhi === 1) phi = halfPi + epsilon;
  else if (sinPhi === -1) phi = -halfPi - epsilon;

  for (var i = 0, n = polygon.length; i < n; ++i) {
    if (!(m = (ring = polygon[i]).length)) continue;
    var ring,
        m,
        point0 = ring[m - 1],
        lambda0 = point0[0],
        phi0 = point0[1] / 2 + quarterPi,
        sinPhi0 = sin(phi0),
        cosPhi0 = cos(phi0);

    for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {
      var point1 = ring[j],
          lambda1 = point1[0],
          phi1 = point1[1] / 2 + quarterPi,
          sinPhi1 = sin(phi1),
          cosPhi1 = cos(phi1),
          delta = lambda1 - lambda0,
          sign = delta >= 0 ? 1 : -1,
          absDelta = sign * delta,
          antimeridian = absDelta > pi,
          k = sinPhi0 * sinPhi1;

      sum.add(atan2(k * sign * sin(absDelta), cosPhi0 * cosPhi1 + k * cos(absDelta)));
      angle += antimeridian ? delta + sign * tau : delta;

      // Are the longitudes either side of the point’s meridian (lambda),
      // and are the latitudes smaller than the parallel (phi)?
      if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
        var arc = cartesianCross(cartesian_cartesian(point0), cartesian_cartesian(point1));
        cartesianNormalizeInPlace(arc);
        var intersection = cartesianCross(normal, arc);
        cartesianNormalizeInPlace(intersection);
        var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);
        if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
          winding += antimeridian ^ delta >= 0 ? 1 : -1;
        }
      }
    }
  }

  // First, determine whether the South pole is inside or outside:
  //
  // It is inside if:
  // * the polygon winds around it in a clockwise direction.
  // * the polygon does not (cumulatively) wind around it, but has a negative
  //   (counter-clockwise) area.
  //
  // Second, count the (signed) number of times a segment crosses a lambda
  // from the point to the South pole.  If it is zero, then the point is the
  // same side as the South pole.

  return (angle < -epsilon || angle < epsilon && sum < -epsilon) ^ (winding & 1);
});

// EXTERNAL MODULE: ../node_modules/d3-array/src/index.js + 31 modules
var src = __nested_webpack_require_5017397__(8);

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/index.js






/* harmony default export */ var src_clip = (function(pointVisible, clipLine, interpolate, start) {
  return function(sink) {
    var line = clipLine(sink),
        ringBuffer = buffer(),
        ringSink = clipLine(ringBuffer),
        polygonStarted = false,
        polygon,
        segments,
        ring;

    var clip = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() {
        clip.point = pointRing;
        clip.lineStart = ringStart;
        clip.lineEnd = ringEnd;
        segments = [];
        polygon = [];
      },
      polygonEnd: function() {
        clip.point = point;
        clip.lineStart = lineStart;
        clip.lineEnd = lineEnd;
        segments = Object(src["merge"])(segments);
        var startInside = polygonContains(polygon, start);
        if (segments.length) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          rejoin(segments, clip_compareIntersection, startInside, interpolate, sink);
        } else if (startInside) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          sink.lineStart();
          interpolate(null, null, 1, sink);
          sink.lineEnd();
        }
        if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
        segments = polygon = null;
      },
      sphere: function() {
        sink.polygonStart();
        sink.lineStart();
        interpolate(null, null, 1, sink);
        sink.lineEnd();
        sink.polygonEnd();
      }
    };

    function point(lambda, phi) {
      if (pointVisible(lambda, phi)) sink.point(lambda, phi);
    }

    function pointLine(lambda, phi) {
      line.point(lambda, phi);
    }

    function lineStart() {
      clip.point = pointLine;
      line.lineStart();
    }

    function lineEnd() {
      clip.point = point;
      line.lineEnd();
    }

    function pointRing(lambda, phi) {
      ring.push([lambda, phi]);
      ringSink.point(lambda, phi);
    }

    function ringStart() {
      ringSink.lineStart();
      ring = [];
    }

    function ringEnd() {
      pointRing(ring[0][0], ring[0][1]);
      ringSink.lineEnd();

      var clean = ringSink.clean(),
          ringSegments = ringBuffer.result(),
          i, n = ringSegments.length, m,
          segment,
          point;

      ring.pop();
      polygon.push(ring);
      ring = null;

      if (!n) return;

      // No intersections.
      if (clean & 1) {
        segment = ringSegments[0];
        if ((m = segment.length - 1) > 0) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          sink.lineStart();
          for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);
          sink.lineEnd();
        }
        return;
      }

      // Rejoin connected segments.
      // TODO reuse ringBuffer.rejoin()?
      if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));

      segments.push(ringSegments.filter(validSegment));
    }

    return clip;
  };
});

function validSegment(segment) {
  return segment.length > 1;
}

// Intersections are sorted along the clip edge. For both antimeridian cutting
// and circle clipping, the same comparison is used.
function clip_compareIntersection(a, b) {
  return ((a = a.x)[0] < 0 ? a[1] - halfPi - epsilon : halfPi - a[1])
       - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon : halfPi - b[1]);
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/antimeridian.js



/* harmony default export */ var clip_antimeridian = (src_clip(
  function() { return true; },
  clipAntimeridianLine,
  clipAntimeridianInterpolate,
  [-pi, -halfPi]
));

// Takes a line and cuts into visible segments. Return values: 0 - there were
// intersections or the line was empty; 1 - no intersections; 2 - there were
// intersections, and the first and last segments should be rejoined.
function clipAntimeridianLine(stream) {
  var lambda0 = NaN,
      phi0 = NaN,
      sign0 = NaN,
      clean; // no intersections

  return {
    lineStart: function() {
      stream.lineStart();
      clean = 1;
    },
    point: function(lambda1, phi1) {
      var sign1 = lambda1 > 0 ? pi : -pi,
          delta = abs(lambda1 - lambda0);
      if (abs(delta - pi) < epsilon) { // line crosses a pole
        stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi : -halfPi);
        stream.point(sign0, phi0);
        stream.lineEnd();
        stream.lineStart();
        stream.point(sign1, phi0);
        stream.point(lambda1, phi0);
        clean = 0;
      } else if (sign0 !== sign1 && delta >= pi) { // line crosses antimeridian
        if (abs(lambda0 - sign0) < epsilon) lambda0 -= sign0 * epsilon; // handle degeneracies
        if (abs(lambda1 - sign1) < epsilon) lambda1 -= sign1 * epsilon;
        phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);
        stream.point(sign0, phi0);
        stream.lineEnd();
        stream.lineStart();
        stream.point(sign1, phi0);
        clean = 0;
      }
      stream.point(lambda0 = lambda1, phi0 = phi1);
      sign0 = sign1;
    },
    lineEnd: function() {
      stream.lineEnd();
      lambda0 = phi0 = NaN;
    },
    clean: function() {
      return 2 - clean; // if intersections, rejoin first and last segments
    }
  };
}

function clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {
  var cosPhi0,
      cosPhi1,
      sinLambda0Lambda1 = sin(lambda0 - lambda1);
  return abs(sinLambda0Lambda1) > epsilon
      ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1)
          - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0))
          / (cosPhi0 * cosPhi1 * sinLambda0Lambda1))
      : (phi0 + phi1) / 2;
}

function clipAntimeridianInterpolate(from, to, direction, stream) {
  var phi;
  if (from == null) {
    phi = direction * halfPi;
    stream.point(-pi, phi);
    stream.point(0, phi);
    stream.point(pi, phi);
    stream.point(pi, 0);
    stream.point(pi, -phi);
    stream.point(0, -phi);
    stream.point(-pi, -phi);
    stream.point(-pi, 0);
    stream.point(-pi, phi);
  } else if (abs(from[0] - to[0]) > epsilon) {
    var lambda = from[0] < to[0] ? pi : -pi;
    phi = direction * lambda / 2;
    stream.point(-lambda, phi);
    stream.point(0, phi);
    stream.point(lambda, phi);
  } else {
    stream.point(to[0], to[1]);
  }
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/circle.js






/* harmony default export */ var clip_circle = (function(radius) {
  var cr = cos(radius),
      delta = 6 * radians,
      smallRadius = cr > 0,
      notHemisphere = abs(cr) > epsilon; // TODO optimise for this common case

  function interpolate(from, to, direction, stream) {
    circleStream(stream, radius, delta, direction, from, to);
  }

  function visible(lambda, phi) {
    return cos(lambda) * cos(phi) > cr;
  }

  // Takes a line and cuts into visible segments. Return values used for polygon
  // clipping: 0 - there were intersections or the line was empty; 1 - no
  // intersections 2 - there were intersections, and the first and last segments
  // should be rejoined.
  function clipLine(stream) {
    var point0, // previous point
        c0, // code for previous point
        v0, // visibility of previous point
        v00, // visibility of first point
        clean; // no intersections
    return {
      lineStart: function() {
        v00 = v0 = false;
        clean = 1;
      },
      point: function(lambda, phi) {
        var point1 = [lambda, phi],
            point2,
            v = visible(lambda, phi),
            c = smallRadius
              ? v ? 0 : code(lambda, phi)
              : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0;
        if (!point0 && (v00 = v0 = v)) stream.lineStart();
        // Handle degeneracies.
        // TODO ignore if not clipping polygons.
        if (v !== v0) {
          point2 = intersect(point0, point1);
          if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2)) {
            point1[0] += epsilon;
            point1[1] += epsilon;
            v = visible(point1[0], point1[1]);
          }
        }
        if (v !== v0) {
          clean = 0;
          if (v) {
            // outside going in
            stream.lineStart();
            point2 = intersect(point1, point0);
            stream.point(point2[0], point2[1]);
          } else {
            // inside going out
            point2 = intersect(point0, point1);
            stream.point(point2[0], point2[1]);
            stream.lineEnd();
          }
          point0 = point2;
        } else if (notHemisphere && point0 && smallRadius ^ v) {
          var t;
          // If the codes for two points are different, or are both zero,
          // and there this segment intersects with the small circle.
          if (!(c & c0) && (t = intersect(point1, point0, true))) {
            clean = 0;
            if (smallRadius) {
              stream.lineStart();
              stream.point(t[0][0], t[0][1]);
              stream.point(t[1][0], t[1][1]);
              stream.lineEnd();
            } else {
              stream.point(t[1][0], t[1][1]);
              stream.lineEnd();
              stream.lineStart();
              stream.point(t[0][0], t[0][1]);
            }
          }
        }
        if (v && (!point0 || !pointEqual(point0, point1))) {
          stream.point(point1[0], point1[1]);
        }
        point0 = point1, v0 = v, c0 = c;
      },
      lineEnd: function() {
        if (v0) stream.lineEnd();
        point0 = null;
      },
      // Rejoin first and last segments if there were intersections and the first
      // and last points were visible.
      clean: function() {
        return clean | ((v00 && v0) << 1);
      }
    };
  }

  // Intersects the great circle between a and b with the clip circle.
  function intersect(a, b, two) {
    var pa = cartesian_cartesian(a),
        pb = cartesian_cartesian(b);

    // We have two planes, n1.p = d1 and n2.p = d2.
    // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).
    var n1 = [1, 0, 0], // normal
        n2 = cartesianCross(pa, pb),
        n2n2 = cartesianDot(n2, n2),
        n1n2 = n2[0], // cartesianDot(n1, n2),
        determinant = n2n2 - n1n2 * n1n2;

    // Two polar points.
    if (!determinant) return !two && a;

    var c1 =  cr * n2n2 / determinant,
        c2 = -cr * n1n2 / determinant,
        n1xn2 = cartesianCross(n1, n2),
        A = cartesianScale(n1, c1),
        B = cartesianScale(n2, c2);
    cartesianAddInPlace(A, B);

    // Solve |p(t)|^2 = 1.
    var u = n1xn2,
        w = cartesianDot(A, u),
        uu = cartesianDot(u, u),
        t2 = w * w - uu * (cartesianDot(A, A) - 1);

    if (t2 < 0) return;

    var t = sqrt(t2),
        q = cartesianScale(u, (-w - t) / uu);
    cartesianAddInPlace(q, A);
    q = cartesian_spherical(q);

    if (!two) return q;

    // Two intersection points.
    var lambda0 = a[0],
        lambda1 = b[0],
        phi0 = a[1],
        phi1 = b[1],
        z;

    if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;

    var delta = lambda1 - lambda0,
        polar = abs(delta - pi) < epsilon,
        meridian = polar || delta < epsilon;

    if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;

    // Check that the first point is between a and b.
    if (meridian
        ? polar
          ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1)
          : phi0 <= q[1] && q[1] <= phi1
        : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
      var q1 = cartesianScale(u, (-w + t) / uu);
      cartesianAddInPlace(q1, A);
      return [q, cartesian_spherical(q1)];
    }
  }

  // Generates a 4-bit vector representing the location of a point relative to
  // the small circle's bounding box.
  function code(lambda, phi) {
    var r = smallRadius ? radius : pi - radius,
        code = 0;
    if (lambda < -r) code |= 1; // left
    else if (lambda > r) code |= 2; // right
    if (phi < -r) code |= 4; // below
    else if (phi > r) code |= 8; // above
    return code;
  }

  return src_clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi, radius - pi]);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/line.js
/* harmony default export */ var clip_line = (function(a, b, x0, y0, x1, y1) {
  var ax = a[0],
      ay = a[1],
      bx = b[0],
      by = b[1],
      t0 = 0,
      t1 = 1,
      dx = bx - ax,
      dy = by - ay,
      r;

  r = x0 - ax;
  if (!dx && r > 0) return;
  r /= dx;
  if (dx < 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  } else if (dx > 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  }

  r = x1 - ax;
  if (!dx && r < 0) return;
  r /= dx;
  if (dx < 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  } else if (dx > 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  }

  r = y0 - ay;
  if (!dy && r > 0) return;
  r /= dy;
  if (dy < 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  } else if (dy > 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  }

  r = y1 - ay;
  if (!dy && r < 0) return;
  r /= dy;
  if (dy < 0) {
    if (r > t1) return;
    if (r > t0) t0 = r;
  } else if (dy > 0) {
    if (r < t0) return;
    if (r < t1) t1 = r;
  }

  if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;
  if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;
  return true;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/rectangle.js






var clipMax = 1e9, clipMin = -clipMax;

// TODO Use d3-polygon’s polygonContains here for the ring check?
// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?

function clipRectangle(x0, y0, x1, y1) {

  function visible(x, y) {
    return x0 <= x && x <= x1 && y0 <= y && y <= y1;
  }

  function interpolate(from, to, direction, stream) {
    var a = 0, a1 = 0;
    if (from == null
        || (a = corner(from, direction)) !== (a1 = corner(to, direction))
        || comparePoint(from, to) < 0 ^ direction > 0) {
      do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
      while ((a = (a + direction + 4) % 4) !== a1);
    } else {
      stream.point(to[0], to[1]);
    }
  }

  function corner(p, direction) {
    return abs(p[0] - x0) < epsilon ? direction > 0 ? 0 : 3
        : abs(p[0] - x1) < epsilon ? direction > 0 ? 2 : 1
        : abs(p[1] - y0) < epsilon ? direction > 0 ? 1 : 0
        : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon
  }

  function compareIntersection(a, b) {
    return comparePoint(a.x, b.x);
  }

  function comparePoint(a, b) {
    var ca = corner(a, 1),
        cb = corner(b, 1);
    return ca !== cb ? ca - cb
        : ca === 0 ? b[1] - a[1]
        : ca === 1 ? a[0] - b[0]
        : ca === 2 ? a[1] - b[1]
        : b[0] - a[0];
  }

  return function(stream) {
    var activeStream = stream,
        bufferStream = buffer(),
        segments,
        polygon,
        ring,
        x__, y__, v__, // first point
        x_, y_, v_, // previous point
        first,
        clean;

    var clipStream = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: polygonStart,
      polygonEnd: polygonEnd
    };

    function point(x, y) {
      if (visible(x, y)) activeStream.point(x, y);
    }

    function polygonInside() {
      var winding = 0;

      for (var i = 0, n = polygon.length; i < n; ++i) {
        for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {
          a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];
          if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }
          else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }
        }
      }

      return winding;
    }

    // Buffer geometry within a polygon and then clip it en masse.
    function polygonStart() {
      activeStream = bufferStream, segments = [], polygon = [], clean = true;
    }

    function polygonEnd() {
      var startInside = polygonInside(),
          cleanInside = clean && startInside,
          visible = (segments = Object(src["merge"])(segments)).length;
      if (cleanInside || visible) {
        stream.polygonStart();
        if (cleanInside) {
          stream.lineStart();
          interpolate(null, null, 1, stream);
          stream.lineEnd();
        }
        if (visible) {
          rejoin(segments, compareIntersection, startInside, interpolate, stream);
        }
        stream.polygonEnd();
      }
      activeStream = stream, segments = polygon = ring = null;
    }

    function lineStart() {
      clipStream.point = linePoint;
      if (polygon) polygon.push(ring = []);
      first = true;
      v_ = false;
      x_ = y_ = NaN;
    }

    // TODO rather than special-case polygons, simply handle them separately.
    // Ideally, coincident intersection points should be jittered to avoid
    // clipping issues.
    function lineEnd() {
      if (segments) {
        linePoint(x__, y__);
        if (v__ && v_) bufferStream.rejoin();
        segments.push(bufferStream.result());
      }
      clipStream.point = point;
      if (v_) activeStream.lineEnd();
    }

    function linePoint(x, y) {
      var v = visible(x, y);
      if (polygon) ring.push([x, y]);
      if (first) {
        x__ = x, y__ = y, v__ = v;
        first = false;
        if (v) {
          activeStream.lineStart();
          activeStream.point(x, y);
        }
      } else {
        if (v && v_) activeStream.point(x, y);
        else {
          var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))],
              b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))];
          if (clip_line(a, b, x0, y0, x1, y1)) {
            if (!v_) {
              activeStream.lineStart();
              activeStream.point(a[0], a[1]);
            }
            activeStream.point(b[0], b[1]);
            if (!v) activeStream.lineEnd();
            clean = false;
          } else if (v) {
            activeStream.lineStart();
            activeStream.point(x, y);
            clean = false;
          }
        }
      }
      x_ = x, y_ = y, v_ = v;
    }

    return clipStream;
  };
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/clip/extent.js


/* harmony default export */ var clip_extent = (function() {
  var x0 = 0,
      y0 = 0,
      x1 = 960,
      y1 = 500,
      cache,
      cacheStream,
      clip;

  return clip = {
    stream: function(stream) {
      return cache && cacheStream === stream ? cache : cache = clipRectangle(x0, y0, x1, y1)(cacheStream = stream);
    },
    extent: function(_) {
      return arguments.length ? (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1], cache = cacheStream = null, clip) : [[x0, y0], [x1, y1]];
    }
  };
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/length.js





var lengthSum = adder(),
    length_lambda0,
    length_sinPhi0,
    length_cosPhi0;

var lengthStream = {
  sphere: noop,
  point: noop,
  lineStart: lengthLineStart,
  lineEnd: noop,
  polygonStart: noop,
  polygonEnd: noop
};

function lengthLineStart() {
  lengthStream.point = lengthPointFirst;
  lengthStream.lineEnd = lengthLineEnd;
}

function lengthLineEnd() {
  lengthStream.point = lengthStream.lineEnd = noop;
}

function lengthPointFirst(lambda, phi) {
  lambda *= radians, phi *= radians;
  length_lambda0 = lambda, length_sinPhi0 = sin(phi), length_cosPhi0 = cos(phi);
  lengthStream.point = lengthPoint;
}

function lengthPoint(lambda, phi) {
  lambda *= radians, phi *= radians;
  var sinPhi = sin(phi),
      cosPhi = cos(phi),
      delta = abs(lambda - length_lambda0),
      cosDelta = cos(delta),
      sinDelta = sin(delta),
      x = cosPhi * sinDelta,
      y = length_cosPhi0 * sinPhi - length_sinPhi0 * cosPhi * cosDelta,
      z = length_sinPhi0 * sinPhi + length_cosPhi0 * cosPhi * cosDelta;
  lengthSum.add(atan2(sqrt(x * x + y * y), z));
  length_lambda0 = lambda, length_sinPhi0 = sinPhi, length_cosPhi0 = cosPhi;
}

/* harmony default export */ var src_length = (function(object) {
  lengthSum.reset();
  src_stream(object, lengthStream);
  return +lengthSum;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/distance.js


var distance_coordinates = [null, null],
    distance_object = {type: "LineString", coordinates: distance_coordinates};

/* harmony default export */ var distance = (function(a, b) {
  distance_coordinates[0] = a;
  distance_coordinates[1] = b;
  return src_length(distance_object);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/contains.js




var containsObjectType = {
  Feature: function(object, point) {
    return containsGeometry(object.geometry, point);
  },
  FeatureCollection: function(object, point) {
    var features = object.features, i = -1, n = features.length;
    while (++i < n) if (containsGeometry(features[i].geometry, point)) return true;
    return false;
  }
};

var containsGeometryType = {
  Sphere: function() {
    return true;
  },
  Point: function(object, point) {
    return containsPoint(object.coordinates, point);
  },
  MultiPoint: function(object, point) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) if (containsPoint(coordinates[i], point)) return true;
    return false;
  },
  LineString: function(object, point) {
    return containsLine(object.coordinates, point);
  },
  MultiLineString: function(object, point) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) if (containsLine(coordinates[i], point)) return true;
    return false;
  },
  Polygon: function(object, point) {
    return containsPolygon(object.coordinates, point);
  },
  MultiPolygon: function(object, point) {
    var coordinates = object.coordinates, i = -1, n = coordinates.length;
    while (++i < n) if (containsPolygon(coordinates[i], point)) return true;
    return false;
  },
  GeometryCollection: function(object, point) {
    var geometries = object.geometries, i = -1, n = geometries.length;
    while (++i < n) if (containsGeometry(geometries[i], point)) return true;
    return false;
  }
};

function containsGeometry(geometry, point) {
  return geometry && containsGeometryType.hasOwnProperty(geometry.type)
      ? containsGeometryType[geometry.type](geometry, point)
      : false;
}

function containsPoint(coordinates, point) {
  return distance(coordinates, point) === 0;
}

function containsLine(coordinates, point) {
  var ab = distance(coordinates[0], coordinates[1]),
      ao = distance(coordinates[0], point),
      ob = distance(point, coordinates[1]);
  return ao + ob <= ab + epsilon;
}

function containsPolygon(coordinates, point) {
  return !!polygonContains(coordinates.map(ringRadians), pointRadians(point));
}

function ringRadians(ring) {
  return ring = ring.map(pointRadians), ring.pop(), ring;
}

function pointRadians(point) {
  return [point[0] * radians, point[1] * radians];
}

/* harmony default export */ var contains = (function(object, point) {
  return (object && containsObjectType.hasOwnProperty(object.type)
      ? containsObjectType[object.type]
      : containsGeometry)(object, point);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/graticule.js



function graticuleX(y0, y1, dy) {
  var y = Object(src["range"])(y0, y1 - epsilon, dy).concat(y1);
  return function(x) { return y.map(function(y) { return [x, y]; }); };
}

function graticuleY(x0, x1, dx) {
  var x = Object(src["range"])(x0, x1 - epsilon, dx).concat(x1);
  return function(y) { return x.map(function(x) { return [x, y]; }); };
}

function graticule_graticule() {
  var x1, x0, X1, X0,
      y1, y0, Y1, Y0,
      dx = 10, dy = dx, DX = 90, DY = 360,
      x, y, X, Y,
      precision = 2.5;

  function graticule() {
    return {type: "MultiLineString", coordinates: lines()};
  }

  function lines() {
    return Object(src["range"])(ceil(X0 / DX) * DX, X1, DX).map(X)
        .concat(Object(src["range"])(ceil(Y0 / DY) * DY, Y1, DY).map(Y))
        .concat(Object(src["range"])(ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > epsilon; }).map(x))
        .concat(Object(src["range"])(ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > epsilon; }).map(y));
  }

  graticule.lines = function() {
    return lines().map(function(coordinates) { return {type: "LineString", coordinates: coordinates}; });
  };

  graticule.outline = function() {
    return {
      type: "Polygon",
      coordinates: [
        X(X0).concat(
        Y(Y1).slice(1),
        X(X1).reverse().slice(1),
        Y(Y0).reverse().slice(1))
      ]
    };
  };

  graticule.extent = function(_) {
    if (!arguments.length) return graticule.extentMinor();
    return graticule.extentMajor(_).extentMinor(_);
  };

  graticule.extentMajor = function(_) {
    if (!arguments.length) return [[X0, Y0], [X1, Y1]];
    X0 = +_[0][0], X1 = +_[1][0];
    Y0 = +_[0][1], Y1 = +_[1][1];
    if (X0 > X1) _ = X0, X0 = X1, X1 = _;
    if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
    return graticule.precision(precision);
  };

  graticule.extentMinor = function(_) {
    if (!arguments.length) return [[x0, y0], [x1, y1]];
    x0 = +_[0][0], x1 = +_[1][0];
    y0 = +_[0][1], y1 = +_[1][1];
    if (x0 > x1) _ = x0, x0 = x1, x1 = _;
    if (y0 > y1) _ = y0, y0 = y1, y1 = _;
    return graticule.precision(precision);
  };

  graticule.step = function(_) {
    if (!arguments.length) return graticule.stepMinor();
    return graticule.stepMajor(_).stepMinor(_);
  };

  graticule.stepMajor = function(_) {
    if (!arguments.length) return [DX, DY];
    DX = +_[0], DY = +_[1];
    return graticule;
  };

  graticule.stepMinor = function(_) {
    if (!arguments.length) return [dx, dy];
    dx = +_[0], dy = +_[1];
    return graticule;
  };

  graticule.precision = function(_) {
    if (!arguments.length) return precision;
    precision = +_;
    x = graticuleX(y0, y1, 90);
    y = graticuleY(x0, x1, precision);
    X = graticuleX(Y0, Y1, 90);
    Y = graticuleY(X0, X1, precision);
    return graticule;
  };

  return graticule
      .extentMajor([[-180, -90 + epsilon], [180, 90 - epsilon]])
      .extentMinor([[-180, -80 - epsilon], [180, 80 + epsilon]]);
}

function graticule10() {
  return graticule_graticule()();
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/interpolate.js


/* harmony default export */ var src_interpolate = (function(a, b) {
  var x0 = a[0] * radians,
      y0 = a[1] * radians,
      x1 = b[0] * radians,
      y1 = b[1] * radians,
      cy0 = cos(y0),
      sy0 = sin(y0),
      cy1 = cos(y1),
      sy1 = sin(y1),
      kx0 = cy0 * cos(x0),
      ky0 = cy0 * sin(x0),
      kx1 = cy1 * cos(x1),
      ky1 = cy1 * sin(x1),
      d = 2 * asin(sqrt(haversin(y1 - y0) + cy0 * cy1 * haversin(x1 - x0))),
      k = sin(d);

  var interpolate = d ? function(t) {
    var B = sin(t *= d) / k,
        A = sin(d - t) / k,
        x = A * kx0 + B * kx1,
        y = A * ky0 + B * ky1,
        z = A * sy0 + B * sy1;
    return [
      atan2(y, x) * degrees,
      atan2(z, sqrt(x * x + y * y)) * degrees
    ];
  } : function() {
    return [x0 * degrees, y0 * degrees];
  };

  interpolate.distance = d;

  return interpolate;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/identity.js
/* harmony default export */ var identity = (function(x) {
  return x;
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/area.js




var area_areaSum = adder(),
    area_areaRingSum = adder(),
    area_x00,
    area_y00,
    area_x0,
    area_y0;

var area_areaStream = {
  point: noop,
  lineStart: noop,
  lineEnd: noop,
  polygonStart: function() {
    area_areaStream.lineStart = area_areaRingStart;
    area_areaStream.lineEnd = area_areaRingEnd;
  },
  polygonEnd: function() {
    area_areaStream.lineStart = area_areaStream.lineEnd = area_areaStream.point = noop;
    area_areaSum.add(abs(area_areaRingSum));
    area_areaRingSum.reset();
  },
  result: function() {
    var area = area_areaSum / 2;
    area_areaSum.reset();
    return area;
  }
};

function area_areaRingStart() {
  area_areaStream.point = area_areaPointFirst;
}

function area_areaPointFirst(x, y) {
  area_areaStream.point = area_areaPoint;
  area_x00 = area_x0 = x, area_y00 = area_y0 = y;
}

function area_areaPoint(x, y) {
  area_areaRingSum.add(area_y0 * x - area_x0 * y);
  area_x0 = x, area_y0 = y;
}

function area_areaRingEnd() {
  area_areaPoint(area_x00, area_y00);
}

/* harmony default export */ var path_area = (area_areaStream);

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/bounds.js


var bounds_x0 = Infinity,
    bounds_y0 = bounds_x0,
    bounds_x1 = -bounds_x0,
    bounds_y1 = bounds_x1;

var bounds_boundsStream = {
  point: bounds_boundsPoint,
  lineStart: noop,
  lineEnd: noop,
  polygonStart: noop,
  polygonEnd: noop,
  result: function() {
    var bounds = [[bounds_x0, bounds_y0], [bounds_x1, bounds_y1]];
    bounds_x1 = bounds_y1 = -(bounds_y0 = bounds_x0 = Infinity);
    return bounds;
  }
};

function bounds_boundsPoint(x, y) {
  if (x < bounds_x0) bounds_x0 = x;
  if (x > bounds_x1) bounds_x1 = x;
  if (y < bounds_y0) bounds_y0 = y;
  if (y > bounds_y1) bounds_y1 = y;
}

/* harmony default export */ var path_bounds = (bounds_boundsStream);

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/centroid.js


// TODO Enforce positive area for exterior, negative area for interior?

var path_centroid_X0 = 0,
    path_centroid_Y0 = 0,
    centroid_Z0 = 0,
    path_centroid_X1 = 0,
    path_centroid_Y1 = 0,
    centroid_Z1 = 0,
    centroid_X2 = 0,
    centroid_Y2 = 0,
    centroid_Z2 = 0,
    centroid_x00,
    centroid_y00,
    path_centroid_x0,
    path_centroid_y0;

var centroid_centroidStream = {
  point: centroid_centroidPoint,
  lineStart: centroid_centroidLineStart,
  lineEnd: centroid_centroidLineEnd,
  polygonStart: function() {
    centroid_centroidStream.lineStart = centroid_centroidRingStart;
    centroid_centroidStream.lineEnd = centroid_centroidRingEnd;
  },
  polygonEnd: function() {
    centroid_centroidStream.point = centroid_centroidPoint;
    centroid_centroidStream.lineStart = centroid_centroidLineStart;
    centroid_centroidStream.lineEnd = centroid_centroidLineEnd;
  },
  result: function() {
    var centroid = centroid_Z2 ? [centroid_X2 / centroid_Z2, centroid_Y2 / centroid_Z2]
        : centroid_Z1 ? [path_centroid_X1 / centroid_Z1, path_centroid_Y1 / centroid_Z1]
        : centroid_Z0 ? [path_centroid_X0 / centroid_Z0, path_centroid_Y0 / centroid_Z0]
        : [NaN, NaN];
    path_centroid_X0 = path_centroid_Y0 = centroid_Z0 =
    path_centroid_X1 = path_centroid_Y1 = centroid_Z1 =
    centroid_X2 = centroid_Y2 = centroid_Z2 = 0;
    return centroid;
  }
};

function centroid_centroidPoint(x, y) {
  path_centroid_X0 += x;
  path_centroid_Y0 += y;
  ++centroid_Z0;
}

function centroid_centroidLineStart() {
  centroid_centroidStream.point = centroidPointFirstLine;
}

function centroidPointFirstLine(x, y) {
  centroid_centroidStream.point = centroidPointLine;
  centroid_centroidPoint(path_centroid_x0 = x, path_centroid_y0 = y);
}

function centroidPointLine(x, y) {
  var dx = x - path_centroid_x0, dy = y - path_centroid_y0, z = sqrt(dx * dx + dy * dy);
  path_centroid_X1 += z * (path_centroid_x0 + x) / 2;
  path_centroid_Y1 += z * (path_centroid_y0 + y) / 2;
  centroid_Z1 += z;
  centroid_centroidPoint(path_centroid_x0 = x, path_centroid_y0 = y);
}

function centroid_centroidLineEnd() {
  centroid_centroidStream.point = centroid_centroidPoint;
}

function centroid_centroidRingStart() {
  centroid_centroidStream.point = centroidPointFirstRing;
}

function centroid_centroidRingEnd() {
  centroidPointRing(centroid_x00, centroid_y00);
}

function centroidPointFirstRing(x, y) {
  centroid_centroidStream.point = centroidPointRing;
  centroid_centroidPoint(centroid_x00 = path_centroid_x0 = x, centroid_y00 = path_centroid_y0 = y);
}

function centroidPointRing(x, y) {
  var dx = x - path_centroid_x0,
      dy = y - path_centroid_y0,
      z = sqrt(dx * dx + dy * dy);

  path_centroid_X1 += z * (path_centroid_x0 + x) / 2;
  path_centroid_Y1 += z * (path_centroid_y0 + y) / 2;
  centroid_Z1 += z;

  z = path_centroid_y0 * x - path_centroid_x0 * y;
  centroid_X2 += z * (path_centroid_x0 + x);
  centroid_Y2 += z * (path_centroid_y0 + y);
  centroid_Z2 += z * 3;
  centroid_centroidPoint(path_centroid_x0 = x, path_centroid_y0 = y);
}

/* harmony default export */ var path_centroid = (centroid_centroidStream);

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/context.js



function PathContext(context) {
  this._context = context;
}

PathContext.prototype = {
  _radius: 4.5,
  pointRadius: function(_) {
    return this._radius = _, this;
  },
  polygonStart: function() {
    this._line = 0;
  },
  polygonEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line === 0) this._context.closePath();
    this._point = NaN;
  },
  point: function(x, y) {
    switch (this._point) {
      case 0: {
        this._context.moveTo(x, y);
        this._point = 1;
        break;
      }
      case 1: {
        this._context.lineTo(x, y);
        break;
      }
      default: {
        this._context.moveTo(x + this._radius, y);
        this._context.arc(x, y, this._radius, 0, tau);
        break;
      }
    }
  },
  result: noop
};

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/measure.js




var measure_lengthSum = adder(),
    lengthRing,
    measure_x00,
    measure_y00,
    measure_x0,
    measure_y0;

var measure_lengthStream = {
  point: noop,
  lineStart: function() {
    measure_lengthStream.point = measure_lengthPointFirst;
  },
  lineEnd: function() {
    if (lengthRing) measure_lengthPoint(measure_x00, measure_y00);
    measure_lengthStream.point = noop;
  },
  polygonStart: function() {
    lengthRing = true;
  },
  polygonEnd: function() {
    lengthRing = null;
  },
  result: function() {
    var length = +measure_lengthSum;
    measure_lengthSum.reset();
    return length;
  }
};

function measure_lengthPointFirst(x, y) {
  measure_lengthStream.point = measure_lengthPoint;
  measure_x00 = measure_x0 = x, measure_y00 = measure_y0 = y;
}

function measure_lengthPoint(x, y) {
  measure_x0 -= x, measure_y0 -= y;
  measure_lengthSum.add(sqrt(measure_x0 * measure_x0 + measure_y0 * measure_y0));
  measure_x0 = x, measure_y0 = y;
}

/* harmony default export */ var measure = (measure_lengthStream);

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/string.js
function PathString() {
  this._string = [];
}

PathString.prototype = {
  _radius: 4.5,
  _circle: string_circle(4.5),
  pointRadius: function(_) {
    if ((_ = +_) !== this._radius) this._radius = _, this._circle = null;
    return this;
  },
  polygonStart: function() {
    this._line = 0;
  },
  polygonEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line === 0) this._string.push("Z");
    this._point = NaN;
  },
  point: function(x, y) {
    switch (this._point) {
      case 0: {
        this._string.push("M", x, ",", y);
        this._point = 1;
        break;
      }
      case 1: {
        this._string.push("L", x, ",", y);
        break;
      }
      default: {
        if (this._circle == null) this._circle = string_circle(this._radius);
        this._string.push("M", x, ",", y, this._circle);
        break;
      }
    }
  },
  result: function() {
    if (this._string.length) {
      var result = this._string.join("");
      this._string = [];
      return result;
    } else {
      return null;
    }
  }
};

function string_circle(radius) {
  return "m0," + radius
      + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius
      + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius
      + "z";
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/path/index.js









/* harmony default export */ var src_path = (function(projection, context) {
  var pointRadius = 4.5,
      projectionStream,
      contextStream;

  function path(object) {
    if (object) {
      if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
      src_stream(object, projectionStream(contextStream));
    }
    return contextStream.result();
  }

  path.area = function(object) {
    src_stream(object, projectionStream(path_area));
    return path_area.result();
  };

  path.measure = function(object) {
    src_stream(object, projectionStream(measure));
    return measure.result();
  };

  path.bounds = function(object) {
    src_stream(object, projectionStream(path_bounds));
    return path_bounds.result();
  };

  path.centroid = function(object) {
    src_stream(object, projectionStream(path_centroid));
    return path_centroid.result();
  };

  path.projection = function(_) {
    return arguments.length ? (projectionStream = _ == null ? (projection = null, identity) : (projection = _).stream, path) : projection;
  };

  path.context = function(_) {
    if (!arguments.length) return context;
    contextStream = _ == null ? (context = null, new PathString) : new PathContext(context = _);
    if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
    return path;
  };

  path.pointRadius = function(_) {
    if (!arguments.length) return pointRadius;
    pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
    return path;
  };

  return path.projection(projection).context(context);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/transform.js
/* harmony default export */ var src_transform = (function(methods) {
  return {
    stream: transformer(methods)
  };
});

function transformer(methods) {
  return function(stream) {
    var s = new TransformStream;
    for (var key in methods) s[key] = methods[key];
    s.stream = stream;
    return s;
  };
}

function TransformStream() {}

TransformStream.prototype = {
  constructor: TransformStream,
  point: function(x, y) { this.stream.point(x, y); },
  sphere: function() { this.stream.sphere(); },
  lineStart: function() { this.stream.lineStart(); },
  lineEnd: function() { this.stream.lineEnd(); },
  polygonStart: function() { this.stream.polygonStart(); },
  polygonEnd: function() { this.stream.polygonEnd(); }
};

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/fit.js



function fit(projection, fitBounds, object) {
  var clip = projection.clipExtent && projection.clipExtent();
  projection.scale(150).translate([0, 0]);
  if (clip != null) projection.clipExtent(null);
  src_stream(object, projection.stream(path_bounds));
  fitBounds(path_bounds.result());
  if (clip != null) projection.clipExtent(clip);
  return projection;
}

function fitExtent(projection, extent, object) {
  return fit(projection, function(b) {
    var w = extent[1][0] - extent[0][0],
        h = extent[1][1] - extent[0][1],
        k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),
        x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,
        y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
    projection.scale(150 * k).translate([x, y]);
  }, object);
}

function fitSize(projection, size, object) {
  return fitExtent(projection, [[0, 0], size], object);
}

function fitWidth(projection, width, object) {
  return fit(projection, function(b) {
    var w = +width,
        k = w / (b[1][0] - b[0][0]),
        x = (w - k * (b[1][0] + b[0][0])) / 2,
        y = -k * b[0][1];
    projection.scale(150 * k).translate([x, y]);
  }, object);
}

function fitHeight(projection, height, object) {
  return fit(projection, function(b) {
    var h = +height,
        k = h / (b[1][1] - b[0][1]),
        x = -k * b[0][0],
        y = (h - k * (b[1][1] + b[0][1])) / 2;
    projection.scale(150 * k).translate([x, y]);
  }, object);
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/resample.js




var maxDepth = 16, // maximum depth of subdivision
    cosMinDistance = cos(30 * radians); // cos(minimum angular distance)

/* harmony default export */ var resample = (function(project, delta2) {
  return +delta2 ? resample_resample(project, delta2) : resampleNone(project);
});

function resampleNone(project) {
  return transformer({
    point: function(x, y) {
      x = project(x, y);
      this.stream.point(x[0], x[1]);
    }
  });
}

function resample_resample(project, delta2) {

  function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {
    var dx = x1 - x0,
        dy = y1 - y0,
        d2 = dx * dx + dy * dy;
    if (d2 > 4 * delta2 && depth--) {
      var a = a0 + a1,
          b = b0 + b1,
          c = c0 + c1,
          m = sqrt(a * a + b * b + c * c),
          phi2 = asin(c /= m),
          lambda2 = abs(abs(c) - 1) < epsilon || abs(lambda0 - lambda1) < epsilon ? (lambda0 + lambda1) / 2 : atan2(b, a),
          p = project(lambda2, phi2),
          x2 = p[0],
          y2 = p[1],
          dx2 = x2 - x0,
          dy2 = y2 - y0,
          dz = dy * dx2 - dx * dy2;
      if (dz * dz / d2 > delta2 // perpendicular projected distance
          || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end
          || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { // angular distance
        resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);
        stream.point(x2, y2);
        resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);
      }
    }
  }
  return function(stream) {
    var lambda00, x00, y00, a00, b00, c00, // first point
        lambda0, x0, y0, a0, b0, c0; // previous point

    var resampleStream = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },
      polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }
    };

    function point(x, y) {
      x = project(x, y);
      stream.point(x[0], x[1]);
    }

    function lineStart() {
      x0 = NaN;
      resampleStream.point = linePoint;
      stream.lineStart();
    }

    function linePoint(lambda, phi) {
      var c = cartesian_cartesian([lambda, phi]), p = project(lambda, phi);
      resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
      stream.point(x0, y0);
    }

    function lineEnd() {
      resampleStream.point = point;
      stream.lineEnd();
    }

    function ringStart() {
      lineStart();
      resampleStream.point = ringPoint;
      resampleStream.lineEnd = ringEnd;
    }

    function ringPoint(lambda, phi) {
      linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
      resampleStream.point = linePoint;
    }

    function ringEnd() {
      resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, maxDepth, stream);
      resampleStream.lineEnd = lineEnd;
      lineEnd();
    }

    return resampleStream;
  };
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/index.js











var transformRadians = transformer({
  point: function(x, y) {
    this.stream.point(x * radians, y * radians);
  }
});

function transformRotate(rotate) {
  return transformer({
    point: function(x, y) {
      var r = rotate(x, y);
      return this.stream.point(r[0], r[1]);
    }
  });
}

function scaleTranslate(k, dx, dy) {
  function transform(x, y) {
    return [dx + k * x, dy - k * y];
  }
  transform.invert = function(x, y) {
    return [(x - dx) / k, (dy - y) / k];
  };
  return transform;
}

function scaleTranslateRotate(k, dx, dy, alpha) {
  var cosAlpha = cos(alpha),
      sinAlpha = sin(alpha),
      a = cosAlpha * k,
      b = sinAlpha * k,
      ai = cosAlpha / k,
      bi = sinAlpha / k,
      ci = (sinAlpha * dy - cosAlpha * dx) / k,
      fi = (sinAlpha * dx + cosAlpha * dy) / k;
  function transform(x, y) {
    return [a * x - b * y + dx, dy - b * x - a * y];
  }
  transform.invert = function(x, y) {
    return [ai * x - bi * y + ci, fi - bi * x - ai * y];
  };
  return transform;
}

function projection_projection(project) {
  return projectionMutator(function() { return project; })();
}

function projectionMutator(projectAt) {
  var project,
      k = 150, // scale
      x = 480, y = 250, // translate
      lambda = 0, phi = 0, // center
      deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, // pre-rotate
      alpha = 0, // post-rotate
      theta = null, preclip = clip_antimeridian, // pre-clip angle
      x0 = null, y0, x1, y1, postclip = identity, // post-clip extent
      delta2 = 0.5, // precision
      projectResample,
      projectTransform,
      projectRotateTransform,
      cache,
      cacheStream;

  function projection(point) {
    return projectRotateTransform(point[0] * radians, point[1] * radians);
  }

  function invert(point) {
    point = projectRotateTransform.invert(point[0], point[1]);
    return point && [point[0] * degrees, point[1] * degrees];
  }

  projection.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));
  };

  projection.preclip = function(_) {
    return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;
  };

  projection.postclip = function(_) {
    return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
  };

  projection.clipAngle = function(_) {
    return arguments.length ? (preclip = +_ ? clip_circle(theta = _ * radians) : (theta = null, clip_antimeridian), reset()) : theta * degrees;
  };

  projection.clipExtent = function(_) {
    return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  };

  projection.scale = function(_) {
    return arguments.length ? (k = +_, recenter()) : k;
  };

  projection.translate = function(_) {
    return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];
  };

  projection.center = function(_) {
    return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * degrees, phi * degrees];
  };

  projection.rotate = function(_) {
    return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * degrees, deltaPhi * degrees, deltaGamma * degrees];
  };

  projection.angle = function(_) {
    return arguments.length ? (alpha = _ % 360 * radians, recenter()) : alpha * degrees;
  };

  projection.precision = function(_) {
    return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);
  };

  projection.fitExtent = function(extent, object) {
    return fitExtent(projection, extent, object);
  };

  projection.fitSize = function(size, object) {
    return fitSize(projection, size, object);
  };

  projection.fitWidth = function(width, object) {
    return fitWidth(projection, width, object);
  };

  projection.fitHeight = function(height, object) {
    return fitHeight(projection, height, object);
  };

  function recenter() {
    var center = scaleTranslateRotate(k, 0, 0, alpha).apply(null, project(lambda, phi)),
        transform = (alpha ? scaleTranslateRotate : scaleTranslate)(k, x - center[0], y - center[1], alpha);
    rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma);
    projectTransform = compose(project, transform);
    projectRotateTransform = compose(rotate, projectTransform);
    projectResample = resample(projectTransform, delta2);
    return reset();
  }

  function reset() {
    cache = cacheStream = null;
    return projection;
  }

  return function() {
    project = projectAt.apply(this, arguments);
    projection.invert = project.invert && invert;
    return recenter();
  };
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/conic.js



function conicProjection(projectAt) {
  var phi0 = 0,
      phi1 = pi / 3,
      m = projectionMutator(projectAt),
      p = m(phi0, phi1);

  p.parallels = function(_) {
    return arguments.length ? m(phi0 = _[0] * radians, phi1 = _[1] * radians) : [phi0 * degrees, phi1 * degrees];
  };

  return p;
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/cylindricalEqualArea.js


function cylindricalEqualAreaRaw(phi0) {
  var cosPhi0 = cos(phi0);

  function forward(lambda, phi) {
    return [lambda * cosPhi0, sin(phi) / cosPhi0];
  }

  forward.invert = function(x, y) {
    return [x / cosPhi0, asin(y * cosPhi0)];
  };

  return forward;
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/conicEqualArea.js




function conicEqualAreaRaw(y0, y1) {
  var sy0 = sin(y0), n = (sy0 + sin(y1)) / 2;

  // Are the parallels symmetrical around the Equator?
  if (abs(n) < epsilon) return cylindricalEqualAreaRaw(y0);

  var c = 1 + sy0 * (2 * n - sy0), r0 = sqrt(c) / n;

  function project(x, y) {
    var r = sqrt(c - 2 * n * sin(y)) / n;
    return [r * sin(x *= n), r0 - r * cos(x)];
  }

  project.invert = function(x, y) {
    var r0y = r0 - y;
    return [atan2(x, abs(r0y)) / n * math_sign(r0y), asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];
  };

  return project;
}

/* harmony default export */ var conicEqualArea = (function() {
  return conicProjection(conicEqualAreaRaw)
      .scale(155.424)
      .center([0, 33.6442]);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/albers.js


/* harmony default export */ var albers = (function() {
  return conicEqualArea()
      .parallels([29.5, 45.5])
      .scale(1070)
      .translate([480, 250])
      .rotate([96, 0])
      .center([-0.6, 38.7]);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/albersUsa.js





// The projections must have mutually exclusive clip regions on the sphere,
// as this will avoid emitting interleaving lines and polygons.
function multiplex(streams) {
  var n = streams.length;
  return {
    point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); },
    sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); },
    lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); },
    lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); },
    polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); },
    polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); }
  };
}

// A composite projection for the United States, configured by default for
// 960×500. The projection also works quite well at 960×600 if you change the
// scale to 1285 and adjust the translate accordingly. The set of standard
// parallels for each region comes from USGS, which is published here:
// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers
/* harmony default export */ var projection_albersUsa = (function() {
  var cache,
      cacheStream,
      lower48 = albers(), lower48Point,
      alaska = conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338
      hawaii = conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007
      point, pointStream = {point: function(x, y) { point = [x, y]; }};

  function albersUsa(coordinates) {
    var x = coordinates[0], y = coordinates[1];
    return point = null,
        (lower48Point.point(x, y), point)
        || (alaskaPoint.point(x, y), point)
        || (hawaiiPoint.point(x, y), point);
  }

  albersUsa.invert = function(coordinates) {
    var k = lower48.scale(),
        t = lower48.translate(),
        x = (coordinates[0] - t[0]) / k,
        y = (coordinates[1] - t[1]) / k;
    return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska
        : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii
        : lower48).invert(coordinates);
  };

  albersUsa.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);
  };

  albersUsa.precision = function(_) {
    if (!arguments.length) return lower48.precision();
    lower48.precision(_), alaska.precision(_), hawaii.precision(_);
    return reset();
  };

  albersUsa.scale = function(_) {
    if (!arguments.length) return lower48.scale();
    lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
    return albersUsa.translate(lower48.translate());
  };

  albersUsa.translate = function(_) {
    if (!arguments.length) return lower48.translate();
    var k = lower48.scale(), x = +_[0], y = +_[1];

    lower48Point = lower48
        .translate(_)
        .clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])
        .stream(pointStream);

    alaskaPoint = alaska
        .translate([x - 0.307 * k, y + 0.201 * k])
        .clipExtent([[x - 0.425 * k + epsilon, y + 0.120 * k + epsilon], [x - 0.214 * k - epsilon, y + 0.234 * k - epsilon]])
        .stream(pointStream);

    hawaiiPoint = hawaii
        .translate([x - 0.205 * k, y + 0.212 * k])
        .clipExtent([[x - 0.214 * k + epsilon, y + 0.166 * k + epsilon], [x - 0.115 * k - epsilon, y + 0.234 * k - epsilon]])
        .stream(pointStream);

    return reset();
  };

  albersUsa.fitExtent = function(extent, object) {
    return fitExtent(albersUsa, extent, object);
  };

  albersUsa.fitSize = function(size, object) {
    return fitSize(albersUsa, size, object);
  };

  albersUsa.fitWidth = function(width, object) {
    return fitWidth(albersUsa, width, object);
  };

  albersUsa.fitHeight = function(height, object) {
    return fitHeight(albersUsa, height, object);
  };

  function reset() {
    cache = cacheStream = null;
    return albersUsa;
  }

  return albersUsa.scale(1070);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/azimuthal.js


function azimuthalRaw(scale) {
  return function(x, y) {
    var cx = cos(x),
        cy = cos(y),
        k = scale(cx * cy);
    return [
      k * cy * sin(x),
      k * sin(y)
    ];
  }
}

function azimuthalInvert(angle) {
  return function(x, y) {
    var z = sqrt(x * x + y * y),
        c = angle(z),
        sc = sin(c),
        cc = cos(c);
    return [
      atan2(x * sc, z * cc),
      asin(z && y * sc / z)
    ];
  }
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/azimuthalEqualArea.js




var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
  return sqrt(2 / (1 + cxcy));
});

azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
  return 2 * asin(z / 2);
});

/* harmony default export */ var azimuthalEqualArea = (function() {
  return projection_projection(azimuthalEqualAreaRaw)
      .scale(124.75)
      .clipAngle(180 - 1e-3);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/azimuthalEquidistant.js




var azimuthalEquidistantRaw = azimuthalRaw(function(c) {
  return (c = acos(c)) && c / sin(c);
});

azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {
  return z;
});

/* harmony default export */ var azimuthalEquidistant = (function() {
  return projection_projection(azimuthalEquidistantRaw)
      .scale(79.4188)
      .clipAngle(180 - 1e-3);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/mercator.js




function mercatorRaw(lambda, phi) {
  return [lambda, log(tan((halfPi + phi) / 2))];
}

mercatorRaw.invert = function(x, y) {
  return [x, 2 * atan(exp(y)) - halfPi];
};

/* harmony default export */ var mercator = (function() {
  return mercatorProjection(mercatorRaw)
      .scale(961 / tau);
});

function mercatorProjection(project) {
  var m = projection_projection(project),
      center = m.center,
      scale = m.scale,
      translate = m.translate,
      clipExtent = m.clipExtent,
      x0 = null, y0, x1, y1; // clip extent

  m.scale = function(_) {
    return arguments.length ? (scale(_), reclip()) : scale();
  };

  m.translate = function(_) {
    return arguments.length ? (translate(_), reclip()) : translate();
  };

  m.center = function(_) {
    return arguments.length ? (center(_), reclip()) : center();
  };

  m.clipExtent = function(_) {
    return arguments.length ? ((_ == null ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1])), reclip()) : x0 == null ? null : [[x0, y0], [x1, y1]];
  };

  function reclip() {
    var k = pi * scale(),
        t = m(src_rotation(m.rotate()).invert([0, 0]));
    return clipExtent(x0 == null
        ? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === mercatorRaw
        ? [[Math.max(t[0] - k, x0), y0], [Math.min(t[0] + k, x1), y1]]
        : [[x0, Math.max(t[1] - k, y0)], [x1, Math.min(t[1] + k, y1)]]);
  }

  return reclip();
}

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/conicConformal.js




function tany(y) {
  return tan((halfPi + y) / 2);
}

function conicConformalRaw(y0, y1) {
  var cy0 = cos(y0),
      n = y0 === y1 ? sin(y0) : log(cy0 / cos(y1)) / log(tany(y1) / tany(y0)),
      f = cy0 * pow(tany(y0), n) / n;

  if (!n) return mercatorRaw;

  function project(x, y) {
    if (f > 0) { if (y < -halfPi + epsilon) y = -halfPi + epsilon; }
    else { if (y > halfPi - epsilon) y = halfPi - epsilon; }
    var r = f / pow(tany(y), n);
    return [r * sin(n * x), f - r * cos(n * x)];
  }

  project.invert = function(x, y) {
    var fy = f - y, r = math_sign(n) * sqrt(x * x + fy * fy);
    return [atan2(x, abs(fy)) / n * math_sign(fy), 2 * atan(pow(f / r, 1 / n)) - halfPi];
  };

  return project;
}

/* harmony default export */ var conicConformal = (function() {
  return conicProjection(conicConformalRaw)
      .scale(109.5)
      .parallels([30, 30]);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/equirectangular.js


function equirectangularRaw(lambda, phi) {
  return [lambda, phi];
}

equirectangularRaw.invert = equirectangularRaw;

/* harmony default export */ var equirectangular = (function() {
  return projection_projection(equirectangularRaw)
      .scale(152.63);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/conicEquidistant.js




function conicEquidistantRaw(y0, y1) {
  var cy0 = cos(y0),
      n = y0 === y1 ? sin(y0) : (cy0 - cos(y1)) / (y1 - y0),
      g = cy0 / n + y0;

  if (abs(n) < epsilon) return equirectangularRaw;

  function project(x, y) {
    var gy = g - y, nx = n * x;
    return [gy * sin(nx), g - gy * cos(nx)];
  }

  project.invert = function(x, y) {
    var gy = g - y;
    return [atan2(x, abs(gy)) / n * math_sign(gy), g - math_sign(n) * sqrt(x * x + gy * gy)];
  };

  return project;
}

/* harmony default export */ var conicEquidistant = (function() {
  return conicProjection(conicEquidistantRaw)
      .scale(131.154)
      .center([0, 13.9389]);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/equalEarth.js



var A1 = 1.340264,
    A2 = -0.081106,
    A3 = 0.000893,
    A4 = 0.003796,
    M = sqrt(3) / 2,
    iterations = 12;

function equalEarthRaw(lambda, phi) {
  var l = asin(M * sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;
  return [
    lambda * cos(l) / (M * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2))),
    l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2))
  ];
}

equalEarthRaw.invert = function(x, y) {
  var l = y, l2 = l * l, l6 = l2 * l2 * l2;
  for (var i = 0, delta, fy, fpy; i < iterations; ++i) {
    fy = l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2)) - y;
    fpy = A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2);
    l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;
    if (abs(delta) < epsilon2) break;
  }
  return [
    M * x * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2)) / cos(l),
    asin(sin(l) / M)
  ];
};

/* harmony default export */ var equalEarth = (function() {
  return projection_projection(equalEarthRaw)
      .scale(177.158);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/gnomonic.js




function gnomonicRaw(x, y) {
  var cy = cos(y), k = cos(x) * cy;
  return [cy * sin(x) / k, sin(y) / k];
}

gnomonicRaw.invert = azimuthalInvert(atan);

/* harmony default export */ var gnomonic = (function() {
  return projection_projection(gnomonicRaw)
      .scale(144.049)
      .clipAngle(60);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/identity.js





function identity_scaleTranslate(kx, ky, tx, ty) {
  return kx === 1 && ky === 1 && tx === 0 && ty === 0 ? identity : transformer({
    point: function(x, y) {
      this.stream.point(x * kx + tx, y * ky + ty);
    }
  });
}

/* harmony default export */ var projection_identity = (function() {
  var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, transform = identity, // scale, translate and reflect
      x0 = null, y0, x1, y1, // clip extent
      postclip = identity,
      cache,
      cacheStream,
      projection;

  function reset() {
    cache = cacheStream = null;
    return projection;
  }

  return projection = {
    stream: function(stream) {
      return cache && cacheStream === stream ? cache : cache = transform(postclip(cacheStream = stream));
    },
    postclip: function(_) {
      return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
    },
    clipExtent: function(_) {
      return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
    },
    scale: function(_) {
      return arguments.length ? (transform = identity_scaleTranslate((k = +_) * sx, k * sy, tx, ty), reset()) : k;
    },
    translate: function(_) {
      return arguments.length ? (transform = identity_scaleTranslate(k * sx, k * sy, tx = +_[0], ty = +_[1]), reset()) : [tx, ty];
    },
    reflectX: function(_) {
      return arguments.length ? (transform = identity_scaleTranslate(k * (sx = _ ? -1 : 1), k * sy, tx, ty), reset()) : sx < 0;
    },
    reflectY: function(_) {
      return arguments.length ? (transform = identity_scaleTranslate(k * sx, k * (sy = _ ? -1 : 1), tx, ty), reset()) : sy < 0;
    },
    fitExtent: function(extent, object) {
      return fitExtent(projection, extent, object);
    },
    fitSize: function(size, object) {
      return fitSize(projection, size, object);
    },
    fitWidth: function(width, object) {
      return fitWidth(projection, width, object);
    },
    fitHeight: function(height, object) {
      return fitHeight(projection, height, object);
    }
  };
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/naturalEarth1.js



function naturalEarth1Raw(lambda, phi) {
  var phi2 = phi * phi, phi4 = phi2 * phi2;
  return [
    lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),
    phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))
  ];
}

naturalEarth1Raw.invert = function(x, y) {
  var phi = y, i = 25, delta;
  do {
    var phi2 = phi * phi, phi4 = phi2 * phi2;
    phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /
        (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));
  } while (abs(delta) > epsilon && --i > 0);
  return [
    x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),
    phi
  ];
};

/* harmony default export */ var naturalEarth1 = (function() {
  return projection_projection(naturalEarth1Raw)
      .scale(175.295);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/orthographic.js




function orthographicRaw(x, y) {
  return [cos(y) * sin(x), sin(y)];
}

orthographicRaw.invert = azimuthalInvert(asin);

/* harmony default export */ var orthographic = (function() {
  return projection_projection(orthographicRaw)
      .scale(249.5)
      .clipAngle(90 + epsilon);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/stereographic.js




function stereographicRaw(x, y) {
  var cy = cos(y), k = 1 + cos(x) * cy;
  return [cy * sin(x) / k, sin(y) / k];
}

stereographicRaw.invert = azimuthalInvert(function(z) {
  return 2 * atan(z);
});

/* harmony default export */ var stereographic = (function() {
  return projection_projection(stereographicRaw)
      .scale(250)
      .clipAngle(142);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/projection/transverseMercator.js



function transverseMercatorRaw(lambda, phi) {
  return [log(tan((halfPi + phi) / 2)), -lambda];
}

transverseMercatorRaw.invert = function(x, y) {
  return [-y, 2 * atan(exp(x)) - halfPi];
};

/* harmony default export */ var transverseMercator = (function() {
  var m = mercatorProjection(transverseMercatorRaw),
      center = m.center,
      rotate = m.rotate;

  m.center = function(_) {
    return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);
  };

  m.rotate = function(_) {
    return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);
  };

  return rotate([0, 0, 90])
      .scale(159.155);
});

// CONCATENATED MODULE: ../node_modules/d3-geo/src/index.js
/* concated harmony reexport geoArea */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoArea", function() { return src_area; });
/* concated harmony reexport geoBounds */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoBounds", function() { return bounds; });
/* concated harmony reexport geoCentroid */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoCentroid", function() { return centroid; });
/* concated harmony reexport geoCircle */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoCircle", function() { return src_circle; });
/* concated harmony reexport geoClipAntimeridian */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoClipAntimeridian", function() { return clip_antimeridian; });
/* concated harmony reexport geoClipCircle */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoClipCircle", function() { return clip_circle; });
/* concated harmony reexport geoClipExtent */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoClipExtent", function() { return clip_extent; });
/* concated harmony reexport geoClipRectangle */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoClipRectangle", function() { return clipRectangle; });
/* concated harmony reexport geoContains */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoContains", function() { return contains; });
/* concated harmony reexport geoDistance */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoDistance", function() { return distance; });
/* concated harmony reexport geoGraticule */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoGraticule", function() { return graticule_graticule; });
/* concated harmony reexport geoGraticule10 */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoGraticule10", function() { return graticule10; });
/* concated harmony reexport geoInterpolate */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoInterpolate", function() { return src_interpolate; });
/* concated harmony reexport geoLength */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoLength", function() { return src_length; });
/* concated harmony reexport geoPath */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoPath", function() { return src_path; });
/* concated harmony reexport geoAlbers */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoAlbers", function() { return albers; });
/* concated harmony reexport geoAlbersUsa */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoAlbersUsa", function() { return projection_albersUsa; });
/* concated harmony reexport geoAzimuthalEqualArea */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoAzimuthalEqualArea", function() { return azimuthalEqualArea; });
/* concated harmony reexport geoAzimuthalEqualAreaRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoAzimuthalEqualAreaRaw", function() { return azimuthalEqualAreaRaw; });
/* concated harmony reexport geoAzimuthalEquidistant */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoAzimuthalEquidistant", function() { return azimuthalEquidistant; });
/* concated harmony reexport geoAzimuthalEquidistantRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoAzimuthalEquidistantRaw", function() { return azimuthalEquidistantRaw; });
/* concated harmony reexport geoConicConformal */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoConicConformal", function() { return conicConformal; });
/* concated harmony reexport geoConicConformalRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoConicConformalRaw", function() { return conicConformalRaw; });
/* concated harmony reexport geoConicEqualArea */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoConicEqualArea", function() { return conicEqualArea; });
/* concated harmony reexport geoConicEqualAreaRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoConicEqualAreaRaw", function() { return conicEqualAreaRaw; });
/* concated harmony reexport geoConicEquidistant */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoConicEquidistant", function() { return conicEquidistant; });
/* concated harmony reexport geoConicEquidistantRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoConicEquidistantRaw", function() { return conicEquidistantRaw; });
/* concated harmony reexport geoEqualEarth */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoEqualEarth", function() { return equalEarth; });
/* concated harmony reexport geoEqualEarthRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoEqualEarthRaw", function() { return equalEarthRaw; });
/* concated harmony reexport geoEquirectangular */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoEquirectangular", function() { return equirectangular; });
/* concated harmony reexport geoEquirectangularRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoEquirectangularRaw", function() { return equirectangularRaw; });
/* concated harmony reexport geoGnomonic */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoGnomonic", function() { return gnomonic; });
/* concated harmony reexport geoGnomonicRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoGnomonicRaw", function() { return gnomonicRaw; });
/* concated harmony reexport geoIdentity */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoIdentity", function() { return projection_identity; });
/* concated harmony reexport geoProjection */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoProjection", function() { return projection_projection; });
/* concated harmony reexport geoProjectionMutator */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoProjectionMutator", function() { return projectionMutator; });
/* concated harmony reexport geoMercator */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoMercator", function() { return mercator; });
/* concated harmony reexport geoMercatorRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoMercatorRaw", function() { return mercatorRaw; });
/* concated harmony reexport geoNaturalEarth1 */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoNaturalEarth1", function() { return naturalEarth1; });
/* concated harmony reexport geoNaturalEarth1Raw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoNaturalEarth1Raw", function() { return naturalEarth1Raw; });
/* concated harmony reexport geoOrthographic */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoOrthographic", function() { return orthographic; });
/* concated harmony reexport geoOrthographicRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoOrthographicRaw", function() { return orthographicRaw; });
/* concated harmony reexport geoStereographic */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoStereographic", function() { return stereographic; });
/* concated harmony reexport geoStereographicRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoStereographicRaw", function() { return stereographicRaw; });
/* concated harmony reexport geoTransverseMercator */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoTransverseMercator", function() { return transverseMercator; });
/* concated harmony reexport geoTransverseMercatorRaw */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoTransverseMercatorRaw", function() { return transverseMercatorRaw; });
/* concated harmony reexport geoRotation */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoRotation", function() { return src_rotation; });
/* concated harmony reexport geoStream */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoStream", function() { return src_stream; });
/* concated harmony reexport geoTransform */__nested_webpack_require_5017397__.d(__webpack_exports__, "geoTransform", function() { return src_transform; });






 // DEPRECATED! Use d3.geoIdentity().clipExtent(…).





























/***/ }),
/* 1088 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_5119914__) {

"use strict";
__nested_webpack_require_5119914__.r(__webpack_exports__);

// EXTERNAL MODULE: ../node_modules/d3-collection/src/index.js + 6 modules
var src = __nested_webpack_require_5119914__(72);

// EXTERNAL MODULE: ../node_modules/d3-dispatch/src/index.js + 1 modules
var d3_dispatch_src = __nested_webpack_require_5119914__(65);

// CONCATENATED MODULE: ../node_modules/d3-request/src/request.js



/* harmony default export */ var src_request = (function(url, callback) {
  var request,
      event = Object(d3_dispatch_src["a" /* dispatch */])("beforesend", "progress", "load", "error"),
      mimeType,
      headers = Object(src["a" /* map */])(),
      xhr = new XMLHttpRequest,
      user = null,
      password = null,
      response,
      responseType,
      timeout = 0;

  // If IE does not support CORS, use XDomainRequest.
  if (typeof XDomainRequest !== "undefined"
      && !("withCredentials" in xhr)
      && /^(http(s)?:)?\/\//.test(url)) xhr = new XDomainRequest;

  "onload" in xhr
      ? xhr.onload = xhr.onerror = xhr.ontimeout = respond
      : xhr.onreadystatechange = function(o) { xhr.readyState > 3 && respond(o); };

  function respond(o) {
    var status = xhr.status, result;
    if (!status && hasResponse(xhr)
        || status >= 200 && status < 300
        || status === 304) {
      if (response) {
        try {
          result = response.call(request, xhr);
        } catch (e) {
          event.call("error", request, e);
          return;
        }
      } else {
        result = xhr;
      }
      event.call("load", request, result);
    } else {
      event.call("error", request, o);
    }
  }

  xhr.onprogress = function(e) {
    event.call("progress", request, e);
  };

  request = {
    header: function(name, value) {
      name = (name + "").toLowerCase();
      if (arguments.length < 2) return headers.get(name);
      if (value == null) headers.remove(name);
      else headers.set(name, value + "");
      return request;
    },

    // If mimeType is non-null and no Accept header is set, a default is used.
    mimeType: function(value) {
      if (!arguments.length) return mimeType;
      mimeType = value == null ? null : value + "";
      return request;
    },

    // Specifies what type the response value should take;
    // for instance, arraybuffer, blob, document, or text.
    responseType: function(value) {
      if (!arguments.length) return responseType;
      responseType = value;
      return request;
    },

    timeout: function(value) {
      if (!arguments.length) return timeout;
      timeout = +value;
      return request;
    },

    user: function(value) {
      return arguments.length < 1 ? user : (user = value == null ? null : value + "", request);
    },

    password: function(value) {
      return arguments.length < 1 ? password : (password = value == null ? null : value + "", request);
    },

    // Specify how to convert the response content to a specific type;
    // changes the callback value on "load" events.
    response: function(value) {
      response = value;
      return request;
    },

    // Alias for send("GET", …).
    get: function(data, callback) {
      return request.send("GET", data, callback);
    },

    // Alias for send("POST", …).
    post: function(data, callback) {
      return request.send("POST", data, callback);
    },

    // If callback is non-null, it will be used for error and load events.
    send: function(method, data, callback) {
      xhr.open(method, url, true, user, password);
      if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*");
      if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); });
      if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType);
      if (responseType != null) xhr.responseType = responseType;
      if (timeout > 0) xhr.timeout = timeout;
      if (callback == null && typeof data === "function") callback = data, data = null;
      if (callback != null && callback.length === 1) callback = fixCallback(callback);
      if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); });
      event.call("beforesend", request, xhr);
      xhr.send(data == null ? null : data);
      return request;
    },

    abort: function() {
      xhr.abort();
      return request;
    },

    on: function() {
      var value = event.on.apply(event, arguments);
      return value === event ? request : value;
    }
  };

  if (callback != null) {
    if (typeof callback !== "function") throw new Error("invalid callback: " + callback);
    return request.get(callback);
  }

  return request;
});

function fixCallback(callback) {
  return function(error, xhr) {
    callback(error == null ? xhr : null);
  };
}

function hasResponse(xhr) {
  var type = xhr.responseType;
  return type && type !== "text"
      ? xhr.response // null on error
      : xhr.responseText; // "" on error
}

// CONCATENATED MODULE: ../node_modules/d3-request/src/type.js


/* harmony default export */ var type = (function(defaultMimeType, response) {
  return function(url, callback) {
    var r = src_request(url).mimeType(defaultMimeType).response(response);
    if (callback != null) {
      if (typeof callback !== "function") throw new Error("invalid callback: " + callback);
      return r.get(callback);
    }
    return r;
  };
});

// CONCATENATED MODULE: ../node_modules/d3-request/src/html.js


/* harmony default export */ var html = (type("text/html", function(xhr) {
  return document.createRange().createContextualFragment(xhr.responseText);
}));

// CONCATENATED MODULE: ../node_modules/d3-request/src/json.js


/* harmony default export */ var json = (type("application/json", function(xhr) {
  return JSON.parse(xhr.responseText);
}));

// CONCATENATED MODULE: ../node_modules/d3-request/src/text.js


/* harmony default export */ var src_text = (type("text/plain", function(xhr) {
  return xhr.responseText;
}));

// CONCATENATED MODULE: ../node_modules/d3-request/src/xml.js


/* harmony default export */ var xml = (type("application/xml", function(xhr) {
  var xml = xhr.responseXML;
  if (!xml) throw new Error("parse error");
  return xml;
}));

// EXTERNAL MODULE: ../node_modules/d3-dsv/src/index.js + 4 modules
var d3_dsv_src = __nested_webpack_require_5119914__(104);

// CONCATENATED MODULE: ../node_modules/d3-request/src/dsv.js


/* harmony default export */ var dsv = (function(defaultMimeType, parse) {
  return function(url, row, callback) {
    if (arguments.length < 3) callback = row, row = null;
    var r = src_request(url).mimeType(defaultMimeType);
    r.row = function(_) { return arguments.length ? r.response(responseOf(parse, row = _)) : row; };
    r.row(row);
    return callback ? r.get(callback) : r;
  };
});

function responseOf(parse, row) {
  return function(request) {
    return parse(request.responseText, row);
  };
}

// CONCATENATED MODULE: ../node_modules/d3-request/src/csv.js



/* harmony default export */ var csv = (dsv("text/csv", d3_dsv_src["csvParse"]));

// CONCATENATED MODULE: ../node_modules/d3-request/src/tsv.js



/* harmony default export */ var tsv = (dsv("text/tab-separated-values", d3_dsv_src["tsvParse"]));

// CONCATENATED MODULE: ../node_modules/d3-request/index.js
/* concated harmony reexport request */__nested_webpack_require_5119914__.d(__webpack_exports__, "request", function() { return src_request; });
/* concated harmony reexport html */__nested_webpack_require_5119914__.d(__webpack_exports__, "html", function() { return html; });
/* concated harmony reexport json */__nested_webpack_require_5119914__.d(__webpack_exports__, "json", function() { return json; });
/* concated harmony reexport text */__nested_webpack_require_5119914__.d(__webpack_exports__, "text", function() { return src_text; });
/* concated harmony reexport xml */__nested_webpack_require_5119914__.d(__webpack_exports__, "xml", function() { return xml; });
/* concated harmony reexport csv */__nested_webpack_require_5119914__.d(__webpack_exports__, "csv", function() { return csv; });
/* concated harmony reexport tsv */__nested_webpack_require_5119914__.d(__webpack_exports__, "tsv", function() { return tsv; });









/***/ }),
/* 1089 */
/***/ (function(module, __webpack_exports__, __nested_webpack_require_5128136__) {

"use strict";
__nested_webpack_require_5128136__.r(__webpack_exports__);

// CONCATENATED MODULE: ../node_modules/d3-queue/src/array.js
var slice = [].slice;

// CONCATENATED MODULE: ../node_modules/d3-queue/src/queue.js


var noabort = {};

function Queue(size) {
  this._size = size;
  this._call =
  this._error = null;
  this._tasks = [];
  this._data = [];
  this._waiting =
  this._active =
  this._ended =
  this._start = 0; // inside a synchronous task callback?
}

Queue.prototype = queue.prototype = {
  constructor: Queue,
  defer: function(callback) {
    if (typeof callback !== "function") throw new Error("invalid callback");
    if (this._call) throw new Error("defer after await");
    if (this._error != null) return this;
    var t = slice.call(arguments, 1);
    t.push(callback);
    ++this._waiting, this._tasks.push(t);
    poke(this);
    return this;
  },
  abort: function() {
    if (this._error == null) abort(this, new Error("abort"));
    return this;
  },
  await: function(callback) {
    if (typeof callback !== "function") throw new Error("invalid callback");
    if (this._call) throw new Error("multiple await");
    this._call = function(error, results) { callback.apply(null, [error].concat(results)); };
    maybeNotify(this);
    return this;
  },
  awaitAll: function(callback) {
    if (typeof callback !== "function") throw new Error("invalid callback");
    if (this._call) throw new Error("multiple await");
    this._call = callback;
    maybeNotify(this);
    return this;
  }
};

function poke(q) {
  if (!q._start) {
    try { start(q); } // let the current task complete
    catch (e) {
      if (q._tasks[q._ended + q._active - 1]) abort(q, e); // task errored synchronously
      else if (!q._data) throw e; // await callback errored synchronously
    }
  }
}

function start(q) {
  while (q._start = q._waiting && q._active < q._size) {
    var i = q._ended + q._active,
        t = q._tasks[i],
        j = t.length - 1,
        c = t[j];
    t[j] = end(q, i);
    --q._waiting, ++q._active;
    t = c.apply(null, t);
    if (!q._tasks[i]) continue; // task finished synchronously
    q._tasks[i] = t || noabort;
  }
}

function end(q, i) {
  return function(e, r) {
    if (!q._tasks[i]) return; // ignore multiple callbacks
    --q._active, ++q._ended;
    q._tasks[i] = null;
    if (q._error != null) return; // ignore secondary errors
    if (e != null) {
      abort(q, e);
    } else {
      q._data[i] = r;
      if (q._waiting) poke(q);
      else maybeNotify(q);
    }
  };
}

function abort(q, e) {
  var i = q._tasks.length, t;
  q._error = e; // ignore active callbacks
  q._data = undefined; // allow gc
  q._waiting = NaN; // prevent starting

  while (--i >= 0) {
    if (t = q._tasks[i]) {
      q._tasks[i] = null;
      if (t.abort) {
        try { t.abort(); }
        catch (e) { /* ignore */ }
      }
    }
  }

  q._active = NaN; // allow notification
  maybeNotify(q);
}

function maybeNotify(q) {
  if (!q._active && q._call) {
    var d = q._data;
    q._data = undefined; // allow gc
    q._call(q._error, d);
  }
}

function queue(concurrency) {
  if (concurrency == null) concurrency = Infinity;
  else if (!((concurrency = +concurrency) >= 1)) throw new Error("invalid concurrency");
  return new Queue(concurrency);
}

// CONCATENATED MODULE: ../node_modules/d3-queue/index.js
/* concated harmony reexport queue */__nested_webpack_require_5128136__.d(__webpack_exports__, "queue", function() { return queue; });



/***/ })
/******/ ]);
});

/***/ }),

/***/ 645:
/***/ ((__unused_webpack_module, exports) => {

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),

/***/ 6898:
/***/ ((module) => {

"use strict";


module.exports = value => {
	if (!value) {
		return false;
	}

	// eslint-disable-next-line no-use-extend-native/no-use-extend-native
	if (typeof Symbol.observable === 'symbol' && typeof value[Symbol.observable] === 'function') {
		// eslint-disable-next-line no-use-extend-native/no-use-extend-native
		return value === value[Symbol.observable]();
	}

	if (typeof value['@@observable'] === 'function') {
		return value === value['@@observable']();
	}

	return false;
};


/***/ }),

/***/ 8277:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g;

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (freeGlobal);


/***/ }),

/***/ 9730:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8277);
/* module decorator */ module = __webpack_require__.hmd(module);


/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"].process */ .Z.process;

/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
  try {
    // Use `util.types` for Node.js 10+.
    var types = freeModule && freeModule.require && freeModule.require('util').types;

    if (types) {
      return types;
    }

    // Legacy `process.binding('util')` for Node.js < 10.
    return freeProcess && freeProcess.binding && freeProcess.binding('util');
  } catch (e) {}
}());

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (nodeUtil);


/***/ }),

/***/ 6169:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8277);


/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

/** Used as a reference to the global object. */
var root = _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z || freeSelf || Function('return this')();

/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (root);


/***/ }),

/***/ 4002:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "Z": () => (/* binding */ lodash_es_isBuffer)
});

// EXTERNAL MODULE: ./node_modules/lodash-es/_root.js
var _root = __webpack_require__(6169);
;// CONCATENATED MODULE: ./node_modules/lodash-es/stubFalse.js
/**
 * This method returns `false`.
 *
 * @static
 * @memberOf _
 * @since 4.13.0
 * @category Util
 * @returns {boolean} Returns `false`.
 * @example
 *
 * _.times(2, _.stubFalse);
 * // => [false, false]
 */
function stubFalse() {
  return false;
}

/* harmony default export */ const lodash_es_stubFalse = (stubFalse);

;// CONCATENATED MODULE: ./node_modules/lodash-es/isBuffer.js
/* module decorator */ module = __webpack_require__.hmd(module);



/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;

/** Detect free variable `module`. */
var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module;

/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;

/** Built-in value references. */
var Buffer = moduleExports ? _root/* default.Buffer */.Z.Buffer : undefined;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;

/**
 * Checks if `value` is a buffer.
 *
 * @static
 * @memberOf _
 * @since 4.3.0
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
 * @example
 *
 * _.isBuffer(new Buffer(2));
 * // => true
 *
 * _.isBuffer(new Uint8Array(2));
 * // => false
 */
var isBuffer = nativeIsBuffer || lodash_es_stubFalse;

/* harmony default export */ const lodash_es_isBuffer = (isBuffer);


/***/ }),

/***/ 7824:
/***/ ((module) => {

/**
 * Helpers.
 */

var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;

/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} [options]
 * @throws {Error} throw an error if val is not a non-empty string or a number
 * @return {String|Number}
 * @api public
 */

module.exports = function(val, options) {
  options = options || {};
  var type = typeof val;
  if (type === 'string' && val.length > 0) {
    return parse(val);
  } else if (type === 'number' && isFinite(val)) {
    return options.long ? fmtLong(val) : fmtShort(val);
  }
  throw new Error(
    'val is not a non-empty string or a valid number. val=' +
      JSON.stringify(val)
  );
};

/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function parse(str) {
  str = String(str);
  if (str.length > 100) {
    return;
  }
  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
    str
  );
  if (!match) {
    return;
  }
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'weeks':
    case 'week':
    case 'w':
      return n * w;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
    default:
      return undefined;
  }
}

/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtShort(ms) {
  var msAbs = Math.abs(ms);
  if (msAbs >= d) {
    return Math.round(ms / d) + 'd';
  }
  if (msAbs >= h) {
    return Math.round(ms / h) + 'h';
  }
  if (msAbs >= m) {
    return Math.round(ms / m) + 'm';
  }
  if (msAbs >= s) {
    return Math.round(ms / s) + 's';
  }
  return ms + 'ms';
}

/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtLong(ms) {
  var msAbs = Math.abs(ms);
  if (msAbs >= d) {
    return plural(ms, msAbs, d, 'day');
  }
  if (msAbs >= h) {
    return plural(ms, msAbs, h, 'hour');
  }
  if (msAbs >= m) {
    return plural(ms, msAbs, m, 'minute');
  }
  if (msAbs >= s) {
    return plural(ms, msAbs, s, 'second');
  }
  return ms + ' ms';
}

/**
 * Pluralization helper.
 */

function plural(ms, msAbs, n, name) {
  var isPlural = msAbs >= n * 1.5;
  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}


/***/ }),

/***/ 7418:
/***/ ((module) => {

"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/


/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};


/***/ }),

/***/ 9599:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "Observable": () => (/* reexport */ dist_esm_observable),
  "Subject": () => (/* reexport */ dist_esm_subject),
  "filter": () => (/* reexport */ dist_esm_filter),
  "flatMap": () => (/* reexport */ dist_esm_flatMap),
  "interval": () => (/* reexport */ interval),
  "map": () => (/* reexport */ dist_esm_map),
  "merge": () => (/* reexport */ dist_esm_merge),
  "multicast": () => (/* reexport */ dist_esm_multicast),
  "scan": () => (/* reexport */ dist_esm_scan),
  "unsubscribe": () => (/* reexport */ dist_esm_unsubscribe)
});

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/_scheduler.js
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
class AsyncSerialScheduler {
    constructor(observer) {
        this._baseObserver = observer;
        this._pendingPromises = new Set();
    }
    complete() {
        Promise.all(this._pendingPromises)
            .then(() => this._baseObserver.complete())
            .catch(error => this._baseObserver.error(error));
    }
    error(error) {
        this._baseObserver.error(error);
    }
    schedule(task) {
        const prevPromisesCompletion = Promise.all(this._pendingPromises);
        const values = [];
        const next = (value) => values.push(value);
        const promise = Promise.resolve()
            .then(() => __awaiter(this, void 0, void 0, function* () {
            yield prevPromisesCompletion;
            yield task(next);
            this._pendingPromises.delete(promise);
            for (const value of values) {
                this._baseObserver.next(value);
            }
        }))
            .catch(error => {
            this._pendingPromises.delete(promise);
            this._baseObserver.error(error);
        });
        this._pendingPromises.add(promise);
    }
}

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/_symbols.js
const hasSymbols = () => typeof Symbol === "function";
const hasSymbol = (name) => hasSymbols() && Boolean(Symbol[name]);
const getSymbol = (name) => hasSymbol(name) ? Symbol[name] : "@@" + name;
function registerObservableSymbol() {
    if (hasSymbols() && !hasSymbol("observable")) {
        Symbol.observable = Symbol("observable");
    }
}
if (!hasSymbol("asyncIterator")) {
    Symbol.asyncIterator = Symbol.asyncIterator || Symbol.for("Symbol.asyncIterator");
}

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/observable.js
/**
 * Based on <https://raw.githubusercontent.com/zenparsing/zen-observable/master/src/Observable.js>
 * At commit: f63849a8c60af5d514efc8e9d6138d8273c49ad6
 */


const SymbolIterator = getSymbol("iterator");
const SymbolObservable = getSymbol("observable");
const SymbolSpecies = getSymbol("species");
// === Abstract Operations ===
function getMethod(obj, key) {
    const value = obj[key];
    if (value == null) {
        return undefined;
    }
    if (typeof value !== "function") {
        throw new TypeError(value + " is not a function");
    }
    return value;
}
function getSpecies(obj) {
    let ctor = obj.constructor;
    if (ctor !== undefined) {
        ctor = ctor[SymbolSpecies];
        if (ctor === null) {
            ctor = undefined;
        }
    }
    return ctor !== undefined ? ctor : Observable;
}
function isObservable(x) {
    return x instanceof Observable; // SPEC: Brand check
}
function hostReportError(error) {
    if (hostReportError.log) {
        hostReportError.log(error);
    }
    else {
        setTimeout(() => { throw error; }, 0);
    }
}
function enqueue(fn) {
    Promise.resolve().then(() => {
        try {
            fn();
        }
        catch (e) {
            hostReportError(e);
        }
    });
}
function cleanupSubscription(subscription) {
    const cleanup = subscription._cleanup;
    if (cleanup === undefined) {
        return;
    }
    subscription._cleanup = undefined;
    if (!cleanup) {
        return;
    }
    try {
        if (typeof cleanup === "function") {
            cleanup();
        }
        else {
            const unsubscribe = getMethod(cleanup, "unsubscribe");
            if (unsubscribe) {
                unsubscribe.call(cleanup);
            }
        }
    }
    catch (e) {
        hostReportError(e);
    }
}
function closeSubscription(subscription) {
    subscription._observer = undefined;
    subscription._queue = undefined;
    subscription._state = "closed";
}
function flushSubscription(subscription) {
    const queue = subscription._queue;
    if (!queue) {
        return;
    }
    subscription._queue = undefined;
    subscription._state = "ready";
    for (const item of queue) {
        notifySubscription(subscription, item.type, item.value);
        if (subscription._state === "closed") {
            break;
        }
    }
}
function notifySubscription(subscription, type, value) {
    subscription._state = "running";
    const observer = subscription._observer;
    try {
        const m = observer ? getMethod(observer, type) : undefined;
        switch (type) {
            case "next":
                if (m)
                    m.call(observer, value);
                break;
            case "error":
                closeSubscription(subscription);
                if (m)
                    m.call(observer, value);
                else
                    throw value;
                break;
            case "complete":
                closeSubscription(subscription);
                if (m)
                    m.call(observer);
                break;
        }
    }
    catch (e) {
        hostReportError(e);
    }
    if (subscription._state === "closed") {
        cleanupSubscription(subscription);
    }
    else if (subscription._state === "running") {
        subscription._state = "ready";
    }
}
function onNotify(subscription, type, value) {
    if (subscription._state === "closed") {
        return;
    }
    if (subscription._state === "buffering") {
        subscription._queue = subscription._queue || [];
        subscription._queue.push({ type, value });
        return;
    }
    if (subscription._state !== "ready") {
        subscription._state = "buffering";
        subscription._queue = [{ type, value }];
        enqueue(() => flushSubscription(subscription));
        return;
    }
    notifySubscription(subscription, type, value);
}
class Subscription {
    constructor(observer, subscriber) {
        // ASSERT: observer is an object
        // ASSERT: subscriber is callable
        this._cleanup = undefined;
        this._observer = observer;
        this._queue = undefined;
        this._state = "initializing";
        const subscriptionObserver = new SubscriptionObserver(this);
        try {
            this._cleanup = subscriber.call(undefined, subscriptionObserver);
        }
        catch (e) {
            subscriptionObserver.error(e);
        }
        if (this._state === "initializing") {
            this._state = "ready";
        }
    }
    get closed() {
        return this._state === "closed";
    }
    unsubscribe() {
        if (this._state !== "closed") {
            closeSubscription(this);
            cleanupSubscription(this);
        }
    }
}
class SubscriptionObserver {
    constructor(subscription) { this._subscription = subscription; }
    get closed() { return this._subscription._state === "closed"; }
    next(value) { onNotify(this._subscription, "next", value); }
    error(value) { onNotify(this._subscription, "error", value); }
    complete() { onNotify(this._subscription, "complete"); }
}
/**
 * The basic Observable class. This primitive is used to wrap asynchronous
 * data streams in a common standardized data type that is interoperable
 * between libraries and can be composed to represent more complex processes.
 */
class Observable {
    constructor(subscriber) {
        if (!(this instanceof Observable)) {
            throw new TypeError("Observable cannot be called as a function");
        }
        if (typeof subscriber !== "function") {
            throw new TypeError("Observable initializer must be a function");
        }
        this._subscriber = subscriber;
    }
    subscribe(nextOrObserver, onError, onComplete) {
        if (typeof nextOrObserver !== "object" || nextOrObserver === null) {
            nextOrObserver = {
                next: nextOrObserver,
                error: onError,
                complete: onComplete
            };
        }
        return new Subscription(nextOrObserver, this._subscriber);
    }
    pipe(first, ...mappers) {
        // tslint:disable-next-line no-this-assignment
        let intermediate = this;
        for (const mapper of [first, ...mappers]) {
            intermediate = mapper(intermediate);
        }
        return intermediate;
    }
    tap(nextOrObserver, onError, onComplete) {
        const tapObserver = typeof nextOrObserver !== "object" || nextOrObserver === null
            ? {
                next: nextOrObserver,
                error: onError,
                complete: onComplete
            }
            : nextOrObserver;
        return new Observable(observer => {
            return this.subscribe({
                next(value) {
                    tapObserver.next && tapObserver.next(value);
                    observer.next(value);
                },
                error(error) {
                    tapObserver.error && tapObserver.error(error);
                    observer.error(error);
                },
                complete() {
                    tapObserver.complete && tapObserver.complete();
                    observer.complete();
                },
                start(subscription) {
                    tapObserver.start && tapObserver.start(subscription);
                }
            });
        });
    }
    forEach(fn) {
        return new Promise((resolve, reject) => {
            if (typeof fn !== "function") {
                reject(new TypeError(fn + " is not a function"));
                return;
            }
            function done() {
                subscription.unsubscribe();
                resolve(undefined);
            }
            const subscription = this.subscribe({
                next(value) {
                    try {
                        fn(value, done);
                    }
                    catch (e) {
                        reject(e);
                        subscription.unsubscribe();
                    }
                },
                error(error) {
                    reject(error);
                },
                complete() {
                    resolve(undefined);
                }
            });
        });
    }
    map(fn) {
        if (typeof fn !== "function") {
            throw new TypeError(fn + " is not a function");
        }
        const C = getSpecies(this);
        return new C(observer => this.subscribe({
            next(value) {
                let propagatedValue = value;
                try {
                    propagatedValue = fn(value);
                }
                catch (e) {
                    return observer.error(e);
                }
                observer.next(propagatedValue);
            },
            error(e) { observer.error(e); },
            complete() { observer.complete(); },
        }));
    }
    filter(fn) {
        if (typeof fn !== "function") {
            throw new TypeError(fn + " is not a function");
        }
        const C = getSpecies(this);
        return new C(observer => this.subscribe({
            next(value) {
                try {
                    if (!fn(value))
                        return;
                }
                catch (e) {
                    return observer.error(e);
                }
                observer.next(value);
            },
            error(e) { observer.error(e); },
            complete() { observer.complete(); },
        }));
    }
    reduce(fn, seed) {
        if (typeof fn !== "function") {
            throw new TypeError(fn + " is not a function");
        }
        const C = getSpecies(this);
        const hasSeed = arguments.length > 1;
        let hasValue = false;
        let acc = seed;
        return new C(observer => this.subscribe({
            next(value) {
                const first = !hasValue;
                hasValue = true;
                if (!first || hasSeed) {
                    try {
                        acc = fn(acc, value);
                    }
                    catch (e) {
                        return observer.error(e);
                    }
                }
                else {
                    acc = value;
                }
            },
            error(e) { observer.error(e); },
            complete() {
                if (!hasValue && !hasSeed) {
                    return observer.error(new TypeError("Cannot reduce an empty sequence"));
                }
                observer.next(acc);
                observer.complete();
            },
        }));
    }
    concat(...sources) {
        const C = getSpecies(this);
        return new C(observer => {
            let subscription;
            let index = 0;
            function startNext(next) {
                subscription = next.subscribe({
                    next(v) { observer.next(v); },
                    error(e) { observer.error(e); },
                    complete() {
                        if (index === sources.length) {
                            subscription = undefined;
                            observer.complete();
                        }
                        else {
                            startNext(C.from(sources[index++]));
                        }
                    },
                });
            }
            startNext(this);
            return () => {
                if (subscription) {
                    subscription.unsubscribe();
                    subscription = undefined;
                }
            };
        });
    }
    flatMap(fn) {
        if (typeof fn !== "function") {
            throw new TypeError(fn + " is not a function");
        }
        const C = getSpecies(this);
        return new C(observer => {
            const subscriptions = [];
            const outer = this.subscribe({
                next(value) {
                    let normalizedValue;
                    if (fn) {
                        try {
                            normalizedValue = fn(value);
                        }
                        catch (e) {
                            return observer.error(e);
                        }
                    }
                    else {
                        normalizedValue = value;
                    }
                    const inner = C.from(normalizedValue).subscribe({
                        next(innerValue) { observer.next(innerValue); },
                        error(e) { observer.error(e); },
                        complete() {
                            const i = subscriptions.indexOf(inner);
                            if (i >= 0)
                                subscriptions.splice(i, 1);
                            completeIfDone();
                        },
                    });
                    subscriptions.push(inner);
                },
                error(e) { observer.error(e); },
                complete() { completeIfDone(); },
            });
            function completeIfDone() {
                if (outer.closed && subscriptions.length === 0) {
                    observer.complete();
                }
            }
            return () => {
                subscriptions.forEach(s => s.unsubscribe());
                outer.unsubscribe();
            };
        });
    }
    [(Symbol.observable, SymbolObservable)]() { return this; }
    static from(x) {
        const C = (typeof this === "function" ? this : Observable);
        if (x == null) {
            throw new TypeError(x + " is not an object");
        }
        const observableMethod = getMethod(x, SymbolObservable);
        if (observableMethod) {
            const observable = observableMethod.call(x);
            if (Object(observable) !== observable) {
                throw new TypeError(observable + " is not an object");
            }
            if (isObservable(observable) && observable.constructor === C) {
                return observable;
            }
            return new C(observer => observable.subscribe(observer));
        }
        if (hasSymbol("iterator")) {
            const iteratorMethod = getMethod(x, SymbolIterator);
            if (iteratorMethod) {
                return new C(observer => {
                    enqueue(() => {
                        if (observer.closed)
                            return;
                        for (const item of iteratorMethod.call(x)) {
                            observer.next(item);
                            if (observer.closed)
                                return;
                        }
                        observer.complete();
                    });
                });
            }
        }
        if (Array.isArray(x)) {
            return new C(observer => {
                enqueue(() => {
                    if (observer.closed)
                        return;
                    for (const item of x) {
                        observer.next(item);
                        if (observer.closed)
                            return;
                    }
                    observer.complete();
                });
            });
        }
        throw new TypeError(x + " is not observable");
    }
    static of(...items) {
        const C = (typeof this === "function" ? this : Observable);
        return new C(observer => {
            enqueue(() => {
                if (observer.closed)
                    return;
                for (const item of items) {
                    observer.next(item);
                    if (observer.closed)
                        return;
                }
                observer.complete();
            });
        });
    }
    static get [SymbolSpecies]() { return this; }
}
if (hasSymbols()) {
    Object.defineProperty(Observable, Symbol("extensions"), {
        value: {
            symbol: SymbolObservable,
            hostReportError,
        },
        configurable: true,
    });
}
/* harmony default export */ const dist_esm_observable = (Observable);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/unsubscribe.js
/**
 * Unsubscribe from a subscription returned by something that looks like an observable,
 * but is not necessarily our observable implementation.
 */
function unsubscribe(subscription) {
    if (typeof subscription === "function") {
        subscription();
    }
    else if (subscription && typeof subscription.unsubscribe === "function") {
        subscription.unsubscribe();
    }
}
/* harmony default export */ const dist_esm_unsubscribe = (unsubscribe);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/filter.js
var filter_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



/**
 * Filters the values emitted by another observable.
 * To be applied to an input observable using `pipe()`.
 */
function filter(test) {
    return (observable) => {
        return new dist_esm_observable(observer => {
            const scheduler = new AsyncSerialScheduler(observer);
            const subscription = observable.subscribe({
                complete() {
                    scheduler.complete();
                },
                error(error) {
                    scheduler.error(error);
                },
                next(input) {
                    scheduler.schedule((next) => filter_awaiter(this, void 0, void 0, function* () {
                        if (yield test(input)) {
                            next(input);
                        }
                    }));
                }
            });
            return () => dist_esm_unsubscribe(subscription);
        });
    };
}
/* harmony default export */ const dist_esm_filter = (filter);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/_util.js
/// <reference lib="es2018" />

function isAsyncIterator(thing) {
    return thing && hasSymbol("asyncIterator") && thing[Symbol.asyncIterator];
}
function isIterator(thing) {
    return thing && hasSymbol("iterator") && thing[Symbol.iterator];
}

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/flatMap.js
var flatMap_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};




/**
 * Maps the values emitted by another observable. In contrast to `map()`
 * the `mapper` function returns an array of values that will be emitted
 * separately.
 * Use `flatMap()` to map input values to zero, one or multiple output
 * values. To be applied to an input observable using `pipe()`.
 */
function flatMap(mapper) {
    return (observable) => {
        return new dist_esm_observable(observer => {
            const scheduler = new AsyncSerialScheduler(observer);
            const subscription = observable.subscribe({
                complete() {
                    scheduler.complete();
                },
                error(error) {
                    scheduler.error(error);
                },
                next(input) {
                    scheduler.schedule((next) => flatMap_awaiter(this, void 0, void 0, function* () {
                        var e_1, _a;
                        const mapped = yield mapper(input);
                        if (isIterator(mapped) || isAsyncIterator(mapped)) {
                            try {
                                for (var mapped_1 = __asyncValues(mapped), mapped_1_1; mapped_1_1 = yield mapped_1.next(), !mapped_1_1.done;) {
                                    const element = mapped_1_1.value;
                                    next(element);
                                }
                            }
                            catch (e_1_1) { e_1 = { error: e_1_1 }; }
                            finally {
                                try {
                                    if (mapped_1_1 && !mapped_1_1.done && (_a = mapped_1.return)) yield _a.call(mapped_1);
                                }
                                finally { if (e_1) throw e_1.error; }
                            }
                        }
                        else {
                            mapped.map(output => next(output));
                        }
                    }));
                }
            });
            return () => dist_esm_unsubscribe(subscription);
        });
    };
}
/* harmony default export */ const dist_esm_flatMap = (flatMap);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/interval.js

/**
 * Creates an observable that yields a new value every `period` milliseconds.
 * The first value emitted is 0, then 1, 2, etc. The first value is not emitted
 * immediately, but after the first interval.
 */
function interval(period) {
    return new Observable(observer => {
        let counter = 0;
        const handle = setInterval(() => {
            observer.next(counter++);
        }, period);
        return () => clearInterval(handle);
    });
}

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/map.js
var map_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



/**
 * Maps the values emitted by another observable to different values.
 * To be applied to an input observable using `pipe()`.
 */
function map(mapper) {
    return (observable) => {
        return new dist_esm_observable(observer => {
            const scheduler = new AsyncSerialScheduler(observer);
            const subscription = observable.subscribe({
                complete() {
                    scheduler.complete();
                },
                error(error) {
                    scheduler.error(error);
                },
                next(input) {
                    scheduler.schedule((next) => map_awaiter(this, void 0, void 0, function* () {
                        const mapped = yield mapper(input);
                        next(mapped);
                    }));
                }
            });
            return () => dist_esm_unsubscribe(subscription);
        });
    };
}
/* harmony default export */ const dist_esm_map = (map);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/merge.js


function merge(...observables) {
    if (observables.length === 0) {
        return Observable.from([]);
    }
    return new Observable(observer => {
        let completed = 0;
        const subscriptions = observables.map(input => {
            return input.subscribe({
                error(error) {
                    observer.error(error);
                    unsubscribeAll();
                },
                next(value) {
                    observer.next(value);
                },
                complete() {
                    if (++completed === observables.length) {
                        observer.complete();
                        unsubscribeAll();
                    }
                }
            });
        });
        const unsubscribeAll = () => {
            subscriptions.forEach(subscription => dist_esm_unsubscribe(subscription));
        };
        return unsubscribeAll;
    });
}
/* harmony default export */ const dist_esm_merge = (merge);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/subject.js

// TODO: This observer iteration approach looks inelegant and expensive
// Idea: Come up with super class for Subscription that contains the
//       notify*, ... methods and use it here
/**
 * A subject is a "hot" observable (see `multicast`) that has its observer
 * methods (`.next(value)`, `.error(error)`, `.complete()`) exposed.
 *
 * Be careful, though! With great power comes great responsibility. Only use
 * the `Subject` when you really need to trigger updates "from the outside" and
 * try to keep the code that can access it to a minimum. Return
 * `Observable.from(mySubject)` to not allow other code to mutate.
 */
class MulticastSubject extends dist_esm_observable {
    constructor() {
        super(observer => {
            this._observers.add(observer);
            return () => this._observers.delete(observer);
        });
        this._observers = new Set();
    }
    next(value) {
        for (const observer of this._observers) {
            observer.next(value);
        }
    }
    error(error) {
        for (const observer of this._observers) {
            observer.error(error);
        }
    }
    complete() {
        for (const observer of this._observers) {
            observer.complete();
        }
    }
}
/* harmony default export */ const dist_esm_subject = (MulticastSubject);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/multicast.js



// TODO: Subject already creates additional observables "under the hood",
//       now we introduce even more. A true native MulticastObservable
//       would be preferable.
/**
 * Takes a "cold" observable and returns a wrapping "hot" observable that
 * proxies the input observable's values and errors.
 *
 * An observable is called "cold" when its initialization function is run
 * for each new subscriber. This is how observable-fns's `Observable`
 * implementation works.
 *
 * A hot observable is an observable where new subscribers subscribe to
 * the upcoming values of an already-initialiazed observable.
 *
 * The multicast observable will lazily subscribe to the source observable
 * once it has its first own subscriber and will unsubscribe from the
 * source observable when its last own subscriber unsubscribed.
 */
function multicast(coldObservable) {
    const subject = new dist_esm_subject();
    let sourceSubscription;
    let subscriberCount = 0;
    return new dist_esm_observable(observer => {
        // Init source subscription lazily
        if (!sourceSubscription) {
            sourceSubscription = coldObservable.subscribe(subject);
        }
        // Pipe all events from `subject` into this observable
        const subscription = subject.subscribe(observer);
        subscriberCount++;
        return () => {
            subscriberCount--;
            subscription.unsubscribe();
            // Close source subscription once last subscriber has unsubscribed
            if (subscriberCount === 0) {
                dist_esm_unsubscribe(sourceSubscription);
                sourceSubscription = undefined;
            }
        };
    });
}
/* harmony default export */ const dist_esm_multicast = (multicast);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/scan.js
var scan_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};



function scan(accumulator, seed) {
    return (observable) => {
        return new dist_esm_observable(observer => {
            let accumulated;
            let index = 0;
            const scheduler = new AsyncSerialScheduler(observer);
            const subscription = observable.subscribe({
                complete() {
                    scheduler.complete();
                },
                error(error) {
                    scheduler.error(error);
                },
                next(value) {
                    scheduler.schedule((next) => scan_awaiter(this, void 0, void 0, function* () {
                        const prevAcc = index === 0
                            ? (typeof seed === "undefined" ? value : seed)
                            : accumulated;
                        accumulated = yield accumulator(prevAcc, value, index++);
                        next(accumulated);
                    }));
                }
            });
            return () => dist_esm_unsubscribe(subscription);
        });
    };
}
/* harmony default export */ const dist_esm_scan = (scan);

;// CONCATENATED MODULE: ./node_modules/observable-fns/dist.esm/index.js












/***/ }),

/***/ 9618:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "ALPHA_MODES": () => (/* reexport */ constants_ALPHA_MODES),
  "AbstractBatchRenderer": () => (/* reexport */ AbstractBatchRenderer),
  "AbstractMultiResource": () => (/* reexport */ AbstractMultiResource),
  "AbstractRenderer": () => (/* reexport */ AbstractRenderer),
  "AccessibilityManager": () => (/* reexport */ AccessibilityManager),
  "AnimatedSprite": () => (/* reexport */ AnimatedSprite),
  "AppLoaderPlugin": () => (/* reexport */ AppLoaderPlugin),
  "Application": () => (/* reexport */ Application),
  "ArrayResource": () => (/* reexport */ ArrayResource),
  "Attribute": () => (/* reexport */ Attribute),
  "BLEND_MODES": () => (/* reexport */ constants_BLEND_MODES),
  "BUFFER_BITS": () => (/* reexport */ constants_BUFFER_BITS),
  "BUFFER_TYPE": () => (/* reexport */ constants_BUFFER_TYPE),
  "BaseImageResource": () => (/* reexport */ BaseImageResource),
  "BasePrepare": () => (/* reexport */ BasePrepare),
  "BaseRenderTexture": () => (/* reexport */ BaseRenderTexture),
  "BaseTexture": () => (/* reexport */ BaseTexture),
  "BatchDrawCall": () => (/* reexport */ BatchDrawCall),
  "BatchGeometry": () => (/* reexport */ BatchGeometry),
  "BatchPluginFactory": () => (/* reexport */ BatchPluginFactory),
  "BatchRenderer": () => (/* reexport */ BatchRenderer),
  "BatchShaderGenerator": () => (/* reexport */ BatchShaderGenerator),
  "BatchSystem": () => (/* reexport */ BatchSystem),
  "BatchTextureArray": () => (/* reexport */ BatchTextureArray),
  "BitmapFont": () => (/* reexport */ BitmapFont),
  "BitmapFontData": () => (/* reexport */ BitmapFontData),
  "BitmapFontLoader": () => (/* reexport */ BitmapFontLoader),
  "BitmapText": () => (/* reexport */ BitmapText),
  "BlobResource": () => (/* reexport */ BlobResource),
  "Bounds": () => (/* reexport */ Bounds),
  "Buffer": () => (/* reexport */ Buffer),
  "BufferResource": () => (/* reexport */ BufferResource),
  "CLEAR_MODES": () => (/* reexport */ constants_CLEAR_MODES),
  "CanvasResource": () => (/* reexport */ CanvasResource),
  "Circle": () => (/* reexport */ Circle),
  "CompressedTextureLoader": () => (/* reexport */ CompressedTextureLoader),
  "CompressedTextureResource": () => (/* reexport */ CompressedTextureResource),
  "Container": () => (/* reexport */ Container),
  "ContextSystem": () => (/* reexport */ ContextSystem),
  "CountLimiter": () => (/* reexport */ CountLimiter),
  "CubeResource": () => (/* reexport */ CubeResource),
  "DDSLoader": () => (/* reexport */ DDSLoader),
  "DEG_TO_RAD": () => (/* reexport */ DEG_TO_RAD),
  "DRAW_MODES": () => (/* reexport */ constants_DRAW_MODES),
  "DisplayObject": () => (/* reexport */ DisplayObject),
  "ENV": () => (/* reexport */ constants_ENV),
  "Ellipse": () => (/* reexport */ Ellipse),
  "Extract": () => (/* reexport */ Extract),
  "FORMATS": () => (/* reexport */ constants_FORMATS),
  "FORMATS_TO_COMPONENTS": () => (/* reexport */ FORMATS_TO_COMPONENTS),
  "FillStyle": () => (/* reexport */ FillStyle),
  "Filter": () => (/* reexport */ Filter),
  "FilterState": () => (/* reexport */ FilterState),
  "FilterSystem": () => (/* reexport */ FilterSystem),
  "Framebuffer": () => (/* reexport */ Framebuffer),
  "FramebufferSystem": () => (/* reexport */ FramebufferSystem),
  "GC_MODES": () => (/* reexport */ constants_GC_MODES),
  "GLFramebuffer": () => (/* reexport */ GLFramebuffer),
  "GLProgram": () => (/* reexport */ GLProgram),
  "GLTexture": () => (/* reexport */ GLTexture),
  "GRAPHICS_CURVES": () => (/* reexport */ GRAPHICS_CURVES),
  "Geometry": () => (/* reexport */ Geometry),
  "GeometrySystem": () => (/* reexport */ GeometrySystem),
  "Graphics": () => (/* reexport */ Graphics),
  "GraphicsData": () => (/* reexport */ GraphicsData),
  "GraphicsGeometry": () => (/* reexport */ GraphicsGeometry),
  "IGLUniformData": () => (/* reexport */ IGLUniformData),
  "INSTALLED": () => (/* reexport */ INSTALLED),
  "INTERNAL_FORMATS": () => (/* reexport */ INTERNAL_FORMATS),
  "INTERNAL_FORMAT_TO_BYTES_PER_PIXEL": () => (/* reexport */ INTERNAL_FORMAT_TO_BYTES_PER_PIXEL),
  "ImageBitmapResource": () => (/* reexport */ ImageBitmapResource),
  "ImageResource": () => (/* reexport */ ImageResource),
  "InteractionData": () => (/* reexport */ InteractionData),
  "InteractionEvent": () => (/* reexport */ InteractionEvent),
  "InteractionManager": () => (/* reexport */ InteractionManager),
  "InteractionTrackingData": () => (/* reexport */ InteractionTrackingData),
  "KTXLoader": () => (/* reexport */ KTXLoader),
  "LINE_CAP": () => (/* reexport */ LINE_CAP),
  "LINE_JOIN": () => (/* reexport */ LINE_JOIN),
  "LineStyle": () => (/* reexport */ LineStyle),
  "Loader": () => (/* reexport */ Loader),
  "LoaderResource": () => (/* reexport */ LoaderResource),
  "MASK_TYPES": () => (/* reexport */ constants_MASK_TYPES),
  "MIPMAP_MODES": () => (/* reexport */ constants_MIPMAP_MODES),
  "MSAA_QUALITY": () => (/* reexport */ constants_MSAA_QUALITY),
  "MaskData": () => (/* reexport */ MaskData),
  "MaskSystem": () => (/* reexport */ MaskSystem),
  "Matrix": () => (/* reexport */ Matrix),
  "Mesh": () => (/* reexport */ Mesh),
  "MeshBatchUvs": () => (/* reexport */ MeshBatchUvs),
  "MeshGeometry": () => (/* reexport */ MeshGeometry),
  "MeshMaterial": () => (/* reexport */ MeshMaterial),
  "NineSlicePlane": () => (/* reexport */ NineSlicePlane),
  "ObjectRenderer": () => (/* reexport */ ObjectRenderer),
  "ObservablePoint": () => (/* reexport */ ObservablePoint),
  "PI_2": () => (/* reexport */ PI_2),
  "PRECISION": () => (/* reexport */ constants_PRECISION),
  "ParticleContainer": () => (/* reexport */ ParticleContainer),
  "ParticleRenderer": () => (/* reexport */ ParticleRenderer),
  "PlaneGeometry": () => (/* reexport */ PlaneGeometry),
  "Point": () => (/* reexport */ Point),
  "Polygon": () => (/* reexport */ Polygon),
  "Prepare": () => (/* reexport */ Prepare),
  "Program": () => (/* reexport */ Program),
  "ProjectionSystem": () => (/* reexport */ ProjectionSystem),
  "Quad": () => (/* reexport */ Quad),
  "QuadUv": () => (/* reexport */ QuadUv),
  "RAD_TO_DEG": () => (/* reexport */ RAD_TO_DEG),
  "RENDERER_TYPE": () => (/* reexport */ constants_RENDERER_TYPE),
  "Rectangle": () => (/* reexport */ Rectangle),
  "RenderTexture": () => (/* reexport */ RenderTexture),
  "RenderTexturePool": () => (/* reexport */ RenderTexturePool),
  "RenderTextureSystem": () => (/* reexport */ RenderTextureSystem),
  "Renderer": () => (/* reexport */ Renderer),
  "Resource": () => (/* reexport */ Resource),
  "RopeGeometry": () => (/* reexport */ RopeGeometry),
  "RoundedRectangle": () => (/* reexport */ RoundedRectangle),
  "Runner": () => (/* reexport */ Runner),
  "SAMPLER_TYPES": () => (/* reexport */ constants_SAMPLER_TYPES),
  "SCALE_MODES": () => (/* reexport */ constants_SCALE_MODES),
  "SHAPES": () => (/* reexport */ SHAPES),
  "SVGResource": () => (/* reexport */ SVGResource),
  "ScissorSystem": () => (/* reexport */ ScissorSystem),
  "Shader": () => (/* reexport */ Shader),
  "ShaderSystem": () => (/* reexport */ ShaderSystem),
  "SimpleMesh": () => (/* reexport */ SimpleMesh),
  "SimplePlane": () => (/* reexport */ SimplePlane),
  "SimpleRope": () => (/* reexport */ SimpleRope),
  "Sprite": () => (/* reexport */ Sprite),
  "SpriteMaskFilter": () => (/* reexport */ SpriteMaskFilter),
  "Spritesheet": () => (/* reexport */ Spritesheet),
  "SpritesheetLoader": () => (/* reexport */ SpritesheetLoader),
  "State": () => (/* reexport */ State),
  "StateSystem": () => (/* reexport */ StateSystem),
  "StencilSystem": () => (/* reexport */ StencilSystem),
  "System": () => (/* reexport */ System),
  "TARGETS": () => (/* reexport */ constants_TARGETS),
  "TEXT_GRADIENT": () => (/* reexport */ TEXT_GRADIENT),
  "TYPES": () => (/* reexport */ constants_TYPES),
  "TYPES_TO_BYTES_PER_COMPONENT": () => (/* reexport */ TYPES_TO_BYTES_PER_COMPONENT),
  "TYPES_TO_BYTES_PER_PIXEL": () => (/* reexport */ TYPES_TO_BYTES_PER_PIXEL),
  "TemporaryDisplayObject": () => (/* reexport */ TemporaryDisplayObject),
  "Text": () => (/* reexport */ Text),
  "TextMetrics": () => (/* reexport */ TextMetrics),
  "TextStyle": () => (/* reexport */ TextStyle),
  "Texture": () => (/* reexport */ Texture),
  "TextureGCSystem": () => (/* reexport */ TextureGCSystem),
  "TextureLoader": () => (/* reexport */ TextureLoader),
  "TextureMatrix": () => (/* reexport */ TextureMatrix),
  "TextureSystem": () => (/* reexport */ TextureSystem),
  "TextureUvs": () => (/* reexport */ TextureUvs),
  "Ticker": () => (/* reexport */ Ticker),
  "TickerPlugin": () => (/* reexport */ TickerPlugin),
  "TilingSprite": () => (/* reexport */ TilingSprite),
  "TilingSpriteRenderer": () => (/* reexport */ TilingSpriteRenderer),
  "TimeLimiter": () => (/* reexport */ TimeLimiter),
  "Transform": () => (/* reexport */ Transform),
  "UPDATE_PRIORITY": () => (/* reexport */ UPDATE_PRIORITY),
  "UniformGroup": () => (/* reexport */ UniformGroup),
  "VERSION": () => (/* binding */ pixi_VERSION),
  "VideoResource": () => (/* reexport */ VideoResource),
  "ViewableBuffer": () => (/* reexport */ ViewableBuffer),
  "WRAP_MODES": () => (/* reexport */ constants_WRAP_MODES),
  "accessibleTarget": () => (/* reexport */ accessibleTarget),
  "autoDetectRenderer": () => (/* reexport */ autoDetectRenderer),
  "autoDetectResource": () => (/* reexport */ autoDetectResource),
  "checkMaxIfStatementsInShader": () => (/* reexport */ checkMaxIfStatementsInShader),
  "createUBOElements": () => (/* reexport */ createUBOElements),
  "defaultFilterVertex": () => (/* reexport */ defaultFilterVertex),
  "defaultVertex": () => (/* reexport */ defaultVertex$2),
  "filters": () => (/* binding */ filters),
  "generateProgram": () => (/* reexport */ generateProgram),
  "generateUniformBufferSync": () => (/* reexport */ generateUniformBufferSync),
  "getTestContext": () => (/* reexport */ getTestContext),
  "getUBOData": () => (/* reexport */ getUBOData),
  "graphicsUtils": () => (/* reexport */ graphicsUtils),
  "groupD8": () => (/* reexport */ groupD8),
  "interactiveTarget": () => (/* reexport */ interactiveTarget),
  "isMobile": () => (/* reexport */ settings_isMobile),
  "resources": () => (/* reexport */ resources),
  "settings": () => (/* reexport */ settings),
  "systems": () => (/* reexport */ systems),
  "uniformParsers": () => (/* reexport */ uniformParsers),
  "utils": () => (/* reexport */ utils_namespaceObject)
});

// NAMESPACE OBJECT: ./node_modules/@pixi/utils/dist/esm/utils.js
var utils_namespaceObject = {};
__webpack_require__.r(utils_namespaceObject);
__webpack_require__.d(utils_namespaceObject, {
  "BaseTextureCache": () => (BaseTextureCache),
  "CanvasRenderTarget": () => (CanvasRenderTarget),
  "DATA_URI": () => (DATA_URI),
  "EventEmitter": () => ((eventemitter3_default())),
  "ProgramCache": () => (ProgramCache),
  "TextureCache": () => (TextureCache),
  "clearTextureCache": () => (clearTextureCache),
  "correctBlendMode": () => (correctBlendMode),
  "createIndicesForQuads": () => (createIndicesForQuads),
  "decomposeDataUri": () => (decomposeDataUri),
  "deprecation": () => (deprecation),
  "destroyTextureCache": () => (destroyTextureCache),
  "determineCrossOrigin": () => (determineCrossOrigin),
  "earcut": () => ((earcut_default())),
  "getBufferType": () => (getBufferType),
  "getResolutionOfUrl": () => (getResolutionOfUrl),
  "hex2rgb": () => (hex2rgb),
  "hex2string": () => (hex2string),
  "interleaveTypedArrays": () => (interleaveTypedArrays),
  "isMobile": () => (settings_isMobile),
  "isPow2": () => (isPow2),
  "isWebGLSupported": () => (isWebGLSupported),
  "log2": () => (log2),
  "nextPow2": () => (nextPow2),
  "premultiplyBlendMode": () => (premultiplyBlendMode),
  "premultiplyRgba": () => (premultiplyRgba),
  "premultiplyTint": () => (premultiplyTint),
  "premultiplyTintToRgba": () => (premultiplyTintToRgba),
  "removeItems": () => (removeItems),
  "rgb2hex": () => (rgb2hex),
  "sayHello": () => (sayHello),
  "sign": () => (sign),
  "skipHello": () => (skipHello),
  "string2hex": () => (string2hex),
  "trimCanvas": () => (trimCanvas),
  "uid": () => (uid),
  "url": () => (utils_url)
});

;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/finally.js
/**
 * @this {Promise}
 */
function finallyConstructor(callback) {
  var constructor = this.constructor;
  return this.then(
    function(value) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        return value;
      });
    },
    function(reason) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        // @ts-ignore
        return constructor.reject(reason);
      });
    }
  );
}

/* harmony default export */ const src_finally = (finallyConstructor);

;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/allSettled.js
function allSettled(arr) {
  var P = this;
  return new P(function(resolve, reject) {
    if (!(arr && typeof arr.length !== 'undefined')) {
      return reject(
        new TypeError(
          typeof arr +
            ' ' +
            arr +
            ' is not iterable(cannot read property Symbol(Symbol.iterator))'
        )
      );
    }
    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;

    function res(i, val) {
      if (val && (typeof val === 'object' || typeof val === 'function')) {
        var then = val.then;
        if (typeof then === 'function') {
          then.call(
            val,
            function(val) {
              res(i, val);
            },
            function(e) {
              args[i] = { status: 'rejected', reason: e };
              if (--remaining === 0) {
                resolve(args);
              }
            }
          );
          return;
        }
      }
      args[i] = { status: 'fulfilled', value: val };
      if (--remaining === 0) {
        resolve(args);
      }
    }

    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
}

/* harmony default export */ const src_allSettled = (allSettled);

;// CONCATENATED MODULE: ./node_modules/promise-polyfill/src/index.js



// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;

function isArray(x) {
  return Boolean(x && typeof x.length !== 'undefined');
}

function noop() {}

// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
  return function() {
    fn.apply(thisArg, arguments);
  };
}

/**
 * @constructor
 * @param {Function} fn
 */
function src_Promise(fn) {
  if (!(this instanceof src_Promise))
    throw new TypeError('Promises must be constructed via new');
  if (typeof fn !== 'function') throw new TypeError('not a function');
  /** @type {!number} */
  this._state = 0;
  /** @type {!boolean} */
  this._handled = false;
  /** @type {Promise|undefined} */
  this._value = undefined;
  /** @type {!Array<!Function>} */
  this._deferreds = [];

  doResolve(fn, this);
}

function handle(self, deferred) {
  while (self._state === 3) {
    self = self._value;
  }
  if (self._state === 0) {
    self._deferreds.push(deferred);
    return;
  }
  self._handled = true;
  src_Promise._immediateFn(function() {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  });
}

function resolve(self, newValue) {
  try {
    // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
    if (newValue === self)
      throw new TypeError('A promise cannot be resolved with itself.');
    if (
      newValue &&
      (typeof newValue === 'object' || typeof newValue === 'function')
    ) {
      var then = newValue.then;
      if (newValue instanceof src_Promise) {
        self._state = 3;
        self._value = newValue;
        finale(self);
        return;
      } else if (typeof then === 'function') {
        doResolve(bind(then, newValue), self);
        return;
      }
    }
    self._state = 1;
    self._value = newValue;
    finale(self);
  } catch (e) {
    reject(self, e);
  }
}

function reject(self, newValue) {
  self._state = 2;
  self._value = newValue;
  finale(self);
}

function finale(self) {
  if (self._state === 2 && self._deferreds.length === 0) {
    src_Promise._immediateFn(function() {
      if (!self._handled) {
        src_Promise._unhandledRejectionFn(self._value);
      }
    });
  }

  for (var i = 0, len = self._deferreds.length; i < len; i++) {
    handle(self, self._deferreds[i]);
  }
  self._deferreds = null;
}

/**
 * @constructor
 */
function Handler(onFulfilled, onRejected, promise) {
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  this.promise = promise;
}

/**
 * Take a potentially misbehaving resolver function and make sure
 * onFulfilled and onRejected are only called once.
 *
 * Makes no guarantees about asynchrony.
 */
function doResolve(fn, self) {
  var done = false;
  try {
    fn(
      function(value) {
        if (done) return;
        done = true;
        resolve(self, value);
      },
      function(reason) {
        if (done) return;
        done = true;
        reject(self, reason);
      }
    );
  } catch (ex) {
    if (done) return;
    done = true;
    reject(self, ex);
  }
}

src_Promise.prototype['catch'] = function(onRejected) {
  return this.then(null, onRejected);
};

src_Promise.prototype.then = function(onFulfilled, onRejected) {
  // @ts-ignore
  var prom = new this.constructor(noop);

  handle(this, new Handler(onFulfilled, onRejected, prom));
  return prom;
};

src_Promise.prototype['finally'] = src_finally;

src_Promise.all = function(arr) {
  return new src_Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.all accepts an array'));
    }

    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;

    function res(i, val) {
      try {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then;
          if (typeof then === 'function') {
            then.call(
              val,
              function(val) {
                res(i, val);
              },
              reject
            );
            return;
          }
        }
        args[i] = val;
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex);
      }
    }

    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
};

src_Promise.allSettled = src_allSettled;

src_Promise.resolve = function(value) {
  if (value && typeof value === 'object' && value.constructor === src_Promise) {
    return value;
  }

  return new src_Promise(function(resolve) {
    resolve(value);
  });
};

src_Promise.reject = function(value) {
  return new src_Promise(function(resolve, reject) {
    reject(value);
  });
};

src_Promise.race = function(arr) {
  return new src_Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.race accepts an array'));
    }

    for (var i = 0, len = arr.length; i < len; i++) {
      src_Promise.resolve(arr[i]).then(resolve, reject);
    }
  });
};

// Use polyfill for setImmediate for performance gains
src_Promise._immediateFn =
  // @ts-ignore
  (typeof setImmediate === 'function' &&
    function(fn) {
      // @ts-ignore
      setImmediate(fn);
    }) ||
  function(fn) {
    setTimeoutFunc(fn, 0);
  };

src_Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  if (typeof console !== 'undefined' && console) {
    console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  }
};

/* harmony default export */ const src = (src_Promise);

// EXTERNAL MODULE: ./node_modules/object-assign/index.js
var object_assign = __webpack_require__(7418);
var object_assign_default = /*#__PURE__*/__webpack_require__.n(object_assign);
;// CONCATENATED MODULE: ./node_modules/@pixi/polyfill/dist/esm/polyfill.js
/*!
 * @pixi/polyfill - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/polyfill is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */



if (typeof globalThis === 'undefined') {
    if (typeof self !== 'undefined') {
        // covers browsers
        // @ts-expect-error not-writable ts(2540) error only on node
        self.globalThis = self;
    }
    else if (typeof __webpack_require__.g !== 'undefined') {
        // covers versions of Node < 12
        // @ts-expect-error not-writable ts(2540) error only on node
        __webpack_require__.g.globalThis = __webpack_require__.g;
    }
}

// Support for IE 9 - 11 which does not include Promises
if (!globalThis.Promise) {
    globalThis.Promise = src;
}

// References:
if (!Object.assign) {
    Object.assign = (object_assign_default());
}

// References:
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// https://gist.github.com/1579671
// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
// https://gist.github.com/timhall/4078614
// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame
// Expected to be used with Browserfiy
// Browserify automatically detects the use of `global` and passes the
// correct reference of `global`, `globalThis`, and finally `window`
var ONE_FRAME_TIME = 16;
// Date.now
if (!(Date.now && Date.prototype.getTime)) {
    Date.now = function now() {
        return new Date().getTime();
    };
}
// performance.now
if (!(globalThis.performance && globalThis.performance.now)) {
    var startTime_1 = Date.now();
    if (!globalThis.performance) {
        globalThis.performance = {};
    }
    globalThis.performance.now = function () { return Date.now() - startTime_1; };
}
// requestAnimationFrame
var lastTime = Date.now();
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !globalThis.requestAnimationFrame; ++x) {
    var p = vendors[x];
    globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"];
    globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"]
        || globalThis[p + "CancelRequestAnimationFrame"];
}
if (!globalThis.requestAnimationFrame) {
    globalThis.requestAnimationFrame = function (callback) {
        if (typeof callback !== 'function') {
            throw new TypeError(callback + "is not a function");
        }
        var currentTime = Date.now();
        var delay = ONE_FRAME_TIME + lastTime - currentTime;
        if (delay < 0) {
            delay = 0;
        }
        lastTime = currentTime;
        return globalThis.self.setTimeout(function () {
            lastTime = Date.now();
            callback(performance.now());
        }, delay);
    };
}
if (!globalThis.cancelAnimationFrame) {
    globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); };
}

// References:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
if (!Math.sign) {
    Math.sign = function mathSign(x) {
        x = Number(x);
        if (x === 0 || isNaN(x)) {
            return x;
        }
        return x > 0 ? 1 : -1;
    };
}

// References:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
if (!Number.isInteger) {
    Number.isInteger = function numberIsInteger(value) {
        return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
    };
}

if (!globalThis.ArrayBuffer) {
    globalThis.ArrayBuffer = Array;
}
if (!globalThis.Float32Array) {
    globalThis.Float32Array = Array;
}
if (!globalThis.Uint32Array) {
    globalThis.Uint32Array = Array;
}
if (!globalThis.Uint16Array) {
    globalThis.Uint16Array = Array;
}
if (!globalThis.Uint8Array) {
    globalThis.Uint8Array = Array;
}
if (!globalThis.Int32Array) {
    globalThis.Int32Array = Array;
}
//# sourceMappingURL=polyfill.js.map

;// CONCATENATED MODULE: ./node_modules/ismobilejs/esm/isMobile.js
var appleIphone = /iPhone/i;
var appleIpod = /iPod/i;
var appleTablet = /iPad/i;
var appleUniversal = /\biOS-universal(?:.+)Mac\b/i;
var androidPhone = /\bAndroid(?:.+)Mobile\b/i;
var androidTablet = /Android/i;
var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i;
var amazonTablet = /Silk/i;
var windowsPhone = /Windows Phone/i;
var windowsTablet = /\bWindows(?:.+)ARM\b/i;
var otherBlackBerry = /BlackBerry/i;
var otherBlackBerry10 = /BB10/i;
var otherOpera = /Opera Mini/i;
var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i;
var otherFirefox = /Mobile(?:.+)Firefox\b/i;
var isAppleTabletOnIos13 = function (navigator) {
    return (typeof navigator !== 'undefined' &&
        navigator.platform === 'MacIntel' &&
        typeof navigator.maxTouchPoints === 'number' &&
        navigator.maxTouchPoints > 1 &&
        typeof MSStream === 'undefined');
};
function createMatch(userAgent) {
    return function (regex) { return regex.test(userAgent); };
}
function isMobile(param) {
    var nav = {
        userAgent: '',
        platform: '',
        maxTouchPoints: 0
    };
    if (!param && typeof navigator !== 'undefined') {
        nav = {
            userAgent: navigator.userAgent,
            platform: navigator.platform,
            maxTouchPoints: navigator.maxTouchPoints || 0
        };
    }
    else if (typeof param === 'string') {
        nav.userAgent = param;
    }
    else if (param && param.userAgent) {
        nav = {
            userAgent: param.userAgent,
            platform: param.platform,
            maxTouchPoints: param.maxTouchPoints || 0
        };
    }
    var userAgent = nav.userAgent;
    var tmp = userAgent.split('[FBAN');
    if (typeof tmp[1] !== 'undefined') {
        userAgent = tmp[0];
    }
    tmp = userAgent.split('Twitter');
    if (typeof tmp[1] !== 'undefined') {
        userAgent = tmp[0];
    }
    var match = createMatch(userAgent);
    var result = {
        apple: {
            phone: match(appleIphone) && !match(windowsPhone),
            ipod: match(appleIpod),
            tablet: !match(appleIphone) &&
                (match(appleTablet) || isAppleTabletOnIos13(nav)) &&
                !match(windowsPhone),
            universal: match(appleUniversal),
            device: (match(appleIphone) ||
                match(appleIpod) ||
                match(appleTablet) ||
                match(appleUniversal) ||
                isAppleTabletOnIos13(nav)) &&
                !match(windowsPhone)
        },
        amazon: {
            phone: match(amazonPhone),
            tablet: !match(amazonPhone) && match(amazonTablet),
            device: match(amazonPhone) || match(amazonTablet)
        },
        android: {
            phone: (!match(windowsPhone) && match(amazonPhone)) ||
                (!match(windowsPhone) && match(androidPhone)),
            tablet: !match(windowsPhone) &&
                !match(amazonPhone) &&
                !match(androidPhone) &&
                (match(amazonTablet) || match(androidTablet)),
            device: (!match(windowsPhone) &&
                (match(amazonPhone) ||
                    match(amazonTablet) ||
                    match(androidPhone) ||
                    match(androidTablet))) ||
                match(/\bokhttp\b/i)
        },
        windows: {
            phone: match(windowsPhone),
            tablet: match(windowsTablet),
            device: match(windowsPhone) || match(windowsTablet)
        },
        other: {
            blackberry: match(otherBlackBerry),
            blackberry10: match(otherBlackBerry10),
            opera: match(otherOpera),
            firefox: match(otherFirefox),
            chrome: match(otherChrome),
            device: match(otherBlackBerry) ||
                match(otherBlackBerry10) ||
                match(otherOpera) ||
                match(otherFirefox) ||
                match(otherChrome)
        },
        any: false,
        phone: false,
        tablet: false
    };
    result.any =
        result.apple.device ||
            result.android.device ||
            result.windows.device ||
            result.other.device;
    result.phone =
        result.apple.phone || result.android.phone || result.windows.phone;
    result.tablet =
        result.apple.tablet || result.android.tablet || result.windows.tablet;
    return result;
}
//# sourceMappingURL=isMobile.js.map
;// CONCATENATED MODULE: ./node_modules/@pixi/settings/dist/esm/settings.js
/*!
 * @pixi/settings - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/settings is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


// The ESM/CJS versions of ismobilejs only
var settings_isMobile = isMobile(globalThis.navigator);

/**
 * The maximum recommended texture units to use.
 * In theory the bigger the better, and for desktop we'll use as many as we can.
 * But some mobile devices slow down if there is to many branches in the shader.
 * So in practice there seems to be a sweet spot size that varies depending on the device.
 *
 * In v4, all mobile devices were limited to 4 texture units because for this.
 * In v5, we allow all texture units to be used on modern Apple or Android devices.
 *
 * @private
 * @param {number} max
 * @returns {number}
 */
function maxRecommendedTextures(max) {
    var allowMax = true;
    if (settings_isMobile.tablet || settings_isMobile.phone) {
        if (settings_isMobile.apple.device) {
            var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/);
            if (match) {
                var majorVersion = parseInt(match[1], 10);
                // Limit texture units on devices below iOS 11, which will be older hardware
                if (majorVersion < 11) {
                    allowMax = false;
                }
            }
        }
        if (settings_isMobile.android.device) {
            var match = (navigator.userAgent).match(/Android\s([0-9.]*)/);
            if (match) {
                var majorVersion = parseInt(match[1], 10);
                // Limit texture units on devices below Android 7 (Nougat), which will be older hardware
                if (majorVersion < 7) {
                    allowMax = false;
                }
            }
        }
    }
    return allowMax ? max : 4;
}

/**
 * Uploading the same buffer multiple times in a single frame can cause performance issues.
 * Apparent on iOS so only check for that at the moment
 * This check may become more complex if this issue pops up elsewhere.
 *
 * @private
 * @returns {boolean}
 */
function canUploadSameBuffer() {
    return !settings_isMobile.apple.device;
}

/*!
 * @pixi/constants - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/constants is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * Different types of environments for WebGL.
 *
 * @static
 * @memberof PIXI
 * @name ENV
 * @enum {number}
 * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
 *  with older / less advanced devices. If you experience unexplained flickering prefer this environment.
 * @property {number} WEBGL - Version 1 of WebGL
 * @property {number} WEBGL2 - Version 2 of WebGL
 */
var ENV;
(function (ENV) {
    ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
    ENV[ENV["WEBGL"] = 1] = "WEBGL";
    ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
})(ENV || (ENV = {}));
/**
 * Constant to identify the Renderer Type.
 *
 * @static
 * @memberof PIXI
 * @name RENDERER_TYPE
 * @enum {number}
 * @property {number} UNKNOWN - Unknown render type.
 * @property {number} WEBGL - WebGL render type.
 * @property {number} CANVAS - Canvas render type.
 */
var RENDERER_TYPE;
(function (RENDERER_TYPE) {
    RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
    RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
    RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
})(RENDERER_TYPE || (RENDERER_TYPE = {}));
/**
 * Bitwise OR of masks that indicate the buffers to be cleared.
 *
 * @static
 * @memberof PIXI
 * @name BUFFER_BITS
 * @enum {number}
 * @property {number} COLOR - Indicates the buffers currently enabled for color writing.
 * @property {number} DEPTH - Indicates the depth buffer.
 * @property {number} STENCIL - Indicates the stencil buffer.
 */
var BUFFER_BITS;
(function (BUFFER_BITS) {
    BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR";
    BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH";
    BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL";
})(BUFFER_BITS || (BUFFER_BITS = {}));
/**
 * Various blend modes supported by PIXI.
 *
 * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
 * Anything else will silently act like NORMAL.
 *
 * @memberof PIXI
 * @name BLEND_MODES
 * @enum {number}
 * @property {number} NORMAL
 * @property {number} ADD
 * @property {number} MULTIPLY
 * @property {number} SCREEN
 * @property {number} OVERLAY
 * @property {number} DARKEN
 * @property {number} LIGHTEN
 * @property {number} COLOR_DODGE
 * @property {number} COLOR_BURN
 * @property {number} HARD_LIGHT
 * @property {number} SOFT_LIGHT
 * @property {number} DIFFERENCE
 * @property {number} EXCLUSION
 * @property {number} HUE
 * @property {number} SATURATION
 * @property {number} COLOR
 * @property {number} LUMINOSITY
 * @property {number} NORMAL_NPM
 * @property {number} ADD_NPM
 * @property {number} SCREEN_NPM
 * @property {number} NONE
 * @property {number} SRC_IN
 * @property {number} SRC_OUT
 * @property {number} SRC_ATOP
 * @property {number} DST_OVER
 * @property {number} DST_IN
 * @property {number} DST_OUT
 * @property {number} DST_ATOP
 * @property {number} SUBTRACT
 * @property {number} SRC_OVER
 * @property {number} ERASE
 * @property {number} XOR
 */
var BLEND_MODES;
(function (BLEND_MODES) {
    BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
    BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
    BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
    BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
    BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
    BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
    BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
    BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
    BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
    BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
    BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
    BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
    BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
    BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
    BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
    BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
    BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
    BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
    BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
    BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
    BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
    BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER";
    BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN";
    BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT";
    BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP";
    BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER";
    BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN";
    BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT";
    BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP";
    BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE";
    BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT";
    BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR";
})(BLEND_MODES || (BLEND_MODES = {}));
/**
 * Various webgl draw modes. These can be used to specify which GL drawMode to use
 * under certain situations and renderers.
 *
 * @memberof PIXI
 * @static
 * @name DRAW_MODES
 * @enum {number}
 * @property {number} POINTS
 * @property {number} LINES
 * @property {number} LINE_LOOP
 * @property {number} LINE_STRIP
 * @property {number} TRIANGLES
 * @property {number} TRIANGLE_STRIP
 * @property {number} TRIANGLE_FAN
 */
var DRAW_MODES;
(function (DRAW_MODES) {
    DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
    DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
    DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
    DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
    DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
})(DRAW_MODES || (DRAW_MODES = {}));
/**
 * Various GL texture/resources formats.
 *
 * @memberof PIXI
 * @static
 * @name FORMATS
 * @enum {number}
 * @property {number} RGBA=6408
 * @property {number} RGB=6407
 * @property {number} RG=33319
 * @property {number} RED=6403
 * @property {number} RGBA_INTEGER=36249
 * @property {number} RGB_INTEGER=36248
 * @property {number} RG_INTEGER=33320
 * @property {number} RED_INTEGER=36244
 * @property {number} ALPHA=6406
 * @property {number} LUMINANCE=6409
 * @property {number} LUMINANCE_ALPHA=6410
 * @property {number} DEPTH_COMPONENT=6402
 * @property {number} DEPTH_STENCIL=34041
 */
var FORMATS;
(function (FORMATS) {
    FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
    FORMATS[FORMATS["RGB"] = 6407] = "RGB";
    FORMATS[FORMATS["RG"] = 33319] = "RG";
    FORMATS[FORMATS["RED"] = 6403] = "RED";
    FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
    FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
    FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
    FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
    FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA";
    FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE";
    FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
    FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
    FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
})(FORMATS || (FORMATS = {}));
/**
 * Various GL target types.
 *
 * @memberof PIXI
 * @static
 * @name TARGETS
 * @enum {number}
 * @property {number} TEXTURE_2D=3553
 * @property {number} TEXTURE_CUBE_MAP=34067
 * @property {number} TEXTURE_2D_ARRAY=35866
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074
 */
var TARGETS;
(function (TARGETS) {
    TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
    TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
})(TARGETS || (TARGETS = {}));
/**
 * Various GL data format types.
 *
 * @memberof PIXI
 * @static
 * @name TYPES
 * @enum {number}
 * @property {number} UNSIGNED_BYTE=5121
 * @property {number} UNSIGNED_SHORT=5123
 * @property {number} UNSIGNED_SHORT_5_6_5=33635
 * @property {number} UNSIGNED_SHORT_4_4_4_4=32819
 * @property {number} UNSIGNED_SHORT_5_5_5_1=32820
 * @property {number} UNSIGNED_INT=5125
 * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
 * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
 * @property {number} UNSIGNED_INT_24_8=34042
 * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
 * @property {number} BYTE=5120
 * @property {number} SHORT=5122
 * @property {number} INT=5124
 * @property {number} FLOAT=5126
 * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
 * @property {number} HALF_FLOAT=36193
 */
var TYPES;
(function (TYPES) {
    TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
    TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
    TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
    TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
    TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
    TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
    TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
    TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
    TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
    TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
    TYPES[TYPES["BYTE"] = 5120] = "BYTE";
    TYPES[TYPES["SHORT"] = 5122] = "SHORT";
    TYPES[TYPES["INT"] = 5124] = "INT";
    TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
    TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
    TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
})(TYPES || (TYPES = {}));
/**
 * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
 * WebGL1 works only with FLOAT.
 *
 * @memberof PIXI
 * @static
 * @name SAMPLER_TYPES
 * @enum {number}
 * @property {number} FLOAT=0
 * @property {number} INT=1
 * @property {number} UINT=2
 */
var SAMPLER_TYPES;
(function (SAMPLER_TYPES) {
    SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
    SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
    SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
})(SAMPLER_TYPES || (SAMPLER_TYPES = {}));
/**
 * The scale modes that are supported by pixi.
 *
 * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
 * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
 *
 * @memberof PIXI
 * @static
 * @name SCALE_MODES
 * @enum {number}
 * @property {number} LINEAR Smooth scaling
 * @property {number} NEAREST Pixelating scaling
 */
var SCALE_MODES;
(function (SCALE_MODES) {
    SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
    SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
})(SCALE_MODES || (SCALE_MODES = {}));
/**
 * The wrap modes that are supported by pixi.
 *
 * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
 * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
 * If the texture is non power of two then clamp will be used regardless as WebGL can
 * only use REPEAT if the texture is po2.
 *
 * This property only affects WebGL.
 *
 * @name WRAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} CLAMP - The textures uvs are clamped
 * @property {number} REPEAT - The texture uvs tile and repeat
 * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
 */
var WRAP_MODES;
(function (WRAP_MODES) {
    WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
    WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
    WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
})(WRAP_MODES || (WRAP_MODES = {}));
/**
 * Mipmap filtering modes that are supported by pixi.
 *
 * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
 * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
 * or its `POW2` and texture dimensions are powers of 2.
 * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
 *
 * This property only affects WebGL.
 *
 * @name MIPMAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} OFF - No mipmaps
 * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
 * @property {number} ON - Always generate mipmaps
 * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
 *   that supports buffering each level-of-detail.
 */
var MIPMAP_MODES;
(function (MIPMAP_MODES) {
    MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF";
    MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2";
    MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON";
    MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL";
})(MIPMAP_MODES || (MIPMAP_MODES = {}));
/**
 * How to treat textures with premultiplied alpha
 *
 * @name ALPHA_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that.
 *  Option for compressed and data textures that are created from typed arrays.
 * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload.
 *  Default option, used for all loaded images.
 * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied
 *  Example: spine atlases with `_pma` suffix.
 * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA.
 * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD.
 * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA.
 */
var ALPHA_MODES;
(function (ALPHA_MODES) {
    ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM";
    ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK";
    ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA";
    ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
})(ALPHA_MODES || (ALPHA_MODES = {}));
/**
 * Configure whether filter textures are cleared after binding.
 *
 * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
 * this and skip clearing as an optimization.
 *
 * @name CLEAR_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
 * @property {number} CLEAR - Always clear the filter texture.
 * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
 * @property {number} NO - Alias for BLEND, same as `false` in earlier versions
 * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions
 * @property {number} AUTO - Alias for BLIT
 */
var CLEAR_MODES;
(function (CLEAR_MODES) {
    CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO";
    CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES";
    CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO";
    CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND";
    CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR";
    CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT";
})(CLEAR_MODES || (CLEAR_MODES = {}));
/**
 * The gc modes that are supported by pixi.
 *
 * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
 * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
 * used for a specified period of time they will be removed from the GPU. They will of course
 * be uploaded again when they are required. This is a silent behind the scenes process that
 * should ensure that the GPU does not  get filled up.
 *
 * Handy for mobile devices!
 * This property only affects WebGL.
 *
 * @name GC_MODES
 * @enum {number}
 * @static
 * @memberof PIXI
 * @property {number} AUTO - Garbage collection will happen periodically automatically
 * @property {number} MANUAL - Garbage collection will need to be called manually
 */
var GC_MODES;
(function (GC_MODES) {
    GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
    GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
})(GC_MODES || (GC_MODES = {}));
/**
 * Constants that specify float precision in shaders.
 *
 * @name PRECISION
 * @memberof PIXI
 * @constant
 * @static
 * @enum {string}
 * @property {string} LOW='lowp'
 * @property {string} MEDIUM='mediump'
 * @property {string} HIGH='highp'
 */
var PRECISION;
(function (PRECISION) {
    PRECISION["LOW"] = "lowp";
    PRECISION["MEDIUM"] = "mediump";
    PRECISION["HIGH"] = "highp";
})(PRECISION || (PRECISION = {}));
/**
 * Constants for mask implementations.
 * We use `type` suffix because it leads to very different behaviours
 *
 * @name MASK_TYPES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - Mask is ignored
 * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap
 * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil
 * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture
 */
var MASK_TYPES;
(function (MASK_TYPES) {
    MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE";
    MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR";
    MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL";
    MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE";
})(MASK_TYPES || (MASK_TYPES = {}));
/**
 * Constants for multi-sampling antialiasing.
 *
 * @see PIXI.Framebuffer#multisample
 *
 * @name MSAA_QUALITY
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - No multisampling for this renderTexture
 * @property {number} LOW - Try 2 samples
 * @property {number} MEDIUM - Try 4 samples
 * @property {number} HIGH - Try 8 samples
 */
var MSAA_QUALITY;
(function (MSAA_QUALITY) {
    MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE";
    MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW";
    MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM";
    MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH";
})(MSAA_QUALITY || (MSAA_QUALITY = {}));
/**
 * Constants for various buffer types in Pixi
 *
 * @see PIXI.BUFFER_TYPE
 *
 * @name BUFFER_TYPE
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
 * @property {number} ARRAY_BUFFER - buffer type for using attribute data
 * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
 */
var BUFFER_TYPE;
(function (BUFFER_TYPE) {
    BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
    BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
    // NOT YET SUPPORTED
    BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
})(BUFFER_TYPE || (BUFFER_TYPE = {}));

/**
 * User's customizable globals for overriding the default PIXI settings, such
 * as a renderer's default resolution, framerate, float precision, etc.
 * @example
 * // Use the native window resolution as the default resolution
 * // will support high-density displays when rendering
 * PIXI.settings.RESOLUTION = window.devicePixelRatio;
 *
 * // Disable interpolation when scaling, will make texture be pixelated
 * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
 * @namespace PIXI.settings
 */
var settings = {
    /**
     * If set to true WebGL will attempt make textures mimpaped by default.
     * Mipmapping will only succeed if the base texture uploaded has power of two dimensions.
     *
     * @static
     * @name MIPMAP_TEXTURES
     * @memberof PIXI.settings
     * @type {PIXI.MIPMAP_MODES}
     * @default PIXI.MIPMAP_MODES.POW2
     */
    MIPMAP_TEXTURES: MIPMAP_MODES.POW2,
    /**
     * Default anisotropic filtering level of textures.
     * Usually from 0 to 16
     *
     * @static
     * @name ANISOTROPIC_LEVEL
     * @memberof PIXI.settings
     * @type {number}
     * @default 0
     */
    ANISOTROPIC_LEVEL: 0,
    /**
     * Default resolution / device pixel ratio of the renderer.
     *
     * @static
     * @name RESOLUTION
     * @memberof PIXI.settings
     * @type {number}
     * @default 1
     */
    RESOLUTION: 1,
    /**
     * Default filter resolution.
     *
     * @static
     * @name FILTER_RESOLUTION
     * @memberof PIXI.settings
     * @type {number}
     * @default 1
     */
    FILTER_RESOLUTION: 1,
    /**
     * Default filter samples.
     *
     * @static
     * @name FILTER_MULTISAMPLE
     * @memberof PIXI.settings
     * @type {PIXI.MSAA_QUALITY}
     * @default PIXI.MSAA_QUALITY.NONE
     */
    FILTER_MULTISAMPLE: MSAA_QUALITY.NONE,
    /**
     * The maximum textures that this device supports.
     *
     * @static
     * @name SPRITE_MAX_TEXTURES
     * @memberof PIXI.settings
     * @type {number}
     * @default 32
     */
    SPRITE_MAX_TEXTURES: maxRecommendedTextures(32),
    // TODO: maybe change to SPRITE.BATCH_SIZE: 2000
    // TODO: maybe add PARTICLE.BATCH_SIZE: 15000
    /**
     * The default sprite batch size.
     *
     * The default aims to balance desktop and mobile devices.
     *
     * @static
     * @name SPRITE_BATCH_SIZE
     * @memberof PIXI.settings
     * @type {number}
     * @default 4096
     */
    SPRITE_BATCH_SIZE: 4096,
    /**
     * The default render options if none are supplied to {@link PIXI.Renderer}
     * or {@link PIXI.CanvasRenderer}.
     *
     * @static
     * @name RENDER_OPTIONS
     * @memberof PIXI.settings
     * @type {object}
     * @property {HTMLCanvasElement} view=null
     * @property {boolean} antialias=false
     * @property {boolean} autoDensity=false
     * @property {boolean} useContextAlpha=true
     * @property {number} backgroundColor=0x000000
     * @property {number} backgroundAlpha=1
     * @property {boolean} clearBeforeRender=true
     * @property {boolean} preserveDrawingBuffer=false
     * @property {number} width=800
     * @property {number} height=600
     * @property {boolean} legacy=false
     */
    RENDER_OPTIONS: {
        view: null,
        antialias: false,
        autoDensity: false,
        backgroundColor: 0x000000,
        backgroundAlpha: 1,
        useContextAlpha: true,
        clearBeforeRender: true,
        preserveDrawingBuffer: false,
        width: 800,
        height: 600,
        legacy: false,
    },
    /**
     * Default Garbage Collection mode.
     *
     * @static
     * @name GC_MODE
     * @memberof PIXI.settings
     * @type {PIXI.GC_MODES}
     * @default PIXI.GC_MODES.AUTO
     */
    GC_MODE: GC_MODES.AUTO,
    /**
     * Default Garbage Collection max idle.
     *
     * @static
     * @name GC_MAX_IDLE
     * @memberof PIXI.settings
     * @type {number}
     * @default 3600
     */
    GC_MAX_IDLE: 60 * 60,
    /**
     * Default Garbage Collection maximum check count.
     *
     * @static
     * @name GC_MAX_CHECK_COUNT
     * @memberof PIXI.settings
     * @type {number}
     * @default 600
     */
    GC_MAX_CHECK_COUNT: 60 * 10,
    /**
     * Default wrap modes that are supported by pixi.
     *
     * @static
     * @name WRAP_MODE
     * @memberof PIXI.settings
     * @type {PIXI.WRAP_MODES}
     * @default PIXI.WRAP_MODES.CLAMP
     */
    WRAP_MODE: WRAP_MODES.CLAMP,
    /**
     * Default scale mode for textures.
     *
     * @static
     * @name SCALE_MODE
     * @memberof PIXI.settings
     * @type {PIXI.SCALE_MODES}
     * @default PIXI.SCALE_MODES.LINEAR
     */
    SCALE_MODE: SCALE_MODES.LINEAR,
    /**
     * Default specify float precision in vertex shader.
     *
     * @static
     * @name PRECISION_VERTEX
     * @memberof PIXI.settings
     * @type {PIXI.PRECISION}
     * @default PIXI.PRECISION.HIGH
     */
    PRECISION_VERTEX: PRECISION.HIGH,
    /**
     * Default specify float precision in fragment shader.
     * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742
     *
     * @static
     * @name PRECISION_FRAGMENT
     * @memberof PIXI.settings
     * @type {PIXI.PRECISION}
     * @default PIXI.PRECISION.MEDIUM
     */
    PRECISION_FRAGMENT: settings_isMobile.apple.device ? PRECISION.HIGH : PRECISION.MEDIUM,
    /**
     * Can we upload the same buffer in a single frame?
     *
     * @static
     * @name CAN_UPLOAD_SAME_BUFFER
     * @memberof PIXI.settings
     * @type {boolean}
     */
    CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(),
    /**
     * Enables bitmap creation before image load. This feature is experimental.
     *
     * @static
     * @name CREATE_IMAGE_BITMAP
     * @memberof PIXI.settings
     * @type {boolean}
     * @default false
     */
    CREATE_IMAGE_BITMAP: false,
    /**
     * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
     * Advantages can include sharper image quality (like text) and faster rendering on canvas.
     * The main disadvantage is movement of objects may appear less smooth.
     *
     * @static
     * @constant
     * @memberof PIXI.settings
     * @type {boolean}
     * @default false
     */
    ROUND_PIXELS: false,
};


//# sourceMappingURL=settings.js.map

// EXTERNAL MODULE: ./node_modules/@pixi/utils/node_modules/eventemitter3/index.js
var eventemitter3 = __webpack_require__(8718);
var eventemitter3_default = /*#__PURE__*/__webpack_require__.n(eventemitter3);
// EXTERNAL MODULE: ./node_modules/earcut/src/earcut.js
var earcut = __webpack_require__(9187);
var earcut_default = /*#__PURE__*/__webpack_require__.n(earcut);
// EXTERNAL MODULE: ./node_modules/url/url.js
var url = __webpack_require__(8575);
;// CONCATENATED MODULE: ./node_modules/@pixi/constants/dist/esm/constants.js
/*!
 * @pixi/constants - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/constants is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * Different types of environments for WebGL.
 *
 * @static
 * @memberof PIXI
 * @name ENV
 * @enum {number}
 * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
 *  with older / less advanced devices. If you experience unexplained flickering prefer this environment.
 * @property {number} WEBGL - Version 1 of WebGL
 * @property {number} WEBGL2 - Version 2 of WebGL
 */
var constants_ENV;
(function (ENV) {
    ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
    ENV[ENV["WEBGL"] = 1] = "WEBGL";
    ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
})(constants_ENV || (constants_ENV = {}));
/**
 * Constant to identify the Renderer Type.
 *
 * @static
 * @memberof PIXI
 * @name RENDERER_TYPE
 * @enum {number}
 * @property {number} UNKNOWN - Unknown render type.
 * @property {number} WEBGL - WebGL render type.
 * @property {number} CANVAS - Canvas render type.
 */
var constants_RENDERER_TYPE;
(function (RENDERER_TYPE) {
    RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
    RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
    RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
})(constants_RENDERER_TYPE || (constants_RENDERER_TYPE = {}));
/**
 * Bitwise OR of masks that indicate the buffers to be cleared.
 *
 * @static
 * @memberof PIXI
 * @name BUFFER_BITS
 * @enum {number}
 * @property {number} COLOR - Indicates the buffers currently enabled for color writing.
 * @property {number} DEPTH - Indicates the depth buffer.
 * @property {number} STENCIL - Indicates the stencil buffer.
 */
var constants_BUFFER_BITS;
(function (BUFFER_BITS) {
    BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR";
    BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH";
    BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL";
})(constants_BUFFER_BITS || (constants_BUFFER_BITS = {}));
/**
 * Various blend modes supported by PIXI.
 *
 * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
 * Anything else will silently act like NORMAL.
 *
 * @memberof PIXI
 * @name BLEND_MODES
 * @enum {number}
 * @property {number} NORMAL
 * @property {number} ADD
 * @property {number} MULTIPLY
 * @property {number} SCREEN
 * @property {number} OVERLAY
 * @property {number} DARKEN
 * @property {number} LIGHTEN
 * @property {number} COLOR_DODGE
 * @property {number} COLOR_BURN
 * @property {number} HARD_LIGHT
 * @property {number} SOFT_LIGHT
 * @property {number} DIFFERENCE
 * @property {number} EXCLUSION
 * @property {number} HUE
 * @property {number} SATURATION
 * @property {number} COLOR
 * @property {number} LUMINOSITY
 * @property {number} NORMAL_NPM
 * @property {number} ADD_NPM
 * @property {number} SCREEN_NPM
 * @property {number} NONE
 * @property {number} SRC_IN
 * @property {number} SRC_OUT
 * @property {number} SRC_ATOP
 * @property {number} DST_OVER
 * @property {number} DST_IN
 * @property {number} DST_OUT
 * @property {number} DST_ATOP
 * @property {number} SUBTRACT
 * @property {number} SRC_OVER
 * @property {number} ERASE
 * @property {number} XOR
 */
var constants_BLEND_MODES;
(function (BLEND_MODES) {
    BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
    BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
    BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
    BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
    BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
    BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
    BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
    BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
    BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
    BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
    BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
    BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
    BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
    BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
    BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
    BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
    BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
    BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
    BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
    BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
    BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
    BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER";
    BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN";
    BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT";
    BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP";
    BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER";
    BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN";
    BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT";
    BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP";
    BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE";
    BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT";
    BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR";
})(constants_BLEND_MODES || (constants_BLEND_MODES = {}));
/**
 * Various webgl draw modes. These can be used to specify which GL drawMode to use
 * under certain situations and renderers.
 *
 * @memberof PIXI
 * @static
 * @name DRAW_MODES
 * @enum {number}
 * @property {number} POINTS
 * @property {number} LINES
 * @property {number} LINE_LOOP
 * @property {number} LINE_STRIP
 * @property {number} TRIANGLES
 * @property {number} TRIANGLE_STRIP
 * @property {number} TRIANGLE_FAN
 */
var constants_DRAW_MODES;
(function (DRAW_MODES) {
    DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
    DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
    DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
    DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
    DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
})(constants_DRAW_MODES || (constants_DRAW_MODES = {}));
/**
 * Various GL texture/resources formats.
 *
 * @memberof PIXI
 * @static
 * @name FORMATS
 * @enum {number}
 * @property {number} RGBA=6408
 * @property {number} RGB=6407
 * @property {number} RG=33319
 * @property {number} RED=6403
 * @property {number} RGBA_INTEGER=36249
 * @property {number} RGB_INTEGER=36248
 * @property {number} RG_INTEGER=33320
 * @property {number} RED_INTEGER=36244
 * @property {number} ALPHA=6406
 * @property {number} LUMINANCE=6409
 * @property {number} LUMINANCE_ALPHA=6410
 * @property {number} DEPTH_COMPONENT=6402
 * @property {number} DEPTH_STENCIL=34041
 */
var constants_FORMATS;
(function (FORMATS) {
    FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
    FORMATS[FORMATS["RGB"] = 6407] = "RGB";
    FORMATS[FORMATS["RG"] = 33319] = "RG";
    FORMATS[FORMATS["RED"] = 6403] = "RED";
    FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
    FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
    FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
    FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
    FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA";
    FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE";
    FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
    FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
    FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
})(constants_FORMATS || (constants_FORMATS = {}));
/**
 * Various GL target types.
 *
 * @memberof PIXI
 * @static
 * @name TARGETS
 * @enum {number}
 * @property {number} TEXTURE_2D=3553
 * @property {number} TEXTURE_CUBE_MAP=34067
 * @property {number} TEXTURE_2D_ARRAY=35866
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074
 */
var constants_TARGETS;
(function (TARGETS) {
    TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
    TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
})(constants_TARGETS || (constants_TARGETS = {}));
/**
 * Various GL data format types.
 *
 * @memberof PIXI
 * @static
 * @name TYPES
 * @enum {number}
 * @property {number} UNSIGNED_BYTE=5121
 * @property {number} UNSIGNED_SHORT=5123
 * @property {number} UNSIGNED_SHORT_5_6_5=33635
 * @property {number} UNSIGNED_SHORT_4_4_4_4=32819
 * @property {number} UNSIGNED_SHORT_5_5_5_1=32820
 * @property {number} UNSIGNED_INT=5125
 * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
 * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
 * @property {number} UNSIGNED_INT_24_8=34042
 * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
 * @property {number} BYTE=5120
 * @property {number} SHORT=5122
 * @property {number} INT=5124
 * @property {number} FLOAT=5126
 * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
 * @property {number} HALF_FLOAT=36193
 */
var constants_TYPES;
(function (TYPES) {
    TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
    TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
    TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
    TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
    TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
    TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
    TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
    TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
    TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
    TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
    TYPES[TYPES["BYTE"] = 5120] = "BYTE";
    TYPES[TYPES["SHORT"] = 5122] = "SHORT";
    TYPES[TYPES["INT"] = 5124] = "INT";
    TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
    TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
    TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
})(constants_TYPES || (constants_TYPES = {}));
/**
 * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
 * WebGL1 works only with FLOAT.
 *
 * @memberof PIXI
 * @static
 * @name SAMPLER_TYPES
 * @enum {number}
 * @property {number} FLOAT=0
 * @property {number} INT=1
 * @property {number} UINT=2
 */
var constants_SAMPLER_TYPES;
(function (SAMPLER_TYPES) {
    SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
    SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
    SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
})(constants_SAMPLER_TYPES || (constants_SAMPLER_TYPES = {}));
/**
 * The scale modes that are supported by pixi.
 *
 * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
 * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
 *
 * @memberof PIXI
 * @static
 * @name SCALE_MODES
 * @enum {number}
 * @property {number} LINEAR Smooth scaling
 * @property {number} NEAREST Pixelating scaling
 */
var constants_SCALE_MODES;
(function (SCALE_MODES) {
    SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
    SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
})(constants_SCALE_MODES || (constants_SCALE_MODES = {}));
/**
 * The wrap modes that are supported by pixi.
 *
 * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
 * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
 * If the texture is non power of two then clamp will be used regardless as WebGL can
 * only use REPEAT if the texture is po2.
 *
 * This property only affects WebGL.
 *
 * @name WRAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} CLAMP - The textures uvs are clamped
 * @property {number} REPEAT - The texture uvs tile and repeat
 * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
 */
var constants_WRAP_MODES;
(function (WRAP_MODES) {
    WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
    WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
    WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
})(constants_WRAP_MODES || (constants_WRAP_MODES = {}));
/**
 * Mipmap filtering modes that are supported by pixi.
 *
 * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
 * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
 * or its `POW2` and texture dimensions are powers of 2.
 * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
 *
 * This property only affects WebGL.
 *
 * @name MIPMAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} OFF - No mipmaps
 * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
 * @property {number} ON - Always generate mipmaps
 * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
 *   that supports buffering each level-of-detail.
 */
var constants_MIPMAP_MODES;
(function (MIPMAP_MODES) {
    MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF";
    MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2";
    MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON";
    MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL";
})(constants_MIPMAP_MODES || (constants_MIPMAP_MODES = {}));
/**
 * How to treat textures with premultiplied alpha
 *
 * @name ALPHA_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that.
 *  Option for compressed and data textures that are created from typed arrays.
 * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload.
 *  Default option, used for all loaded images.
 * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied
 *  Example: spine atlases with `_pma` suffix.
 * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA.
 * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD.
 * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA.
 */
var constants_ALPHA_MODES;
(function (ALPHA_MODES) {
    ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM";
    ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK";
    ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA";
    ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
})(constants_ALPHA_MODES || (constants_ALPHA_MODES = {}));
/**
 * Configure whether filter textures are cleared after binding.
 *
 * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
 * this and skip clearing as an optimization.
 *
 * @name CLEAR_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
 * @property {number} CLEAR - Always clear the filter texture.
 * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
 * @property {number} NO - Alias for BLEND, same as `false` in earlier versions
 * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions
 * @property {number} AUTO - Alias for BLIT
 */
var constants_CLEAR_MODES;
(function (CLEAR_MODES) {
    CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO";
    CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES";
    CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO";
    CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND";
    CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR";
    CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT";
})(constants_CLEAR_MODES || (constants_CLEAR_MODES = {}));
/**
 * The gc modes that are supported by pixi.
 *
 * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
 * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
 * used for a specified period of time they will be removed from the GPU. They will of course
 * be uploaded again when they are required. This is a silent behind the scenes process that
 * should ensure that the GPU does not  get filled up.
 *
 * Handy for mobile devices!
 * This property only affects WebGL.
 *
 * @name GC_MODES
 * @enum {number}
 * @static
 * @memberof PIXI
 * @property {number} AUTO - Garbage collection will happen periodically automatically
 * @property {number} MANUAL - Garbage collection will need to be called manually
 */
var constants_GC_MODES;
(function (GC_MODES) {
    GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
    GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
})(constants_GC_MODES || (constants_GC_MODES = {}));
/**
 * Constants that specify float precision in shaders.
 *
 * @name PRECISION
 * @memberof PIXI
 * @constant
 * @static
 * @enum {string}
 * @property {string} LOW='lowp'
 * @property {string} MEDIUM='mediump'
 * @property {string} HIGH='highp'
 */
var constants_PRECISION;
(function (PRECISION) {
    PRECISION["LOW"] = "lowp";
    PRECISION["MEDIUM"] = "mediump";
    PRECISION["HIGH"] = "highp";
})(constants_PRECISION || (constants_PRECISION = {}));
/**
 * Constants for mask implementations.
 * We use `type` suffix because it leads to very different behaviours
 *
 * @name MASK_TYPES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - Mask is ignored
 * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap
 * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil
 * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture
 */
var constants_MASK_TYPES;
(function (MASK_TYPES) {
    MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE";
    MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR";
    MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL";
    MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE";
})(constants_MASK_TYPES || (constants_MASK_TYPES = {}));
/**
 * Constants for multi-sampling antialiasing.
 *
 * @see PIXI.Framebuffer#multisample
 *
 * @name MSAA_QUALITY
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - No multisampling for this renderTexture
 * @property {number} LOW - Try 2 samples
 * @property {number} MEDIUM - Try 4 samples
 * @property {number} HIGH - Try 8 samples
 */
var constants_MSAA_QUALITY;
(function (MSAA_QUALITY) {
    MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE";
    MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW";
    MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM";
    MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH";
})(constants_MSAA_QUALITY || (constants_MSAA_QUALITY = {}));
/**
 * Constants for various buffer types in Pixi
 *
 * @see PIXI.BUFFER_TYPE
 *
 * @name BUFFER_TYPE
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
 * @property {number} ARRAY_BUFFER - buffer type for using attribute data
 * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
 */
var constants_BUFFER_TYPE;
(function (BUFFER_TYPE) {
    BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
    BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
    // NOT YET SUPPORTED
    BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
})(constants_BUFFER_TYPE || (constants_BUFFER_TYPE = {}));


//# sourceMappingURL=constants.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/utils/dist/esm/utils.js
/*!
 * @pixi/utils - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/utils is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */







/**
 * This file contains redeclared types for Node `url` and `querystring` modules. These modules
 * don't provide their own typings but instead are a part of the full Node typings. The purpose of
 * this file is to redeclare the required types to avoid having the whole Node types as a
 * dependency.
 */
var utils_url = {
    parse: url/* parse */.Qc,
    format: url/* format */.WU,
    resolve: url/* resolve */.DB,
};

/**
 * The prefix that denotes a URL is for a retina asset.
 *
 * @static
 * @name RETINA_PREFIX
 * @memberof PIXI.settings
 * @type {RegExp}
 * @default /@([0-9\.]+)x/
 * @example `@2x`
 */
settings.RETINA_PREFIX = /@([0-9\.]+)x/;
/**
 * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function.
 * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when
 * using WebGL.
 *
 * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible.
 * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the
 * browser.
 *
 * If your application requires high performance rendering, you may wish to set this to false.
 * We recommend one of two options if you decide to set this flag to false:
 *
 * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is
 *    not supported.
 *
 * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS
 *    renderer, and show an error message to the user if the function returns false, explaining that their device & browser
 *    combination does not support high performance WebGL.
 *    This is a much better strategy than trying to create a PixiJS renderer and finding it then fails.
 *
 * @static
 * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT
 * @memberof PIXI.settings
 * @type {boolean}
 * @default false
 */
settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false;

var saidHello = false;
var VERSION = '6.3.0';
/**
 * Skips the hello message of renderers that are created after this is run.
 *
 * @function skipHello
 * @memberof PIXI.utils
 */
function skipHello() {
    saidHello = true;
}
/**
 * Logs out the version and renderer information for this running instance of PIXI.
 * If you don't want to see this message you can run `PIXI.utils.skipHello()` before
 * creating your renderer. Keep in mind that doing that will forever make you a jerk face.
 *
 * @static
 * @function sayHello
 * @memberof PIXI.utils
 * @param {string} type - The string renderer type to log.
 */
function sayHello(type) {
    var _a;
    if (saidHello) {
        return;
    }
    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        var args = [
            "\n %c %c %c PixiJS " + VERSION + " - \u2730 " + type + " \u2730  %c  %c  http://www.pixijs.com/  %c %c \u2665%c\u2665%c\u2665 \n\n",
            'background: #ff66a5; padding:5px 0;',
            'background: #ff66a5; padding:5px 0;',
            'color: #ff66a5; background: #030307; padding:5px 0;',
            'background: #ff66a5; padding:5px 0;',
            'background: #ffc3dc; padding:5px 0;',
            'background: #ff66a5; padding:5px 0;',
            'color: #ff2424; background: #fff; padding:5px 0;',
            'color: #ff2424; background: #fff; padding:5px 0;',
            'color: #ff2424; background: #fff; padding:5px 0;' ];
        (_a = globalThis.console).log.apply(_a, args);
    }
    else if (globalThis.console) {
        globalThis.console.log("PixiJS " + VERSION + " - " + type + " - http://www.pixijs.com/");
    }
    saidHello = true;
}

var supported;
/**
 * Helper for checking for WebGL support.
 *
 * @memberof PIXI.utils
 * @function isWebGLSupported
 * @return {boolean} Is WebGL supported.
 */
function isWebGLSupported() {
    if (typeof supported === 'undefined') {
        supported = (function supported() {
            var contextOptions = {
                stencil: true,
                failIfMajorPerformanceCaveat: settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT,
            };
            try {
                if (!globalThis.WebGLRenderingContext) {
                    return false;
                }
                var canvas = document.createElement('canvas');
                var gl = (canvas.getContext('webgl', contextOptions)
                    || canvas.getContext('experimental-webgl', contextOptions));
                var success = !!(gl && gl.getContextAttributes().stencil);
                if (gl) {
                    var loseContext = gl.getExtension('WEBGL_lose_context');
                    if (loseContext) {
                        loseContext.loseContext();
                    }
                }
                gl = null;
                return success;
            }
            catch (e) {
                return false;
            }
        })();
    }
    return supported;
}

var aliceblue = "#f0f8ff";
var antiquewhite = "#faebd7";
var aqua = "#00ffff";
var aquamarine = "#7fffd4";
var azure = "#f0ffff";
var beige = "#f5f5dc";
var bisque = "#ffe4c4";
var black = "#000000";
var blanchedalmond = "#ffebcd";
var blue = "#0000ff";
var blueviolet = "#8a2be2";
var brown = "#a52a2a";
var burlywood = "#deb887";
var cadetblue = "#5f9ea0";
var chartreuse = "#7fff00";
var chocolate = "#d2691e";
var coral = "#ff7f50";
var cornflowerblue = "#6495ed";
var cornsilk = "#fff8dc";
var crimson = "#dc143c";
var cyan = "#00ffff";
var darkblue = "#00008b";
var darkcyan = "#008b8b";
var darkgoldenrod = "#b8860b";
var darkgray = "#a9a9a9";
var darkgreen = "#006400";
var darkgrey = "#a9a9a9";
var darkkhaki = "#bdb76b";
var darkmagenta = "#8b008b";
var darkolivegreen = "#556b2f";
var darkorange = "#ff8c00";
var darkorchid = "#9932cc";
var darkred = "#8b0000";
var darksalmon = "#e9967a";
var darkseagreen = "#8fbc8f";
var darkslateblue = "#483d8b";
var darkslategray = "#2f4f4f";
var darkslategrey = "#2f4f4f";
var darkturquoise = "#00ced1";
var darkviolet = "#9400d3";
var deeppink = "#ff1493";
var deepskyblue = "#00bfff";
var dimgray = "#696969";
var dimgrey = "#696969";
var dodgerblue = "#1e90ff";
var firebrick = "#b22222";
var floralwhite = "#fffaf0";
var forestgreen = "#228b22";
var fuchsia = "#ff00ff";
var gainsboro = "#dcdcdc";
var ghostwhite = "#f8f8ff";
var goldenrod = "#daa520";
var gold = "#ffd700";
var gray = "#808080";
var green = "#008000";
var greenyellow = "#adff2f";
var grey = "#808080";
var honeydew = "#f0fff0";
var hotpink = "#ff69b4";
var indianred = "#cd5c5c";
var indigo = "#4b0082";
var ivory = "#fffff0";
var khaki = "#f0e68c";
var lavenderblush = "#fff0f5";
var lavender = "#e6e6fa";
var lawngreen = "#7cfc00";
var lemonchiffon = "#fffacd";
var lightblue = "#add8e6";
var lightcoral = "#f08080";
var lightcyan = "#e0ffff";
var lightgoldenrodyellow = "#fafad2";
var lightgray = "#d3d3d3";
var lightgreen = "#90ee90";
var lightgrey = "#d3d3d3";
var lightpink = "#ffb6c1";
var lightsalmon = "#ffa07a";
var lightseagreen = "#20b2aa";
var lightskyblue = "#87cefa";
var lightslategray = "#778899";
var lightslategrey = "#778899";
var lightsteelblue = "#b0c4de";
var lightyellow = "#ffffe0";
var lime = "#00ff00";
var limegreen = "#32cd32";
var linen = "#faf0e6";
var magenta = "#ff00ff";
var maroon = "#800000";
var mediumaquamarine = "#66cdaa";
var mediumblue = "#0000cd";
var mediumorchid = "#ba55d3";
var mediumpurple = "#9370db";
var mediumseagreen = "#3cb371";
var mediumslateblue = "#7b68ee";
var mediumspringgreen = "#00fa9a";
var mediumturquoise = "#48d1cc";
var mediumvioletred = "#c71585";
var midnightblue = "#191970";
var mintcream = "#f5fffa";
var mistyrose = "#ffe4e1";
var moccasin = "#ffe4b5";
var navajowhite = "#ffdead";
var navy = "#000080";
var oldlace = "#fdf5e6";
var olive = "#808000";
var olivedrab = "#6b8e23";
var orange = "#ffa500";
var orangered = "#ff4500";
var orchid = "#da70d6";
var palegoldenrod = "#eee8aa";
var palegreen = "#98fb98";
var paleturquoise = "#afeeee";
var palevioletred = "#db7093";
var papayawhip = "#ffefd5";
var peachpuff = "#ffdab9";
var peru = "#cd853f";
var pink = "#ffc0cb";
var plum = "#dda0dd";
var powderblue = "#b0e0e6";
var purple = "#800080";
var rebeccapurple = "#663399";
var red = "#ff0000";
var rosybrown = "#bc8f8f";
var royalblue = "#4169e1";
var saddlebrown = "#8b4513";
var salmon = "#fa8072";
var sandybrown = "#f4a460";
var seagreen = "#2e8b57";
var seashell = "#fff5ee";
var sienna = "#a0522d";
var silver = "#c0c0c0";
var skyblue = "#87ceeb";
var slateblue = "#6a5acd";
var slategray = "#708090";
var slategrey = "#708090";
var snow = "#fffafa";
var springgreen = "#00ff7f";
var steelblue = "#4682b4";
var tan = "#d2b48c";
var teal = "#008080";
var thistle = "#d8bfd8";
var tomato = "#ff6347";
var turquoise = "#40e0d0";
var violet = "#ee82ee";
var wheat = "#f5deb3";
var white = "#ffffff";
var whitesmoke = "#f5f5f5";
var yellow = "#ffff00";
var yellowgreen = "#9acd32";
var cssColorNames = {
	aliceblue: aliceblue,
	antiquewhite: antiquewhite,
	aqua: aqua,
	aquamarine: aquamarine,
	azure: azure,
	beige: beige,
	bisque: bisque,
	black: black,
	blanchedalmond: blanchedalmond,
	blue: blue,
	blueviolet: blueviolet,
	brown: brown,
	burlywood: burlywood,
	cadetblue: cadetblue,
	chartreuse: chartreuse,
	chocolate: chocolate,
	coral: coral,
	cornflowerblue: cornflowerblue,
	cornsilk: cornsilk,
	crimson: crimson,
	cyan: cyan,
	darkblue: darkblue,
	darkcyan: darkcyan,
	darkgoldenrod: darkgoldenrod,
	darkgray: darkgray,
	darkgreen: darkgreen,
	darkgrey: darkgrey,
	darkkhaki: darkkhaki,
	darkmagenta: darkmagenta,
	darkolivegreen: darkolivegreen,
	darkorange: darkorange,
	darkorchid: darkorchid,
	darkred: darkred,
	darksalmon: darksalmon,
	darkseagreen: darkseagreen,
	darkslateblue: darkslateblue,
	darkslategray: darkslategray,
	darkslategrey: darkslategrey,
	darkturquoise: darkturquoise,
	darkviolet: darkviolet,
	deeppink: deeppink,
	deepskyblue: deepskyblue,
	dimgray: dimgray,
	dimgrey: dimgrey,
	dodgerblue: dodgerblue,
	firebrick: firebrick,
	floralwhite: floralwhite,
	forestgreen: forestgreen,
	fuchsia: fuchsia,
	gainsboro: gainsboro,
	ghostwhite: ghostwhite,
	goldenrod: goldenrod,
	gold: gold,
	gray: gray,
	green: green,
	greenyellow: greenyellow,
	grey: grey,
	honeydew: honeydew,
	hotpink: hotpink,
	indianred: indianred,
	indigo: indigo,
	ivory: ivory,
	khaki: khaki,
	lavenderblush: lavenderblush,
	lavender: lavender,
	lawngreen: lawngreen,
	lemonchiffon: lemonchiffon,
	lightblue: lightblue,
	lightcoral: lightcoral,
	lightcyan: lightcyan,
	lightgoldenrodyellow: lightgoldenrodyellow,
	lightgray: lightgray,
	lightgreen: lightgreen,
	lightgrey: lightgrey,
	lightpink: lightpink,
	lightsalmon: lightsalmon,
	lightseagreen: lightseagreen,
	lightskyblue: lightskyblue,
	lightslategray: lightslategray,
	lightslategrey: lightslategrey,
	lightsteelblue: lightsteelblue,
	lightyellow: lightyellow,
	lime: lime,
	limegreen: limegreen,
	linen: linen,
	magenta: magenta,
	maroon: maroon,
	mediumaquamarine: mediumaquamarine,
	mediumblue: mediumblue,
	mediumorchid: mediumorchid,
	mediumpurple: mediumpurple,
	mediumseagreen: mediumseagreen,
	mediumslateblue: mediumslateblue,
	mediumspringgreen: mediumspringgreen,
	mediumturquoise: mediumturquoise,
	mediumvioletred: mediumvioletred,
	midnightblue: midnightblue,
	mintcream: mintcream,
	mistyrose: mistyrose,
	moccasin: moccasin,
	navajowhite: navajowhite,
	navy: navy,
	oldlace: oldlace,
	olive: olive,
	olivedrab: olivedrab,
	orange: orange,
	orangered: orangered,
	orchid: orchid,
	palegoldenrod: palegoldenrod,
	palegreen: palegreen,
	paleturquoise: paleturquoise,
	palevioletred: palevioletred,
	papayawhip: papayawhip,
	peachpuff: peachpuff,
	peru: peru,
	pink: pink,
	plum: plum,
	powderblue: powderblue,
	purple: purple,
	rebeccapurple: rebeccapurple,
	red: red,
	rosybrown: rosybrown,
	royalblue: royalblue,
	saddlebrown: saddlebrown,
	salmon: salmon,
	sandybrown: sandybrown,
	seagreen: seagreen,
	seashell: seashell,
	sienna: sienna,
	silver: silver,
	skyblue: skyblue,
	slateblue: slateblue,
	slategray: slategray,
	slategrey: slategrey,
	snow: snow,
	springgreen: springgreen,
	steelblue: steelblue,
	tan: tan,
	teal: teal,
	thistle: thistle,
	tomato: tomato,
	turquoise: turquoise,
	violet: violet,
	wheat: wheat,
	white: white,
	whitesmoke: whitesmoke,
	yellow: yellow,
	yellowgreen: yellowgreen
};

/**
 * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0).
 *
 * @example
 * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1]
 * @memberof PIXI.utils
 * @function hex2rgb
 * @param {number} hex - The hexadecimal number to convert
 * @param  {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one
 * @return {number[]} An array representing the [R, G, B] of the color where all values are floats.
 */
function hex2rgb(hex, out) {
    if (out === void 0) { out = []; }
    out[0] = ((hex >> 16) & 0xFF) / 255;
    out[1] = ((hex >> 8) & 0xFF) / 255;
    out[2] = (hex & 0xFF) / 255;
    return out;
}
/**
 * Converts a hexadecimal color number to a string.
 *
 * @example
 * PIXI.utils.hex2string(0xffffff); // returns "#ffffff"
 * @memberof PIXI.utils
 * @function hex2string
 * @param {number} hex - Number in hex (e.g., `0xffffff`)
 * @return {string} The string color (e.g., `"#ffffff"`).
 */
function hex2string(hex) {
    var hexString = hex.toString(16);
    hexString = '000000'.substring(0, 6 - hexString.length) + hexString;
    return "#" + hexString;
}
/**
 * Converts a string to a hexadecimal color number.
 * It can handle:
 *  hex strings starting with #: "#ffffff"
 *  hex strings starting with 0x: "0xffffff"
 *  hex strings without prefix: "ffffff"
 *  css colors: "black"
 *
 * @example
 * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff
 * @memberof PIXI.utils
 * @function string2hex
 * @param {string} string - The string color (e.g., `"#ffffff"`)
 * @return {number} Number in hexadecimal.
 */
function string2hex(string) {
    if (typeof string === 'string') {
        string = cssColorNames[string.toLowerCase()] || string;
        if (string[0] === '#') {
            string = string.slice(1);
        }
    }
    return parseInt(string, 16);
}
/**
 * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number.
 *
 * @example
 * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff
 * @memberof PIXI.utils
 * @function rgb2hex
 * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0.
 * @return {number} Number in hexadecimal.
 */
function rgb2hex(rgb) {
    return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0));
}

/**
 * Corrects PixiJS blend, takes premultiplied alpha into account
 *
 * @memberof PIXI.utils
 * @function mapPremultipliedBlendModes
 * @private
 * @return {Array<number[]>} Mapped modes.
 */
function mapPremultipliedBlendModes() {
    var pm = [];
    var npm = [];
    for (var i = 0; i < 32; i++) {
        pm[i] = i;
        npm[i] = i;
    }
    pm[constants_BLEND_MODES.NORMAL_NPM] = constants_BLEND_MODES.NORMAL;
    pm[constants_BLEND_MODES.ADD_NPM] = constants_BLEND_MODES.ADD;
    pm[constants_BLEND_MODES.SCREEN_NPM] = constants_BLEND_MODES.SCREEN;
    npm[constants_BLEND_MODES.NORMAL] = constants_BLEND_MODES.NORMAL_NPM;
    npm[constants_BLEND_MODES.ADD] = constants_BLEND_MODES.ADD_NPM;
    npm[constants_BLEND_MODES.SCREEN] = constants_BLEND_MODES.SCREEN_NPM;
    var array = [];
    array.push(npm);
    array.push(pm);
    return array;
}
/**
 * maps premultiply flag and blendMode to adjusted blendMode
 * @memberof PIXI.utils
 * @const premultiplyBlendMode
 * @type {Array<number[]>}
 */
var premultiplyBlendMode = mapPremultipliedBlendModes();
/**
 * changes blendMode according to texture format
 *
 * @memberof PIXI.utils
 * @function correctBlendMode
 * @param {number} blendMode - supposed blend mode
 * @param {boolean} premultiplied - whether source is premultiplied
 * @returns {number} true blend mode for this texture
 */
function correctBlendMode(blendMode, premultiplied) {
    return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode];
}
/**
 * combines rgb and alpha to out array
 *
 * @memberof PIXI.utils
 * @function premultiplyRgba
 * @param {Float32Array|number[]} rgb - input rgb
 * @param {number} alpha - alpha param
 * @param {Float32Array} [out] - output
 * @param {boolean} [premultiply=true] - do premultiply it
 * @returns {Float32Array} vec4 rgba
 */
function premultiplyRgba(rgb, alpha, out, premultiply) {
    out = out || new Float32Array(4);
    if (premultiply || premultiply === undefined) {
        out[0] = rgb[0] * alpha;
        out[1] = rgb[1] * alpha;
        out[2] = rgb[2] * alpha;
    }
    else {
        out[0] = rgb[0];
        out[1] = rgb[1];
        out[2] = rgb[2];
    }
    out[3] = alpha;
    return out;
}
/**
 * premultiplies tint
 *
 * @memberof PIXI.utils
 * @function premultiplyTint
 * @param {number} tint - integer RGB
 * @param {number} alpha - floating point alpha (0.0-1.0)
 * @returns {number} tint multiplied by alpha
 */
function premultiplyTint(tint, alpha) {
    if (alpha === 1.0) {
        return (alpha * 255 << 24) + tint;
    }
    if (alpha === 0.0) {
        return 0;
    }
    var R = ((tint >> 16) & 0xFF);
    var G = ((tint >> 8) & 0xFF);
    var B = (tint & 0xFF);
    R = ((R * alpha) + 0.5) | 0;
    G = ((G * alpha) + 0.5) | 0;
    B = ((B * alpha) + 0.5) | 0;
    return (alpha * 255 << 24) + (R << 16) + (G << 8) + B;
}
/**
 * converts integer tint and float alpha to vec4 form, premultiplies by default
 *
 * @memberof PIXI.utils
 * @function premultiplyTintToRgba
 * @param {number} tint - input tint
 * @param {number} alpha - alpha param
 * @param {Float32Array} [out] - output
 * @param {boolean} [premultiply=true] - do premultiply it
 * @returns {Float32Array} vec4 rgba
 */
function premultiplyTintToRgba(tint, alpha, out, premultiply) {
    out = out || new Float32Array(4);
    out[0] = ((tint >> 16) & 0xFF) / 255.0;
    out[1] = ((tint >> 8) & 0xFF) / 255.0;
    out[2] = (tint & 0xFF) / 255.0;
    if (premultiply || premultiply === undefined) {
        out[0] *= alpha;
        out[1] *= alpha;
        out[2] *= alpha;
    }
    out[3] = alpha;
    return out;
}

/**
 * Generic Mask Stack data structure
 *
 * @memberof PIXI.utils
 * @function createIndicesForQuads
 * @param {number} size - Number of quads
 * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size`
 * @return {Uint16Array|Uint32Array} - Resulting index buffer
 */
function createIndicesForQuads(size, outBuffer) {
    if (outBuffer === void 0) { outBuffer = null; }
    // the total number of indices in our array, there are 6 points per quad.
    var totalIndices = size * 6;
    outBuffer = outBuffer || new Uint16Array(totalIndices);
    if (outBuffer.length !== totalIndices) {
        throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices);
    }
    // fill the indices with the quads to draw
    for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) {
        outBuffer[i + 0] = j + 0;
        outBuffer[i + 1] = j + 1;
        outBuffer[i + 2] = j + 2;
        outBuffer[i + 3] = j + 0;
        outBuffer[i + 4] = j + 2;
        outBuffer[i + 5] = j + 3;
    }
    return outBuffer;
}

function getBufferType(array) {
    if (array.BYTES_PER_ELEMENT === 4) {
        if (array instanceof Float32Array) {
            return 'Float32Array';
        }
        else if (array instanceof Uint32Array) {
            return 'Uint32Array';
        }
        return 'Int32Array';
    }
    else if (array.BYTES_PER_ELEMENT === 2) {
        if (array instanceof Uint16Array) {
            return 'Uint16Array';
        }
    }
    else if (array.BYTES_PER_ELEMENT === 1) {
        if (array instanceof Uint8Array) {
            return 'Uint8Array';
        }
    }
    // TODO map out the rest of the array elements!
    return null;
}

/* eslint-disable object-shorthand */
var map = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array };
function interleaveTypedArrays(arrays, sizes) {
    var outSize = 0;
    var stride = 0;
    var views = {};
    for (var i = 0; i < arrays.length; i++) {
        stride += sizes[i];
        outSize += arrays[i].length;
    }
    var buffer = new ArrayBuffer(outSize * 4);
    var out = null;
    var littleOffset = 0;
    for (var i = 0; i < arrays.length; i++) {
        var size = sizes[i];
        var array = arrays[i];
        /*
        @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way
              or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed?
         */
        var type = getBufferType(array);
        if (!views[type]) {
            views[type] = new map[type](buffer);
        }
        out = views[type];
        for (var j = 0; j < array.length; j++) {
            var indexStart = ((j / size | 0) * stride) + littleOffset;
            var index = j % size;
            out[indexStart + index] = array[j];
        }
        littleOffset += size;
    }
    return new Float32Array(buffer);
}

// Taken from the bit-twiddle package
/**
 * Rounds to next power of two.
 *
 * @function nextPow2
 * @memberof PIXI.utils
 * @param {number} v - input value
 * @return {number}
 */
function nextPow2(v) {
    v += v === 0 ? 1 : 0;
    --v;
    v |= v >>> 1;
    v |= v >>> 2;
    v |= v >>> 4;
    v |= v >>> 8;
    v |= v >>> 16;
    return v + 1;
}
/**
 * Checks if a number is a power of two.
 *
 * @function isPow2
 * @memberof PIXI.utils
 * @param {number} v - input value
 * @return {boolean} `true` if value is power of two
 */
function isPow2(v) {
    return !(v & (v - 1)) && (!!v);
}
/**
 * Computes ceil of log base 2
 *
 * @function log2
 * @memberof PIXI.utils
 * @param {number} v - input value
 * @return {number} logarithm base 2
 */
function log2(v) {
    var r = (v > 0xFFFF ? 1 : 0) << 4;
    v >>>= r;
    var shift = (v > 0xFF ? 1 : 0) << 3;
    v >>>= shift;
    r |= shift;
    shift = (v > 0xF ? 1 : 0) << 2;
    v >>>= shift;
    r |= shift;
    shift = (v > 0x3 ? 1 : 0) << 1;
    v >>>= shift;
    r |= shift;
    return r | (v >> 1);
}

/**
 * Remove items from a javascript array without generating garbage
 *
 * @function removeItems
 * @memberof PIXI.utils
 * @param {Array<any>} arr - Array to remove elements from
 * @param {number} startIdx - starting index
 * @param {number} removeCount - how many to remove
 */
function removeItems(arr, startIdx, removeCount) {
    var length = arr.length;
    var i;
    if (startIdx >= length || removeCount === 0) {
        return;
    }
    removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount);
    var len = length - removeCount;
    for (i = startIdx; i < len; ++i) {
        arr[i] = arr[i + removeCount];
    }
    arr.length = len;
}

/**
 * Returns sign of number
 *
 * @memberof PIXI.utils
 * @function sign
 * @param {number} n - the number to check the sign of
 * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive
 */
function sign(n) {
    if (n === 0)
        { return 0; }
    return n < 0 ? -1 : 1;
}

var nextUid = 0;
/**
 * Gets the next unique identifier
 *
 * @memberof PIXI.utils
 * @function uid
 * @return {number} The next unique identifier to use.
 */
function uid() {
    return ++nextUid;
}

// A map of warning messages already fired
var warnings = {};
/**
 * Helper for warning developers about deprecated features & settings.
 * A stack track for warnings is given; useful for tracking-down where
 * deprecated methods/properties/classes are being used within the code.
 *
 * @memberof PIXI.utils
 * @function deprecation
 * @param {string} version - The version where the feature became deprecated
 * @param {string} message - Message should include what is deprecated, where, and the new solution
 * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack
 *        this is mostly to ignore internal deprecation calls.
 */
function deprecation(version, message, ignoreDepth) {
    if (ignoreDepth === void 0) { ignoreDepth = 3; }
    // Ignore duplicat
    if (warnings[message]) {
        return;
    }
    /* eslint-disable no-console */
    var stack = new Error().stack;
    // Handle IE < 10 and Safari < 6
    if (typeof stack === 'undefined') {
        console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version);
    }
    else {
        // chop off the stack trace which includes PixiJS internal calls
        stack = stack.split('\n').splice(ignoreDepth).join('\n');
        if (console.groupCollapsed) {
            console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version);
            console.warn(stack);
            console.groupEnd();
        }
        else {
            console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version);
            console.warn(stack);
        }
    }
    /* eslint-enable no-console */
    warnings[message] = true;
}

/**
 * @todo Describe property usage
 *
 * @static
 * @name ProgramCache
 * @memberof PIXI.utils
 * @type {Object}
 */
var ProgramCache = {};
/**
 * @todo Describe property usage
 *
 * @static
 * @name TextureCache
 * @memberof PIXI.utils
 * @type {Object}
 */
var TextureCache = Object.create(null);
/**
 * @todo Describe property usage
 *
 * @static
 * @name BaseTextureCache
 * @memberof PIXI.utils
 * @type {Object}
 */
var BaseTextureCache = Object.create(null);
/**
 * Destroys all texture in the cache
 *
 * @memberof PIXI.utils
 * @function destroyTextureCache
 */
function destroyTextureCache() {
    var key;
    for (key in TextureCache) {
        TextureCache[key].destroy();
    }
    for (key in BaseTextureCache) {
        BaseTextureCache[key].destroy();
    }
}
/**
 * Removes all textures from cache, but does not destroy them
 *
 * @memberof PIXI.utils
 * @function clearTextureCache
 */
function clearTextureCache() {
    var key;
    for (key in TextureCache) {
        delete TextureCache[key];
    }
    for (key in BaseTextureCache) {
        delete BaseTextureCache[key];
    }
}

/**
 * Creates a Canvas element of the given size to be used as a target for rendering to.
 *
 * @class
 * @memberof PIXI.utils
 */
var CanvasRenderTarget = /** @class */ (function () {
    /**
     * @param width - the width for the newly created canvas
     * @param height - the height for the newly created canvas
     * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas
     */
    function CanvasRenderTarget(width, height, resolution) {
        this.canvas = document.createElement('canvas');
        this.context = this.canvas.getContext('2d');
        this.resolution = resolution || settings.RESOLUTION;
        this.resize(width, height);
    }
    /**
     * Clears the canvas that was created by the CanvasRenderTarget class.
     *
     * @private
     */
    CanvasRenderTarget.prototype.clear = function () {
        this.context.setTransform(1, 0, 0, 1, 0, 0);
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    };
    /**
     * Resizes the canvas to the specified width and height.
     *
     * @param desiredWidth - the desired width of the canvas
     * @param desiredHeight - the desired height of the canvas
     */
    CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) {
        this.canvas.width = Math.round(desiredWidth * this.resolution);
        this.canvas.height = Math.round(desiredHeight * this.resolution);
    };
    /** Destroys this canvas. */
    CanvasRenderTarget.prototype.destroy = function () {
        this.context = null;
        this.canvas = null;
    };
    Object.defineProperty(CanvasRenderTarget.prototype, "width", {
        /**
         * The width of the canvas buffer in pixels.
         *
         * @member {number}
         */
        get: function () {
            return this.canvas.width;
        },
        set: function (val) {
            this.canvas.width = Math.round(val);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CanvasRenderTarget.prototype, "height", {
        /**
         * The height of the canvas buffer in pixels.
         *
         * @member {number}
         */
        get: function () {
            return this.canvas.height;
        },
        set: function (val) {
            this.canvas.height = Math.round(val);
        },
        enumerable: false,
        configurable: true
    });
    return CanvasRenderTarget;
}());

/**
 * Trim transparent borders from a canvas
 *
 * @memberof PIXI.utils
 * @function trimCanvas
 * @param {HTMLCanvasElement} canvas - the canvas to trim
 * @returns {object} Trim data
 */
function trimCanvas(canvas) {
    // https://gist.github.com/remy/784508
    var width = canvas.width;
    var height = canvas.height;
    var context = canvas.getContext('2d');
    var imageData = context.getImageData(0, 0, width, height);
    var pixels = imageData.data;
    var len = pixels.length;
    var bound = {
        top: null,
        left: null,
        right: null,
        bottom: null,
    };
    var data = null;
    var i;
    var x;
    var y;
    for (i = 0; i < len; i += 4) {
        if (pixels[i + 3] !== 0) {
            x = (i / 4) % width;
            y = ~~((i / 4) / width);
            if (bound.top === null) {
                bound.top = y;
            }
            if (bound.left === null) {
                bound.left = x;
            }
            else if (x < bound.left) {
                bound.left = x;
            }
            if (bound.right === null) {
                bound.right = x + 1;
            }
            else if (bound.right < x) {
                bound.right = x + 1;
            }
            if (bound.bottom === null) {
                bound.bottom = y;
            }
            else if (bound.bottom < y) {
                bound.bottom = y;
            }
        }
    }
    if (bound.top !== null) {
        width = bound.right - bound.left;
        height = bound.bottom - bound.top + 1;
        data = context.getImageData(bound.left, bound.top, width, height);
    }
    return {
        height: height,
        width: width,
        data: data,
    };
}

/**
 * Regexp for data URI.
 * Based on: {@link https://github.com/ragingwind/data-uri-regex}
 *
 * @static
 * @constant {RegExp|string} DATA_URI
 * @memberof PIXI
 * @example data:image/png;base64
 */
var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;

/**
 * @memberof PIXI.utils
 * @interface DecomposedDataUri
 */
/**
 * type, eg. `image`
 * @memberof PIXI.utils.DecomposedDataUri#
 * @member {string} mediaType
 */
/**
 * Sub type, eg. `png`
 * @memberof PIXI.utils.DecomposedDataUri#
 * @member {string} subType
 */
/**
 * @memberof PIXI.utils.DecomposedDataUri#
 * @member {string} charset
 */
/**
 * Data encoding, eg. `base64`
 * @memberof PIXI.utils.DecomposedDataUri#
 * @member {string} encoding
 */
/**
 * The actual data
 * @memberof PIXI.utils.DecomposedDataUri#
 * @member {string} data
 */
/**
 * Split a data URI into components. Returns undefined if
 * parameter `dataUri` is not a valid data URI.
 *
 * @memberof PIXI.utils
 * @function decomposeDataUri
 * @param {string} dataUri - the data URI to check
 * @return {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined
 */
function decomposeDataUri(dataUri) {
    var dataUriMatch = DATA_URI.exec(dataUri);
    if (dataUriMatch) {
        return {
            mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined,
            subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined,
            charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined,
            encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined,
            data: dataUriMatch[5],
        };
    }
    return undefined;
}

var tempAnchor;
/**
 * Sets the `crossOrigin` property for this resource based on if the url
 * for this resource is cross-origin. If crossOrigin was manually set, this
 * function does nothing.
 * Nipped from the resource loader!
 *
 * @ignore
 * @param {string} url - The url to test.
 * @param {object} [loc=window.location] - The location object to test against.
 * @return {string} The crossOrigin value to use (or empty string for none).
 */
function determineCrossOrigin(url$1, loc) {
    if (loc === void 0) { loc = globalThis.location; }
    // data: and javascript: urls are considered same-origin
    if (url$1.indexOf('data:') === 0) {
        return '';
    }
    // default is window.location
    loc = loc || globalThis.location;
    if (!tempAnchor) {
        tempAnchor = document.createElement('a');
    }
    // let the browser determine the full href for the url of this resource and then
    // parse with the node url lib, we can't use the properties of the anchor element
    // because they don't work in IE9 :(
    tempAnchor.href = url$1;
    var parsedUrl = utils_url.parse(tempAnchor.href);
    var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port);
    // if cross origin
    if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) {
        return 'anonymous';
    }
    return '';
}

/**
 * get the resolution / device pixel ratio of an asset by looking for the prefix
 * used by spritesheets and image urls
 *
 * @memberof PIXI.utils
 * @function getResolutionOfUrl
 * @param {string} url - the image path
 * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set.
 * @return {number} resolution / device pixel ratio of an asset
 */
function getResolutionOfUrl(url, defaultValue) {
    var resolution = settings.RETINA_PREFIX.exec(url);
    if (resolution) {
        return parseFloat(resolution[1]);
    }
    return defaultValue !== undefined ? defaultValue : 1;
}


//# sourceMappingURL=utils.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/math/dist/esm/math.js
/*!
 * @pixi/math - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/math is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * Two Pi.
 *
 * @static
 * @member {number}
 * @memberof PIXI
 */
var PI_2 = Math.PI * 2;
/**
 * Conversion factor for converting radians to degrees.
 *
 * @static
 * @member {number} RAD_TO_DEG
 * @memberof PIXI
 */
var RAD_TO_DEG = 180 / Math.PI;
/**
 * Conversion factor for converting degrees to radians.
 *
 * @static
 * @member {number}
 * @memberof PIXI
 */
var DEG_TO_RAD = Math.PI / 180;
/**
 * Constants that identify shapes, mainly to prevent `instanceof` calls.
 *
 * @static
 * @memberof PIXI
 * @enum {number}
 * @property {number} POLY Polygon
 * @property {number} RECT Rectangle
 * @property {number} CIRC Circle
 * @property {number} ELIP Ellipse
 * @property {number} RREC Rounded Rectangle
 */
var SHAPES;
(function (SHAPES) {
    SHAPES[SHAPES["POLY"] = 0] = "POLY";
    SHAPES[SHAPES["RECT"] = 1] = "RECT";
    SHAPES[SHAPES["CIRC"] = 2] = "CIRC";
    SHAPES[SHAPES["ELIP"] = 3] = "ELIP";
    SHAPES[SHAPES["RREC"] = 4] = "RREC";
})(SHAPES || (SHAPES = {}));

/**
 * The Point object represents a location in a two-dimensional coordinate system, where `x` represents
 * the position on the horizontal axis and `y` represents the position on the vertical axis
 *
 * @class
 * @memberof PIXI
 * @implements IPoint
 */
var Point = /** @class */ (function () {
    /** Creates a new `Point`
     * @param {number} [x=0] - position of the point on the x axis
     * @param {number} [y=0] - position of the point on the y axis
     */
    function Point(x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        /** Position of the point on the x axis */
        this.x = 0;
        /** Position of the point on the y axis */
        this.y = 0;
        this.x = x;
        this.y = y;
    }
    /** Creates a clone of this point
     * @returns A clone of this point
     */
    Point.prototype.clone = function () {
        return new Point(this.x, this.y);
    };
    /**
     * Copies `x` and `y` from the given point into this point
     *
     * @param p - The point to copy from
     * @returns The point instance itself
     */
    Point.prototype.copyFrom = function (p) {
        this.set(p.x, p.y);
        return this;
    };
    /**
     * Copies this point's x and y into the given point (`p`).
     *
     * @param p - The point to copy to. Can be any of type that is or extends `IPointData`
     * @returns The point (`p`) with values updated
     */
    Point.prototype.copyTo = function (p) {
        p.set(this.x, this.y);
        return p;
    };
    /**
     * Accepts another point (`p`) and returns `true` if the given point is equal to this point
     *
     * @param p - The point to check
     * @returns Returns `true` if both `x` and `y` are equal
     */
    Point.prototype.equals = function (p) {
        return (p.x === this.x) && (p.y === this.y);
    };
    /**
     * Sets the point to a new `x` and `y` position.
     * If `y` is omitted, both `x` and `y` will be set to `x`.
     *
     * @param {number} [x=0] - position of the point on the `x` axis
     * @param {number} [y=x] - position of the point on the `y` axis
     * @returns The point instance itself
     */
    Point.prototype.set = function (x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = x; }
        this.x = x;
        this.y = y;
        return this;
    };
    Point.prototype.toString = function () {
        return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]";
    };
    return Point;
}());

var tempPoints = [new Point(), new Point(), new Point(), new Point()];
/**
 * Size object, contains width and height
 *
 * @memberof PIXI
 * @typedef {object} ISize
 */
/**
 * Rectangle object is an area defined by its position, as indicated by its top-left corner
 * point (x, y) and by its width and its height.
 *
 * @memberof PIXI
 */
var Rectangle = /** @class */ (function () {
    /**
     * @param x - The X coordinate of the upper-left corner of the rectangle
     * @param y - The Y coordinate of the upper-left corner of the rectangle
     * @param width - The overall width of the rectangle
     * @param height - The overall height of the rectangle
     */
    function Rectangle(x, y, width, height) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (width === void 0) { width = 0; }
        if (height === void 0) { height = 0; }
        this.x = Number(x);
        this.y = Number(y);
        this.width = Number(width);
        this.height = Number(height);
        this.type = SHAPES.RECT;
    }
    Object.defineProperty(Rectangle.prototype, "left", {
        /** Returns the left edge of the rectangle. */
        get: function () {
            return this.x;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rectangle.prototype, "right", {
        /** Returns the right edge of the rectangle. */
        get: function () {
            return this.x + this.width;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rectangle.prototype, "top", {
        /** Returns the top edge of the rectangle. */
        get: function () {
            return this.y;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rectangle.prototype, "bottom", {
        /** Returns the bottom edge of the rectangle. */
        get: function () {
            return this.y + this.height;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Rectangle, "EMPTY", {
        /** A constant empty rectangle. */
        get: function () {
            return new Rectangle(0, 0, 0, 0);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Creates a clone of this Rectangle
     *
     * @return a copy of the rectangle
     */
    Rectangle.prototype.clone = function () {
        return new Rectangle(this.x, this.y, this.width, this.height);
    };
    /**
     * Copies another rectangle to this one.
     *
     * @param rectangle - The rectangle to copy from.
     * @return Returns itself.
     */
    Rectangle.prototype.copyFrom = function (rectangle) {
        this.x = rectangle.x;
        this.y = rectangle.y;
        this.width = rectangle.width;
        this.height = rectangle.height;
        return this;
    };
    /**
     * Copies this rectangle to another one.
     *
     * @param rectangle - The rectangle to copy to.
     * @return Returns given parameter.
     */
    Rectangle.prototype.copyTo = function (rectangle) {
        rectangle.x = this.x;
        rectangle.y = this.y;
        rectangle.width = this.width;
        rectangle.height = this.height;
        return rectangle;
    };
    /**
     * Checks whether the x and y coordinates given are contained within this Rectangle
     *
     * @param x - The X coordinate of the point to test
     * @param y - The Y coordinate of the point to test
     * @return Whether the x/y coordinates are within this Rectangle
     */
    Rectangle.prototype.contains = function (x, y) {
        if (this.width <= 0 || this.height <= 0) {
            return false;
        }
        if (x >= this.x && x < this.x + this.width) {
            if (y >= this.y && y < this.y + this.height) {
                return true;
            }
        }
        return false;
    };
    /**
     * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object.
     * Returns true only if the area of the intersection is >0, this means that Rectangles
     * sharing a side are not overlapping. Another side effect is that an arealess rectangle
     * (width or height equal to zero) can't intersect any other rectangle.
     *
     * @param {Rectangle} other - The Rectangle to intersect with `this`.
     * @param {Matrix} transform - The transformation matrix of `other`.
     * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`.
     */
    Rectangle.prototype.intersects = function (other, transform) {
        if (!transform) {
            var x0_1 = this.x < other.x ? other.x : this.x;
            var x1_1 = this.right > other.right ? other.right : this.right;
            if (x1_1 <= x0_1) {
                return false;
            }
            var y0_1 = this.y < other.y ? other.y : this.y;
            var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom;
            return y1_1 > y0_1;
        }
        var x0 = this.left;
        var x1 = this.right;
        var y0 = this.top;
        var y1 = this.bottom;
        if (x1 <= x0 || y1 <= y0) {
            return false;
        }
        var lt = tempPoints[0].set(other.left, other.top);
        var lb = tempPoints[1].set(other.left, other.bottom);
        var rt = tempPoints[2].set(other.right, other.top);
        var rb = tempPoints[3].set(other.right, other.bottom);
        if (rt.x <= lt.x || lb.y <= lt.y) {
            return false;
        }
        var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c));
        if (s === 0) {
            return false;
        }
        transform.apply(lt, lt);
        transform.apply(lb, lb);
        transform.apply(rt, rt);
        transform.apply(rb, rb);
        if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0
            || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1
            || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0
            || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) {
            return false;
        }
        var nx = s * (lb.y - lt.y);
        var ny = s * (lt.x - lb.x);
        var n00 = (nx * x0) + (ny * y0);
        var n10 = (nx * x1) + (ny * y0);
        var n01 = (nx * x0) + (ny * y1);
        var n11 = (nx * x1) + (ny * y1);
        if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y)
            || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) {
            return false;
        }
        var mx = s * (lt.y - rt.y);
        var my = s * (rt.x - lt.x);
        var m00 = (mx * x0) + (my * y0);
        var m10 = (mx * x1) + (my * y0);
        var m01 = (mx * x0) + (my * y1);
        var m11 = (mx * x1) + (my * y1);
        if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y)
            || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) {
            return false;
        }
        return true;
    };
    /**
     * Pads the rectangle making it grow in all directions.
     * If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
     *
     * @param paddingX - The horizontal padding amount.
     * @param paddingY - The vertical padding amount.
     * @return Returns itself.
     */
    Rectangle.prototype.pad = function (paddingX, paddingY) {
        if (paddingX === void 0) { paddingX = 0; }
        if (paddingY === void 0) { paddingY = paddingX; }
        this.x -= paddingX;
        this.y -= paddingY;
        this.width += paddingX * 2;
        this.height += paddingY * 2;
        return this;
    };
    /**
     * Fits this rectangle around the passed one.
     *
     * @param rectangle - The rectangle to fit.
     * @return Returns itself.
     */
    Rectangle.prototype.fit = function (rectangle) {
        var x1 = Math.max(this.x, rectangle.x);
        var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width);
        var y1 = Math.max(this.y, rectangle.y);
        var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height);
        this.x = x1;
        this.width = Math.max(x2 - x1, 0);
        this.y = y1;
        this.height = Math.max(y2 - y1, 0);
        return this;
    };
    /**
     * Enlarges rectangle that way its corners lie on grid
     *
     * @param resolution - resolution
     * @param eps - precision
     * @return Returns itself.
     */
    Rectangle.prototype.ceil = function (resolution, eps) {
        if (resolution === void 0) { resolution = 1; }
        if (eps === void 0) { eps = 0.001; }
        var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution;
        var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution;
        this.x = Math.floor((this.x + eps) * resolution) / resolution;
        this.y = Math.floor((this.y + eps) * resolution) / resolution;
        this.width = x2 - this.x;
        this.height = y2 - this.y;
        return this;
    };
    /**
     * Enlarges this rectangle to include the passed rectangle.
     *
     * @param rectangle - The rectangle to include.
     * @return Returns itself.
     */
    Rectangle.prototype.enlarge = function (rectangle) {
        var x1 = Math.min(this.x, rectangle.x);
        var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width);
        var y1 = Math.min(this.y, rectangle.y);
        var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height);
        this.x = x1;
        this.width = x2 - x1;
        this.y = y1;
        this.height = y2 - y1;
        return this;
    };
    Rectangle.prototype.toString = function () {
        return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]";
    };
    return Rectangle;
}());

/**
 * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
 *
 * @memberof PIXI
 */
var Circle = /** @class */ (function () {
    /**
     * @param x - The X coordinate of the center of this circle
     * @param y - The Y coordinate of the center of this circle
     * @param radius - The radius of the circle
     */
    function Circle(x, y, radius) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (radius === void 0) { radius = 0; }
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.type = SHAPES.CIRC;
    }
    /**
     * Creates a clone of this Circle instance
     *
     * @return A copy of the Circle
     */
    Circle.prototype.clone = function () {
        return new Circle(this.x, this.y, this.radius);
    };
    /**
     * Checks whether the x and y coordinates given are contained within this circle
     *
     * @param x - The X coordinate of the point to test
     * @param y - The Y coordinate of the point to test
     * @return Whether the x/y coordinates are within this Circle
     */
    Circle.prototype.contains = function (x, y) {
        if (this.radius <= 0) {
            return false;
        }
        var r2 = this.radius * this.radius;
        var dx = (this.x - x);
        var dy = (this.y - y);
        dx *= dx;
        dy *= dy;
        return (dx + dy <= r2);
    };
    /**
    * Returns the framing rectangle of the circle as a Rectangle object
    *
    * @return The framing rectangle
    */
    Circle.prototype.getBounds = function () {
        return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
    };
    Circle.prototype.toString = function () {
        return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]";
    };
    return Circle;
}());

/**
 * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
 *
 * @memberof PIXI
 */
var Ellipse = /** @class */ (function () {
    /**
     * @param x - The X coordinate of the center of this ellipse
     * @param y - The Y coordinate of the center of this ellipse
     * @param halfWidth - The half width of this ellipse
     * @param halfHeight - The half height of this ellipse
     */
    function Ellipse(x, y, halfWidth, halfHeight) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (halfWidth === void 0) { halfWidth = 0; }
        if (halfHeight === void 0) { halfHeight = 0; }
        this.x = x;
        this.y = y;
        this.width = halfWidth;
        this.height = halfHeight;
        this.type = SHAPES.ELIP;
    }
    /**
     * Creates a clone of this Ellipse instance
     *
     * @return {PIXI.Ellipse} A copy of the ellipse
     */
    Ellipse.prototype.clone = function () {
        return new Ellipse(this.x, this.y, this.width, this.height);
    };
    /**
     * Checks whether the x and y coordinates given are contained within this ellipse
     *
     * @param x - The X coordinate of the point to test
     * @param y - The Y coordinate of the point to test
     * @return Whether the x/y coords are within this ellipse
     */
    Ellipse.prototype.contains = function (x, y) {
        if (this.width <= 0 || this.height <= 0) {
            return false;
        }
        // normalize the coords to an ellipse with center 0,0
        var normx = ((x - this.x) / this.width);
        var normy = ((y - this.y) / this.height);
        normx *= normx;
        normy *= normy;
        return (normx + normy <= 1);
    };
    /**
     * Returns the framing rectangle of the ellipse as a Rectangle object
     *
     * @return The framing rectangle
     */
    Ellipse.prototype.getBounds = function () {
        return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
    };
    Ellipse.prototype.toString = function () {
        return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]";
    };
    return Ellipse;
}());

/**
 * A class to define a shape via user defined coordinates.
 *
 * @memberof PIXI
 */
var Polygon = /** @class */ (function () {
    /**
     * @param {PIXI.IPointData[]|number[]} points - This can be an array of Points
     *  that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or
     *  the arguments passed can be all the points of the polygon e.g.
     *  `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat
     *  x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers.
     */
    function Polygon() {
        var arguments$1 = arguments;

        var points = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            points[_i] = arguments$1[_i];
        }
        var flat = Array.isArray(points[0]) ? points[0] : points;
        // if this is an array of points, convert it to a flat array of numbers
        if (typeof flat[0] !== 'number') {
            var p = [];
            for (var i = 0, il = flat.length; i < il; i++) {
                p.push(flat[i].x, flat[i].y);
            }
            flat = p;
        }
        this.points = flat;
        this.type = SHAPES.POLY;
        this.closeStroke = true;
    }
    /**
     * Creates a clone of this polygon.
     *
     * @return - A copy of the polygon.
     */
    Polygon.prototype.clone = function () {
        var points = this.points.slice();
        var polygon = new Polygon(points);
        polygon.closeStroke = this.closeStroke;
        return polygon;
    };
    /**
     * Checks whether the x and y coordinates passed to this function are contained within this polygon.
     *
     * @param x - The X coordinate of the point to test.
     * @param y - The Y coordinate of the point to test.
     * @return - Whether the x/y coordinates are within this polygon.
     */
    Polygon.prototype.contains = function (x, y) {
        var inside = false;
        // use some raycasting to test hits
        // https://github.com/substack/point-in-polygon/blob/master/index.js
        var length = this.points.length / 2;
        for (var i = 0, j = length - 1; i < length; j = i++) {
            var xi = this.points[i * 2];
            var yi = this.points[(i * 2) + 1];
            var xj = this.points[j * 2];
            var yj = this.points[(j * 2) + 1];
            var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi);
            if (intersect) {
                inside = !inside;
            }
        }
        return inside;
    };
    Polygon.prototype.toString = function () {
        return "[@pixi/math:Polygon"
            + ("closeStroke=" + this.closeStroke)
            + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]");
    };
    return Polygon;
}());

/**
 * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its
 * top-left corner point (x, y) and by its width and its height and its radius.
 *
 * @memberof PIXI
 */
var RoundedRectangle = /** @class */ (function () {
    /**
     * @param x - The X coordinate of the upper-left corner of the rounded rectangle
     * @param y - The Y coordinate of the upper-left corner of the rounded rectangle
     * @param width - The overall width of this rounded rectangle
     * @param height - The overall height of this rounded rectangle
     * @param radius - Controls the radius of the rounded corners
     */
    function RoundedRectangle(x, y, width, height, radius) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (width === void 0) { width = 0; }
        if (height === void 0) { height = 0; }
        if (radius === void 0) { radius = 20; }
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.radius = radius;
        this.type = SHAPES.RREC;
    }
    /**
     * Creates a clone of this Rounded Rectangle.
     *
     * @return - A copy of the rounded rectangle.
     */
    RoundedRectangle.prototype.clone = function () {
        return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
    };
    /**
     * Checks whether the x and y coordinates given are contained within this Rounded Rectangle
     *
     * @param x - The X coordinate of the point to test.
     * @param y - The Y coordinate of the point to test.
     * @return - Whether the x/y coordinates are within this Rounded Rectangle.
     */
    RoundedRectangle.prototype.contains = function (x, y) {
        if (this.width <= 0 || this.height <= 0) {
            return false;
        }
        if (x >= this.x && x <= this.x + this.width) {
            if (y >= this.y && y <= this.y + this.height) {
                var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2));
                if ((y >= this.y + radius && y <= this.y + this.height - radius)
                    || (x >= this.x + radius && x <= this.x + this.width - radius)) {
                    return true;
                }
                var dx = x - (this.x + radius);
                var dy = y - (this.y + radius);
                var radius2 = radius * radius;
                if ((dx * dx) + (dy * dy) <= radius2) {
                    return true;
                }
                dx = x - (this.x + this.width - radius);
                if ((dx * dx) + (dy * dy) <= radius2) {
                    return true;
                }
                dy = y - (this.y + this.height - radius);
                if ((dx * dx) + (dy * dy) <= radius2) {
                    return true;
                }
                dx = x - (this.x + radius);
                if ((dx * dx) + (dy * dy) <= radius2) {
                    return true;
                }
            }
        }
        return false;
    };
    RoundedRectangle.prototype.toString = function () {
        return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y
            + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]");
    };
    return RoundedRectangle;
}());

/**
 * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents
 * the position on the horizontal axis and `y` represents the position on the vertical axis.
 *
 * An `ObservablePoint` is a point that triggers a callback when the point's position is changed.
 *
 * @memberof PIXI
 */
var ObservablePoint = /** @class */ (function () {
    /**
     * Creates a new `ObservablePoint`
     *
     * @param cb - callback function triggered when `x` and/or `y` are changed
     * @param scope - owner of callback
     * @param {number} [x=0] - position of the point on the x axis
     * @param {number} [y=0] - position of the point on the y axis
    */
    function ObservablePoint(cb, scope, x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        this._x = x;
        this._y = y;
        this.cb = cb;
        this.scope = scope;
    }
    /**
     * Creates a clone of this point.
     * The callback and scope params can be overridden otherwise they will default
     * to the clone object's values.
     *
     * @override
     * @param cb - The callback function triggered when `x` and/or `y` are changed
     * @param scope - The owner of the callback
     * @return a copy of this observable point
     */
    ObservablePoint.prototype.clone = function (cb, scope) {
        if (cb === void 0) { cb = this.cb; }
        if (scope === void 0) { scope = this.scope; }
        return new ObservablePoint(cb, scope, this._x, this._y);
    };
    /**
     * Sets the point to a new `x` and `y` position.
     * If `y` is omitted, both `x` and `y` will be set to `x`.
     *
     * @param {number} [x=0] - position of the point on the x axis
     * @param {number} [y=x] - position of the point on the y axis
     * @returns The observable point instance itself
     */
    ObservablePoint.prototype.set = function (x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = x; }
        if (this._x !== x || this._y !== y) {
            this._x = x;
            this._y = y;
            this.cb.call(this.scope);
        }
        return this;
    };
    /**
     * Copies x and y from the given point (`p`)
     *
     * @param p - The point to copy from. Can be any of type that is or extends `IPointData`
     * @returns The observable point instance itself
     */
    ObservablePoint.prototype.copyFrom = function (p) {
        if (this._x !== p.x || this._y !== p.y) {
            this._x = p.x;
            this._y = p.y;
            this.cb.call(this.scope);
        }
        return this;
    };
    /**
     * Copies this point's x and y into that of the given point (`p`)
     *
     * @param p - The point to copy to. Can be any of type that is or extends `IPointData`
     * @returns The point (`p`) with values updated
     */
    ObservablePoint.prototype.copyTo = function (p) {
        p.set(this._x, this._y);
        return p;
    };
    /**
     * Accepts another point (`p`) and returns `true` if the given point is equal to this point
     *
     * @param p - The point to check
     * @returns Returns `true` if both `x` and `y` are equal
     */
    ObservablePoint.prototype.equals = function (p) {
        return (p.x === this._x) && (p.y === this._y);
    };
    ObservablePoint.prototype.toString = function () {
        return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]";
    };
    Object.defineProperty(ObservablePoint.prototype, "x", {
        /** Position of the observable point on the x axis. */
        get: function () {
            return this._x;
        },
        set: function (value) {
            if (this._x !== value) {
                this._x = value;
                this.cb.call(this.scope);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ObservablePoint.prototype, "y", {
        /** Position of the observable point on the y axis. */
        get: function () {
            return this._y;
        },
        set: function (value) {
            if (this._y !== value) {
                this._y = value;
                this.cb.call(this.scope);
            }
        },
        enumerable: false,
        configurable: true
    });
    return ObservablePoint;
}());

/**
 * The PixiJS Matrix as a class makes it a lot faster.
 *
 * Here is a representation of it:
 * ```js
 * | a | c | tx|
 * | b | d | ty|
 * | 0 | 0 | 1 |
 * ```
 *
 * @memberof PIXI
 */
var Matrix = /** @class */ (function () {
    /**
     * @param a - x scale
     * @param b - y skew
     * @param c - x skew
     * @param d - y scale
     * @param tx - x translation
     * @param ty - y translation
     */
    function Matrix(a, b, c, d, tx, ty) {
        if (a === void 0) { a = 1; }
        if (b === void 0) { b = 0; }
        if (c === void 0) { c = 0; }
        if (d === void 0) { d = 1; }
        if (tx === void 0) { tx = 0; }
        if (ty === void 0) { ty = 0; }
        this.array = null;
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.tx = tx;
        this.ty = ty;
    }
    /**
     * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows:
     *
     * a = array[0]
     * b = array[1]
     * c = array[3]
     * d = array[4]
     * tx = array[2]
     * ty = array[5]
     *
     * @param array - The array that the matrix will be populated from.
     */
    Matrix.prototype.fromArray = function (array) {
        this.a = array[0];
        this.b = array[1];
        this.c = array[3];
        this.d = array[4];
        this.tx = array[2];
        this.ty = array[5];
    };
    /**
     * Sets the matrix properties.
     *
     * @param a - Matrix component
     * @param b - Matrix component
     * @param c - Matrix component
     * @param d - Matrix component
     * @param tx - Matrix component
     * @param ty - Matrix component
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.set = function (a, b, c, d, tx, ty) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.tx = tx;
        this.ty = ty;
        return this;
    };
    /**
     * Creates an array from the current Matrix object.
     *
     * @param transpose - Whether we need to transpose the matrix or not
     * @param [out=new Float32Array(9)] - If provided the array will be assigned to out
     * @return The newly created array which contains the matrix
     */
    Matrix.prototype.toArray = function (transpose, out) {
        if (!this.array) {
            this.array = new Float32Array(9);
        }
        var array = out || this.array;
        if (transpose) {
            array[0] = this.a;
            array[1] = this.b;
            array[2] = 0;
            array[3] = this.c;
            array[4] = this.d;
            array[5] = 0;
            array[6] = this.tx;
            array[7] = this.ty;
            array[8] = 1;
        }
        else {
            array[0] = this.a;
            array[1] = this.c;
            array[2] = this.tx;
            array[3] = this.b;
            array[4] = this.d;
            array[5] = this.ty;
            array[6] = 0;
            array[7] = 0;
            array[8] = 1;
        }
        return array;
    };
    /**
     * Get a new position with the current transformation applied.
     * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
     *
     * @param pos - The origin
     * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
     * @return {PIXI.Point} The new point, transformed through this matrix
     */
    Matrix.prototype.apply = function (pos, newPos) {
        newPos = (newPos || new Point());
        var x = pos.x;
        var y = pos.y;
        newPos.x = (this.a * x) + (this.c * y) + this.tx;
        newPos.y = (this.b * x) + (this.d * y) + this.ty;
        return newPos;
    };
    /**
     * Get a new position with the inverse of the current transformation applied.
     * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
     *
     * @param pos - The origin
     * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
     * @return {PIXI.Point} The new point, inverse-transformed through this matrix
     */
    Matrix.prototype.applyInverse = function (pos, newPos) {
        newPos = (newPos || new Point());
        var id = 1 / ((this.a * this.d) + (this.c * -this.b));
        var x = pos.x;
        var y = pos.y;
        newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id);
        newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id);
        return newPos;
    };
    /**
     * Translates the matrix on the x and y.
     *
     * @param x - How much to translate x by
     * @param y - How much to translate y by
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.translate = function (x, y) {
        this.tx += x;
        this.ty += y;
        return this;
    };
    /**
     * Applies a scale transformation to the matrix.
     *
     * @param x - The amount to scale horizontally
     * @param y - The amount to scale vertically
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.scale = function (x, y) {
        this.a *= x;
        this.d *= y;
        this.c *= x;
        this.b *= y;
        this.tx *= x;
        this.ty *= y;
        return this;
    };
    /**
     * Applies a rotation transformation to the matrix.
     *
     * @param angle - The angle in radians.
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.rotate = function (angle) {
        var cos = Math.cos(angle);
        var sin = Math.sin(angle);
        var a1 = this.a;
        var c1 = this.c;
        var tx1 = this.tx;
        this.a = (a1 * cos) - (this.b * sin);
        this.b = (a1 * sin) + (this.b * cos);
        this.c = (c1 * cos) - (this.d * sin);
        this.d = (c1 * sin) + (this.d * cos);
        this.tx = (tx1 * cos) - (this.ty * sin);
        this.ty = (tx1 * sin) + (this.ty * cos);
        return this;
    };
    /**
     * Appends the given Matrix to this Matrix.
     *
     * @param matrix - The matrix to append.
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.append = function (matrix) {
        var a1 = this.a;
        var b1 = this.b;
        var c1 = this.c;
        var d1 = this.d;
        this.a = (matrix.a * a1) + (matrix.b * c1);
        this.b = (matrix.a * b1) + (matrix.b * d1);
        this.c = (matrix.c * a1) + (matrix.d * c1);
        this.d = (matrix.c * b1) + (matrix.d * d1);
        this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx;
        this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty;
        return this;
    };
    /**
     * Sets the matrix based on all the available properties
     *
     * @param x - Position on the x axis
     * @param y - Position on the y axis
     * @param pivotX - Pivot on the x axis
     * @param pivotY - Pivot on the y axis
     * @param scaleX - Scale on the x axis
     * @param scaleY - Scale on the y axis
     * @param rotation - Rotation in radians
     * @param skewX - Skew on the x axis
     * @param skewY - Skew on the y axis
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) {
        this.a = Math.cos(rotation + skewY) * scaleX;
        this.b = Math.sin(rotation + skewY) * scaleX;
        this.c = -Math.sin(rotation - skewX) * scaleY;
        this.d = Math.cos(rotation - skewX) * scaleY;
        this.tx = x - ((pivotX * this.a) + (pivotY * this.c));
        this.ty = y - ((pivotX * this.b) + (pivotY * this.d));
        return this;
    };
    /**
     * Prepends the given Matrix to this Matrix.
     *
     * @param matrix - The matrix to prepend
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.prepend = function (matrix) {
        var tx1 = this.tx;
        if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) {
            var a1 = this.a;
            var c1 = this.c;
            this.a = (a1 * matrix.a) + (this.b * matrix.c);
            this.b = (a1 * matrix.b) + (this.b * matrix.d);
            this.c = (c1 * matrix.a) + (this.d * matrix.c);
            this.d = (c1 * matrix.b) + (this.d * matrix.d);
        }
        this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx;
        this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty;
        return this;
    };
    /**
     * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform.
     *
     * @param transform - The transform to apply the properties to.
     * @return The transform with the newly applied properties
     */
    Matrix.prototype.decompose = function (transform) {
        // sort out rotation / skew..
        var a = this.a;
        var b = this.b;
        var c = this.c;
        var d = this.d;
        var pivot = transform.pivot;
        var skewX = -Math.atan2(-c, d);
        var skewY = Math.atan2(b, a);
        var delta = Math.abs(skewX + skewY);
        if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) {
            transform.rotation = skewY;
            transform.skew.x = transform.skew.y = 0;
        }
        else {
            transform.rotation = 0;
            transform.skew.x = skewX;
            transform.skew.y = skewY;
        }
        // next set scale
        transform.scale.x = Math.sqrt((a * a) + (b * b));
        transform.scale.y = Math.sqrt((c * c) + (d * d));
        // next set position
        transform.position.x = this.tx + ((pivot.x * a) + (pivot.y * c));
        transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d));
        return transform;
    };
    /**
     * Inverts this matrix
     *
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.invert = function () {
        var a1 = this.a;
        var b1 = this.b;
        var c1 = this.c;
        var d1 = this.d;
        var tx1 = this.tx;
        var n = (a1 * d1) - (b1 * c1);
        this.a = d1 / n;
        this.b = -b1 / n;
        this.c = -c1 / n;
        this.d = a1 / n;
        this.tx = ((c1 * this.ty) - (d1 * tx1)) / n;
        this.ty = -((a1 * this.ty) - (b1 * tx1)) / n;
        return this;
    };
    /**
     * Resets this Matrix to an identity (default) matrix.
     *
     * @return This matrix. Good for chaining method calls.
     */
    Matrix.prototype.identity = function () {
        this.a = 1;
        this.b = 0;
        this.c = 0;
        this.d = 1;
        this.tx = 0;
        this.ty = 0;
        return this;
    };
    /**
     * Creates a new Matrix object with the same values as this one.
     *
     * @return A copy of this matrix. Good for chaining method calls.
     */
    Matrix.prototype.clone = function () {
        var matrix = new Matrix();
        matrix.a = this.a;
        matrix.b = this.b;
        matrix.c = this.c;
        matrix.d = this.d;
        matrix.tx = this.tx;
        matrix.ty = this.ty;
        return matrix;
    };
    /**
     * Changes the values of the given matrix to be the same as the ones in this matrix
     *
     * @param matrix - The matrix to copy to.
     * @return The matrix given in parameter with its values updated.
     */
    Matrix.prototype.copyTo = function (matrix) {
        matrix.a = this.a;
        matrix.b = this.b;
        matrix.c = this.c;
        matrix.d = this.d;
        matrix.tx = this.tx;
        matrix.ty = this.ty;
        return matrix;
    };
    /**
     * Changes the values of the matrix to be the same as the ones in given matrix
     *
     * @param {PIXI.Matrix} matrix - The matrix to copy from.
     * @return {PIXI.Matrix} this
     */
    Matrix.prototype.copyFrom = function (matrix) {
        this.a = matrix.a;
        this.b = matrix.b;
        this.c = matrix.c;
        this.d = matrix.d;
        this.tx = matrix.tx;
        this.ty = matrix.ty;
        return this;
    };
    Matrix.prototype.toString = function () {
        return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]";
    };
    Object.defineProperty(Matrix, "IDENTITY", {
        /**
         * A default (identity) matrix
         *
         * @readonly
         */
        get: function () {
            return new Matrix();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Matrix, "TEMP_MATRIX", {
        /**
         * A temp matrix
         *
         * @readonly
         */
        get: function () {
            return new Matrix();
        },
        enumerable: false,
        configurable: true
    });
    return Matrix;
}());

// Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group
/*
 * Transform matrix for operation n is:
 * | ux | vx |
 * | uy | vy |
 */
var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1];
var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1];
var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1];
var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1];
/**
 * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table}
 * for the composition of each rotation in the dihederal group D8.
 *
 * @type number[][]
 * @private
 */
var rotationCayley = [];
/**
 * Matrices for each `GD8Symmetry` rotation.
 *
 * @type Matrix[]
 * @private
 */
var rotationMatrices = [];
/*
 * Alias for {@code Math.sign}.
 */
var signum = Math.sign;
/*
 * Initializes `rotationCayley` and `rotationMatrices`. It is called
 * only once below.
 */
function init() {
    for (var i = 0; i < 16; i++) {
        var row = [];
        rotationCayley.push(row);
        for (var j = 0; j < 16; j++) {
            /* Multiplies rotation matrices i and j. */
            var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j]));
            var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j]));
            var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j]));
            var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j]));
            /* Finds rotation matrix matching the product and pushes it. */
            for (var k = 0; k < 16; k++) {
                if (ux[k] === _ux && uy[k] === _uy
                    && vx[k] === _vx && vy[k] === _vy) {
                    row.push(k);
                    break;
                }
            }
        }
    }
    for (var i = 0; i < 16; i++) {
        var mat = new Matrix();
        mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0);
        rotationMatrices.push(mat);
    }
}
init();
/**
 * @memberof PIXI
 * @typedef {number} GD8Symmetry
 * @see PIXI.groupD8
 */
/**
 * Implements the dihedral group D8, which is similar to
 * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html};
 * D8 is the same but with diagonals, and it is used for texture
 * rotations.
 *
 * The directions the U- and V- axes after rotation
 * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))`
 * and `(vX(a), vY(a))`. These aren't necessarily unit vectors.
 *
 * **Origin:**<br>
 *  This is the small part of gameofbombs.com portal system. It works.
 *
 * @see PIXI.groupD8.E
 * @see PIXI.groupD8.SE
 * @see PIXI.groupD8.S
 * @see PIXI.groupD8.SW
 * @see PIXI.groupD8.W
 * @see PIXI.groupD8.NW
 * @see PIXI.groupD8.N
 * @see PIXI.groupD8.NE
 * @author Ivan @ivanpopelyshev
 * @namespace PIXI.groupD8
 * @memberof PIXI
 */
var groupD8 = {
    /**
     * | Rotation | Direction |
     * |----------|-----------|
     * | 0°       | East      |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    E: 0,
    /**
     * | Rotation | Direction |
     * |----------|-----------|
     * | 45°↻     | Southeast |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    SE: 1,
    /**
     * | Rotation | Direction |
     * |----------|-----------|
     * | 90°↻     | South     |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    S: 2,
    /**
     * | Rotation | Direction |
     * |----------|-----------|
     * | 135°↻    | Southwest |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    SW: 3,
    /**
     * | Rotation | Direction |
     * |----------|-----------|
     * | 180°     | West      |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    W: 4,
    /**
     * | Rotation    | Direction    |
     * |-------------|--------------|
     * | -135°/225°↻ | Northwest    |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    NW: 5,
    /**
     * | Rotation    | Direction    |
     * |-------------|--------------|
     * | -90°/270°↻  | North        |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    N: 6,
    /**
     * | Rotation    | Direction    |
     * |-------------|--------------|
     * | -45°/315°↻  | Northeast    |
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    NE: 7,
    /**
     * Reflection about Y-axis.
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    MIRROR_VERTICAL: 8,
    /**
     * Reflection about the main diagonal.
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    MAIN_DIAGONAL: 10,
    /**
     * Reflection about X-axis.
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    MIRROR_HORIZONTAL: 12,
    /**
     * Reflection about reverse diagonal.
     *
     * @memberof PIXI.groupD8
     * @constant {PIXI.GD8Symmetry}
     */
    REVERSE_DIAGONAL: 14,
    /**
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
     * @return {PIXI.GD8Symmetry} The X-component of the U-axis
     *    after rotating the axes.
     */
    uX: function (ind) { return ux[ind]; },
    /**
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
     * @return {PIXI.GD8Symmetry} The Y-component of the U-axis
     *    after rotating the axes.
     */
    uY: function (ind) { return uy[ind]; },
    /**
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
     * @return {PIXI.GD8Symmetry} The X-component of the V-axis
     *    after rotating the axes.
     */
    vX: function (ind) { return vx[ind]; },
    /**
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
     * @return {PIXI.GD8Symmetry} The Y-component of the V-axis
     *    after rotating the axes.
     */
    vY: function (ind) { return vy[ind]; },
    /**
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite
     *   is needed. Only rotations have opposite symmetries while
     *   reflections don't.
     * @return {PIXI.GD8Symmetry} The opposite symmetry of `rotation`
     */
    inv: function (rotation) {
        if (rotation & 8) // true only if between 8 & 15 (reflections)
         {
            return rotation & 15; // or rotation % 16
        }
        return (-rotation) & 7; // or (8 - rotation) % 8
    },
    /**
     * Composes the two D8 operations.
     *
     * Taking `^` as reflection:
     *
     * |       | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 |
     * |-------|-----|-----|-----|-----|------|-------|-------|-------|
     * | E=0   | E   | S   | W   | N   | E^   | S^    | W^    | N^    |
     * | S=2   | S   | W   | N   | E   | S^   | W^    | N^    | E^    |
     * | W=4   | W   | N   | E   | S   | W^   | N^    | E^    | S^    |
     * | N=6   | N   | E   | S   | W   | N^   | E^    | S^    | W^    |
     * | E^=8  | E^  | N^  | W^  | S^  | E    | N     | W     | S     |
     * | S^=10 | S^  | E^  | N^  | W^  | S    | E     | N     | W     |
     * | W^=12 | W^  | S^  | E^  | N^  | W    | S     | E     | N     |
     * | N^=14 | N^  | W^  | S^  | E^  | N    | W     | S     | E     |
     *
     * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table}
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which
     *   is the row in the above cayley table.
     * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which
     *   is the column in the above cayley table.
     * @return {PIXI.GD8Symmetry} Composed operation
     */
    add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); },
    /**
     * Reverse of `add`.
     *
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} rotationSecond - Second operation
     * @param {PIXI.GD8Symmetry} rotationFirst - First operation
     * @return {PIXI.GD8Symmetry} Result
     */
    sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); },
    /**
     * Adds 180 degrees to rotation, which is a commutative
     * operation.
     *
     * @memberof PIXI.groupD8
     * @param {number} rotation - The number to rotate.
     * @returns {number} Rotated number
     */
    rotate180: function (rotation) { return rotation ^ 4; },
    /**
     * Checks if the rotation angle is vertical, i.e. south
     * or north. It doesn't work for reflections.
     *
     * @memberof PIXI.groupD8
     * @param {PIXI.GD8Symmetry} rotation - The number to check.
     * @returns {boolean} Whether or not the direction is vertical
     */
    isVertical: function (rotation) { return (rotation & 3) === 2; },
    /**
     * Approximates the vector `V(dx,dy)` into one of the
     * eight directions provided by `groupD8`.
     *
     * @memberof PIXI.groupD8
     * @param {number} dx - X-component of the vector
     * @param {number} dy - Y-component of the vector
     * @return {PIXI.GD8Symmetry} Approximation of the vector into
     *  one of the eight symmetries.
     */
    byDirection: function (dx, dy) {
        if (Math.abs(dx) * 2 <= Math.abs(dy)) {
            if (dy >= 0) {
                return groupD8.S;
            }
            return groupD8.N;
        }
        else if (Math.abs(dy) * 2 <= Math.abs(dx)) {
            if (dx > 0) {
                return groupD8.E;
            }
            return groupD8.W;
        }
        else if (dy > 0) {
            if (dx > 0) {
                return groupD8.SE;
            }
            return groupD8.SW;
        }
        else if (dx > 0) {
            return groupD8.NE;
        }
        return groupD8.NW;
    },
    /**
     * Helps sprite to compensate texture packer rotation.
     *
     * @memberof PIXI.groupD8
     * @param {PIXI.Matrix} matrix - sprite world matrix
     * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use.
     * @param {number} tx - sprite anchoring
     * @param {number} ty - sprite anchoring
     */
    matrixAppendRotationInv: function (matrix, rotation, tx, ty) {
        if (tx === void 0) { tx = 0; }
        if (ty === void 0) { ty = 0; }
        // Packer used "rotation", we use "inv(rotation)"
        var mat = rotationMatrices[groupD8.inv(rotation)];
        mat.tx = tx;
        mat.ty = ty;
        matrix.append(mat);
    },
};

/**
 * Transform that takes care about its versions.
 *
 * @memberof PIXI
 */
var Transform = /** @class */ (function () {
    function Transform() {
        this.worldTransform = new Matrix();
        this.localTransform = new Matrix();
        this.position = new ObservablePoint(this.onChange, this, 0, 0);
        this.scale = new ObservablePoint(this.onChange, this, 1, 1);
        this.pivot = new ObservablePoint(this.onChange, this, 0, 0);
        this.skew = new ObservablePoint(this.updateSkew, this, 0, 0);
        this._rotation = 0;
        this._cx = 1;
        this._sx = 0;
        this._cy = 0;
        this._sy = 1;
        this._localID = 0;
        this._currentLocalID = 0;
        this._worldID = 0;
        this._parentID = 0;
    }
    /** Called when a value changes. */
    Transform.prototype.onChange = function () {
        this._localID++;
    };
    /** Called when the skew or the rotation changes. */
    Transform.prototype.updateSkew = function () {
        this._cx = Math.cos(this._rotation + this.skew.y);
        this._sx = Math.sin(this._rotation + this.skew.y);
        this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2
        this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2
        this._localID++;
    };
    Transform.prototype.toString = function () {
        return "[@pixi/math:Transform "
            + ("position=(" + this.position.x + ", " + this.position.y + ") ")
            + ("rotation=" + this.rotation + " ")
            + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ")
            + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ")
            + "]";
    };
    /** Updates the local transformation matrix. */
    Transform.prototype.updateLocalTransform = function () {
        var lt = this.localTransform;
        if (this._localID !== this._currentLocalID) {
            // get the matrix values of the displayobject based on its transform properties..
            lt.a = this._cx * this.scale.x;
            lt.b = this._sx * this.scale.x;
            lt.c = this._cy * this.scale.y;
            lt.d = this._sy * this.scale.y;
            lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c));
            lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d));
            this._currentLocalID = this._localID;
            // force an update..
            this._parentID = -1;
        }
    };
    /**
     * Updates the local and the world transformation matrices.
     *
     * @param parentTransform - The parent transform
     */
    Transform.prototype.updateTransform = function (parentTransform) {
        var lt = this.localTransform;
        if (this._localID !== this._currentLocalID) {
            // get the matrix values of the displayobject based on its transform properties..
            lt.a = this._cx * this.scale.x;
            lt.b = this._sx * this.scale.x;
            lt.c = this._cy * this.scale.y;
            lt.d = this._sy * this.scale.y;
            lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c));
            lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d));
            this._currentLocalID = this._localID;
            // force an update..
            this._parentID = -1;
        }
        if (this._parentID !== parentTransform._worldID) {
            // concat the parent matrix with the objects transform.
            var pt = parentTransform.worldTransform;
            var wt = this.worldTransform;
            wt.a = (lt.a * pt.a) + (lt.b * pt.c);
            wt.b = (lt.a * pt.b) + (lt.b * pt.d);
            wt.c = (lt.c * pt.a) + (lt.d * pt.c);
            wt.d = (lt.c * pt.b) + (lt.d * pt.d);
            wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx;
            wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty;
            this._parentID = parentTransform._worldID;
            // update the id of the transform..
            this._worldID++;
        }
    };
    /**
     * Decomposes a matrix and sets the transforms properties based on it.
     *
     * @param matrix - The matrix to decompose
     */
    Transform.prototype.setFromMatrix = function (matrix) {
        matrix.decompose(this);
        this._localID++;
    };
    Object.defineProperty(Transform.prototype, "rotation", {
        /** The rotation of the object in radians. */
        get: function () {
            return this._rotation;
        },
        set: function (value) {
            if (this._rotation !== value) {
                this._rotation = value;
                this.updateSkew();
            }
        },
        enumerable: false,
        configurable: true
    });
    /** A default (identity) transform. */
    Transform.IDENTITY = new Transform();
    return Transform;
}());


//# sourceMappingURL=math.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/display/dist/esm/display.js
/*!
 * @pixi/display - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/display is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */




/**
 * Sets the default value for the container property 'sortableChildren'.
 * If set to true, the container will sort its children by zIndex value
 * when updateTransform() is called, or manually if sortChildren() is called.
 *
 * This actually changes the order of elements in the array, so should be treated
 * as a basic solution that is not performant compared to other solutions,
 * such as @link https://github.com/pixijs/pixi-display
 *
 * Also be aware of that this may not work nicely with the addChildAt() function,
 * as the zIndex sorting may cause the child to automatically sorted to another position.
 *
 * @static
 * @constant
 * @name SORTABLE_CHILDREN
 * @memberof PIXI.settings
 * @type {boolean}
 * @default false
 */
settings.SORTABLE_CHILDREN = false;

/**
 * 'Builder' pattern for bounds rectangles.
 *
 * This could be called an Axis-Aligned Bounding Box.
 * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems.
 *
 * @memberof PIXI
 */
var Bounds = /** @class */ (function () {
    function Bounds() {
        this.minX = Infinity;
        this.minY = Infinity;
        this.maxX = -Infinity;
        this.maxY = -Infinity;
        this.rect = null;
        this.updateID = -1;
    }
    /**
     * Checks if bounds are empty.
     *
     * @return - True if empty.
     */
    Bounds.prototype.isEmpty = function () {
        return this.minX > this.maxX || this.minY > this.maxY;
    };
    /** Clears the bounds and resets. */
    Bounds.prototype.clear = function () {
        this.minX = Infinity;
        this.minY = Infinity;
        this.maxX = -Infinity;
        this.maxY = -Infinity;
    };
    /**
     * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle
     * It is not guaranteed that it will return tempRect
     *
     * @param rect - Temporary object will be used if AABB is not empty
     * @returns - A rectangle of the bounds
     */
    Bounds.prototype.getRectangle = function (rect) {
        if (this.minX > this.maxX || this.minY > this.maxY) {
            return Rectangle.EMPTY;
        }
        rect = rect || new Rectangle(0, 0, 1, 1);
        rect.x = this.minX;
        rect.y = this.minY;
        rect.width = this.maxX - this.minX;
        rect.height = this.maxY - this.minY;
        return rect;
    };
    /**
     * This function should be inlined when its possible.
     *
     * @param point - The point to add.
     */
    Bounds.prototype.addPoint = function (point) {
        this.minX = Math.min(this.minX, point.x);
        this.maxX = Math.max(this.maxX, point.x);
        this.minY = Math.min(this.minY, point.y);
        this.maxY = Math.max(this.maxY, point.y);
    };
    /** Adds a point, after transformed. This should be inlined when its possible. */
    Bounds.prototype.addPointMatrix = function (matrix, point) {
        var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty;
        var x = (a * point.x) + (c * point.y) + tx;
        var y = (b * point.x) + (d * point.y) + ty;
        this.minX = Math.min(this.minX, x);
        this.maxX = Math.max(this.maxX, x);
        this.minY = Math.min(this.minY, y);
        this.maxY = Math.max(this.maxY, y);
    };
    /**
     * Adds a quad, not transformed
     *
     * @param vertices - The verts to add.
     */
    Bounds.prototype.addQuad = function (vertices) {
        var minX = this.minX;
        var minY = this.minY;
        var maxX = this.maxX;
        var maxY = this.maxY;
        var x = vertices[0];
        var y = vertices[1];
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        x = vertices[2];
        y = vertices[3];
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        x = vertices[4];
        y = vertices[5];
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        x = vertices[6];
        y = vertices[7];
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        this.minX = minX;
        this.minY = minY;
        this.maxX = maxX;
        this.maxY = maxY;
    };
    /**
     * Adds sprite frame, transformed.
     *
     * @param transform - transform to apply
     * @param x0 - left X of frame
     * @param y0 - top Y of frame
     * @param x1 - right X of frame
     * @param y1 - bottom Y of frame
     */
    Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) {
        this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1);
    };
    /**
     * Adds sprite frame, multiplied by matrix
     *
     * @param matrix - matrix to apply
     * @param x0 - left X of frame
     * @param y0 - top Y of frame
     * @param x1 - right X of frame
     * @param y1 - bottom Y of frame
     */
    Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) {
        var a = matrix.a;
        var b = matrix.b;
        var c = matrix.c;
        var d = matrix.d;
        var tx = matrix.tx;
        var ty = matrix.ty;
        var minX = this.minX;
        var minY = this.minY;
        var maxX = this.maxX;
        var maxY = this.maxY;
        var x = (a * x0) + (c * y0) + tx;
        var y = (b * x0) + (d * y0) + ty;
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        x = (a * x1) + (c * y0) + tx;
        y = (b * x1) + (d * y0) + ty;
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        x = (a * x0) + (c * y1) + tx;
        y = (b * x0) + (d * y1) + ty;
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        x = (a * x1) + (c * y1) + tx;
        y = (b * x1) + (d * y1) + ty;
        minX = x < minX ? x : minX;
        minY = y < minY ? y : minY;
        maxX = x > maxX ? x : maxX;
        maxY = y > maxY ? y : maxY;
        this.minX = minX;
        this.minY = minY;
        this.maxX = maxX;
        this.maxY = maxY;
    };
    /**
     * Adds screen vertices from array
     *
     * @param vertexData - calculated vertices
     * @param beginOffset - begin offset
     * @param endOffset - end offset, excluded
     */
    Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) {
        var minX = this.minX;
        var minY = this.minY;
        var maxX = this.maxX;
        var maxY = this.maxY;
        for (var i = beginOffset; i < endOffset; i += 2) {
            var x = vertexData[i];
            var y = vertexData[i + 1];
            minX = x < minX ? x : minX;
            minY = y < minY ? y : minY;
            maxX = x > maxX ? x : maxX;
            maxY = y > maxY ? y : maxY;
        }
        this.minX = minX;
        this.minY = minY;
        this.maxX = maxX;
        this.maxY = maxY;
    };
    /**
     * Add an array of mesh vertices
     *
     * @param transform - mesh transform
     * @param vertices - mesh coordinates in array
     * @param beginOffset - begin offset
     * @param endOffset - end offset, excluded
     */
    Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) {
        this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset);
    };
    /**
     * Add an array of mesh vertices.
     *
     * @param matrix - mesh matrix
     * @param vertices - mesh coordinates in array
     * @param beginOffset - begin offset
     * @param endOffset - end offset, excluded
     * @param padX - x padding
     * @param padY - y padding
     */
    Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) {
        if (padX === void 0) { padX = 0; }
        if (padY === void 0) { padY = padX; }
        var a = matrix.a;
        var b = matrix.b;
        var c = matrix.c;
        var d = matrix.d;
        var tx = matrix.tx;
        var ty = matrix.ty;
        var minX = this.minX;
        var minY = this.minY;
        var maxX = this.maxX;
        var maxY = this.maxY;
        for (var i = beginOffset; i < endOffset; i += 2) {
            var rawX = vertices[i];
            var rawY = vertices[i + 1];
            var x = (a * rawX) + (c * rawY) + tx;
            var y = (d * rawY) + (b * rawX) + ty;
            minX = Math.min(minX, x - padX);
            maxX = Math.max(maxX, x + padX);
            minY = Math.min(minY, y - padY);
            maxY = Math.max(maxY, y + padY);
        }
        this.minX = minX;
        this.minY = minY;
        this.maxX = maxX;
        this.maxY = maxY;
    };
    /**
     * Adds other {@link Bounds}.
     *
     * @param bounds - The Bounds to be added
     */
    Bounds.prototype.addBounds = function (bounds) {
        var minX = this.minX;
        var minY = this.minY;
        var maxX = this.maxX;
        var maxY = this.maxY;
        this.minX = bounds.minX < minX ? bounds.minX : minX;
        this.minY = bounds.minY < minY ? bounds.minY : minY;
        this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX;
        this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY;
    };
    /**
     * Adds other Bounds, masked with Bounds.
     *
     * @param bounds - The Bounds to be added.
     * @param mask - TODO
     */
    Bounds.prototype.addBoundsMask = function (bounds, mask) {
        var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX;
        var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY;
        var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX;
        var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY;
        if (_minX <= _maxX && _minY <= _maxY) {
            var minX = this.minX;
            var minY = this.minY;
            var maxX = this.maxX;
            var maxY = this.maxY;
            this.minX = _minX < minX ? _minX : minX;
            this.minY = _minY < minY ? _minY : minY;
            this.maxX = _maxX > maxX ? _maxX : maxX;
            this.maxY = _maxY > maxY ? _maxY : maxY;
        }
    };
    /**
     * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty.
     *
     * @param bounds - other bounds
     * @param matrix - multiplicator
     */
    Bounds.prototype.addBoundsMatrix = function (bounds, matrix) {
        this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
    };
    /**
     * Adds other Bounds, masked with Rectangle.
     *
     * @param bounds - TODO
     * @param area - TODO
     */
    Bounds.prototype.addBoundsArea = function (bounds, area) {
        var _minX = bounds.minX > area.x ? bounds.minX : area.x;
        var _minY = bounds.minY > area.y ? bounds.minY : area.y;
        var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width);
        var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height);
        if (_minX <= _maxX && _minY <= _maxY) {
            var minX = this.minX;
            var minY = this.minY;
            var maxX = this.maxX;
            var maxY = this.maxY;
            this.minX = _minX < minX ? _minX : minX;
            this.minY = _minY < minY ? _minY : minY;
            this.maxX = _maxX > maxX ? _maxX : maxX;
            this.maxY = _maxY > maxY ? _maxY : maxY;
        }
    };
    /**
     * Pads bounds object, making it grow in all directions.
     * If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
     *
     * @param paddingX - The horizontal padding amount.
     * @param paddingY - The vertical padding amount.
     */
    Bounds.prototype.pad = function (paddingX, paddingY) {
        if (paddingX === void 0) { paddingX = 0; }
        if (paddingY === void 0) { paddingY = paddingX; }
        if (!this.isEmpty()) {
            this.minX -= paddingX;
            this.maxX += paddingX;
            this.minY -= paddingY;
            this.maxY += paddingY;
        }
    };
    /**
     * Adds padded frame. (x0, y0) should be strictly less than (x1, y1)
     *
     * @param x0 - left X of frame
     * @param y0 - top Y of frame
     * @param x1 - right X of frame
     * @param y1 - bottom Y of frame
     * @param padX - padding X
     * @param padY - padding Y
     */
    Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) {
        x0 -= padX;
        y0 -= padY;
        x1 += padX;
        y1 += padY;
        this.minX = this.minX < x0 ? this.minX : x0;
        this.maxX = this.maxX > x1 ? this.maxX : x1;
        this.minY = this.minY < y0 ? this.minY : y0;
        this.maxY = this.maxY > y1 ? this.maxY : y1;
    };
    return Bounds;
}());

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * The base class for all objects that are rendered on the screen.
 *
 * This is an abstract class and can not be used on its own; rather it should be extended.
 *
 * ## Display objects implemented in PixiJS
 *
 * | Display Object                  | Description                                                           |
 * | ------------------------------- | --------------------------------------------------------------------- |
 * | {@link PIXI.Container}          | Adds support for `children` to DisplayObject                          |
 * | {@link PIXI.Graphics}           | Shape-drawing display object similar to the Canvas API                |
 * | {@link PIXI.Sprite}             | Draws textures (i.e. images)                                          |
 * | {@link PIXI.Text}               | Draws text using the Canvas API internally                            |
 * | {@link PIXI.BitmapText}         | More scaleable solution for text rendering, reusing glyph textures    |
 * | {@link PIXI.TilingSprite}       | Draws textures/images in a tiled fashion                              |
 * | {@link PIXI.AnimatedSprite}     | Draws an animation of multiple images                                 |
 * | {@link PIXI.Mesh}               | Provides a lower-level API for drawing meshes with custom data        |
 * | {@link PIXI.NineSlicePlane}     | Mesh-related                                                          |
 * | {@link PIXI.SimpleMesh}         | v4-compatible mesh                                                    |
 * | {@link PIXI.SimplePlane}        | Mesh-related                                                          |
 * | {@link PIXI.SimpleRope}         | Mesh-related                                                          |
 *
 * ## Transforms
 *
 * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its
 * local coordinate space to its parent's local coordinate space. The following properties are derived
 * from the transform:
 *
 * <table>
 *   <thead>
 *     <tr>
 *       <th>Property</th>
 *       <th>Description</th>
 *     </tr>
 *   </thead>
 *   <tbody>
 *     <tr>
 *       <td>[pivot]{@link PIXI.DisplayObject#pivot}</td>
 *       <td>
 *         Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot
 *         is equal to position, regardless of the other three transformations. In other words, It is the center of
 *         rotation, scaling, and skewing.
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>[position]{@link PIXI.DisplayObject#position}</td>
 *       <td>
 *         Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local
 *         space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object
 *         is (0,0) in its local space, then the position will be its top-left corner in the parent's local space.
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>[scale]{@link PIXI.DisplayObject#scale}</td>
 *       <td>
 *         Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the
 *         local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center
 *         of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}.
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>[rotation]{@link PIXI.DisplayObject#rotation}</td>
 *       <td>
 *          Rotation. This will rotate the display object's projection by this angle (in radians).
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>[skew]{@link PIXI.DisplayObject#skew}</td>
 *       <td>
 *         <p>Skewing. This can be used to deform a rectangular display object into a parallelogram.</p>
 *         <p>
 *         In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be
 *         thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is
 *         ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be
 *         rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will
 *         be rotated by an angle between ⍺ and β.
 *         </p>
 *         <p>
 *         It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying
 *         a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ.
 *         </p>
 *         <p>
 *         Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed,
 *         because rotation is essentially a careful combination of the two.
 *         </p>
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>angle</td>
 *       <td>Rotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.</td>
 *     </tr>
 *     <tr>
 *       <td>x</td>
 *       <td>Translation. This is an alias for position.x!</td>
 *     </tr>
 *     <tr>
 *       <td>y</td>
 *       <td>Translation. This is an alias for position.y!</td>
 *     </tr>
 *     <tr>
 *       <td>width</td>
 *       <td>
 *         Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing
 *         the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there
 *         is no concept of user-defined width.
 *       </td>
 *     </tr>
 *     <tr>
 *       <td>height</td>
 *       <td>
 *         Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing
 *         the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there
 *         is no concept of user-defined height.
 *       </td>
 *     </tr>
 *   </tbody>
 * </table>
 *
 * ## Bounds
 *
 * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit
 * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the
 * `worldTransform` to calculate in world space).
 *
 * There are a few additional types of bounding boxes:
 *
 * | Bounds                | Description                                                                              |
 * | --------------------- | ---------------------------------------------------------------------------------------- |
 * | World Bounds          | This is synonymous is the regular bounds described above. See `getBounds()`.             |
 * | Local Bounds          | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`.  |
 * | Render Bounds         | The bounds, but including extra rendering effects like filter padding.                   |
 * | Projected Bounds      | The bounds of the projected display object onto the screen. Usually equals world bounds. |
 * | Relative Bounds       | The bounds of a display object when projected onto a ancestor's (or parent's) space.     |
 * | Natural Bounds        | The bounds of an object in its own local space (not parent's space, like in local bounds)|
 * | Content Bounds        | The natural bounds when excluding all children of a `Container`.                         |
 *
 * ### calculateBounds
 *
 * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children.
 *
 * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and
 * `getLocalBounds` to work. This method must write the bounds into `this._bounds`.
 *
 * Generally, the following technique works for most simple cases: take the list of points
 * forming the "hull" of the object (i.e. outline of the object's shape), and then add them
 * using {@link PIXI.Bounds#addPointMatrix}.
 *
 * ```js
 * calculateBounds(): void
 * {
 *     const points = [...];
 *
 *     for (let i = 0, j = points.length; i < j; i++)
 *     {
 *         this._bounds.addPointMatrix(this.worldTransform, points[i]);
 *     }
 * }
 * ```
 *
 * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them
 * in one array together.
 *
 * ## Alpha
 *
 * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display
 * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not
 * applied on any ancestor further up the chain).
 *
 * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}.
 *
 * ## Renderable vs Visible
 *
 * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the
 * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms  of the display
 * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not
 * be calculated.
 *
 * It is recommended that applications use the `renderable` property for culling. See
 * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or
 * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details.
 *
 * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This
 * one is also better in terms of performance.
 *
 * @memberof PIXI
 */
var DisplayObject = /** @class */ (function (_super) {
    __extends(DisplayObject, _super);
    function DisplayObject() {
        var _this = _super.call(this) || this;
        _this.tempDisplayObjectParent = null;
        // TODO: need to create Transform from factory
        _this.transform = new Transform();
        _this.alpha = 1;
        _this.visible = true;
        _this.renderable = true;
        _this.cullable = false;
        _this.cullArea = null;
        _this.parent = null;
        _this.worldAlpha = 1;
        _this._lastSortedIndex = 0;
        _this._zIndex = 0;
        _this.filterArea = null;
        _this.filters = null;
        _this._enabledFilters = null;
        _this._bounds = new Bounds();
        _this._localBounds = null;
        _this._boundsID = 0;
        _this._boundsRect = null;
        _this._localBoundsRect = null;
        _this._mask = null;
        _this._maskRefCount = 0;
        _this._destroyed = false;
        _this.isSprite = false;
        _this.isMask = false;
        return _this;
    }
    /**
     * Mixes all enumerable properties and methods from a source object to DisplayObject.
     *
     * @param source - The source of properties and methods to mix in.
     */
    DisplayObject.mixin = function (source) {
        // in ES8/ES2017, this would be really easy:
        // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source));
        // get all the enumerable property keys
        var keys = Object.keys(source);
        // loop through properties
        for (var i = 0; i < keys.length; ++i) {
            var propertyName = keys[i];
            // Set the property using the property descriptor - this works for accessors and normal value properties
            Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName));
        }
    };
    Object.defineProperty(DisplayObject.prototype, "destroyed", {
        /**
         * Fired when this DisplayObject is added to a Container.
         *
         * @instance
         * @event added
         * @param {PIXI.Container} container - The container added to.
         */
        /**
         * Fired when this DisplayObject is removed from a Container.
         *
         * @instance
         * @event removed
         * @param {PIXI.Container} container - The container removed from.
         */
        /**
         * Fired when this DisplayObject is destroyed.
         *
         * @instance
         * @event destroyed
         */
        /** Readonly flag for destroyed display objects. */
        get: function () {
            return this._destroyed;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Recursively updates transform of all objects from the root to this one
     * internal function for toLocal()
     */
    DisplayObject.prototype._recursivePostUpdateTransform = function () {
        if (this.parent) {
            this.parent._recursivePostUpdateTransform();
            this.transform.updateTransform(this.parent.transform);
        }
        else {
            this.transform.updateTransform(this._tempDisplayObjectParent.transform);
        }
    };
    /**
     * Updates the object transform for rendering.
     *
     * TODO - Optimization pass!
     */
    DisplayObject.prototype.updateTransform = function () {
        this._boundsID++;
        this.transform.updateTransform(this.parent.transform);
        // multiply the alphas..
        this.worldAlpha = this.alpha * this.parent.worldAlpha;
    };
    /**
     * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}.
     *
     * This method is expensive on containers with a large subtree (like the stage). This is because the bounds
     * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to
     * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update
     * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using
     * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise,
     * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as
     * its height increases.
     *
     * * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated.
     * * The world bounds of all display objects in a container's **subtree** will also be recalculated.
     *
     * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds
     * calculation if needed.
     *
     * ```js
     * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect);
     * ```
     *
     * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This
     * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more
     * details.
     *
     * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms
     * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain
     * cases.
     *
     * @param skipUpdate - Setting to `true` will stop the transforms of the scene graph from
     *  being updated. This means the calculation returned MAY be out of date BUT will give you a
     *  nice performance boost.
     * @param rect - Optional rectangle to store the result of the bounds calculation.
     * @return - The minimum axis-aligned rectangle in world space that fits around this object.
     */
    DisplayObject.prototype.getBounds = function (skipUpdate, rect) {
        if (!skipUpdate) {
            if (!this.parent) {
                this.parent = this._tempDisplayObjectParent;
                this.updateTransform();
                this.parent = null;
            }
            else {
                this._recursivePostUpdateTransform();
                this.updateTransform();
            }
        }
        if (this._bounds.updateID !== this._boundsID) {
            this.calculateBounds();
            this._bounds.updateID = this._boundsID;
        }
        if (!rect) {
            if (!this._boundsRect) {
                this._boundsRect = new Rectangle();
            }
            rect = this._boundsRect;
        }
        return this._bounds.getRectangle(rect);
    };
    /**
     * Retrieves the local bounds of the displayObject as a rectangle object.
     *
     * @param rect - Optional rectangle to store the result of the bounds calculation.
     * @return - The rectangular bounding area.
     */
    DisplayObject.prototype.getLocalBounds = function (rect) {
        if (!rect) {
            if (!this._localBoundsRect) {
                this._localBoundsRect = new Rectangle();
            }
            rect = this._localBoundsRect;
        }
        if (!this._localBounds) {
            this._localBounds = new Bounds();
        }
        var transformRef = this.transform;
        var parentRef = this.parent;
        this.parent = null;
        this.transform = this._tempDisplayObjectParent.transform;
        var worldBounds = this._bounds;
        var worldBoundsID = this._boundsID;
        this._bounds = this._localBounds;
        var bounds = this.getBounds(false, rect);
        this.parent = parentRef;
        this.transform = transformRef;
        this._bounds = worldBounds;
        this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects
        return bounds;
    };
    /**
     * Calculates the global position of the display object.
     *
     * @param position - The world origin to calculate from.
     * @param point - A Point object in which to store the value, optional
     *  (otherwise will create a new Point).
     * @param skipUpdate - Should we skip the update transform.
     * @return - A point object representing the position of this object.
     */
    DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) {
        if (skipUpdate === void 0) { skipUpdate = false; }
        if (!skipUpdate) {
            this._recursivePostUpdateTransform();
            // this parent check is for just in case the item is a root object.
            // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
            // this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
            if (!this.parent) {
                this.parent = this._tempDisplayObjectParent;
                this.displayObjectUpdateTransform();
                this.parent = null;
            }
            else {
                this.displayObjectUpdateTransform();
            }
        }
        // don't need to update the lot
        return this.worldTransform.apply(position, point);
    };
    /**
     * Calculates the local position of the display object relative to another point.
     *
     * @param position - The world origin to calculate from.
     * @param from - The DisplayObject to calculate the global position from.
     * @param point - A Point object in which to store the value, optional
     *  (otherwise will create a new Point).
     * @param skipUpdate - Should we skip the update transform
     * @return - A point object representing the position of this object
     */
    DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) {
        if (from) {
            position = from.toGlobal(position, point, skipUpdate);
        }
        if (!skipUpdate) {
            this._recursivePostUpdateTransform();
            // this parent check is for just in case the item is a root object.
            // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
            // this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
            if (!this.parent) {
                this.parent = this._tempDisplayObjectParent;
                this.displayObjectUpdateTransform();
                this.parent = null;
            }
            else {
                this.displayObjectUpdateTransform();
            }
        }
        // simply apply the matrix..
        return this.worldTransform.applyInverse(position, point);
    };
    /**
     * Set the parent Container of this DisplayObject.
     *
     * @param container - The Container to add this DisplayObject to.
     * @return - The Container that this DisplayObject was added to.
     */
    DisplayObject.prototype.setParent = function (container) {
        if (!container || !container.addChild) {
            throw new Error('setParent: Argument must be a Container');
        }
        container.addChild(this);
        return container;
    };
    /**
     * Convenience function to set the position, scale, skew and pivot at once.
     *
     * @param x - The X position
     * @param y - The Y position
     * @param scaleX - The X scale value
     * @param scaleY - The Y scale value
     * @param rotation - The rotation
     * @param skewX - The X skew value
     * @param skewY - The Y skew value
     * @param pivotX - The X pivot value
     * @param pivotY - The Y pivot value
     * @return - The DisplayObject instance
     */
    DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (scaleX === void 0) { scaleX = 1; }
        if (scaleY === void 0) { scaleY = 1; }
        if (rotation === void 0) { rotation = 0; }
        if (skewX === void 0) { skewX = 0; }
        if (skewY === void 0) { skewY = 0; }
        if (pivotX === void 0) { pivotX = 0; }
        if (pivotY === void 0) { pivotY = 0; }
        this.position.x = x;
        this.position.y = y;
        this.scale.x = !scaleX ? 1 : scaleX;
        this.scale.y = !scaleY ? 1 : scaleY;
        this.rotation = rotation;
        this.skew.x = skewX;
        this.skew.y = skewY;
        this.pivot.x = pivotX;
        this.pivot.y = pivotY;
        return this;
    };
    /**
     * Base destroy method for generic display objects. This will automatically
     * remove the display object from its parent Container as well as remove
     * all current event listeners and internal references. Do not use a DisplayObject
     * after calling `destroy()`.
     */
    DisplayObject.prototype.destroy = function (_options) {
        if (this.parent) {
            this.parent.removeChild(this);
        }
        this.emit('destroyed');
        this.removeAllListeners();
        this.transform = null;
        this.parent = null;
        this._bounds = null;
        this.mask = null;
        this.cullArea = null;
        this.filters = null;
        this.filterArea = null;
        this.hitArea = null;
        this.interactive = false;
        this.interactiveChildren = false;
        this._destroyed = true;
    };
    Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", {
        /**
         * @protected
         * @member {PIXI.Container}
         */
        get: function () {
            if (this.tempDisplayObjectParent === null) {
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                this.tempDisplayObjectParent = new TemporaryDisplayObject();
            }
            return this.tempDisplayObjectParent;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root
     *
     * ```
     * const cacheParent = elem.enableTempParent();
     * elem.updateTransform();
     * elem.disableTempParent(cacheParent);
     * ```
     *
     * @returns - current parent
     */
    DisplayObject.prototype.enableTempParent = function () {
        var myParent = this.parent;
        this.parent = this._tempDisplayObjectParent;
        return myParent;
    };
    /**
     * Pair method for `enableTempParent`
     *
     * @param cacheParent - Actual parent of element
     */
    DisplayObject.prototype.disableTempParent = function (cacheParent) {
        this.parent = cacheParent;
    };
    Object.defineProperty(DisplayObject.prototype, "x", {
        /**
         * The position of the displayObject on the x axis relative to the local coordinates of the parent.
         * An alias to position.x
         */
        get: function () {
            return this.position.x;
        },
        set: function (value) {
            this.transform.position.x = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "y", {
        /**
         * The position of the displayObject on the y axis relative to the local coordinates of the parent.
         * An alias to position.y
         */
        get: function () {
            return this.position.y;
        },
        set: function (value) {
            this.transform.position.y = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "worldTransform", {
        /**
         * Current transform of the object based on world (parent) factors.
         *
         * @readonly
         */
        get: function () {
            return this.transform.worldTransform;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "localTransform", {
        /**
         * Current transform of the object based on local factors: position, scale, other stuff.
         *
         * @readonly
         */
        get: function () {
            return this.transform.localTransform;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "position", {
        /**
         * The coordinate of the object relative to the local coordinates of the parent.
         *
         * @since PixiJS 4
         */
        get: function () {
            return this.transform.position;
        },
        set: function (value) {
            this.transform.position.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "scale", {
        /**
         * The scale factors of this object along the local coordinate axes.
         *
         * The default scale is (1, 1).
         *
         * @since PixiJS 4
         */
        get: function () {
            return this.transform.scale;
        },
        set: function (value) {
            this.transform.scale.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "pivot", {
        /**
         * The center of rotation, scaling, and skewing for this display object in its local space. The `position`
         * is the projection of `pivot` in the parent's local space.
         *
         * By default, the pivot is the origin (0, 0).
         *
         * @since PixiJS 4
         */
        get: function () {
            return this.transform.pivot;
        },
        set: function (value) {
            this.transform.pivot.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "skew", {
        /**
         * The skew factor for the object in radians.
         *
         * @since PixiJS 4
         */
        get: function () {
            return this.transform.skew;
        },
        set: function (value) {
            this.transform.skew.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "rotation", {
        /**
         * The rotation of the object in radians.
         * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
         */
        get: function () {
            return this.transform.rotation;
        },
        set: function (value) {
            this.transform.rotation = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "angle", {
        /**
         * The angle of the object in degrees.
         * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
         */
        get: function () {
            return this.transform.rotation * RAD_TO_DEG;
        },
        set: function (value) {
            this.transform.rotation = value * DEG_TO_RAD;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "zIndex", {
        /**
         * The zIndex of the displayObject.
         *
         * If a container has the sortableChildren property set to true, children will be automatically
         * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array,
         * and thus rendered on top of other display objects within the same container.
         *
         * @see PIXI.Container#sortableChildren
         */
        get: function () {
            return this._zIndex;
        },
        set: function (value) {
            this._zIndex = value;
            if (this.parent) {
                this.parent.sortDirty = true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "worldVisible", {
        /**
         * Indicates if the object is globally visible.
         *
         * @readonly
         */
        get: function () {
            var item = this;
            do {
                if (!item.visible) {
                    return false;
                }
                item = item.parent;
            } while (item);
            return true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DisplayObject.prototype, "mask", {
        /**
         * Sets a mask for the displayObject. A mask is an object that limits the visibility of an
         * object to the shape of the mask applied to it. In PixiJS a regular mask must be a
         * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it
         * utilities shape clipping. To remove a mask, set this property to `null`.
         *
         * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
         *
         * @example
         * const graphics = new PIXI.Graphics();
         * graphics.beginFill(0xFF3300);
         * graphics.drawRect(50, 250, 100, 100);
         * graphics.endFill();
         *
         * const sprite = new PIXI.Sprite(texture);
         * sprite.mask = graphics;
         *
         * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask.
         */
        get: function () {
            return this._mask;
        },
        set: function (value) {
            if (this._mask === value) {
                return;
            }
            if (this._mask) {
                var maskObject = (this._mask.maskObject || this._mask);
                maskObject._maskRefCount--;
                if (maskObject._maskRefCount === 0) {
                    maskObject.renderable = true;
                    maskObject.isMask = false;
                }
            }
            this._mask = value;
            if (this._mask) {
                var maskObject = (this._mask.maskObject || this._mask);
                if (maskObject._maskRefCount === 0) {
                    maskObject.renderable = false;
                    maskObject.isMask = true;
                }
                maskObject._maskRefCount++;
            }
        },
        enumerable: false,
        configurable: true
    });
    return DisplayObject;
}((eventemitter3_default())));
/**
 * @private
 */
var TemporaryDisplayObject = /** @class */ (function (_super) {
    __extends(TemporaryDisplayObject, _super);
    function TemporaryDisplayObject() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.sortDirty = null;
        return _this;
    }
    return TemporaryDisplayObject;
}(DisplayObject));
/**
 * DisplayObject default updateTransform, does not update children of container.
 * Will crash if there's no parent element.
 *
 * @memberof PIXI.DisplayObject#
 * @method displayObjectUpdateTransform
 */
DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform;

/*!
 * @pixi/constants - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/constants is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * Different types of environments for WebGL.
 *
 * @static
 * @memberof PIXI
 * @name ENV
 * @enum {number}
 * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
 *  with older / less advanced devices. If you experience unexplained flickering prefer this environment.
 * @property {number} WEBGL - Version 1 of WebGL
 * @property {number} WEBGL2 - Version 2 of WebGL
 */
var display_ENV;
(function (ENV) {
    ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
    ENV[ENV["WEBGL"] = 1] = "WEBGL";
    ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
})(display_ENV || (display_ENV = {}));
/**
 * Constant to identify the Renderer Type.
 *
 * @static
 * @memberof PIXI
 * @name RENDERER_TYPE
 * @enum {number}
 * @property {number} UNKNOWN - Unknown render type.
 * @property {number} WEBGL - WebGL render type.
 * @property {number} CANVAS - Canvas render type.
 */
var display_RENDERER_TYPE;
(function (RENDERER_TYPE) {
    RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
    RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
    RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
})(display_RENDERER_TYPE || (display_RENDERER_TYPE = {}));
/**
 * Bitwise OR of masks that indicate the buffers to be cleared.
 *
 * @static
 * @memberof PIXI
 * @name BUFFER_BITS
 * @enum {number}
 * @property {number} COLOR - Indicates the buffers currently enabled for color writing.
 * @property {number} DEPTH - Indicates the depth buffer.
 * @property {number} STENCIL - Indicates the stencil buffer.
 */
var display_BUFFER_BITS;
(function (BUFFER_BITS) {
    BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR";
    BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH";
    BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL";
})(display_BUFFER_BITS || (display_BUFFER_BITS = {}));
/**
 * Various blend modes supported by PIXI.
 *
 * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
 * Anything else will silently act like NORMAL.
 *
 * @memberof PIXI
 * @name BLEND_MODES
 * @enum {number}
 * @property {number} NORMAL
 * @property {number} ADD
 * @property {number} MULTIPLY
 * @property {number} SCREEN
 * @property {number} OVERLAY
 * @property {number} DARKEN
 * @property {number} LIGHTEN
 * @property {number} COLOR_DODGE
 * @property {number} COLOR_BURN
 * @property {number} HARD_LIGHT
 * @property {number} SOFT_LIGHT
 * @property {number} DIFFERENCE
 * @property {number} EXCLUSION
 * @property {number} HUE
 * @property {number} SATURATION
 * @property {number} COLOR
 * @property {number} LUMINOSITY
 * @property {number} NORMAL_NPM
 * @property {number} ADD_NPM
 * @property {number} SCREEN_NPM
 * @property {number} NONE
 * @property {number} SRC_IN
 * @property {number} SRC_OUT
 * @property {number} SRC_ATOP
 * @property {number} DST_OVER
 * @property {number} DST_IN
 * @property {number} DST_OUT
 * @property {number} DST_ATOP
 * @property {number} SUBTRACT
 * @property {number} SRC_OVER
 * @property {number} ERASE
 * @property {number} XOR
 */
var display_BLEND_MODES;
(function (BLEND_MODES) {
    BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
    BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
    BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
    BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
    BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
    BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
    BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
    BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
    BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
    BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
    BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
    BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
    BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
    BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
    BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
    BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
    BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
    BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
    BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
    BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
    BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
    BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER";
    BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN";
    BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT";
    BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP";
    BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER";
    BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN";
    BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT";
    BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP";
    BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE";
    BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT";
    BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR";
})(display_BLEND_MODES || (display_BLEND_MODES = {}));
/**
 * Various webgl draw modes. These can be used to specify which GL drawMode to use
 * under certain situations and renderers.
 *
 * @memberof PIXI
 * @static
 * @name DRAW_MODES
 * @enum {number}
 * @property {number} POINTS
 * @property {number} LINES
 * @property {number} LINE_LOOP
 * @property {number} LINE_STRIP
 * @property {number} TRIANGLES
 * @property {number} TRIANGLE_STRIP
 * @property {number} TRIANGLE_FAN
 */
var display_DRAW_MODES;
(function (DRAW_MODES) {
    DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
    DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
    DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
    DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
    DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
})(display_DRAW_MODES || (display_DRAW_MODES = {}));
/**
 * Various GL texture/resources formats.
 *
 * @memberof PIXI
 * @static
 * @name FORMATS
 * @enum {number}
 * @property {number} RGBA=6408
 * @property {number} RGB=6407
 * @property {number} RG=33319
 * @property {number} RED=6403
 * @property {number} RGBA_INTEGER=36249
 * @property {number} RGB_INTEGER=36248
 * @property {number} RG_INTEGER=33320
 * @property {number} RED_INTEGER=36244
 * @property {number} ALPHA=6406
 * @property {number} LUMINANCE=6409
 * @property {number} LUMINANCE_ALPHA=6410
 * @property {number} DEPTH_COMPONENT=6402
 * @property {number} DEPTH_STENCIL=34041
 */
var display_FORMATS;
(function (FORMATS) {
    FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
    FORMATS[FORMATS["RGB"] = 6407] = "RGB";
    FORMATS[FORMATS["RG"] = 33319] = "RG";
    FORMATS[FORMATS["RED"] = 6403] = "RED";
    FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
    FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
    FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
    FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
    FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA";
    FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE";
    FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
    FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
    FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
})(display_FORMATS || (display_FORMATS = {}));
/**
 * Various GL target types.
 *
 * @memberof PIXI
 * @static
 * @name TARGETS
 * @enum {number}
 * @property {number} TEXTURE_2D=3553
 * @property {number} TEXTURE_CUBE_MAP=34067
 * @property {number} TEXTURE_2D_ARRAY=35866
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074
 */
var display_TARGETS;
(function (TARGETS) {
    TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
    TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
})(display_TARGETS || (display_TARGETS = {}));
/**
 * Various GL data format types.
 *
 * @memberof PIXI
 * @static
 * @name TYPES
 * @enum {number}
 * @property {number} UNSIGNED_BYTE=5121
 * @property {number} UNSIGNED_SHORT=5123
 * @property {number} UNSIGNED_SHORT_5_6_5=33635
 * @property {number} UNSIGNED_SHORT_4_4_4_4=32819
 * @property {number} UNSIGNED_SHORT_5_5_5_1=32820
 * @property {number} UNSIGNED_INT=5125
 * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
 * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
 * @property {number} UNSIGNED_INT_24_8=34042
 * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
 * @property {number} BYTE=5120
 * @property {number} SHORT=5122
 * @property {number} INT=5124
 * @property {number} FLOAT=5126
 * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
 * @property {number} HALF_FLOAT=36193
 */
var display_TYPES;
(function (TYPES) {
    TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
    TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
    TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
    TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
    TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
    TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
    TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
    TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
    TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
    TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
    TYPES[TYPES["BYTE"] = 5120] = "BYTE";
    TYPES[TYPES["SHORT"] = 5122] = "SHORT";
    TYPES[TYPES["INT"] = 5124] = "INT";
    TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
    TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
    TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
})(display_TYPES || (display_TYPES = {}));
/**
 * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
 * WebGL1 works only with FLOAT.
 *
 * @memberof PIXI
 * @static
 * @name SAMPLER_TYPES
 * @enum {number}
 * @property {number} FLOAT=0
 * @property {number} INT=1
 * @property {number} UINT=2
 */
var display_SAMPLER_TYPES;
(function (SAMPLER_TYPES) {
    SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
    SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
    SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
})(display_SAMPLER_TYPES || (display_SAMPLER_TYPES = {}));
/**
 * The scale modes that are supported by pixi.
 *
 * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
 * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
 *
 * @memberof PIXI
 * @static
 * @name SCALE_MODES
 * @enum {number}
 * @property {number} LINEAR Smooth scaling
 * @property {number} NEAREST Pixelating scaling
 */
var display_SCALE_MODES;
(function (SCALE_MODES) {
    SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
    SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
})(display_SCALE_MODES || (display_SCALE_MODES = {}));
/**
 * The wrap modes that are supported by pixi.
 *
 * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
 * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
 * If the texture is non power of two then clamp will be used regardless as WebGL can
 * only use REPEAT if the texture is po2.
 *
 * This property only affects WebGL.
 *
 * @name WRAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} CLAMP - The textures uvs are clamped
 * @property {number} REPEAT - The texture uvs tile and repeat
 * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
 */
var display_WRAP_MODES;
(function (WRAP_MODES) {
    WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
    WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
    WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
})(display_WRAP_MODES || (display_WRAP_MODES = {}));
/**
 * Mipmap filtering modes that are supported by pixi.
 *
 * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
 * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
 * or its `POW2` and texture dimensions are powers of 2.
 * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
 *
 * This property only affects WebGL.
 *
 * @name MIPMAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} OFF - No mipmaps
 * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
 * @property {number} ON - Always generate mipmaps
 * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
 *   that supports buffering each level-of-detail.
 */
var display_MIPMAP_MODES;
(function (MIPMAP_MODES) {
    MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF";
    MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2";
    MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON";
    MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL";
})(display_MIPMAP_MODES || (display_MIPMAP_MODES = {}));
/**
 * How to treat textures with premultiplied alpha
 *
 * @name ALPHA_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that.
 *  Option for compressed and data textures that are created from typed arrays.
 * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload.
 *  Default option, used for all loaded images.
 * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied
 *  Example: spine atlases with `_pma` suffix.
 * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA.
 * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD.
 * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA.
 */
var display_ALPHA_MODES;
(function (ALPHA_MODES) {
    ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM";
    ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK";
    ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA";
    ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
})(display_ALPHA_MODES || (display_ALPHA_MODES = {}));
/**
 * Configure whether filter textures are cleared after binding.
 *
 * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
 * this and skip clearing as an optimization.
 *
 * @name CLEAR_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
 * @property {number} CLEAR - Always clear the filter texture.
 * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
 * @property {number} NO - Alias for BLEND, same as `false` in earlier versions
 * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions
 * @property {number} AUTO - Alias for BLIT
 */
var display_CLEAR_MODES;
(function (CLEAR_MODES) {
    CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO";
    CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES";
    CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO";
    CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND";
    CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR";
    CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT";
})(display_CLEAR_MODES || (display_CLEAR_MODES = {}));
/**
 * The gc modes that are supported by pixi.
 *
 * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
 * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
 * used for a specified period of time they will be removed from the GPU. They will of course
 * be uploaded again when they are required. This is a silent behind the scenes process that
 * should ensure that the GPU does not  get filled up.
 *
 * Handy for mobile devices!
 * This property only affects WebGL.
 *
 * @name GC_MODES
 * @enum {number}
 * @static
 * @memberof PIXI
 * @property {number} AUTO - Garbage collection will happen periodically automatically
 * @property {number} MANUAL - Garbage collection will need to be called manually
 */
var display_GC_MODES;
(function (GC_MODES) {
    GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
    GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
})(display_GC_MODES || (display_GC_MODES = {}));
/**
 * Constants that specify float precision in shaders.
 *
 * @name PRECISION
 * @memberof PIXI
 * @constant
 * @static
 * @enum {string}
 * @property {string} LOW='lowp'
 * @property {string} MEDIUM='mediump'
 * @property {string} HIGH='highp'
 */
var display_PRECISION;
(function (PRECISION) {
    PRECISION["LOW"] = "lowp";
    PRECISION["MEDIUM"] = "mediump";
    PRECISION["HIGH"] = "highp";
})(display_PRECISION || (display_PRECISION = {}));
/**
 * Constants for mask implementations.
 * We use `type` suffix because it leads to very different behaviours
 *
 * @name MASK_TYPES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - Mask is ignored
 * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap
 * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil
 * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture
 */
var display_MASK_TYPES;
(function (MASK_TYPES) {
    MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE";
    MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR";
    MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL";
    MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE";
})(display_MASK_TYPES || (display_MASK_TYPES = {}));
/**
 * Constants for multi-sampling antialiasing.
 *
 * @see PIXI.Framebuffer#multisample
 *
 * @name MSAA_QUALITY
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - No multisampling for this renderTexture
 * @property {number} LOW - Try 2 samples
 * @property {number} MEDIUM - Try 4 samples
 * @property {number} HIGH - Try 8 samples
 */
var display_MSAA_QUALITY;
(function (MSAA_QUALITY) {
    MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE";
    MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW";
    MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM";
    MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH";
})(display_MSAA_QUALITY || (display_MSAA_QUALITY = {}));
/**
 * Constants for various buffer types in Pixi
 *
 * @see PIXI.BUFFER_TYPE
 *
 * @name BUFFER_TYPE
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
 * @property {number} ARRAY_BUFFER - buffer type for using attribute data
 * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
 */
var display_BUFFER_TYPE;
(function (BUFFER_TYPE) {
    BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
    BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
    // NOT YET SUPPORTED
    BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
})(display_BUFFER_TYPE || (display_BUFFER_TYPE = {}));

function sortChildren(a, b) {
    if (a.zIndex === b.zIndex) {
        return a._lastSortedIndex - b._lastSortedIndex;
    }
    return a.zIndex - b.zIndex;
}
/**
 * Container is a general-purpose display object that holds children. It also adds built-in support for advanced
 * rendering features like masking and filtering.
 *
 * It is the base class of all display objects that act as a container for other objects, including Graphics
 * and Sprite.
 *
 * ```js
 * import { BlurFilter } from '@pixi/filter-blur';
 * import { Container } from '@pixi/display';
 * import { Graphics } from '@pixi/graphics';
 * import { Sprite } from '@pixi/sprite';
 *
 * let container = new Container();
 * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png");
 *
 * sprite.width = 512;
 * sprite.height = 512;
 *
 * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container
 * // is rendered.
 * container.addChild(sprite);
 *
 * // Blurs whatever is rendered by the container
 * container.filters = [new BlurFilter()];
 *
 * // Only the contents within a circle at the center should be rendered onto the screen.
 * container.mask = new Graphics()
 *  .beginFill(0xffffff)
 *  .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2)
 *  .endFill();
 * ```
 *
 * @memberof PIXI
 */
var Container = /** @class */ (function (_super) {
    __extends(Container, _super);
    function Container() {
        var _this = _super.call(this) || this;
        _this.children = [];
        _this.sortableChildren = settings.SORTABLE_CHILDREN;
        _this.sortDirty = false;
        return _this;
        /**
         * Fired when a DisplayObject is added to this Container.
         *
         * @event PIXI.Container#childAdded
         * @param {PIXI.DisplayObject} child - The child added to the Container.
         * @param {PIXI.Container} container - The container that added the child.
         * @param {number} index - The children's index of the added child.
         */
        /**
         * Fired when a DisplayObject is removed from this Container.
         *
         * @event PIXI.DisplayObject#removedFrom
         * @param {PIXI.DisplayObject} child - The child removed from the Container.
         * @param {PIXI.Container} container - The container that removed removed the child.
         * @param {number} index - The former children's index of the removed child
         */
    }
    /** Overridable method that can be used by Container subclasses whenever the children array is modified. */
    Container.prototype.onChildrenChange = function (_length) {
        /* empty */
    };
    /**
     * Adds one or more children to the container.
     *
     * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)`
     *
     * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container
     * @return {PIXI.DisplayObject} - The first child that was added.
     */
    Container.prototype.addChild = function () {
        var arguments$1 = arguments;

        var children = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            children[_i] = arguments$1[_i];
        }
        // if there is only one argument we can bypass looping through the them
        if (children.length > 1) {
            // loop through the array and add all children
            for (var i = 0; i < children.length; i++) {
                // eslint-disable-next-line prefer-rest-params
                this.addChild(children[i]);
            }
        }
        else {
            var child = children[0];
            // if the child has a parent then lets remove it as PixiJS objects can only exist in one place
            if (child.parent) {
                child.parent.removeChild(child);
            }
            child.parent = this;
            this.sortDirty = true;
            // ensure child transform will be recalculated
            child.transform._parentID = -1;
            this.children.push(child);
            // ensure bounds will be recalculated
            this._boundsID++;
            // TODO - lets either do all callbacks or all events.. not both!
            this.onChildrenChange(this.children.length - 1);
            this.emit('childAdded', child, this, this.children.length - 1);
            child.emit('added', this);
        }
        return children[0];
    };
    /**
     * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
     *
     * @param {PIXI.DisplayObject} child - The child to add
     * @param {number} index - The index to place the child in
     * @return {PIXI.DisplayObject} The child that was added.
     */
    Container.prototype.addChildAt = function (child, index) {
        if (index < 0 || index > this.children.length) {
            throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length);
        }
        if (child.parent) {
            child.parent.removeChild(child);
        }
        child.parent = this;
        this.sortDirty = true;
        // ensure child transform will be recalculated
        child.transform._parentID = -1;
        this.children.splice(index, 0, child);
        // ensure bounds will be recalculated
        this._boundsID++;
        // TODO - lets either do all callbacks or all events.. not both!
        this.onChildrenChange(index);
        child.emit('added', this);
        this.emit('childAdded', child, this, index);
        return child;
    };
    /**
     * Swaps the position of 2 Display Objects within this container.
     *
     * @param child - First display object to swap
     * @param child2 - Second display object to swap
     */
    Container.prototype.swapChildren = function (child, child2) {
        if (child === child2) {
            return;
        }
        var index1 = this.getChildIndex(child);
        var index2 = this.getChildIndex(child2);
        this.children[index1] = child2;
        this.children[index2] = child;
        this.onChildrenChange(index1 < index2 ? index1 : index2);
    };
    /**
     * Returns the index position of a child DisplayObject instance
     *
     * @param child - The DisplayObject instance to identify
     * @return - The index position of the child display object to identify
     */
    Container.prototype.getChildIndex = function (child) {
        var index = this.children.indexOf(child);
        if (index === -1) {
            throw new Error('The supplied DisplayObject must be a child of the caller');
        }
        return index;
    };
    /**
     * Changes the position of an existing child in the display object container
     *
     * @param child - The child DisplayObject instance for which you want to change the index number
     * @param index - The resulting index number for the child display object
     */
    Container.prototype.setChildIndex = function (child, index) {
        if (index < 0 || index >= this.children.length) {
            throw new Error("The index " + index + " supplied is out of bounds " + this.children.length);
        }
        var currentIndex = this.getChildIndex(child);
        removeItems(this.children, currentIndex, 1); // remove from old position
        this.children.splice(index, 0, child); // add at new position
        this.onChildrenChange(index);
    };
    /**
     * Returns the child at the specified index
     *
     * @param index - The index to get the child at
     * @return - The child at the given index, if any.
     */
    Container.prototype.getChildAt = function (index) {
        if (index < 0 || index >= this.children.length) {
            throw new Error("getChildAt: Index (" + index + ") does not exist.");
        }
        return this.children[index];
    };
    /**
     * Removes one or more children from the container.
     *
     * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove
     * @return {PIXI.DisplayObject} The first child that was removed.
     */
    Container.prototype.removeChild = function () {
        var arguments$1 = arguments;

        var children = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            children[_i] = arguments$1[_i];
        }
        // if there is only one argument we can bypass looping through the them
        if (children.length > 1) {
            // loop through the arguments property and remove all children
            for (var i = 0; i < children.length; i++) {
                this.removeChild(children[i]);
            }
        }
        else {
            var child = children[0];
            var index = this.children.indexOf(child);
            if (index === -1)
                { return null; }
            child.parent = null;
            // ensure child transform will be recalculated
            child.transform._parentID = -1;
            removeItems(this.children, index, 1);
            // ensure bounds will be recalculated
            this._boundsID++;
            // TODO - lets either do all callbacks or all events.. not both!
            this.onChildrenChange(index);
            child.emit('removed', this);
            this.emit('childRemoved', child, this, index);
        }
        return children[0];
    };
    /**
     * Removes a child from the specified index position.
     *
     * @param index - The index to get the child from
     * @return The child that was removed.
     */
    Container.prototype.removeChildAt = function (index) {
        var child = this.getChildAt(index);
        // ensure child transform will be recalculated..
        child.parent = null;
        child.transform._parentID = -1;
        removeItems(this.children, index, 1);
        // ensure bounds will be recalculated
        this._boundsID++;
        // TODO - lets either do all callbacks or all events.. not both!
        this.onChildrenChange(index);
        child.emit('removed', this);
        this.emit('childRemoved', child, this, index);
        return child;
    };
    /**
     * Removes all children from this container that are within the begin and end indexes.
     *
     * @param beginIndex - The beginning position.
     * @param endIndex - The ending position. Default value is size of the container.
     * @returns - List of removed children
     */
    Container.prototype.removeChildren = function (beginIndex, endIndex) {
        if (beginIndex === void 0) { beginIndex = 0; }
        if (endIndex === void 0) { endIndex = this.children.length; }
        var begin = beginIndex;
        var end = endIndex;
        var range = end - begin;
        var removed;
        if (range > 0 && range <= end) {
            removed = this.children.splice(begin, range);
            for (var i = 0; i < removed.length; ++i) {
                removed[i].parent = null;
                if (removed[i].transform) {
                    removed[i].transform._parentID = -1;
                }
            }
            this._boundsID++;
            this.onChildrenChange(beginIndex);
            for (var i = 0; i < removed.length; ++i) {
                removed[i].emit('removed', this);
                this.emit('childRemoved', removed[i], this, i);
            }
            return removed;
        }
        else if (range === 0 && this.children.length === 0) {
            return [];
        }
        throw new RangeError('removeChildren: numeric values are outside the acceptable range.');
    };
    /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */
    Container.prototype.sortChildren = function () {
        var sortRequired = false;
        for (var i = 0, j = this.children.length; i < j; ++i) {
            var child = this.children[i];
            child._lastSortedIndex = i;
            if (!sortRequired && child.zIndex !== 0) {
                sortRequired = true;
            }
        }
        if (sortRequired && this.children.length > 1) {
            this.children.sort(sortChildren);
        }
        this.sortDirty = false;
    };
    /** Updates the transform on all children of this container for rendering. */
    Container.prototype.updateTransform = function () {
        if (this.sortableChildren && this.sortDirty) {
            this.sortChildren();
        }
        this._boundsID++;
        this.transform.updateTransform(this.parent.transform);
        // TODO: check render flags, how to process stuff here
        this.worldAlpha = this.alpha * this.parent.worldAlpha;
        for (var i = 0, j = this.children.length; i < j; ++i) {
            var child = this.children[i];
            if (child.visible) {
                child.updateTransform();
            }
        }
    };
    /**
     * Recalculates the bounds of the container.
     *
     * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds
     * is limited to its mask's bounds or filterArea, if any is applied.
     */
    Container.prototype.calculateBounds = function () {
        this._bounds.clear();
        this._calculateBounds();
        for (var i = 0; i < this.children.length; i++) {
            var child = this.children[i];
            if (!child.visible || !child.renderable) {
                continue;
            }
            child.calculateBounds();
            // TODO: filter+mask, need to mask both somehow
            if (child._mask) {
                var maskObject = (child._mask.maskObject || child._mask);
                maskObject.calculateBounds();
                this._bounds.addBoundsMask(child._bounds, maskObject._bounds);
            }
            else if (child.filterArea) {
                this._bounds.addBoundsArea(child._bounds, child.filterArea);
            }
            else {
                this._bounds.addBounds(child._bounds);
            }
        }
        this._bounds.updateID = this._boundsID;
    };
    /**
     * Retrieves the local bounds of the displayObject as a rectangle object.
     *
     * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render()
     * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree.
     *
     * @param rect - Optional rectangle to store the result of the bounds calculation.
     * @param skipChildrenUpdate - Setting to `true` will stop re-calculation of children transforms,
     *  it was default behaviour of pixi 4.0-5.2 and caused many problems to users.
     * @return - The rectangular bounding area.
     */
    Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) {
        if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; }
        var result = _super.prototype.getLocalBounds.call(this, rect);
        if (!skipChildrenUpdate) {
            for (var i = 0, j = this.children.length; i < j; ++i) {
                var child = this.children[i];
                if (child.visible) {
                    child.updateTransform();
                }
            }
        }
        return result;
    };
    /**
     * Recalculates the content bounds of this object. This should be overriden to
     * calculate the bounds of this specific object (not including children).
     *
     * @protected
     */
    Container.prototype._calculateBounds = function () {
        // FILL IN//
    };
    /**
     * Renders this object and its children with culling.
     *
     * @protected
     * @param {PIXI.Renderer} renderer - The renderer
     */
    Container.prototype._renderWithCulling = function (renderer) {
        var sourceFrame = renderer.renderTexture.sourceFrame;
        // If the source frame is empty, stop rendering.
        if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) {
            return;
        }
        // Render the content of the container only if its bounds intersect with the source frame.
        // All filters are on the stack at this point, and the filter source frame is bound:
        // therefore, even if the bounds to non intersect the filter frame, the filter
        // is still applied and any filter padding that is in the frame is rendered correctly.
        var bounds;
        var transform;
        // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea
        // rectangle must completely contain the container and its children including filter padding.
        if (this.cullArea) {
            bounds = this.cullArea;
            transform = this.worldTransform;
        }
        // If the container doesn't override _render, we can skip the bounds calculation and intersection test.
        else if (this._render !== Container.prototype._render) {
            bounds = this.getBounds(true);
        }
        // Render the container if the source frame intersects the bounds.
        if (bounds && sourceFrame.intersects(bounds, transform)) {
            this._render(renderer);
        }
        // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering.
        else if (this.cullArea) {
            return;
        }
        // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect
        // the source frame, because the children might have filters with nonzero padding, which may intersect
        // with the source frame while the bounds do not: filter padding is not included in the bounds.
        // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered
        // if they are out of frame; otherwise, render the children normally.
        for (var i = 0, j = this.children.length; i < j; ++i) {
            var child = this.children[i];
            var childCullable = child.cullable;
            child.cullable = childCullable || !this.cullArea;
            child.render(renderer);
            child.cullable = childCullable;
        }
    };
    /**
     * Renders the object using the WebGL renderer.
     *
     * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the
     * container itself. This `render` method will invoke it, and also invoke the `render` methods of all
     * children afterward.
     *
     * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and
     * the bounds of this object are out of frame, this implementation will entirely skip rendering.
     * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally,
     * setting alpha to zero is not recommended for purely skipping rendering.
     *
     * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is
     * advised to employ **culling** to automatically skip rendering objects outside of the current screen.
     * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}.
     * Other culling methods might be better suited for a large number static objects; see
     * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and
     * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}.
     *
     * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or
     * filtering is applied on a container. This does, however, break batching and can affect performance when
     * masking and filtering is applied extensively throughout the scene graph.
     *
     * @param renderer - The renderer
     */
    Container.prototype.render = function (renderer) {
        // if the object is not visible or the alpha is 0 then no need to render this element
        if (!this.visible || this.worldAlpha <= 0 || !this.renderable) {
            return;
        }
        // do a quick check to see if this element has a mask or a filter.
        if (this._mask || (this.filters && this.filters.length)) {
            this.renderAdvanced(renderer);
        }
        else if (this.cullable) {
            this._renderWithCulling(renderer);
        }
        else {
            this._render(renderer);
            for (var i = 0, j = this.children.length; i < j; ++i) {
                this.children[i].render(renderer);
            }
        }
    };
    /**
     * Render the object using the WebGL renderer and advanced features.
     *
     * @param renderer - The renderer
     */
    Container.prototype.renderAdvanced = function (renderer) {
        var filters = this.filters;
        var mask = this._mask;
        // push filter first as we need to ensure the stencil buffer is correct for any masking
        if (filters) {
            if (!this._enabledFilters) {
                this._enabledFilters = [];
            }
            this._enabledFilters.length = 0;
            for (var i = 0; i < filters.length; i++) {
                if (filters[i].enabled) {
                    this._enabledFilters.push(filters[i]);
                }
            }
        }
        var flush = (filters && this._enabledFilters && this._enabledFilters.length)
            || (mask && (!mask.isMaskData
                || (mask.enabled && (mask.autoDetect || mask.type !== display_MASK_TYPES.NONE))));
        if (flush) {
            renderer.batch.flush();
        }
        if (filters && this._enabledFilters && this._enabledFilters.length) {
            renderer.filter.push(this, this._enabledFilters);
        }
        if (mask) {
            renderer.mask.push(this, this._mask);
        }
        if (this.cullable) {
            this._renderWithCulling(renderer);
        }
        else {
            this._render(renderer);
            for (var i = 0, j = this.children.length; i < j; ++i) {
                this.children[i].render(renderer);
            }
        }
        if (flush) {
            renderer.batch.flush();
        }
        if (mask) {
            renderer.mask.pop(this);
        }
        if (filters && this._enabledFilters && this._enabledFilters.length) {
            renderer.filter.pop();
        }
    };
    /**
     * To be overridden by the subclasses.
     *
     * @param renderer - The renderer
     */
    Container.prototype._render = function (_renderer) {
        // this is where content itself gets rendered...
    };
    /**
     * Removes all internal references and listeners as well as removes children from the display list.
     * Do not use a Container after calling `destroy`.
     *
     * @param options - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
     *  method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
     *  Should it destroy the texture of the child sprite
     * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
     *  Should it destroy the base texture of the child sprite
     */
    Container.prototype.destroy = function (options) {
        _super.prototype.destroy.call(this);
        this.sortDirty = false;
        var destroyChildren = typeof options === 'boolean' ? options : options && options.children;
        var oldChildren = this.removeChildren(0, this.children.length);
        if (destroyChildren) {
            for (var i = 0; i < oldChildren.length; ++i) {
                oldChildren[i].destroy(options);
            }
        }
    };
    Object.defineProperty(Container.prototype, "width", {
        /** The width of the Container, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            return this.scale.x * this.getLocalBounds().width;
        },
        set: function (value) {
            var width = this.getLocalBounds().width;
            if (width !== 0) {
                this.scale.x = value / width;
            }
            else {
                this.scale.x = 1;
            }
            this._width = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Container.prototype, "height", {
        /** The height of the Container, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            return this.scale.y * this.getLocalBounds().height;
        },
        set: function (value) {
            var height = this.getLocalBounds().height;
            if (height !== 0) {
                this.scale.y = value / height;
            }
            else {
                this.scale.y = 1;
            }
            this._height = value;
        },
        enumerable: false,
        configurable: true
    });
    return Container;
}(DisplayObject));
/**
 * Container default updateTransform, does update children of container.
 * Will crash if there's no parent element.
 *
 * @memberof PIXI.Container#
 * @method containerUpdateTransform
 */
Container.prototype.containerUpdateTransform = Container.prototype.updateTransform;


//# sourceMappingURL=display.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/accessibility/dist/esm/accessibility.js
/*!
 * @pixi/accessibility - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/accessibility is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */



/**
 * Default property values of accessible objects
 * used by {@link PIXI.AccessibilityManager}.
 *
 * @private
 * @function accessibleTarget
 * @memberof PIXI
 * @type {Object}
 * @example
 *      function MyObject() {}
 *
 *      Object.assign(
 *          MyObject.prototype,
 *          PIXI.accessibleTarget
 *      );
 */
var accessibleTarget = {
    /**
     *  Flag for if the object is accessible. If true AccessibilityManager will overlay a
     *   shadow div with attributes set
     *
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     */
    accessible: false,
    /**
     * Sets the title attribute of the shadow div
     * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
     *
     * @member {?string}
     * @memberof PIXI.DisplayObject#
     */
    accessibleTitle: null,
    /**
     * Sets the aria-label attribute of the shadow div
     *
     * @member {string}
     * @memberof PIXI.DisplayObject#
     */
    accessibleHint: null,
    /**
     * @member {number}
     * @memberof PIXI.DisplayObject#
     * @private
     * @todo Needs docs.
     */
    tabIndex: 0,
    /**
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     * @todo Needs docs.
     */
    _accessibleActive: false,
    /**
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     * @todo Needs docs.
     */
    _accessibleDiv: null,
    /**
     * Specify the type of div the accessible layer is. Screen readers treat the element differently
     * depending on this type. Defaults to button.
     *
     * @member {string}
     * @memberof PIXI.DisplayObject#
     * @default 'button'
     */
    accessibleType: 'button',
    /**
     * Specify the pointer-events the accessible div will use
     * Defaults to auto.
     *
     * @member {string}
     * @memberof PIXI.DisplayObject#
     * @default 'auto'
     */
    accessiblePointerEvents: 'auto',
    /**
     * Setting to false will prevent any children inside this container to
     * be accessible. Defaults to true.
     *
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     * @default true
     */
    accessibleChildren: true,
    renderId: -1,
};

// add some extra variables to the container..
DisplayObject.mixin(accessibleTarget);
var KEY_CODE_TAB = 9;
var DIV_TOUCH_SIZE = 100;
var DIV_TOUCH_POS_X = 0;
var DIV_TOUCH_POS_Y = 0;
var DIV_TOUCH_ZINDEX = 2;
var DIV_HOOK_SIZE = 1;
var DIV_HOOK_POS_X = -1000;
var DIV_HOOK_POS_Y = -1000;
var DIV_HOOK_ZINDEX = 2;
/**
 * The Accessibility manager recreates the ability to tab and have content read by screen readers.
 * This is very important as it can possibly help people with disabilities access PixiJS content.
 *
 * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
 * events as if the mouse was being used, minimizing the effort required to implement.
 *
 * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
 *
 * @class
 * @memberof PIXI
 */
var AccessibilityManager = /** @class */ (function () {
    /**
     * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
     */
    function AccessibilityManager(renderer) {
        /** Setting this to true will visually show the divs. */
        this.debug = false;
        /** Internal variable, see isActive getter. */
        this._isActive = false;
        /** Internal variable, see isMobileAccessibility getter. */
        this._isMobileAccessibility = false;
        /** A simple pool for storing divs. */
        this.pool = [];
        /** This is a tick used to check if an object is no longer being rendered. */
        this.renderId = 0;
        /** The array of currently active accessible items. */
        this.children = [];
        /** Count to throttle div updates on android devices. */
        this.androidUpdateCount = 0;
        /**  The frequency to update the div elements. */
        this.androidUpdateFrequency = 500; // 2fps
        this._hookDiv = null;
        if (settings_isMobile.tablet || settings_isMobile.phone) {
            this.createTouchHook();
        }
        // first we create a div that will sit over the PixiJS element. This is where the div overlays will go.
        var div = document.createElement('div');
        div.style.width = DIV_TOUCH_SIZE + "px";
        div.style.height = DIV_TOUCH_SIZE + "px";
        div.style.position = 'absolute';
        div.style.top = DIV_TOUCH_POS_X + "px";
        div.style.left = DIV_TOUCH_POS_Y + "px";
        div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
        this.div = div;
        this.renderer = renderer;
        /**
         * pre-bind the functions
         *
         * @type {Function}
         * @private
         */
        this._onKeyDown = this._onKeyDown.bind(this);
        /**
         * pre-bind the functions
         *
         * @type {Function}
         * @private
         */
        this._onMouseMove = this._onMouseMove.bind(this);
        // let listen for tab.. once pressed we can fire up and show the accessibility layer
        globalThis.addEventListener('keydown', this._onKeyDown, false);
    }
    Object.defineProperty(AccessibilityManager.prototype, "isActive", {
        /**
         * Value of `true` if accessibility is currently active and accessibility layers are showing.
         * @member {boolean}
         * @readonly
         */
        get: function () {
            return this._isActive;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", {
        /**
         * Value of `true` if accessibility is enabled for touch devices.
         * @member {boolean}
         * @readonly
         */
        get: function () {
            return this._isMobileAccessibility;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Creates the touch hooks.
     *
     * @private
     */
    AccessibilityManager.prototype.createTouchHook = function () {
        var _this = this;
        var hookDiv = document.createElement('button');
        hookDiv.style.width = DIV_HOOK_SIZE + "px";
        hookDiv.style.height = DIV_HOOK_SIZE + "px";
        hookDiv.style.position = 'absolute';
        hookDiv.style.top = DIV_HOOK_POS_X + "px";
        hookDiv.style.left = DIV_HOOK_POS_Y + "px";
        hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString();
        hookDiv.style.backgroundColor = '#FF0000';
        hookDiv.title = 'select to enable accessibility for this content';
        hookDiv.addEventListener('focus', function () {
            _this._isMobileAccessibility = true;
            _this.activate();
            _this.destroyTouchHook();
        });
        document.body.appendChild(hookDiv);
        this._hookDiv = hookDiv;
    };
    /**
     * Destroys the touch hooks.
     *
     * @private
     */
    AccessibilityManager.prototype.destroyTouchHook = function () {
        if (!this._hookDiv) {
            return;
        }
        document.body.removeChild(this._hookDiv);
        this._hookDiv = null;
    };
    /**
     * Activating will cause the Accessibility layer to be shown.
     * This is called when a user presses the tab key.
     *
     * @private
     */
    AccessibilityManager.prototype.activate = function () {
        var _a;
        if (this._isActive) {
            return;
        }
        this._isActive = true;
        globalThis.document.addEventListener('mousemove', this._onMouseMove, true);
        globalThis.removeEventListener('keydown', this._onKeyDown, false);
        this.renderer.on('postrender', this.update, this);
        (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div);
    };
    /**
     * Deactivating will cause the Accessibility layer to be hidden.
     * This is called when a user moves the mouse.
     *
     * @private
     */
    AccessibilityManager.prototype.deactivate = function () {
        var _a;
        if (!this._isActive || this._isMobileAccessibility) {
            return;
        }
        this._isActive = false;
        globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
        globalThis.addEventListener('keydown', this._onKeyDown, false);
        this.renderer.off('postrender', this.update);
        (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div);
    };
    /**
     * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
     *
     * @private
     * @param {PIXI.Container} displayObject - The DisplayObject to check.
     */
    AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) {
        if (!displayObject.visible || !displayObject.accessibleChildren) {
            return;
        }
        if (displayObject.accessible && displayObject.interactive) {
            if (!displayObject._accessibleActive) {
                this.addChild(displayObject);
            }
            displayObject.renderId = this.renderId;
        }
        var children = displayObject.children;
        if (children) {
            for (var i = 0; i < children.length; i++) {
                this.updateAccessibleObjects(children[i]);
            }
        }
    };
    /**
     * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
     *
     * @private
     */
    AccessibilityManager.prototype.update = function () {
        /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex,
        *  moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate,
        *  so I am just running update every half a second, seems to fix it.
        */
        var now = performance.now();
        if (settings_isMobile.android.device && now < this.androidUpdateCount) {
            return;
        }
        this.androidUpdateCount = now + this.androidUpdateFrequency;
        if (!this.renderer.renderingToScreen) {
            return;
        }
        // update children...
        if (this.renderer._lastObjectRendered) {
            this.updateAccessibleObjects(this.renderer._lastObjectRendered);
        }
        var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height;
        var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution;
        var sx = (width / viewWidth) * resolution;
        var sy = (height / viewHeight) * resolution;
        var div = this.div;
        div.style.left = left + "px";
        div.style.top = top + "px";
        div.style.width = viewWidth + "px";
        div.style.height = viewHeight + "px";
        for (var i = 0; i < this.children.length; i++) {
            var child = this.children[i];
            if (child.renderId !== this.renderId) {
                child._accessibleActive = false;
                removeItems(this.children, i, 1);
                this.div.removeChild(child._accessibleDiv);
                this.pool.push(child._accessibleDiv);
                child._accessibleDiv = null;
                i--;
            }
            else {
                // map div to display..
                div = child._accessibleDiv;
                var hitArea = child.hitArea;
                var wt = child.worldTransform;
                if (child.hitArea) {
                    div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px";
                    div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px";
                    div.style.width = hitArea.width * wt.a * sx + "px";
                    div.style.height = hitArea.height * wt.d * sy + "px";
                }
                else {
                    hitArea = child.getBounds();
                    this.capHitArea(hitArea);
                    div.style.left = hitArea.x * sx + "px";
                    div.style.top = hitArea.y * sy + "px";
                    div.style.width = hitArea.width * sx + "px";
                    div.style.height = hitArea.height * sy + "px";
                    // update button titles and hints if they exist and they've changed
                    if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) {
                        div.title = child.accessibleTitle;
                    }
                    if (div.getAttribute('aria-label') !== child.accessibleHint
                        && child.accessibleHint !== null) {
                        div.setAttribute('aria-label', child.accessibleHint);
                    }
                }
                // the title or index may have changed, if so lets update it!
                if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) {
                    div.title = child.accessibleTitle;
                    div.tabIndex = child.tabIndex;
                    if (this.debug)
                        { this.updateDebugHTML(div); }
                }
            }
        }
        // increment the render id..
        this.renderId++;
    };
    /**
     * private function that will visually add the information to the
     * accessability div
     *
     * @param {HTMLElement} div
     */
    AccessibilityManager.prototype.updateDebugHTML = function (div) {
        div.innerHTML = "type: " + div.type + "</br> title : " + div.title + "</br> tabIndex: " + div.tabIndex;
    };
    /**
     * Adjust the hit area based on the bounds of a display object
     *
     * @param {PIXI.Rectangle} hitArea - Bounds of the child
     */
    AccessibilityManager.prototype.capHitArea = function (hitArea) {
        if (hitArea.x < 0) {
            hitArea.width += hitArea.x;
            hitArea.x = 0;
        }
        if (hitArea.y < 0) {
            hitArea.height += hitArea.y;
            hitArea.y = 0;
        }
        var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height;
        if (hitArea.x + hitArea.width > viewWidth) {
            hitArea.width = viewWidth - hitArea.x;
        }
        if (hitArea.y + hitArea.height > viewHeight) {
            hitArea.height = viewHeight - hitArea.y;
        }
    };
    /**
     * Adds a DisplayObject to the accessibility manager
     *
     * @private
     * @param {PIXI.DisplayObject} displayObject - The child to make accessible.
     */
    AccessibilityManager.prototype.addChild = function (displayObject) {
        //    this.activate();
        var div = this.pool.pop();
        if (!div) {
            div = document.createElement('button');
            div.style.width = DIV_TOUCH_SIZE + "px";
            div.style.height = DIV_TOUCH_SIZE + "px";
            div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent';
            div.style.position = 'absolute';
            div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
            div.style.borderStyle = 'none';
            // ARIA attributes ensure that button title and hint updates are announced properly
            if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
                // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused.
                div.setAttribute('aria-live', 'off');
            }
            else {
                div.setAttribute('aria-live', 'polite');
            }
            if (navigator.userAgent.match(/rv:.*Gecko\//)) {
                // FireFox needs this to announce only the new button name
                div.setAttribute('aria-relevant', 'additions');
            }
            else {
                // required by IE, other browsers don't much care
                div.setAttribute('aria-relevant', 'text');
            }
            div.addEventListener('click', this._onClick.bind(this));
            div.addEventListener('focus', this._onFocus.bind(this));
            div.addEventListener('focusout', this._onFocusOut.bind(this));
        }
        // set pointer events
        div.style.pointerEvents = displayObject.accessiblePointerEvents;
        // set the type, this defaults to button!
        div.type = displayObject.accessibleType;
        if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) {
            div.title = displayObject.accessibleTitle;
        }
        else if (!displayObject.accessibleHint
            || displayObject.accessibleHint === null) {
            div.title = "displayObject " + displayObject.tabIndex;
        }
        if (displayObject.accessibleHint
            && displayObject.accessibleHint !== null) {
            div.setAttribute('aria-label', displayObject.accessibleHint);
        }
        if (this.debug)
            { this.updateDebugHTML(div); }
        displayObject._accessibleActive = true;
        displayObject._accessibleDiv = div;
        div.displayObject = displayObject;
        this.children.push(displayObject);
        this.div.appendChild(displayObject._accessibleDiv);
        displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
    };
    /**
     * Maps the div button press to pixi's InteractionManager (click)
     *
     * @private
     * @param {MouseEvent} e - The click event.
     */
    AccessibilityManager.prototype._onClick = function (e) {
        var interactionManager = this.renderer.plugins.interaction;
        var displayObject = e.target.displayObject;
        var eventData = interactionManager.eventData;
        interactionManager.dispatchEvent(displayObject, 'click', eventData);
        interactionManager.dispatchEvent(displayObject, 'pointertap', eventData);
        interactionManager.dispatchEvent(displayObject, 'tap', eventData);
    };
    /**
     * Maps the div focus events to pixi's InteractionManager (mouseover)
     *
     * @private
     * @param {FocusEvent} e - The focus event.
     */
    AccessibilityManager.prototype._onFocus = function (e) {
        if (!e.target.getAttribute('aria-live')) {
            e.target.setAttribute('aria-live', 'assertive');
        }
        var interactionManager = this.renderer.plugins.interaction;
        var displayObject = e.target.displayObject;
        var eventData = interactionManager.eventData;
        interactionManager.dispatchEvent(displayObject, 'mouseover', eventData);
    };
    /**
     * Maps the div focus events to pixi's InteractionManager (mouseout)
     *
     * @private
     * @param {FocusEvent} e - The focusout event.
     */
    AccessibilityManager.prototype._onFocusOut = function (e) {
        if (!e.target.getAttribute('aria-live')) {
            e.target.setAttribute('aria-live', 'polite');
        }
        var interactionManager = this.renderer.plugins.interaction;
        var displayObject = e.target.displayObject;
        var eventData = interactionManager.eventData;
        interactionManager.dispatchEvent(displayObject, 'mouseout', eventData);
    };
    /**
     * Is called when a key is pressed
     *
     * @private
     * @param {KeyboardEvent} e - The keydown event.
     */
    AccessibilityManager.prototype._onKeyDown = function (e) {
        if (e.keyCode !== KEY_CODE_TAB) {
            return;
        }
        this.activate();
    };
    /**
     * Is called when the mouse moves across the renderer element
     *
     * @private
     * @param {MouseEvent} e - The mouse event.
     */
    AccessibilityManager.prototype._onMouseMove = function (e) {
        if (e.movementX === 0 && e.movementY === 0) {
            return;
        }
        this.deactivate();
    };
    /**
     * Destroys the accessibility manager
     *
     */
    AccessibilityManager.prototype.destroy = function () {
        this.destroyTouchHook();
        this.div = null;
        globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
        globalThis.removeEventListener('keydown', this._onKeyDown);
        this.pool = null;
        this.children = null;
        this.renderer = null;
    };
    return AccessibilityManager;
}());


//# sourceMappingURL=accessibility.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/ticker/dist/esm/ticker.js
/*!
 * @pixi/ticker - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/ticker is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/**
 * Target frames per millisecond.
 *
 * @static
 * @name TARGET_FPMS
 * @memberof PIXI.settings
 * @type {number}
 * @default 0.06
 */
settings.TARGET_FPMS = 0.06;

/**
 * Represents the update priorities used by internal PIXI classes when registered with
 * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower
 * priority items, such as render, should go later.
 *
 * @static
 * @constant
 * @name UPDATE_PRIORITY
 * @memberof PIXI
 * @enum {number}
 * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.InteractionManager}
 * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite}
 * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.Ticker#add}.
 * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering.
 * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.BasePrepare} utility.
 */
var UPDATE_PRIORITY;
(function (UPDATE_PRIORITY) {
    UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION";
    UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH";
    UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL";
    UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW";
    UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY";
})(UPDATE_PRIORITY || (UPDATE_PRIORITY = {}));

/**
 * Internal class for handling the priority sorting of ticker handlers.
 *
 * @private
 * @class
 * @memberof PIXI
 */
var TickerListener = /** @class */ (function () {
    /**
     * Constructor
     * @private
     * @param fn - The listener function to be added for one update
     * @param context - The listener context
     * @param priority - The priority for emitting
     * @param once - If the handler should fire once
     */
    function TickerListener(fn, context, priority, once) {
        if (context === void 0) { context = null; }
        if (priority === void 0) { priority = 0; }
        if (once === void 0) { once = false; }
        /** The next item in chain. */
        this.next = null;
        /** The previous item in chain. */
        this.previous = null;
        /** `true` if this listener has been destroyed already. */
        this._destroyed = false;
        this.fn = fn;
        this.context = context;
        this.priority = priority;
        this.once = once;
    }
    /**
     * Simple compare function to figure out if a function and context match.
     * @private
     * @param fn - The listener function to be added for one update
     * @param context - The listener context
     * @return `true` if the listener match the arguments
     */
    TickerListener.prototype.match = function (fn, context) {
        if (context === void 0) { context = null; }
        return this.fn === fn && this.context === context;
    };
    /**
     * Emit by calling the current function.
     * @private
     * @param deltaTime - time since the last emit.
     * @return Next ticker
     */
    TickerListener.prototype.emit = function (deltaTime) {
        if (this.fn) {
            if (this.context) {
                this.fn.call(this.context, deltaTime);
            }
            else {
                this.fn(deltaTime);
            }
        }
        var redirect = this.next;
        if (this.once) {
            this.destroy(true);
        }
        // Soft-destroying should remove
        // the next reference
        if (this._destroyed) {
            this.next = null;
        }
        return redirect;
    };
    /**
     * Connect to the list.
     * @private
     * @param previous - Input node, previous listener
     */
    TickerListener.prototype.connect = function (previous) {
        this.previous = previous;
        if (previous.next) {
            previous.next.previous = this;
        }
        this.next = previous.next;
        previous.next = this;
    };
    /**
     * Destroy and don't use after this.
     * @private
     * @param hard - `true` to remove the `next` reference, this
     *        is considered a hard destroy. Soft destroy maintains the next reference.
     * @return The listener to redirect while emitting or removing.
     */
    TickerListener.prototype.destroy = function (hard) {
        if (hard === void 0) { hard = false; }
        this._destroyed = true;
        this.fn = null;
        this.context = null;
        // Disconnect, hook up next and previous
        if (this.previous) {
            this.previous.next = this.next;
        }
        if (this.next) {
            this.next.previous = this.previous;
        }
        // Redirect to the next item
        var redirect = this.next;
        // Remove references
        this.next = hard ? null : redirect;
        this.previous = null;
        return redirect;
    };
    return TickerListener;
}());

/**
 * A Ticker class that runs an update loop that other objects listen to.
 *
 * This class is composed around listeners meant for execution on the next requested animation frame.
 * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners.
 *
 * @class
 * @memberof PIXI
 */
var Ticker = /** @class */ (function () {
    function Ticker() {
        var _this = this;
        /**
         * Whether or not this ticker should invoke the method
         * {@link PIXI.Ticker#start} automatically
         * when a listener is added.
         */
        this.autoStart = false;
        /**
         * Scalar time value from last frame to this frame.
         * This value is capped by setting {@link PIXI.Ticker#minFPS}
         * and is scaled with {@link PIXI.Ticker#speed}.
         * **Note:** The cap may be exceeded by scaling.
         */
        this.deltaTime = 1;
        /**
         * The last time {@link PIXI.Ticker#update} was invoked.
         * This value is also reset internally outside of invoking
         * update, but only when a new animation frame is requested.
         * If the platform supports DOMHighResTimeStamp,
         * this value will have a precision of 1 µs.
         */
        this.lastTime = -1;
        /**
         * Factor of current {@link PIXI.Ticker#deltaTime}.
         * @example
         * // Scales ticker.deltaTime to what would be
         * // the equivalent of approximately 120 FPS
         * ticker.speed = 2;
         */
        this.speed = 1;
        /**
         * Whether or not this ticker has been started.
         * `true` if {@link PIXI.Ticker#start} has been called.
         * `false` if {@link PIXI.Ticker#stop} has been called.
         * While `false`, this value may change to `true` in the
         * event of {@link PIXI.Ticker#autoStart} being `true`
         * and a listener is added.
         */
        this.started = false;
        /** Internal current frame request ID */
        this._requestId = null;
        /**
         * Internal value managed by minFPS property setter and getter.
         * This is the maximum allowed milliseconds between updates.
         */
        this._maxElapsedMS = 100;
        /**
         * Internal value managed by minFPS property setter and getter.
         * This is the minimum allowed milliseconds between updates.
         */
        this._minElapsedMS = 0;
        /** If enabled, deleting is disabled.*/
        this._protected = false;
        /**
         * The last time keyframe was executed.
         * Maintains a relatively fixed interval with the previous value.
         */
        this._lastFrame = -1;
        this._head = new TickerListener(null, null, Infinity);
        this.deltaMS = 1 / settings.TARGET_FPMS;
        this.elapsedMS = 1 / settings.TARGET_FPMS;
        this._tick = function (time) {
            _this._requestId = null;
            if (_this.started) {
                // Invoke listeners now
                _this.update(time);
                // Listener side effects may have modified ticker state.
                if (_this.started && _this._requestId === null && _this._head.next) {
                    _this._requestId = requestAnimationFrame(_this._tick);
                }
            }
        };
    }
    /**
     * Conditionally requests a new animation frame.
     * If a frame has not already been requested, and if the internal
     * emitter has listeners, a new frame is requested.
     *
     * @private
     */
    Ticker.prototype._requestIfNeeded = function () {
        if (this._requestId === null && this._head.next) {
            // ensure callbacks get correct delta
            this.lastTime = performance.now();
            this._lastFrame = this.lastTime;
            this._requestId = requestAnimationFrame(this._tick);
        }
    };
    /**
     * Conditionally cancels a pending animation frame.
     * @private
     */
    Ticker.prototype._cancelIfNeeded = function () {
        if (this._requestId !== null) {
            cancelAnimationFrame(this._requestId);
            this._requestId = null;
        }
    };
    /**
     * Conditionally requests a new animation frame.
     * If the ticker has been started it checks if a frame has not already
     * been requested, and if the internal emitter has listeners. If these
     * conditions are met, a new frame is requested. If the ticker has not
     * been started, but autoStart is `true`, then the ticker starts now,
     * and continues with the previous conditions to request a new frame.
     *
     * @private
     */
    Ticker.prototype._startIfPossible = function () {
        if (this.started) {
            this._requestIfNeeded();
        }
        else if (this.autoStart) {
            this.start();
        }
    };
    /**
     * Register a handler for tick events. Calls continuously unless
     * it is removed or the ticker is stopped.
     *
     * @param fn - The listener function to be added for updates
     * @param context - The listener context
     * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting
     * @returns This instance of a ticker
     */
    Ticker.prototype.add = function (fn, context, priority) {
        if (priority === void 0) { priority = UPDATE_PRIORITY.NORMAL; }
        return this._addListener(new TickerListener(fn, context, priority));
    };
    /**
     * Add a handler for the tick event which is only execute once.
     *
     * @param fn - The listener function to be added for one update
     * @param context - The listener context
     * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting
     * @returns This instance of a ticker
     */
    Ticker.prototype.addOnce = function (fn, context, priority) {
        if (priority === void 0) { priority = UPDATE_PRIORITY.NORMAL; }
        return this._addListener(new TickerListener(fn, context, priority, true));
    };
    /**
     * Internally adds the event handler so that it can be sorted by priority.
     * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run
     * before the rendering.
     *
     * @private
     * @param listener - Current listener being added.
     * @returns This instance of a ticker
     */
    Ticker.prototype._addListener = function (listener) {
        // For attaching to head
        var current = this._head.next;
        var previous = this._head;
        // Add the first item
        if (!current) {
            listener.connect(previous);
        }
        else {
            // Go from highest to lowest priority
            while (current) {
                if (listener.priority > current.priority) {
                    listener.connect(previous);
                    break;
                }
                previous = current;
                current = current.next;
            }
            // Not yet connected
            if (!listener.previous) {
                listener.connect(previous);
            }
        }
        this._startIfPossible();
        return this;
    };
    /**
     * Removes any handlers matching the function and context parameters.
     * If no handlers are left after removing, then it cancels the animation frame.
     *
     * @param fn - The listener function to be removed
     * @param context - The listener context to be removed
     * @returns This instance of a ticker
     */
    Ticker.prototype.remove = function (fn, context) {
        var listener = this._head.next;
        while (listener) {
            // We found a match, lets remove it
            // no break to delete all possible matches
            // incase a listener was added 2+ times
            if (listener.match(fn, context)) {
                listener = listener.destroy();
            }
            else {
                listener = listener.next;
            }
        }
        if (!this._head.next) {
            this._cancelIfNeeded();
        }
        return this;
    };
    Object.defineProperty(Ticker.prototype, "count", {
        /**
         * The number of listeners on this ticker, calculated by walking through linked list
         *
         * @readonly
         * @member {number}
         */
        get: function () {
            if (!this._head) {
                return 0;
            }
            var count = 0;
            var current = this._head;
            while ((current = current.next)) {
                count++;
            }
            return count;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Starts the ticker. If the ticker has listeners
     * a new animation frame is requested at this point.
     */
    Ticker.prototype.start = function () {
        if (!this.started) {
            this.started = true;
            this._requestIfNeeded();
        }
    };
    /**
     * Stops the ticker. If the ticker has requested
     * an animation frame it is canceled at this point.
     */
    Ticker.prototype.stop = function () {
        if (this.started) {
            this.started = false;
            this._cancelIfNeeded();
        }
    };
    /**
     * Destroy the ticker and don't use after this. Calling
     * this method removes all references to internal events.
     */
    Ticker.prototype.destroy = function () {
        if (!this._protected) {
            this.stop();
            var listener = this._head.next;
            while (listener) {
                listener = listener.destroy(true);
            }
            this._head.destroy();
            this._head = null;
        }
    };
    /**
     * Triggers an update. An update entails setting the
     * current {@link PIXI.Ticker#elapsedMS},
     * the current {@link PIXI.Ticker#deltaTime},
     * invoking all listeners with current deltaTime,
     * and then finally setting {@link PIXI.Ticker#lastTime}
     * with the value of currentTime that was provided.
     * This method will be called automatically by animation
     * frame callbacks if the ticker instance has been started
     * and listeners are added.
     *
     * @param {number} [currentTime=performance.now()] - the current time of execution
     */
    Ticker.prototype.update = function (currentTime) {
        if (currentTime === void 0) { currentTime = performance.now(); }
        var elapsedMS;
        // If the difference in time is zero or negative, we ignore most of the work done here.
        // If there is no valid difference, then should be no reason to let anyone know about it.
        // A zero delta, is exactly that, nothing should update.
        //
        // The difference in time can be negative, and no this does not mean time traveling.
        // This can be the result of a race condition between when an animation frame is requested
        // on the current JavaScript engine event loop, and when the ticker's start method is invoked
        // (which invokes the internal _requestIfNeeded method). If a frame is requested before
        // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests,
        // can receive a time argument that can be less than the lastTime value that was set within
        // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems.
        //
        // This check covers this browser engine timing issue, as well as if consumers pass an invalid
        // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves.
        if (currentTime > this.lastTime) {
            // Save uncapped elapsedMS for measurement
            elapsedMS = this.elapsedMS = currentTime - this.lastTime;
            // cap the milliseconds elapsed used for deltaTime
            if (elapsedMS > this._maxElapsedMS) {
                elapsedMS = this._maxElapsedMS;
            }
            elapsedMS *= this.speed;
            // If not enough time has passed, exit the function.
            // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS
            // adjustment to ensure a relatively stable interval.
            if (this._minElapsedMS) {
                var delta = currentTime - this._lastFrame | 0;
                if (delta < this._minElapsedMS) {
                    return;
                }
                this._lastFrame = currentTime - (delta % this._minElapsedMS);
            }
            this.deltaMS = elapsedMS;
            this.deltaTime = this.deltaMS * settings.TARGET_FPMS;
            // Cache a local reference, in-case ticker is destroyed
            // during the emit, we can still check for head.next
            var head = this._head;
            // Invoke listeners added to internal emitter
            var listener = head.next;
            while (listener) {
                listener = listener.emit(this.deltaTime);
            }
            if (!head.next) {
                this._cancelIfNeeded();
            }
        }
        else {
            this.deltaTime = this.deltaMS = this.elapsedMS = 0;
        }
        this.lastTime = currentTime;
    };
    Object.defineProperty(Ticker.prototype, "FPS", {
        /**
         * The frames per second at which this ticker is running.
         * The default is approximately 60 in most modern browsers.
         * **Note:** This does not factor in the value of
         * {@link PIXI.Ticker#speed}, which is specific
         * to scaling {@link PIXI.Ticker#deltaTime}.
         *
         * @member {number}
         * @readonly
         */
        get: function () {
            return 1000 / this.elapsedMS;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Ticker.prototype, "minFPS", {
        /**
         * Manages the maximum amount of milliseconds allowed to
         * elapse between invoking {@link PIXI.Ticker#update}.
         * This value is used to cap {@link PIXI.Ticker#deltaTime},
         * but does not effect the measured value of {@link PIXI.Ticker#FPS}.
         * When setting this property it is clamped to a value between
         * `0` and `PIXI.settings.TARGET_FPMS * 1000`.
         *
         * @member {number}
         * @default 10
         */
        get: function () {
            return 1000 / this._maxElapsedMS;
        },
        set: function (fps) {
            // Minimum must be below the maxFPS
            var minFPS = Math.min(this.maxFPS, fps);
            // Must be at least 0, but below 1 / settings.TARGET_FPMS
            var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.TARGET_FPMS);
            this._maxElapsedMS = 1 / minFPMS;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Ticker.prototype, "maxFPS", {
        /**
         * Manages the minimum amount of milliseconds required to
         * elapse between invoking {@link PIXI.Ticker#update}.
         * This will effect the measured value of {@link PIXI.Ticker#FPS}.
         * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can.
         * Otherwise it will be at least `minFPS`
         *
         * @member {number}
         * @default 0
         */
        get: function () {
            if (this._minElapsedMS) {
                return Math.round(1000 / this._minElapsedMS);
            }
            return 0;
        },
        set: function (fps) {
            if (fps === 0) {
                this._minElapsedMS = 0;
            }
            else {
                // Max must be at least the minFPS
                var maxFPS = Math.max(this.minFPS, fps);
                this._minElapsedMS = 1 / (maxFPS / 1000);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Ticker, "shared", {
        /**
         * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by
         * {@link PIXI.VideoResource} to update animation frames / video textures.
         *
         * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true.
         *
         * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance.
         * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker.
         *
         * @example
         * let ticker = PIXI.Ticker.shared;
         * // Set this to prevent starting this ticker when listeners are added.
         * // By default this is true only for the PIXI.Ticker.shared instance.
         * ticker.autoStart = false;
         * // FYI, call this to ensure the ticker is stopped. It should be stopped
         * // if you have not attempted to render anything yet.
         * ticker.stop();
         * // Call this when you are ready for a running shared ticker.
         * ticker.start();
         *
         * @example
         * // You may use the shared ticker to render...
         * let renderer = PIXI.autoDetectRenderer();
         * let stage = new PIXI.Container();
         * document.body.appendChild(renderer.view);
         * ticker.add(function (time) {
         *     renderer.render(stage);
         * });
         *
         * @example
         * // Or you can just update it manually.
         * ticker.autoStart = false;
         * ticker.stop();
         * function animate(time) {
         *     ticker.update(time);
         *     renderer.render(stage);
         *     requestAnimationFrame(animate);
         * }
         * animate(performance.now());
         *
         * @member {PIXI.Ticker}
         * @static
         */
        get: function () {
            if (!Ticker._shared) {
                var shared = Ticker._shared = new Ticker();
                shared.autoStart = true;
                shared._protected = true;
            }
            return Ticker._shared;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Ticker, "system", {
        /**
         * The system ticker instance used by {@link PIXI.InteractionManager} and by
         * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused,
         * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused.
         *
         * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance.
         *
         * @member {PIXI.Ticker}
         * @static
         */
        get: function () {
            if (!Ticker._system) {
                var system = Ticker._system = new Ticker();
                system.autoStart = true;
                system._protected = true;
            }
            return Ticker._system;
        },
        enumerable: false,
        configurable: true
    });
    return Ticker;
}());

/**
 * Middleware for for Application Ticker.
 *
 * @example
 * import {TickerPlugin} from '@pixi/ticker';
 * import {Application} from '@pixi/app';
 * Application.registerPlugin(TickerPlugin);
 *
 * @class
 * @memberof PIXI
 */
var TickerPlugin = /** @class */ (function () {
    function TickerPlugin() {
    }
    /**
     * Initialize the plugin with scope of application instance
     *
     * @static
     * @private
     * @param {object} [options] - See application options
     */
    TickerPlugin.init = function (options) {
        var _this = this;
        // Set default
        options = Object.assign({
            autoStart: true,
            sharedTicker: false,
        }, options);
        // Create ticker setter
        Object.defineProperty(this, 'ticker', {
            set: function (ticker) {
                if (this._ticker) {
                    this._ticker.remove(this.render, this);
                }
                this._ticker = ticker;
                if (ticker) {
                    ticker.add(this.render, this, UPDATE_PRIORITY.LOW);
                }
            },
            get: function () {
                return this._ticker;
            },
        });
        /**
         * Convenience method for stopping the render.
         *
         * @method
         * @memberof PIXI.Application
         * @instance
         */
        this.stop = function () {
            _this._ticker.stop();
        };
        /**
         * Convenience method for starting the render.
         *
         * @method
         * @memberof PIXI.Application
         * @instance
         */
        this.start = function () {
            _this._ticker.start();
        };
        /**
         * Internal reference to the ticker.
         *
         * @type {PIXI.Ticker}
         * @name _ticker
         * @memberof PIXI.Application#
         * @private
         */
        this._ticker = null;
        /**
         * Ticker for doing render updates.
         *
         * @type {PIXI.Ticker}
         * @name ticker
         * @memberof PIXI.Application#
         * @default PIXI.Ticker.shared
         */
        this.ticker = options.sharedTicker ? Ticker.shared : new Ticker();
        // Start the rendering
        if (options.autoStart) {
            this.start();
        }
    };
    /**
     * Clean up the ticker, scoped to application.
     *
     * @static
     * @private
     */
    TickerPlugin.destroy = function () {
        if (this._ticker) {
            var oldTicker = this._ticker;
            this.ticker = null;
            oldTicker.destroy();
        }
    };
    return TickerPlugin;
}());


//# sourceMappingURL=ticker.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/interaction/dist/esm/interaction.js
/*!
 * @pixi/interaction - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/interaction is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */





/**
 * Holds all information related to an Interaction event
 *
 * @memberof PIXI
 */
var InteractionData = /** @class */ (function () {
    function InteractionData() {
        /**
         * Pressure applied by the pointing device during the event. A Touch's force property
         * will be represented by this value.
         *
         * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
         */
        this.pressure = 0;
        /**
         * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch.
         *
         * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle
         */
        this.rotationAngle = 0;
        /**
         * Twist of a stylus pointer.
         *
         * @see https://w3c.github.io/pointerevents/#pointerevent-interface
         */
        this.twist = 0;
        /**
         * Barrel pressure on a stylus pointer.
         *
         * @see https://w3c.github.io/pointerevents/#pointerevent-interface
         */
        this.tangentialPressure = 0;
        this.global = new Point();
        this.target = null;
        this.originalEvent = null;
        this.identifier = null;
        this.isPrimary = false;
        this.button = 0;
        this.buttons = 0;
        this.width = 0;
        this.height = 0;
        this.tiltX = 0;
        this.tiltY = 0;
        this.pointerType = null;
        this.pressure = 0;
        this.rotationAngle = 0;
        this.twist = 0;
        this.tangentialPressure = 0;
    }
    Object.defineProperty(InteractionData.prototype, "pointerId", {
        /**
         * The unique identifier of the pointer. It will be the same as `identifier`.
         *
         * @readonly
         * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
         */
        get: function () {
            return this.identifier;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * This will return the local coordinates of the specified displayObject for this InteractionData
     *
     * @param displayObject - The DisplayObject that you would like the local
     *  coords off
     * @param point - A Point object in which to store the value, optional (otherwise
     *  will create a new point)
     * @param globalPos - A Point object containing your custom global coords, optional
     *  (otherwise will use the current global coords)
     * @return - A point containing the coordinates of the InteractionData position relative
     *  to the DisplayObject
     */
    InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) {
        return displayObject.worldTransform.applyInverse(globalPos || this.global, point);
    };
    /**
     * Copies properties from normalized event data.
     *
     * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data
     */
    InteractionData.prototype.copyEvent = function (event) {
        // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite
        // it with "false" on later events when our shim for it on touch events might not be
        // accurate
        if ('isPrimary' in event && event.isPrimary) {
            this.isPrimary = true;
        }
        this.button = 'button' in event && event.button;
        // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard
        // event.which property instead, which conveys the same information.
        var buttons = 'buttons' in event && event.buttons;
        this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which;
        this.width = 'width' in event && event.width;
        this.height = 'height' in event && event.height;
        this.tiltX = 'tiltX' in event && event.tiltX;
        this.tiltY = 'tiltY' in event && event.tiltY;
        this.pointerType = 'pointerType' in event && event.pointerType;
        this.pressure = 'pressure' in event && event.pressure;
        this.rotationAngle = 'rotationAngle' in event && event.rotationAngle;
        this.twist = ('twist' in event && event.twist) || 0;
        this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0;
    };
    /** Resets the data for pooling. */
    InteractionData.prototype.reset = function () {
        // isPrimary is the only property that we really need to reset - everything else is
        // guaranteed to be overwritten
        this.isPrimary = false;
    };
    return InteractionData;
}());

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var interaction_extendStatics = function(d, b) {
    interaction_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return interaction_extendStatics(d, b);
};

function interaction_extends(d, b) {
    interaction_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * Event class that mimics native DOM events.
 *
 * @memberof PIXI
 */
var InteractionEvent = /** @class */ (function () {
    function InteractionEvent() {
        this.stopped = false;
        this.stopsPropagatingAt = null;
        this.stopPropagationHint = false;
        this.target = null;
        this.currentTarget = null;
        this.type = null;
        this.data = null;
    }
    /** Prevents event from reaching any objects other than the current object. */
    InteractionEvent.prototype.stopPropagation = function () {
        this.stopped = true;
        this.stopPropagationHint = true;
        this.stopsPropagatingAt = this.currentTarget;
    };
    /** Resets the event. */
    InteractionEvent.prototype.reset = function () {
        this.stopped = false;
        this.stopsPropagatingAt = null;
        this.stopPropagationHint = false;
        this.currentTarget = null;
        this.target = null;
    };
    return InteractionEvent;
}());

/**
 * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions
 *
 * @class
 * @private
 * @memberof PIXI
 */
var InteractionTrackingData = /** @class */ (function () {
    /**
     * @param {number} pointerId - Unique pointer id of the event
     * @private
     */
    function InteractionTrackingData(pointerId) {
        this._pointerId = pointerId;
        this._flags = InteractionTrackingData.FLAGS.NONE;
    }
    /**
     *
     * @private
     * @param {number} flag - The interaction flag to set
     * @param {boolean} yn - Should the flag be set or unset
     */
    InteractionTrackingData.prototype._doSet = function (flag, yn) {
        if (yn) {
            this._flags = this._flags | flag;
        }
        else {
            this._flags = this._flags & (~flag);
        }
    };
    Object.defineProperty(InteractionTrackingData.prototype, "pointerId", {
        /**
         * Unique pointer id of the event
         *
         * @readonly
         * @private
         * @member {number}
         */
        get: function () {
            return this._pointerId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InteractionTrackingData.prototype, "flags", {
        /**
         * State of the tracking data, expressed as bit flags
         *
         * @private
         * @member {number}
         */
        get: function () {
            return this._flags;
        },
        set: function (flags) {
            this._flags = flags;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InteractionTrackingData.prototype, "none", {
        /**
         * Is the tracked event inactive (not over or down)?
         *
         * @private
         * @member {number}
         */
        get: function () {
            return this._flags === InteractionTrackingData.FLAGS.NONE;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InteractionTrackingData.prototype, "over", {
        /**
         * Is the tracked event over the DisplayObject?
         *
         * @private
         * @member {boolean}
         */
        get: function () {
            return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0;
        },
        set: function (yn) {
            this._doSet(InteractionTrackingData.FLAGS.OVER, yn);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InteractionTrackingData.prototype, "rightDown", {
        /**
         * Did the right mouse button come down in the DisplayObject?
         *
         * @private
         * @member {boolean}
         */
        get: function () {
            return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0;
        },
        set: function (yn) {
            this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InteractionTrackingData.prototype, "leftDown", {
        /**
         * Did the left mouse button come down in the DisplayObject?
         *
         * @private
         * @member {boolean}
         */
        get: function () {
            return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0;
        },
        set: function (yn) {
            this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn);
        },
        enumerable: false,
        configurable: true
    });
    InteractionTrackingData.FLAGS = Object.freeze({
        NONE: 0,
        OVER: 1 << 0,
        LEFT_DOWN: 1 << 1,
        RIGHT_DOWN: 1 << 2,
    });
    return InteractionTrackingData;
}());

/**
 * Strategy how to search through stage tree for interactive objects
 *
 * @memberof PIXI
 */
var TreeSearch = /** @class */ (function () {
    function TreeSearch() {
        this._tempPoint = new Point();
    }
    /**
     * Recursive implementation for findHit
     *
     * @private
     * @param interactionEvent - event containing the point that
     *  is tested for collision
     * @param displayObject - the displayObject
     *  that will be hit test (recursively crawls its children)
     * @param func - the function that will be called on each interactive object. The
     *  interactionEvent, displayObject and hit will be passed to the function
     * @param hitTest - this indicates if the objects inside should be hit test against the point
     * @param interactive - Whether the displayObject is interactive
     * @return - Returns true if the displayObject hit the point
     */
    TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) {
        if (!displayObject || !displayObject.visible) {
            return false;
        }
        var point = interactionEvent.data.global;
        // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^
        //
        // This function will now loop through all objects and then only hit test the objects it HAS
        // to, not all of them. MUCH faster..
        // An object will be hit test if the following is true:
        //
        // 1: It is interactive.
        // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
        //
        // As another little optimization once an interactive object has been hit we can carry on
        // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
        // A final optimization is that an object is not hit test directly if a child has already been hit.
        interactive = displayObject.interactive || interactive;
        var hit = false;
        var interactiveParent = interactive;
        // Flag here can set to false if the event is outside the parents hitArea or mask
        var hitTestChildren = true;
        // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea
        // There is also no longer a need to hitTest children.
        if (displayObject.hitArea) {
            if (hitTest) {
                displayObject.worldTransform.applyInverse(point, this._tempPoint);
                if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
                    hitTest = false;
                    hitTestChildren = false;
                }
                else {
                    hit = true;
                }
            }
            interactiveParent = false;
        }
        // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask.
        // We still want to hitTestChildren, however, to ensure a mouseout can still be generated.
        // https://github.com/pixijs/pixi.js/issues/5135
        else if (displayObject._mask) {
            if (hitTest) {
                if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point))) {
                    hitTest = false;
                }
            }
        }
        // ** FREE TIP **! If an object is not interactive or has no buttons in it
        // (such as a game scene!) set interactiveChildren to false for that displayObject.
        // This will allow PixiJS to completely ignore and bypass checking the displayObjects children.
        if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) {
            var children = displayObject.children;
            for (var i = children.length - 1; i >= 0; i--) {
                var child = children[i];
                // time to get recursive.. if this function will return if something is hit..
                var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent);
                if (childHit) {
                    // its a good idea to check if a child has lost its parent.
                    // this means it has been removed whilst looping so its best
                    if (!child.parent) {
                        continue;
                    }
                    // we no longer need to hit test any more objects in this container as we we
                    // now know the parent has been hit
                    interactiveParent = false;
                    // If the child is interactive , that means that the object hit was actually
                    // interactive and not just the child of an interactive object.
                    // This means we no longer need to hit test anything else. We still need to run
                    // through all objects, but we don't need to perform any hit tests.
                    if (childHit) {
                        if (interactionEvent.target) {
                            hitTest = false;
                        }
                        hit = true;
                    }
                }
            }
        }
        // no point running this if the item is not interactive or does not have an interactive parent.
        if (interactive) {
            // if we are hit testing (as in we have no hit any objects yet)
            // We also don't need to worry about hit testing if once of the displayObjects children
            // has already been hit - but only if it was interactive, otherwise we need to keep
            // looking for an interactive child, just in case we hit one
            if (hitTest && !interactionEvent.target) {
                // already tested against hitArea if it is defined
                if (!displayObject.hitArea && displayObject.containsPoint) {
                    if (displayObject.containsPoint(point)) {
                        hit = true;
                    }
                }
            }
            if (displayObject.interactive) {
                if (hit && !interactionEvent.target) {
                    interactionEvent.target = displayObject;
                }
                if (func) {
                    func(interactionEvent, displayObject, !!hit);
                }
            }
        }
        return hit;
    };
    /**
     * This function is provides a neat way of crawling through the scene graph and running a
     * specified function on all interactive objects it finds. It will also take care of hit
     * testing the interactive objects and passes the hit across in the function.
     *
     * @private
     * @param interactionEvent - event containing the point that
     *  is tested for collision
     * @param displayObject - the displayObject
     *  that will be hit test (recursively crawls its children)
     * @param func - the function that will be called on each interactive object. The
     *  interactionEvent, displayObject and hit will be passed to the function
     * @param hitTest - this indicates if the objects inside should be hit test against the point
     * @return - Returns true if the displayObject hit the point
     */
    TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) {
        this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false);
    };
    return TreeSearch;
}());

/**
 * Interface for classes that represent a hit area.
 *
 * It is implemented by the following classes:
 * - {@link PIXI.Circle}
 * - {@link PIXI.Ellipse}
 * - {@link PIXI.Polygon}
 * - {@link PIXI.RoundedRectangle}
 *
 * @interface IHitArea
 * @memberof PIXI
 */
/**
 * Checks whether the x and y coordinates given are contained within this area
 *
 * @method
 * @name contains
 * @memberof PIXI.IHitArea#
 * @param {number} x - The X coordinate of the point to test
 * @param {number} y - The Y coordinate of the point to test
 * @return {boolean} Whether the x/y coordinates are within this area
 */
/**
 * Default property values of interactive objects
 * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties
 *
 * @private
 * @name interactiveTarget
 * @type {Object}
 * @memberof PIXI
 * @example
 *      function MyObject() {}
 *
 *      Object.assign(
 *          DisplayObject.prototype,
 *          PIXI.interactiveTarget
 *      );
 */
var interactiveTarget = {
    interactive: false,
    interactiveChildren: true,
    hitArea: null,
    /**
     * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive
     * Setting this changes the 'cursor' property to `'pointer'`.
     *
     * @example
     * const sprite = new PIXI.Sprite(texture);
     * sprite.interactive = true;
     * sprite.buttonMode = true;
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     */
    get buttonMode() {
        return this.cursor === 'pointer';
    },
    set buttonMode(value) {
        if (value) {
            this.cursor = 'pointer';
        }
        else if (this.cursor === 'pointer') {
            this.cursor = null;
        }
    },
    /**
     * This defines what cursor mode is used when the mouse cursor
     * is hovered over the displayObject.
     *
     * @example
     * const sprite = new PIXI.Sprite(texture);
     * sprite.interactive = true;
     * sprite.cursor = 'wait';
     * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor
     *
     * @member {string}
     * @memberof PIXI.DisplayObject#
     */
    cursor: null,
    /**
     * Internal set of all active pointers, by identifier
     *
     * @member {Map<number, InteractionTrackingData>}
     * @memberof PIXI.DisplayObject#
     * @private
     */
    get trackedPointers() {
        if (this._trackedPointers === undefined)
            { this._trackedPointers = {}; }
        return this._trackedPointers;
    },
    /**
     * Map of all tracked pointers, by identifier. Use trackedPointers to access.
     *
     * @private
     * @type {Map<number, InteractionTrackingData>}
     */
    _trackedPointers: undefined,
};

// Mix interactiveTarget into DisplayObject.prototype
DisplayObject.mixin(interactiveTarget);
var MOUSE_POINTER_ID = 1;
// helpers for hitTest() - only used inside hitTest()
var hitTestEvent = {
    target: null,
    data: {
        global: null,
    },
};
/**
 * The interaction manager deals with mouse, touch and pointer events.
 *
 * Any DisplayObject can be interactive if its `interactive` property is set to true.
 *
 * This manager also supports multitouch.
 *
 * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction`
 *
 * @memberof PIXI
 */
var InteractionManager = /** @class */ (function (_super) {
    interaction_extends(InteractionManager, _super);
    /**
     * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
     * @param options - The options for the manager.
     * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions.
     * @param {number} [options.interactionFrequency=10] - Maximum frequency (ms) at pointer over/out states will be checked.
     * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}.
     */
    function InteractionManager(renderer, options) {
        var _this = _super.call(this) || this;
        options = options || {};
        _this.renderer = renderer;
        _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true;
        _this.interactionFrequency = options.interactionFrequency || 10;
        _this.mouse = new InteractionData();
        _this.mouse.identifier = MOUSE_POINTER_ID;
        // setting the mouse to start off far off screen will mean that mouse over does
        //  not get called before we even move the mouse.
        _this.mouse.global.set(-999999);
        _this.activeInteractionData = {};
        _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse;
        _this.interactionDataPool = [];
        _this.eventData = new InteractionEvent();
        _this.interactionDOMElement = null;
        _this.moveWhenInside = false;
        _this.eventsAdded = false;
        _this.tickerAdded = false;
        _this.mouseOverRenderer = !('PointerEvent' in globalThis);
        _this.supportsTouchEvents = 'ontouchstart' in globalThis;
        _this.supportsPointerEvents = !!globalThis.PointerEvent;
        // this will make it so that you don't have to call bind all the time
        _this.onPointerUp = _this.onPointerUp.bind(_this);
        _this.processPointerUp = _this.processPointerUp.bind(_this);
        _this.onPointerCancel = _this.onPointerCancel.bind(_this);
        _this.processPointerCancel = _this.processPointerCancel.bind(_this);
        _this.onPointerDown = _this.onPointerDown.bind(_this);
        _this.processPointerDown = _this.processPointerDown.bind(_this);
        _this.onPointerMove = _this.onPointerMove.bind(_this);
        _this.processPointerMove = _this.processPointerMove.bind(_this);
        _this.onPointerOut = _this.onPointerOut.bind(_this);
        _this.processPointerOverOut = _this.processPointerOverOut.bind(_this);
        _this.onPointerOver = _this.onPointerOver.bind(_this);
        _this.cursorStyles = {
            default: 'inherit',
            pointer: 'pointer',
        };
        _this.currentCursorMode = null;
        _this.cursor = null;
        _this.resolution = 1;
        _this.delayedEvents = [];
        _this.search = new TreeSearch();
        _this._tempDisplayObject = new TemporaryDisplayObject();
        _this._eventListenerOptions = { capture: true, passive: false };
        /**
         * Fired when a pointer device button (usually a mouse left-button) is pressed on the display
         * object.
         *
         * @event PIXI.InteractionManager#mousedown
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
         * on the display object.
         *
         * @event PIXI.InteractionManager#rightdown
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is released over the display
         * object.
         *
         * @event PIXI.InteractionManager#mouseup
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is released
         * over the display object.
         *
         * @event PIXI.InteractionManager#rightup
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is pressed and released on
         * the display object.
         *
         * @event PIXI.InteractionManager#click
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
         * and released on the display object.
         *
         * @event PIXI.InteractionManager#rightclick
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is released outside the
         * display object that initially registered a
         * [mousedown]{@link PIXI.InteractionManager#event:mousedown}.
         *
         * @event PIXI.InteractionManager#mouseupoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is released
         * outside the display object that initially registered a
         * [rightdown]{@link PIXI.InteractionManager#event:rightdown}.
         *
         * @event PIXI.InteractionManager#rightupoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device (usually a mouse) is moved while over the display object
         *
         * @event PIXI.InteractionManager#mousemove
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device (usually a mouse) is moved onto the display object
         *
         * @event PIXI.InteractionManager#mouseover
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device (usually a mouse) is moved off the display object
         *
         * @event PIXI.InteractionManager#mouseout
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is pressed on the display object.
         *
         * @event PIXI.InteractionManager#pointerdown
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is released over the display object.
         * Not always fired when some buttons are held down while others are released. In those cases,
         * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and
         * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead.
         *
         * @event PIXI.InteractionManager#pointerup
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when the operating system cancels a pointer event
         *
         * @event PIXI.InteractionManager#pointercancel
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is pressed and released on the display object.
         *
         * @event PIXI.InteractionManager#pointertap
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is released outside the display object that initially
         * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}.
         *
         * @event PIXI.InteractionManager#pointerupoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device is moved while over the display object
         *
         * @event PIXI.InteractionManager#pointermove
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device is moved onto the display object
         *
         * @event PIXI.InteractionManager#pointerover
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device is moved off the display object
         *
         * @event PIXI.InteractionManager#pointerout
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is placed on the display object.
         *
         * @event PIXI.InteractionManager#touchstart
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is removed from the display object.
         *
         * @event PIXI.InteractionManager#touchend
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when the operating system cancels a touch
         *
         * @event PIXI.InteractionManager#touchcancel
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is placed and removed from the display object.
         *
         * @event PIXI.InteractionManager#tap
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is removed outside of the display object that initially
         * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}.
         *
         * @event PIXI.InteractionManager#touchendoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is moved along the display object.
         *
         * @event PIXI.InteractionManager#touchmove
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is pressed on the display.
         * object. DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#mousedown
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
         * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#rightdown
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is released over the display
         * object. DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#mouseup
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is released
         * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#rightup
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is pressed and released on
         * the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#click
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
         * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#rightclick
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button (usually a mouse left-button) is released outside the
         * display object that initially registered a
         * [mousedown]{@link PIXI.DisplayObject#event:mousedown}.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#mouseupoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device secondary button (usually a mouse right-button) is released
         * outside the display object that initially registered a
         * [rightdown]{@link PIXI.DisplayObject#event:rightdown}.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#rightupoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device (usually a mouse) is moved while over the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#mousemove
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device (usually a mouse) is moved onto the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#mouseover
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device (usually a mouse) is moved off the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#mouseout
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is pressed on the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointerdown
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is released over the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointerup
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when the operating system cancels a pointer event.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointercancel
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is pressed and released on the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointertap
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device button is released outside the display object that initially
         * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointerupoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device is moved while over the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointermove
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device is moved onto the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointerover
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a pointer device is moved off the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#pointerout
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is placed on the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#touchstart
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is removed from the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#touchend
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when the operating system cancels a touch.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#touchcancel
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is placed and removed from the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#tap
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is removed outside of the display object that initially
         * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#touchendoutside
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        /**
         * Fired when a touch point is moved along the display object.
         * DisplayObject's `interactive` property must be set to `true` to fire event.
         *
         * This comes from the @pixi/interaction package.
         *
         * @event PIXI.DisplayObject#touchmove
         * @param {PIXI.InteractionEvent} event - Interaction event
         */
        _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true;
        _this.setTargetElement(_this.renderer.view, _this.renderer.resolution);
        return _this;
    }
    Object.defineProperty(InteractionManager.prototype, "useSystemTicker", {
        /**
         * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}.
         *
         * @default true
         */
        get: function () {
            return this._useSystemTicker;
        },
        set: function (useSystemTicker) {
            this._useSystemTicker = useSystemTicker;
            if (useSystemTicker) {
                this.addTickerListener();
            }
            else {
                this.removeTickerListener();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", {
        /**
         * Last rendered object or temp object.
         *
         * @readonly
         * @protected
         */
        get: function () {
            return this.renderer._lastObjectRendered || this._tempDisplayObject;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Hit tests a point against the display tree, returning the first interactive object that is hit.
     *
     * @param globalPoint - A point to hit test with, in global space.
     * @param root - The root display object to start from. If omitted, defaults
     * to the last rendered root of the associated renderer.
     * @return - The hit display object, if any.
     */
    InteractionManager.prototype.hitTest = function (globalPoint, root) {
        // clear the target for our hit test
        hitTestEvent.target = null;
        // assign the global point
        hitTestEvent.data.global = globalPoint;
        // ensure safety of the root
        if (!root) {
            root = this.lastObjectRendered;
        }
        // run the hit test
        this.processInteractive(hitTestEvent, root, null, true);
        // return our found object - it'll be null if we didn't hit anything
        return hitTestEvent.target;
    };
    /**
     * Sets the DOM element which will receive mouse/touch events. This is useful for when you have
     * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate
     * another DOM element to receive those events.
     *
     * @param element - the DOM element which will receive mouse and touch events.
     * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas).
     */
    InteractionManager.prototype.setTargetElement = function (element, resolution) {
        if (resolution === void 0) { resolution = 1; }
        this.removeTickerListener();
        this.removeEvents();
        this.interactionDOMElement = element;
        this.resolution = resolution;
        this.addEvents();
        this.addTickerListener();
    };
    /** Adds the ticker listener. */
    InteractionManager.prototype.addTickerListener = function () {
        if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) {
            return;
        }
        Ticker.system.add(this.tickerUpdate, this, UPDATE_PRIORITY.INTERACTION);
        this.tickerAdded = true;
    };
    /** Removes the ticker listener. */
    InteractionManager.prototype.removeTickerListener = function () {
        if (!this.tickerAdded) {
            return;
        }
        Ticker.system.remove(this.tickerUpdate, this);
        this.tickerAdded = false;
    };
    /** Registers all the DOM events. */
    InteractionManager.prototype.addEvents = function () {
        if (this.eventsAdded || !this.interactionDOMElement) {
            return;
        }
        var style = this.interactionDOMElement.style;
        if (globalThis.navigator.msPointerEnabled) {
            style.msContentZooming = 'none';
            style.msTouchAction = 'none';
        }
        else if (this.supportsPointerEvents) {
            style.touchAction = 'none';
        }
        /*
         * These events are added first, so that if pointer events are normalized, they are fired
         * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd
         */
        if (this.supportsPointerEvents) {
            globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions);
            // pointerout is fired in addition to pointerup (for touch events) and pointercancel
            // we already handle those, so for the purposes of what we do in onPointerOut, we only
            // care about the pointerleave event
            this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions);
            globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions);
            globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions);
        }
        else {
            globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions);
            globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions);
        }
        // always look directly for touch events so that we can provide original data
        // In a future version we should change this to being just a fallback and rely solely on
        // PointerEvents whenever available
        if (this.supportsTouchEvents) {
            this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions);
            this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions);
        }
        this.eventsAdded = true;
    };
    /** Removes all the DOM events that were previously registered. */
    InteractionManager.prototype.removeEvents = function () {
        if (!this.eventsAdded || !this.interactionDOMElement) {
            return;
        }
        var style = this.interactionDOMElement.style;
        if (globalThis.navigator.msPointerEnabled) {
            style.msContentZooming = '';
            style.msTouchAction = '';
        }
        else if (this.supportsPointerEvents) {
            style.touchAction = '';
        }
        if (this.supportsPointerEvents) {
            globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions);
            globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions);
            globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions);
        }
        else {
            globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions);
            globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions);
        }
        if (this.supportsTouchEvents) {
            this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions);
            this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions);
        }
        this.interactionDOMElement = null;
        this.eventsAdded = false;
    };
    /**
     * Updates the state of interactive objects if at least {@link interactionFrequency}
     * milliseconds have passed since the last invocation.
     *
     * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}.
     *
     * @param deltaTime - time delta since the last call
     */
    InteractionManager.prototype.tickerUpdate = function (deltaTime) {
        this._deltaTime += deltaTime;
        if (this._deltaTime < this.interactionFrequency) {
            return;
        }
        this._deltaTime = 0;
        this.update();
    };
    /** Updates the state of interactive objects. */
    InteractionManager.prototype.update = function () {
        if (!this.interactionDOMElement) {
            return;
        }
        // if the user move the mouse this check has already been done using the mouse move!
        if (this._didMove) {
            this._didMove = false;
            return;
        }
        this.cursor = null;
        // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind,
        // but there was a scenario of a display object moving under a static mouse cursor.
        // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function
        for (var k in this.activeInteractionData) {
            // eslint-disable-next-line no-prototype-builtins
            if (this.activeInteractionData.hasOwnProperty(k)) {
                var interactionData = this.activeInteractionData[k];
                if (interactionData.originalEvent && interactionData.pointerType !== 'touch') {
                    var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData);
                    this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true);
                }
            }
        }
        this.setCursorMode(this.cursor);
    };
    /**
     * Sets the current cursor mode, handling any callbacks or CSS style changes.
     *
     * @param mode - cursor mode, a key from the cursorStyles dictionary
     */
    InteractionManager.prototype.setCursorMode = function (mode) {
        mode = mode || 'default';
        var applyStyles = true;
        // offscreen canvas does not support setting styles, but cursor modes can be functions,
        // in order to handle pixi rendered cursors, so we can't bail
        if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) {
            applyStyles = false;
        }
        // if the mode didn't actually change, bail early
        if (this.currentCursorMode === mode) {
            return;
        }
        this.currentCursorMode = mode;
        var style = this.cursorStyles[mode];
        // only do things if there is a cursor style for it
        if (style) {
            switch (typeof style) {
                case 'string':
                    // string styles are handled as cursor CSS
                    if (applyStyles) {
                        this.interactionDOMElement.style.cursor = style;
                    }
                    break;
                case 'function':
                    // functions are just called, and passed the cursor mode
                    style(mode);
                    break;
                case 'object':
                    // if it is an object, assume that it is a dictionary of CSS styles,
                    // apply it to the interactionDOMElement
                    if (applyStyles) {
                        Object.assign(this.interactionDOMElement.style, style);
                    }
                    break;
            }
        }
        else if (applyStyles && typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) {
            // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry
            // for the mode, then assume that the dev wants it to be CSS for the cursor.
            this.interactionDOMElement.style.cursor = mode;
        }
    };
    /**
     * Dispatches an event on the display object that was interacted with.
     *
     * @param displayObject - the display object in question
     * @param eventString - the name of the event (e.g, mousedown)
     * @param eventData - the event data object
     */
    InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) {
        // Even if the event was stopped, at least dispatch any remaining events
        // for the same display object.
        if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) {
            eventData.currentTarget = displayObject;
            eventData.type = eventString;
            displayObject.emit(eventString, eventData);
            if (displayObject[eventString]) {
                displayObject[eventString](eventData);
            }
        }
    };
    /**
     * Puts a event on a queue to be dispatched later. This is used to guarantee correct
     * ordering of over/out events.
     *
     * @param displayObject - the display object in question
     * @param eventString - the name of the event (e.g, mousedown)
     * @param eventData - the event data object
     */
    InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) {
        this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData });
    };
    /**
     * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The
     * resulting value is stored in the point. This takes into account the fact that the DOM
     * element could be scaled and positioned anywhere on the screen.
     *
     * @param point - the point that the result will be stored in
     * @param x - the x coord of the position to map
     * @param y - the y coord of the position to map
     */
    InteractionManager.prototype.mapPositionToPoint = function (point, x, y) {
        var rect;
        // IE 11 fix
        if (!this.interactionDOMElement.parentElement) {
            rect = {
                x: 0,
                y: 0,
                width: this.interactionDOMElement.width,
                height: this.interactionDOMElement.height,
                left: 0,
                top: 0
            };
        }
        else {
            rect = this.interactionDOMElement.getBoundingClientRect();
        }
        var resolutionMultiplier = 1.0 / this.resolution;
        point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier;
        point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier;
    };
    /**
     * This function is provides a neat way of crawling through the scene graph and running a
     * specified function on all interactive objects it finds. It will also take care of hit
     * testing the interactive objects and passes the hit across in the function.
     *
     * @protected
     * @param interactionEvent - event containing the point that
     *  is tested for collision
     * @param displayObject - the displayObject
     *  that will be hit test (recursively crawls its children)
     * @param func - the function that will be called on each interactive object. The
     *  interactionEvent, displayObject and hit will be passed to the function
     * @param hitTest - indicates whether we want to calculate hits
     *  or just iterate through all interactive objects
     */
    InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) {
        var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest);
        var delayedEvents = this.delayedEvents;
        if (!delayedEvents.length) {
            return hit;
        }
        // Reset the propagation hint, because we start deeper in the tree again.
        interactionEvent.stopPropagationHint = false;
        var delayedLen = delayedEvents.length;
        this.delayedEvents = [];
        for (var i = 0; i < delayedLen; i++) {
            var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData;
            // When we reach the object we wanted to stop propagating at,
            // set the propagation hint.
            if (eventData.stopsPropagatingAt === displayObject_1) {
                eventData.stopPropagationHint = true;
            }
            this.dispatchEvent(displayObject_1, eventString, eventData);
        }
        return hit;
    };
    /**
     * Is called when the pointer button is pressed down on the renderer element
     *
     * @param originalEvent - The DOM event of a pointer button being pressed down
     */
    InteractionManager.prototype.onPointerDown = function (originalEvent) {
        // if we support touch events, then only use those for touch events, not pointer events
        if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
            { return; }
        var events = this.normalizeToPointerData(originalEvent);
        /*
         * No need to prevent default on natural pointer events, as there are no side effects
         * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser,
         * so still need to be prevented.
         */
        // Guaranteed that there will be at least one event in events, and all events must have the same pointer type
        if (this.autoPreventDefault && events[0].isNormalized) {
            var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent);
            if (cancelable) {
                originalEvent.preventDefault();
            }
        }
        var eventLen = events.length;
        for (var i = 0; i < eventLen; i++) {
            var event = events[i];
            var interactionData = this.getInteractionDataForPointerId(event);
            var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
            interactionEvent.data.originalEvent = originalEvent;
            this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true);
            this.emit('pointerdown', interactionEvent);
            if (event.pointerType === 'touch') {
                this.emit('touchstart', interactionEvent);
            }
            // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event
            else if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
                var isRightButton = event.button === 2;
                this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData);
            }
        }
    };
    /**
     * Processes the result of the pointer down check and dispatches the event if need be
     *
     * @param interactionEvent - The interaction event wrapping the DOM event
     * @param displayObject - The display object that was tested
     * @param hit - the result of the hit test on the display object
     */
    InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) {
        var data = interactionEvent.data;
        var id = interactionEvent.data.identifier;
        if (hit) {
            if (!displayObject.trackedPointers[id]) {
                displayObject.trackedPointers[id] = new InteractionTrackingData(id);
            }
            this.dispatchEvent(displayObject, 'pointerdown', interactionEvent);
            if (data.pointerType === 'touch') {
                this.dispatchEvent(displayObject, 'touchstart', interactionEvent);
            }
            else if (data.pointerType === 'mouse' || data.pointerType === 'pen') {
                var isRightButton = data.button === 2;
                if (isRightButton) {
                    displayObject.trackedPointers[id].rightDown = true;
                }
                else {
                    displayObject.trackedPointers[id].leftDown = true;
                }
                this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent);
            }
        }
    };
    /**
     * Is called when the pointer button is released on the renderer element
     *
     * @param originalEvent - The DOM event of a pointer button being released
     * @param cancelled - true if the pointer is cancelled
     * @param func - Function passed to {@link processInteractive}
     */
    InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) {
        var events = this.normalizeToPointerData(originalEvent);
        var eventLen = events.length;
        // if the event wasn't targeting our canvas, then consider it to be pointerupoutside
        // in all cases (unless it was a pointercancel)
        var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : '';
        for (var i = 0; i < eventLen; i++) {
            var event = events[i];
            var interactionData = this.getInteractionDataForPointerId(event);
            var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
            interactionEvent.data.originalEvent = originalEvent;
            // perform hit testing for events targeting our canvas or cancel events
            this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend);
            this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent);
            if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
                var isRightButton = event.button === 2;
                this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent);
            }
            else if (event.pointerType === 'touch') {
                this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent);
                this.releaseInteractionDataForPointerId(event.pointerId);
            }
        }
    };
    /**
     * Is called when the pointer button is cancelled
     *
     * @param event - The DOM event of a pointer button being released
     */
    InteractionManager.prototype.onPointerCancel = function (event) {
        // if we support touch events, then only use those for touch events, not pointer events
        if (this.supportsTouchEvents && event.pointerType === 'touch')
            { return; }
        this.onPointerComplete(event, true, this.processPointerCancel);
    };
    /**
     * Processes the result of the pointer cancel check and dispatches the event if need be
     *
     * @param interactionEvent - The interaction event wrapping the DOM event
     * @param displayObject - The display object that was tested
     */
    InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) {
        var data = interactionEvent.data;
        var id = interactionEvent.data.identifier;
        if (displayObject.trackedPointers[id] !== undefined) {
            delete displayObject.trackedPointers[id];
            this.dispatchEvent(displayObject, 'pointercancel', interactionEvent);
            if (data.pointerType === 'touch') {
                this.dispatchEvent(displayObject, 'touchcancel', interactionEvent);
            }
        }
    };
    /**
     * Is called when the pointer button is released on the renderer element
     *
     * @param event - The DOM event of a pointer button being released
     */
    InteractionManager.prototype.onPointerUp = function (event) {
        // if we support touch events, then only use those for touch events, not pointer events
        if (this.supportsTouchEvents && event.pointerType === 'touch')
            { return; }
        this.onPointerComplete(event, false, this.processPointerUp);
    };
    /**
     * Processes the result of the pointer up check and dispatches the event if need be
     *
     * @param interactionEvent - The interaction event wrapping the DOM event
     * @param displayObject - The display object that was tested
     * @param hit - the result of the hit test on the display object
     */
    InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) {
        var data = interactionEvent.data;
        var id = interactionEvent.data.identifier;
        var trackingData = displayObject.trackedPointers[id];
        var isTouch = data.pointerType === 'touch';
        var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
        // need to track mouse down status in the mouse block so that we can emit
        // event in a later block
        var isMouseTap = false;
        // Mouse only
        if (isMouse) {
            var isRightButton = data.button === 2;
            var flags = InteractionTrackingData.FLAGS;
            var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN;
            var isDown = trackingData !== undefined && (trackingData.flags & test);
            if (hit) {
                this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent);
                if (isDown) {
                    this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent);
                    // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap
                    isMouseTap = true;
                }
            }
            else if (isDown) {
                this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent);
            }
            // update the down state of the tracking data
            if (trackingData) {
                if (isRightButton) {
                    trackingData.rightDown = false;
                }
                else {
                    trackingData.leftDown = false;
                }
            }
        }
        // Pointers and Touches, and Mouse
        if (hit) {
            this.dispatchEvent(displayObject, 'pointerup', interactionEvent);
            if (isTouch)
                { this.dispatchEvent(displayObject, 'touchend', interactionEvent); }
            if (trackingData) {
                // emit pointertap if not a mouse, or if the mouse block decided it was a tap
                if (!isMouse || isMouseTap) {
                    this.dispatchEvent(displayObject, 'pointertap', interactionEvent);
                }
                if (isTouch) {
                    this.dispatchEvent(displayObject, 'tap', interactionEvent);
                    // touches are no longer over (if they ever were) when we get the touchend
                    // so we should ensure that we don't keep pretending that they are
                    trackingData.over = false;
                }
            }
        }
        else if (trackingData) {
            this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent);
            if (isTouch)
                { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); }
        }
        // Only remove the tracking data if there is no over/down state still associated with it
        if (trackingData && trackingData.none) {
            delete displayObject.trackedPointers[id];
        }
    };
    /**
     * Is called when the pointer moves across the renderer element
     *
     * @param originalEvent - The DOM event of a pointer moving
     */
    InteractionManager.prototype.onPointerMove = function (originalEvent) {
        // if we support touch events, then only use those for touch events, not pointer events
        if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
            { return; }
        var events = this.normalizeToPointerData(originalEvent);
        if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') {
            this._didMove = true;
            this.cursor = null;
        }
        var eventLen = events.length;
        for (var i = 0; i < eventLen; i++) {
            var event = events[i];
            var interactionData = this.getInteractionDataForPointerId(event);
            var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
            interactionEvent.data.originalEvent = originalEvent;
            this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true);
            this.emit('pointermove', interactionEvent);
            if (event.pointerType === 'touch')
                { this.emit('touchmove', interactionEvent); }
            if (event.pointerType === 'mouse' || event.pointerType === 'pen')
                { this.emit('mousemove', interactionEvent); }
        }
        if (events[0].pointerType === 'mouse') {
            this.setCursorMode(this.cursor);
            // TODO BUG for parents interactive object (border order issue)
        }
    };
    /**
     * Processes the result of the pointer move check and dispatches the event if need be
     *
     * @param interactionEvent - The interaction event wrapping the DOM event
     * @param displayObject - The display object that was tested
     * @param hit - the result of the hit test on the display object
     */
    InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) {
        var data = interactionEvent.data;
        var isTouch = data.pointerType === 'touch';
        var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
        if (isMouse) {
            this.processPointerOverOut(interactionEvent, displayObject, hit);
        }
        if (!this.moveWhenInside || hit) {
            this.dispatchEvent(displayObject, 'pointermove', interactionEvent);
            if (isTouch)
                { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); }
            if (isMouse)
                { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); }
        }
    };
    /**
     * Is called when the pointer is moved out of the renderer element
     *
     * @private
     * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out
     */
    InteractionManager.prototype.onPointerOut = function (originalEvent) {
        // if we support touch events, then only use those for touch events, not pointer events
        if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
            { return; }
        var events = this.normalizeToPointerData(originalEvent);
        // Only mouse and pointer can call onPointerOut, so events will always be length 1
        var event = events[0];
        if (event.pointerType === 'mouse') {
            this.mouseOverRenderer = false;
            this.setCursorMode(null);
        }
        var interactionData = this.getInteractionDataForPointerId(event);
        var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
        interactionEvent.data.originalEvent = event;
        this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false);
        this.emit('pointerout', interactionEvent);
        if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
            this.emit('mouseout', interactionEvent);
        }
        else {
            // we can get touchleave events after touchend, so we want to make sure we don't
            // introduce memory leaks
            this.releaseInteractionDataForPointerId(interactionData.identifier);
        }
    };
    /**
     * Processes the result of the pointer over/out check and dispatches the event if need be.
     *
     * @param interactionEvent - The interaction event wrapping the DOM event
     * @param displayObject - The display object that was tested
     * @param hit - the result of the hit test on the display object
     */
    InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) {
        var data = interactionEvent.data;
        var id = interactionEvent.data.identifier;
        var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
        var trackingData = displayObject.trackedPointers[id];
        // if we just moused over the display object, then we need to track that state
        if (hit && !trackingData) {
            trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id);
        }
        if (trackingData === undefined)
            { return; }
        if (hit && this.mouseOverRenderer) {
            if (!trackingData.over) {
                trackingData.over = true;
                this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent);
                if (isMouse) {
                    this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent);
                }
            }
            // only change the cursor if it has not already been changed (by something deeper in the
            // display tree)
            if (isMouse && this.cursor === null) {
                this.cursor = displayObject.cursor;
            }
        }
        else if (trackingData.over) {
            trackingData.over = false;
            this.dispatchEvent(displayObject, 'pointerout', this.eventData);
            if (isMouse) {
                this.dispatchEvent(displayObject, 'mouseout', interactionEvent);
            }
            // if there is no mouse down information for the pointer, then it is safe to delete
            if (trackingData.none) {
                delete displayObject.trackedPointers[id];
            }
        }
    };
    /**
     * Is called when the pointer is moved into the renderer element.
     *
     * @param originalEvent - The DOM event of a pointer button being moved into the renderer view.
     */
    InteractionManager.prototype.onPointerOver = function (originalEvent) {
        var events = this.normalizeToPointerData(originalEvent);
        // Only mouse and pointer can call onPointerOver, so events will always be length 1
        var event = events[0];
        var interactionData = this.getInteractionDataForPointerId(event);
        var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
        interactionEvent.data.originalEvent = event;
        if (event.pointerType === 'mouse') {
            this.mouseOverRenderer = true;
        }
        this.emit('pointerover', interactionEvent);
        if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
            this.emit('mouseover', interactionEvent);
        }
    };
    /**
     * Get InteractionData for a given pointerId. Store that data as well.
     *
     * @param event - Normalized pointer event, output from normalizeToPointerData.
     * @return - Interaction data for the given pointer identifier.
     */
    InteractionManager.prototype.getInteractionDataForPointerId = function (event) {
        var pointerId = event.pointerId;
        var interactionData;
        if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') {
            interactionData = this.mouse;
        }
        else if (this.activeInteractionData[pointerId]) {
            interactionData = this.activeInteractionData[pointerId];
        }
        else {
            interactionData = this.interactionDataPool.pop() || new InteractionData();
            interactionData.identifier = pointerId;
            this.activeInteractionData[pointerId] = interactionData;
        }
        // copy properties from the event, so that we can make sure that touch/pointer specific
        // data is available
        interactionData.copyEvent(event);
        return interactionData;
    };
    /**
     * Return unused InteractionData to the pool, for a given pointerId
     *
     * @param pointerId - Identifier from a pointer event
     */
    InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) {
        var interactionData = this.activeInteractionData[pointerId];
        if (interactionData) {
            delete this.activeInteractionData[pointerId];
            interactionData.reset();
            this.interactionDataPool.push(interactionData);
        }
    };
    /**
     * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData
     *
     * @param interactionEvent - The event to be configured
     * @param pointerEvent - The DOM event that will be paired with the InteractionEvent
     * @param interactionData - The InteractionData that will be paired
     *        with the InteractionEvent
     * @return - the interaction event that was passed in
     */
    InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) {
        interactionEvent.data = interactionData;
        this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY);
        // Not really sure why this is happening, but it's how a previous version handled things
        if (pointerEvent.pointerType === 'touch') {
            pointerEvent.globalX = interactionData.global.x;
            pointerEvent.globalY = interactionData.global.y;
        }
        interactionData.originalEvent = pointerEvent;
        interactionEvent.reset();
        return interactionEvent;
    };
    /**
     * Ensures that the original event object contains all data that a regular pointer event would have
     *
     * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event
     * @return - An array containing a single normalized pointer event, in the case of a pointer
     *  or mouse event, or a multiple normalized pointer events if there are multiple changed touches
     */
    InteractionManager.prototype.normalizeToPointerData = function (event) {
        var normalizedEvents = [];
        if (this.supportsTouchEvents && event instanceof TouchEvent) {
            for (var i = 0, li = event.changedTouches.length; i < li; i++) {
                var touch = event.changedTouches[i];
                if (typeof touch.button === 'undefined')
                    { touch.button = event.touches.length ? 1 : 0; }
                if (typeof touch.buttons === 'undefined')
                    { touch.buttons = event.touches.length ? 1 : 0; }
                if (typeof touch.isPrimary === 'undefined') {
                    touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
                }
                if (typeof touch.width === 'undefined')
                    { touch.width = touch.radiusX || 1; }
                if (typeof touch.height === 'undefined')
                    { touch.height = touch.radiusY || 1; }
                if (typeof touch.tiltX === 'undefined')
                    { touch.tiltX = 0; }
                if (typeof touch.tiltY === 'undefined')
                    { touch.tiltY = 0; }
                if (typeof touch.pointerType === 'undefined')
                    { touch.pointerType = 'touch'; }
                if (typeof touch.pointerId === 'undefined')
                    { touch.pointerId = touch.identifier || 0; }
                if (typeof touch.pressure === 'undefined')
                    { touch.pressure = touch.force || 0.5; }
                if (typeof touch.twist === 'undefined')
                    { touch.twist = 0; }
                if (typeof touch.tangentialPressure === 'undefined')
                    { touch.tangentialPressure = 0; }
                // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven
                // support, and the fill ins are not quite the same
                // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top
                // left is not 0,0 on the page
                if (typeof touch.layerX === 'undefined')
                    { touch.layerX = touch.offsetX = touch.clientX; }
                if (typeof touch.layerY === 'undefined')
                    { touch.layerY = touch.offsetY = touch.clientY; }
                // mark the touch as normalized, just so that we know we did it
                touch.isNormalized = true;
                normalizedEvents.push(touch);
            }
        }
        // apparently PointerEvent subclasses MouseEvent, so yay
        else if (!globalThis.MouseEvent
            || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent)))) {
            var tempEvent = event;
            if (typeof tempEvent.isPrimary === 'undefined')
                { tempEvent.isPrimary = true; }
            if (typeof tempEvent.width === 'undefined')
                { tempEvent.width = 1; }
            if (typeof tempEvent.height === 'undefined')
                { tempEvent.height = 1; }
            if (typeof tempEvent.tiltX === 'undefined')
                { tempEvent.tiltX = 0; }
            if (typeof tempEvent.tiltY === 'undefined')
                { tempEvent.tiltY = 0; }
            if (typeof tempEvent.pointerType === 'undefined')
                { tempEvent.pointerType = 'mouse'; }
            if (typeof tempEvent.pointerId === 'undefined')
                { tempEvent.pointerId = MOUSE_POINTER_ID; }
            if (typeof tempEvent.pressure === 'undefined')
                { tempEvent.pressure = 0.5; }
            if (typeof tempEvent.twist === 'undefined')
                { tempEvent.twist = 0; }
            if (typeof tempEvent.tangentialPressure === 'undefined')
                { tempEvent.tangentialPressure = 0; }
            // mark the mouse event as normalized, just so that we know we did it
            tempEvent.isNormalized = true;
            normalizedEvents.push(tempEvent);
        }
        else {
            normalizedEvents.push(event);
        }
        return normalizedEvents;
    };
    /** Destroys the interaction manager. */
    InteractionManager.prototype.destroy = function () {
        this.removeEvents();
        this.removeTickerListener();
        this.removeAllListeners();
        this.renderer = null;
        this.mouse = null;
        this.eventData = null;
        this.interactionDOMElement = null;
        this.onPointerDown = null;
        this.processPointerDown = null;
        this.onPointerUp = null;
        this.processPointerUp = null;
        this.onPointerCancel = null;
        this.processPointerCancel = null;
        this.onPointerMove = null;
        this.processPointerMove = null;
        this.onPointerOut = null;
        this.processPointerOverOut = null;
        this.onPointerOver = null;
        this.search = null;
    };
    return InteractionManager;
}((eventemitter3_default())));


//# sourceMappingURL=interaction.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/runner/dist/esm/runner.js
/*!
 * @pixi/runner - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/runner is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * A Runner is a highly performant and simple alternative to signals. Best used in situations
 * where events are dispatched to many objects at high frequency (say every frame!)
 *
 *
 * like a signal..
 * ```
 * import { Runner } from '@pixi/runner';
 *
 * const myObject = {
 *     loaded: new Runner('loaded')
 * }
 *
 * const listener = {
 *     loaded: function(){
 *         // thin
 *     }
 * }
 *
 * myObject.loaded.add(listener);
 *
 * myObject.loaded.emit();
 * ```
 *
 * Or for handling calling the same function on many items
 * ```
 * import { Runner } from '@pixi/runner';
 *
 * const myGame = {
 *     update: new Runner('update')
 * }
 *
 * const gameObject = {
 *     update: function(time){
 *         // update my gamey state
 *     }
 * }
 *
 * myGame.update.add(gameObject);
 *
 * myGame.update.emit(time);
 * ```
 *
 * @memberof PIXI
 */
var Runner = /** @class */ (function () {
    /**
     * @param name - The function name that will be executed on the listeners added to this Runner.
     */
    function Runner(name) {
        this.items = [];
        this._name = name;
        this._aliasCount = 0;
    }
    /**
     * Dispatch/Broadcast Runner to all listeners added to the queue.
     *
     * @param {...any} params - (optional) parameters to pass to each listener
     */
    Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) {
        if (arguments.length > 8) {
            throw new Error('max arguments reached');
        }
        var _a = this, name = _a.name, items = _a.items;
        this._aliasCount++;
        for (var i = 0, len = items.length; i < len; i++) {
            items[i][name](a0, a1, a2, a3, a4, a5, a6, a7);
        }
        if (items === this.items) {
            this._aliasCount--;
        }
        return this;
    };
    Runner.prototype.ensureNonAliasedItems = function () {
        if (this._aliasCount > 0 && this.items.length > 1) {
            this._aliasCount = 0;
            this.items = this.items.slice(0);
        }
    };
    /**
     * Add a listener to the Runner
     *
     * Runners do not need to have scope or functions passed to them.
     * All that is required is to pass the listening object and ensure that it has contains a function that has the same name
     * as the name provided to the Runner when it was created.
     *
     * Eg A listener passed to this Runner will require a 'complete' function.
     *
     * ```
     * import { Runner } from '@pixi/runner';
     *
     * const complete = new Runner('complete');
     * ```
     *
     * The scope used will be the object itself.
     *
     * @param {any} item - The object that will be listening.
     */
    Runner.prototype.add = function (item) {
        if (item[this._name]) {
            this.ensureNonAliasedItems();
            this.remove(item);
            this.items.push(item);
        }
        return this;
    };
    /**
     * Remove a single listener from the dispatch queue.
     *
     * @param {any} item - The listener that you would like to remove.
     */
    Runner.prototype.remove = function (item) {
        var index = this.items.indexOf(item);
        if (index !== -1) {
            this.ensureNonAliasedItems();
            this.items.splice(index, 1);
        }
        return this;
    };
    /**
     * Check to see if the listener is already in the Runner
     *
     * @param {any} item - The listener that you would like to check.
     */
    Runner.prototype.contains = function (item) {
        return this.items.indexOf(item) !== -1;
    };
    /** Remove all listeners from the Runner */
    Runner.prototype.removeAll = function () {
        this.ensureNonAliasedItems();
        this.items.length = 0;
        return this;
    };
    /** Remove all references, don't use after this. */
    Runner.prototype.destroy = function () {
        this.removeAll();
        this.items = null;
        this._name = null;
    };
    Object.defineProperty(Runner.prototype, "empty", {
        /**
         * `true` if there are no this Runner contains no listeners
         *
         * @readonly
         */
        get: function () {
            return this.items.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Runner.prototype, "name", {
        /**
         * The name of the runner.
         *
         * @readonly
         */
        get: function () {
            return this._name;
        },
        enumerable: false,
        configurable: true
    });
    return Runner;
}());
Object.defineProperties(Runner.prototype, {
    /**
     * Alias for `emit`
     * @memberof PIXI.Runner#
     * @method dispatch
     * @see PIXI.Runner#emit
     */
    dispatch: { value: Runner.prototype.emit },
    /**
     * Alias for `emit`
     * @memberof PIXI.Runner#
     * @method run
     * @see PIXI.Runner#emit
     */
    run: { value: Runner.prototype.emit },
});


//# sourceMappingURL=runner.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/core/dist/esm/core.js
/*!
 * @pixi/core - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/core is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */







/**
 * The maximum support for using WebGL. If a device does not
 * support WebGL version, for instance WebGL 2, it will still
 * attempt to fallback support to WebGL 1. If you want to
 * explicitly remove feature support to target a more stable
 * baseline, prefer a lower environment.
 *
 * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium}
 * we disable webgl2 by default for all non-apple mobile devices.
 *
 * @static
 * @name PREFER_ENV
 * @memberof PIXI.settings
 * @type {number}
 * @default PIXI.ENV.WEBGL2
 */
settings.PREFER_ENV = settings_isMobile.any ? constants_ENV.WEBGL : constants_ENV.WEBGL2;
/**
 * If set to `true`, *only* Textures and BaseTexture objects stored
 * in the caches ({@link PIXI.utils.TextureCache TextureCache} and
 * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be
 * used when calling {@link PIXI.Texture.from Texture.from} or
 * {@link PIXI.BaseTexture.from BaseTexture.from}.
 * Otherwise, these `from` calls throw an exception. Using this property
 * can be useful if you want to enforce preloading all assets with
 * {@link PIXI.Loader Loader}.
 *
 * @static
 * @name STRICT_TEXTURE_CACHE
 * @memberof PIXI.settings
 * @type {boolean}
 * @default false
 */
settings.STRICT_TEXTURE_CACHE = false;

/**
 * Collection of installed resource types, class must extend {@link PIXI.Resource}.
 * @example
 * class CustomResource extends PIXI.Resource {
 *   // MUST have source, options constructor signature
 *   // for auto-detected resources to be created.
 *   constructor(source, options) {
 *     super();
 *   }
 *   upload(renderer, baseTexture, glTexture) {
 *     // upload with GL
 *     return true;
 *   }
 *   // used to auto-detect resource
 *   static test(source, extension) {
 *     return extension === 'xyz'|| source instanceof SomeClass;
 *   }
 * }
 * // Install the new resource type
 * PIXI.INSTALLED.push(CustomResource);
 *
 * @memberof PIXI
 * @type {Array<PIXI.IResourcePlugin>}
 * @static
 * @readonly
 */
var INSTALLED = [];
/**
 * Create a resource element from a single source element. This
 * auto-detects which type of resource to create. All resources that
 * are auto-detectable must have a static `test` method and a constructor
 * with the arguments `(source, options?)`. Currently, the supported
 * resources for auto-detection include:
 *  - {@link PIXI.ImageResource}
 *  - {@link PIXI.CanvasResource}
 *  - {@link PIXI.VideoResource}
 *  - {@link PIXI.SVGResource}
 *  - {@link PIXI.BufferResource}
 * @static
 * @memberof PIXI
 * @function autoDetectResource
 * @param {string|*} source - Resource source, this can be the URL to the resource,
 *        a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri
 *        or any other resource that can be auto-detected. If not resource is
 *        detected, it's assumed to be an ImageResource.
 * @param {object} [options] - Pass-through options to use for Resource
 * @param {number} [options.width] - Width of BufferResource or SVG rasterization
 * @param {number} [options.height] - Height of BufferResource or SVG rasterization
 * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading
 * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height
 * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object
 * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin
 * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately
 * @param {number} [options.updateFPS=0] - Video option to update how many times a second the
 *        texture should be updated from the video. Leave at 0 to update at every render
 * @return {PIXI.Resource} The created resource.
 */
function autoDetectResource(source, options) {
    if (!source) {
        return null;
    }
    var extension = '';
    if (typeof source === 'string') {
        // search for file extension: period, 3-4 chars, then ?, # or EOL
        var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source);
        if (result) {
            extension = result[1].toLowerCase();
        }
    }
    for (var i = INSTALLED.length - 1; i >= 0; --i) {
        var ResourcePlugin = INSTALLED[i];
        if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) {
            return new ResourcePlugin(source, options);
        }
    }
    throw new Error('Unrecognized source type to auto-detect Resource');
}

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var core_extendStatics = function(d, b) {
    core_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return core_extendStatics(d, b);
};

function core_extends(d, b) {
    core_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        var arguments$1 = arguments;

        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments$1[i];
            for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } }
        }
        return t;
    };
    return __assign.apply(this, arguments);
};

function __rest(s, e) {
    var t = {};
    for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        { t[p] = s[p]; } }
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0)
            { t[p[i]] = s[p[i]]; } } }
    return t;
}

/**
 * Base resource class for textures that manages validation and uploading, depending on its type.
 *
 * Uploading of a base texture to the GPU is required.
 *
 * @memberof PIXI
 */
var Resource = /** @class */ (function () {
    /**
     * @param width - Width of the resource
     * @param height - Height of the resource
     */
    function Resource(width, height) {
        if (width === void 0) { width = 0; }
        if (height === void 0) { height = 0; }
        this._width = width;
        this._height = height;
        this.destroyed = false;
        this.internal = false;
        this.onResize = new Runner('setRealSize');
        this.onUpdate = new Runner('update');
        this.onError = new Runner('onError');
    }
    /**
     * Bind to a parent BaseTexture
     *
     * @param baseTexture - Parent texture
     */
    Resource.prototype.bind = function (baseTexture) {
        this.onResize.add(baseTexture);
        this.onUpdate.add(baseTexture);
        this.onError.add(baseTexture);
        // Call a resize immediate if we already
        // have the width and height of the resource
        if (this._width || this._height) {
            this.onResize.emit(this._width, this._height);
        }
    };
    /**
     * Unbind to a parent BaseTexture
     *
     * @param baseTexture - Parent texture
     */
    Resource.prototype.unbind = function (baseTexture) {
        this.onResize.remove(baseTexture);
        this.onUpdate.remove(baseTexture);
        this.onError.remove(baseTexture);
    };
    /**
     * Trigger a resize event
     *
     * @param width - X dimension
     * @param height - Y dimension
     */
    Resource.prototype.resize = function (width, height) {
        if (width !== this._width || height !== this._height) {
            this._width = width;
            this._height = height;
            this.onResize.emit(width, height);
        }
    };
    Object.defineProperty(Resource.prototype, "valid", {
        /**
         * Has been validated
         *
         * @readonly
         */
        get: function () {
            return !!this._width && !!this._height;
        },
        enumerable: false,
        configurable: true
    });
    /** Has been updated trigger event. */
    Resource.prototype.update = function () {
        if (!this.destroyed) {
            this.onUpdate.emit();
        }
    };
    /**
     * This can be overridden to start preloading a resource
     * or do any other prepare step.
     *
     * @protected
     * @return Handle the validate event
     */
    Resource.prototype.load = function () {
        return Promise.resolve(this);
    };
    Object.defineProperty(Resource.prototype, "width", {
        /**
         * The width of the resource.
         *
         * @readonly
         */
        get: function () {
            return this._width;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Resource.prototype, "height", {
        /**
         * The height of the resource.
         *
         * @readonly
         */
        get: function () {
            return this._height;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Set the style, optional to override
     *
     * @param renderer - yeah, renderer!
     * @param baseTexture - the texture
     * @param glTexture - texture instance for this webgl context
     * @returns - `true` is success
     */
    Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) {
        return false;
    };
    /** Clean up anything, this happens when destroying is ready. */
    Resource.prototype.dispose = function () {
        // override
    };
    /**
     * Call when destroying resource, unbind any BaseTexture object
     * before calling this method, as reference counts are maintained
     * internally.
     */
    Resource.prototype.destroy = function () {
        if (!this.destroyed) {
            this.destroyed = true;
            this.dispose();
            this.onError.removeAll();
            this.onError = null;
            this.onResize.removeAll();
            this.onResize = null;
            this.onUpdate.removeAll();
            this.onUpdate = null;
        }
    };
    /**
     * Abstract, used to auto-detect resource type.
     *
     * @param {*} source - The source object
     * @param {string} extension - The extension of source, if set
     */
    Resource.test = function (_source, _extension) {
        return false;
    };
    return Resource;
}());

/**
 * @interface SharedArrayBuffer
 */
/**
 * Buffer resource with data of typed array.
 *
 * @memberof PIXI
 */
var BufferResource = /** @class */ (function (_super) {
    core_extends(BufferResource, _super);
    /**
     * @param source - Source buffer
     * @param options - Options
     * @param {number} options.width - Width of the texture
     * @param {number} options.height - Height of the texture
     */
    function BufferResource(source, options) {
        var _this = this;
        var _a = options || {}, width = _a.width, height = _a.height;
        if (!width || !height) {
            throw new Error('BufferResource width or height invalid');
        }
        _this = _super.call(this, width, height) || this;
        _this.data = source;
        return _this;
    }
    /**
     * Upload the texture to the GPU.
     *
     * @param renderer - Upload to the renderer
     * @param baseTexture - Reference to parent texture
     * @param glTexture - glTexture
     * @returns - true is success
     */
    BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) {
        var gl = renderer.gl;
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants_ALPHA_MODES.UNPACK);
        var width = baseTexture.realWidth;
        var height = baseTexture.realHeight;
        if (glTexture.width === width && glTexture.height === height) {
            gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data);
        }
        else {
            glTexture.width = width;
            glTexture.height = height;
            gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data);
        }
        return true;
    };
    /** Destroy and don't use after this. */
    BufferResource.prototype.dispose = function () {
        this.data = null;
    };
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @return {boolean} `true` if <canvas>
     */
    BufferResource.test = function (source) {
        return source instanceof Float32Array
            || source instanceof Uint8Array
            || source instanceof Uint32Array;
    };
    return BufferResource;
}(Resource));

var defaultBufferOptions = {
    scaleMode: constants_SCALE_MODES.NEAREST,
    format: constants_FORMATS.RGBA,
    alphaMode: constants_ALPHA_MODES.NPM,
};
/**
 * A Texture stores the information that represents an image.
 * All textures have a base texture, which contains information about the source.
 * Therefore you can have many textures all using a single BaseTexture
 *
 * @memberof PIXI
 * @typeParam R - The BaseTexture's Resource type.
 * @typeParam RO - The options for constructing resource.
 */
var BaseTexture = /** @class */ (function (_super) {
    core_extends(BaseTexture, _super);
    /**
     * @param {PIXI.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] -
     *        The current resource to use, for things that aren't Resource objects, will be converted
     *        into a Resource.
     * @param options - Collection of options
     * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture
     * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture
     * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures
     * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest
     * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type
     * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type
     * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target
     * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha
     * @param {number} [options.width=0] - Width of the texture
     * @param {number} [options.height=0] - Height of the texture
     * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture
     * @param {object} [options.resourceOptions] - Optional resource options,
     *        see {@link PIXI.autoDetectResource autoDetectResource}
     */
    function BaseTexture(resource, options) {
        if (resource === void 0) { resource = null; }
        if (options === void 0) { options = null; }
        var _this = _super.call(this) || this;
        options = options || {};
        var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions;
        // Convert the resource to a Resource object
        if (resource && !(resource instanceof Resource)) {
            resource = autoDetectResource(resource, resourceOptions);
            resource.internal = true;
        }
        _this.resolution = resolution || settings.RESOLUTION;
        _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution;
        _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution;
        _this._mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES;
        _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.ANISOTROPIC_LEVEL;
        _this._wrapMode = wrapMode || settings.WRAP_MODE;
        _this._scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE;
        _this.format = format || constants_FORMATS.RGBA;
        _this.type = type || constants_TYPES.UNSIGNED_BYTE;
        _this.target = target || constants_TARGETS.TEXTURE_2D;
        _this.alphaMode = alphaMode !== undefined ? alphaMode : constants_ALPHA_MODES.UNPACK;
        _this.uid = uid();
        _this.touched = 0;
        _this.isPowerOfTwo = false;
        _this._refreshPOT();
        _this._glTextures = {};
        _this.dirtyId = 0;
        _this.dirtyStyleId = 0;
        _this.cacheId = null;
        _this.valid = width > 0 && height > 0;
        _this.textureCacheIds = [];
        _this.destroyed = false;
        _this.resource = null;
        _this._batchEnabled = 0;
        _this._batchLocation = 0;
        _this.parentTextureArray = null;
        /**
         * Fired when a not-immediately-available source finishes loading.
         *
         * @protected
         * @event PIXI.BaseTexture#loaded
         * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
         */
        /**
         * Fired when a not-immediately-available source fails to load.
         *
         * @protected
         * @event PIXI.BaseTexture#error
         * @param {PIXI.BaseTexture} baseTexture - Resource errored.
         * @param {ErrorEvent} event - Load error event.
         */
        /**
         * Fired when BaseTexture is updated.
         *
         * @protected
         * @event PIXI.BaseTexture#loaded
         * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
         */
        /**
         * Fired when BaseTexture is updated.
         *
         * @protected
         * @event PIXI.BaseTexture#update
         * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated.
         */
        /**
         * Fired when BaseTexture is destroyed.
         *
         * @protected
         * @event PIXI.BaseTexture#dispose
         * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed.
         */
        // Set the resource
        _this.setResource(resource);
        return _this;
    }
    Object.defineProperty(BaseTexture.prototype, "realWidth", {
        /**
         * Pixel width of the source of this texture
         *
         * @readonly
         */
        get: function () {
            return Math.round(this.width * this.resolution);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BaseTexture.prototype, "realHeight", {
        /**
         * Pixel height of the source of this texture
         *
         * @readonly
         */
        get: function () {
            return Math.round(this.height * this.resolution);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BaseTexture.prototype, "mipmap", {
        /**
         * Mipmap mode of the texture, affects downscaled images
         *
         * @default PIXI.settings.MIPMAP_TEXTURES
         */
        get: function () {
            return this._mipmap;
        },
        set: function (value) {
            if (this._mipmap !== value) {
                this._mipmap = value;
                this.dirtyStyleId++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BaseTexture.prototype, "scaleMode", {
        /**
         * The scale mode to apply when scaling this texture
         *
         * @default PIXI.settings.SCALE_MODE
         */
        get: function () {
            return this._scaleMode;
        },
        set: function (value) {
            if (this._scaleMode !== value) {
                this._scaleMode = value;
                this.dirtyStyleId++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BaseTexture.prototype, "wrapMode", {
        /**
         * How the texture wraps
         *
         * @default PIXI.settings.WRAP_MODE
         */
        get: function () {
            return this._wrapMode;
        },
        set: function (value) {
            if (this._wrapMode !== value) {
                this._wrapMode = value;
                this.dirtyStyleId++;
            }
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Changes style options of BaseTexture
     *
     * @param scaleMode - Pixi scalemode
     * @param mipmap - enable mipmaps
     * @returns - this
     */
    BaseTexture.prototype.setStyle = function (scaleMode, mipmap) {
        var dirty;
        if (scaleMode !== undefined && scaleMode !== this.scaleMode) {
            this.scaleMode = scaleMode;
            dirty = true;
        }
        if (mipmap !== undefined && mipmap !== this.mipmap) {
            this.mipmap = mipmap;
            dirty = true;
        }
        if (dirty) {
            this.dirtyStyleId++;
        }
        return this;
    };
    /**
     * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero.
     *
     * @param desiredWidth - Desired visual width
     * @param desiredHeight - Desired visual height
     * @param resolution - Optionally set resolution
     * @returns - this
     */
    BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) {
        resolution = resolution || this.resolution;
        return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution);
    };
    /**
     * Sets real size of baseTexture, preserves current resolution.
     *
     * @param realWidth - Full rendered width
     * @param realHeight - Full rendered height
     * @param resolution - Optionally set resolution
     * @returns - this
     */
    BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) {
        this.resolution = resolution || this.resolution;
        this.width = Math.round(realWidth) / this.resolution;
        this.height = Math.round(realHeight) / this.resolution;
        this._refreshPOT();
        this.update();
        return this;
    };
    /**
     * Refresh check for isPowerOfTwo texture based on size
     *
     * @private
     */
    BaseTexture.prototype._refreshPOT = function () {
        this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight);
    };
    /**
     * Changes resolution
     *
     * @param resolution - res
     * @returns - this
     */
    BaseTexture.prototype.setResolution = function (resolution) {
        var oldResolution = this.resolution;
        if (oldResolution === resolution) {
            return this;
        }
        this.resolution = resolution;
        if (this.valid) {
            this.width = Math.round(this.width * oldResolution) / resolution;
            this.height = Math.round(this.height * oldResolution) / resolution;
            this.emit('update', this);
        }
        this._refreshPOT();
        return this;
    };
    /**
     * Sets the resource if it wasn't set. Throws error if resource already present
     *
     * @param resource - that is managing this BaseTexture
     * @returns - this
     */
    BaseTexture.prototype.setResource = function (resource) {
        if (this.resource === resource) {
            return this;
        }
        if (this.resource) {
            throw new Error('Resource can be set only once');
        }
        resource.bind(this);
        this.resource = resource;
        return this;
    };
    /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */
    BaseTexture.prototype.update = function () {
        if (!this.valid) {
            if (this.width > 0 && this.height > 0) {
                this.valid = true;
                this.emit('loaded', this);
                this.emit('update', this);
            }
        }
        else {
            this.dirtyId++;
            this.dirtyStyleId++;
            this.emit('update', this);
        }
    };
    /**
     * Handle errors with resources.
     *
     * @private
     * @param event - Error event emitted.
     */
    BaseTexture.prototype.onError = function (event) {
        this.emit('error', this, event);
    };
    /**
     * Destroys this base texture.
     * The method stops if resource doesn't want this texture to be destroyed.
     * Removes texture from all caches.
     */
    BaseTexture.prototype.destroy = function () {
        // remove and destroy the resource
        if (this.resource) {
            this.resource.unbind(this);
            // only destroy resourced created internally
            if (this.resource.internal) {
                this.resource.destroy();
            }
            this.resource = null;
        }
        if (this.cacheId) {
            delete BaseTextureCache[this.cacheId];
            delete TextureCache[this.cacheId];
            this.cacheId = null;
        }
        // finally let the WebGL renderer know..
        this.dispose();
        BaseTexture.removeFromCache(this);
        this.textureCacheIds = null;
        this.destroyed = true;
    };
    /**
     * Frees the texture from WebGL memory without destroying this texture object.
     * This means you can still use the texture later which will upload it to GPU
     * memory again.
     *
     * @fires PIXI.BaseTexture#dispose
     */
    BaseTexture.prototype.dispose = function () {
        this.emit('dispose', this);
    };
    /** Utility function for BaseTexture|Texture cast. */
    BaseTexture.prototype.castToBaseTexture = function () {
        return this;
    };
    /**
     * Helper function that creates a base texture based on the source you provide.
     * The source can be - image url, image element, canvas element. If the
     * source is an image url or an image element and not in the base texture
     * cache, it will be created and loaded.
     *
     * @static
     * @param {string|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The
     *        source to create base texture from.
     * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
     * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
     * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}.
     * @returns {PIXI.BaseTexture} The new base texture.
     */
    BaseTexture.from = function (source, options, strict) {
        if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; }
        var isFrame = typeof source === 'string';
        var cacheId = null;
        if (isFrame) {
            cacheId = source;
        }
        else {
            if (!source._pixiId) {
                var prefix = (options && options.pixiIdPrefix) || 'pixiid';
                source._pixiId = prefix + "_" + uid();
            }
            cacheId = source._pixiId;
        }
        var baseTexture = BaseTextureCache[cacheId];
        // Strict-mode rejects invalid cacheIds
        if (isFrame && strict && !baseTexture) {
            throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache.");
        }
        if (!baseTexture) {
            baseTexture = new BaseTexture(source, options);
            baseTexture.cacheId = cacheId;
            BaseTexture.addToCache(baseTexture, cacheId);
        }
        return baseTexture;
    };
    /**
     * Create a new BaseTexture with a BufferResource from a Float32Array.
     * RGBA values are floats from 0 to 1.
     *
     * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data
     *        is provided, a new Float32Array is created.
     * @param width - Width of the resource
     * @param height - Height of the resource
     * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
     * @return - The resulting new BaseTexture
     */
    BaseTexture.fromBuffer = function (buffer, width, height, options) {
        buffer = buffer || new Float32Array(width * height * 4);
        var resource = new BufferResource(buffer, { width: width, height: height });
        var type = buffer instanceof Float32Array ? constants_TYPES.FLOAT : constants_TYPES.UNSIGNED_BYTE;
        return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type }));
    };
    /**
     * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object.
     *
     *
     * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache.
     * @param {string} id - The id that the BaseTexture will be stored against.
     */
    BaseTexture.addToCache = function (baseTexture, id) {
        if (id) {
            if (baseTexture.textureCacheIds.indexOf(id) === -1) {
                baseTexture.textureCacheIds.push(id);
            }
            if (BaseTextureCache[id]) {
                // eslint-disable-next-line no-console
                console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry");
            }
            BaseTextureCache[id] = baseTexture;
        }
    };
    /**
     * Remove a BaseTexture from the global BaseTextureCache.
     *
     * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself.
     * @return {PIXI.BaseTexture|null} The BaseTexture that was removed.
     */
    BaseTexture.removeFromCache = function (baseTexture) {
        if (typeof baseTexture === 'string') {
            var baseTextureFromCache = BaseTextureCache[baseTexture];
            if (baseTextureFromCache) {
                var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);
                if (index > -1) {
                    baseTextureFromCache.textureCacheIds.splice(index, 1);
                }
                delete BaseTextureCache[baseTexture];
                return baseTextureFromCache;
            }
        }
        else if (baseTexture && baseTexture.textureCacheIds) {
            for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) {
                delete BaseTextureCache[baseTexture.textureCacheIds[i]];
            }
            baseTexture.textureCacheIds.length = 0;
            return baseTexture;
        }
        return null;
    };
    /** Global number of the texture batch, used by multi-texture renderers. */
    BaseTexture._globalBatch = 0;
    return BaseTexture;
}((eventemitter3_default())));

/**
 * Resource that can manage several resource (items) inside.
 * All resources need to have the same pixel size.
 * Parent class for CubeResource and ArrayResource
 *
 * @memberof PIXI
 */
var AbstractMultiResource = /** @class */ (function (_super) {
    core_extends(AbstractMultiResource, _super);
    /**
     * @param length
     * @param options - Options to for Resource constructor
     * @param {number} [options.width] - Width of the resource
     * @param {number} [options.height] - Height of the resource
     */
    function AbstractMultiResource(length, options) {
        var _this = this;
        var _a = options || {}, width = _a.width, height = _a.height;
        _this = _super.call(this, width, height) || this;
        _this.items = [];
        _this.itemDirtyIds = [];
        for (var i = 0; i < length; i++) {
            var partTexture = new BaseTexture();
            _this.items.push(partTexture);
            // -2 - first run of texture array upload
            // -1 - texture item was allocated
            // >=0 - texture item uploaded , in sync with items[i].dirtyId
            _this.itemDirtyIds.push(-2);
        }
        _this.length = length;
        _this._load = null;
        _this.baseTexture = null;
        return _this;
    }
    /**
     * Used from ArrayResource and CubeResource constructors.
     *
     * @param resources - Can be resources, image elements, canvas, etc. ,
     *  length should be same as constructor length
     * @param options - Detect options for resources
     */
    AbstractMultiResource.prototype.initFromArray = function (resources, options) {
        for (var i = 0; i < this.length; i++) {
            if (!resources[i]) {
                continue;
            }
            if (resources[i].castToBaseTexture) {
                this.addBaseTextureAt(resources[i].castToBaseTexture(), i);
            }
            else if (resources[i] instanceof Resource) {
                this.addResourceAt(resources[i], i);
            }
            else {
                this.addResourceAt(autoDetectResource(resources[i], options), i);
            }
        }
    };
    /** Destroy this BaseImageResource. */
    AbstractMultiResource.prototype.dispose = function () {
        for (var i = 0, len = this.length; i < len; i++) {
            this.items[i].destroy();
        }
        this.items = null;
        this.itemDirtyIds = null;
        this._load = null;
    };
    /**
     * Set a resource by ID
     *
     * @param resource
     * @param index - Zero-based index of resource to set
     * @return - Instance for chaining
     */
    AbstractMultiResource.prototype.addResourceAt = function (resource, index) {
        if (!this.items[index]) {
            throw new Error("Index " + index + " is out of bounds");
        }
        // Inherit the first resource dimensions
        if (resource.valid && !this.valid) {
            this.resize(resource.width, resource.height);
        }
        this.items[index].setResource(resource);
        return this;
    };
    /** Set the parent base texture. */
    AbstractMultiResource.prototype.bind = function (baseTexture) {
        if (this.baseTexture !== null) {
            throw new Error('Only one base texture per TextureArray is allowed');
        }
        _super.prototype.bind.call(this, baseTexture);
        for (var i = 0; i < this.length; i++) {
            this.items[i].parentTextureArray = baseTexture;
            this.items[i].on('update', baseTexture.update, baseTexture);
        }
    };
    /** Unset the parent base texture. */
    AbstractMultiResource.prototype.unbind = function (baseTexture) {
        _super.prototype.unbind.call(this, baseTexture);
        for (var i = 0; i < this.length; i++) {
            this.items[i].parentTextureArray = null;
            this.items[i].off('update', baseTexture.update, baseTexture);
        }
    };
    /**
     * Load all the resources simultaneously
     *
     * @return - When load is resolved
     */
    AbstractMultiResource.prototype.load = function () {
        var _this = this;
        if (this._load) {
            return this._load;
        }
        var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; });
        // TODO: also implement load part-by-part strategy
        var promises = resources.map(function (item) { return item.load(); });
        this._load = Promise.all(promises)
            .then(function () {
            var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight;
            _this.resize(realWidth, realHeight);
            return Promise.resolve(_this);
        });
        return this._load;
    };
    return AbstractMultiResource;
}(Resource));

/**
 * A resource that contains a number of sources.
 *
 * @memberof PIXI
 */
var ArrayResource = /** @class */ (function (_super) {
    core_extends(ArrayResource, _super);
    /**
     * @param source - Number of items in array or the collection
     *        of image URLs to use. Can also be resources, image elements, canvas, etc.
     * @param options - Options to apply to {@link PIXI.autoDetectResource}
     * @param {number} [options.width] - Width of the resource
     * @param {number} [options.height] - Height of the resource
     */
    function ArrayResource(source, options) {
        var _this = this;
        var _a = options || {}, width = _a.width, height = _a.height;
        var urls;
        var length;
        if (Array.isArray(source)) {
            urls = source;
            length = source.length;
        }
        else {
            length = source;
        }
        _this = _super.call(this, length, { width: width, height: height }) || this;
        if (urls) {
            _this.initFromArray(urls, options);
        }
        return _this;
    }
    /**
     * Set a baseTexture by ID,
     * ArrayResource just takes resource from it, nothing more
     *
     * @param baseTexture
     * @param index - Zero-based index of resource to set
     * @return - Instance for chaining
     */
    ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) {
        if (baseTexture.resource) {
            this.addResourceAt(baseTexture.resource, index);
        }
        else {
            throw new Error('ArrayResource does not support RenderTexture');
        }
        return this;
    };
    /** Add binding */
    ArrayResource.prototype.bind = function (baseTexture) {
        _super.prototype.bind.call(this, baseTexture);
        baseTexture.target = constants_TARGETS.TEXTURE_2D_ARRAY;
    };
    /**
     * Upload the resources to the GPU.
     *
     * @param renderer
     * @param texture
     * @param glTexture
     * @returns - whether texture was uploaded
     */
    ArrayResource.prototype.upload = function (renderer, texture, glTexture) {
        var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items;
        var gl = renderer.gl;
        if (glTexture.dirtyId < 0) {
            gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null);
        }
        for (var i = 0; i < length; i++) {
            var item = items[i];
            if (itemDirtyIds[i] < item.dirtyId) {
                itemDirtyIds[i] = item.dirtyId;
                if (item.valid) {
                    gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset
                    0, // yoffset
                    i, // zoffset
                    item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source);
                }
            }
        }
        return true;
    };
    return ArrayResource;
}(AbstractMultiResource));

/**
 * Base for all the image/canvas resources.
 *
 * @memberof PIXI
 */
var BaseImageResource = /** @class */ (function (_super) {
    core_extends(BaseImageResource, _super);
    /**
     * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source
     */
    function BaseImageResource(source) {
        var _this = this;
        var sourceAny = source;
        var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width;
        var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height;
        _this = _super.call(this, width, height) || this;
        _this.source = source;
        _this.noSubImage = false;
        return _this;
    }
    /**
     * Set cross origin based detecting the url and the crossorigin
     *
     * @param element - Element to apply crossOrigin
     * @param url - URL to check
     * @param crossorigin - Cross origin value to use
     */
    BaseImageResource.crossOrigin = function (element, url, crossorigin) {
        if (crossorigin === undefined && url.indexOf('data:') !== 0) {
            element.crossOrigin = determineCrossOrigin(url);
        }
        else if (crossorigin !== false) {
            element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous';
        }
    };
    /**
     * Upload the texture to the GPU.
     *
     * @param renderer - Upload to the renderer
     * @param baseTexture - Reference to parent texture
     * @param glTexture
     * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional)
     * @returns - true is success
     */
    BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) {
        var gl = renderer.gl;
        var width = baseTexture.realWidth;
        var height = baseTexture.realHeight;
        source = source || this.source;
        if (source instanceof HTMLImageElement) {
            if (!source.complete || source.naturalWidth === 0) {
                return false;
            }
        }
        else if (source instanceof HTMLVideoElement) {
            if (source.readyState <= 1) {
                return false;
            }
        }
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants_ALPHA_MODES.UNPACK);
        if (!this.noSubImage
            && baseTexture.target === gl.TEXTURE_2D
            && glTexture.width === width
            && glTexture.height === height) {
            gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source);
        }
        else {
            glTexture.width = width;
            glTexture.height = height;
            gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source);
        }
        return true;
    };
    /**
     * Checks if source width/height was changed, resize can cause extra baseTexture update.
     * Triggers one update in any case.
     */
    BaseImageResource.prototype.update = function () {
        if (this.destroyed) {
            return;
        }
        var source = this.source;
        var width = source.naturalWidth || source.videoWidth || source.width;
        var height = source.naturalHeight || source.videoHeight || source.height;
        this.resize(width, height);
        _super.prototype.update.call(this);
    };
    /** Destroy this {@link BaseImageResource} */
    BaseImageResource.prototype.dispose = function () {
        this.source = null;
    };
    return BaseImageResource;
}(Resource));

/**
 * @interface OffscreenCanvas
 */
/**
 * Resource type for HTMLCanvasElement.
 *
 * @memberof PIXI
 */
var CanvasResource = /** @class */ (function (_super) {
    core_extends(CanvasResource, _super);
    /**
     * @param source - Canvas element to use
     */
    // eslint-disable-next-line @typescript-eslint/no-useless-constructor
    function CanvasResource(source) {
        return _super.call(this, source) || this;
    }
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @return {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas
     */
    CanvasResource.test = function (source) {
        var OffscreenCanvas = globalThis.OffscreenCanvas;
        // Check for browsers that don't yet support OffscreenCanvas
        if (OffscreenCanvas && source instanceof OffscreenCanvas) {
            return true;
        }
        return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement;
    };
    return CanvasResource;
}(BaseImageResource));

/**
 * Resource for a CubeTexture which contains six resources.
 *
 * @memberof PIXI
 */
var CubeResource = /** @class */ (function (_super) {
    core_extends(CubeResource, _super);
    /**
     * @param {Array<string|PIXI.Resource>} [source] - Collection of URLs or resources
     *        to use as the sides of the cube.
     * @param options - ImageResource options
     * @param {number} [options.width] - Width of resource
     * @param {number} [options.height] - Height of resource
     * @param {number} [options.autoLoad=true] - Whether to auto-load resources
     * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied,
     *   whether to copy them or use
     */
    function CubeResource(source, options) {
        var _this = this;
        var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture;
        if (source && source.length !== CubeResource.SIDES) {
            throw new Error("Invalid length. Got " + source.length + ", expected 6");
        }
        _this = _super.call(this, 6, { width: width, height: height }) || this;
        for (var i = 0; i < CubeResource.SIDES; i++) {
            _this.items[i].target = constants_TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i;
        }
        _this.linkBaseTexture = linkBaseTexture !== false;
        if (source) {
            _this.initFromArray(source, options);
        }
        if (autoLoad !== false) {
            _this.load();
        }
        return _this;
    }
    /**
     * Add binding.
     *
     * @param baseTexture - parent base texture
     */
    CubeResource.prototype.bind = function (baseTexture) {
        _super.prototype.bind.call(this, baseTexture);
        baseTexture.target = constants_TARGETS.TEXTURE_CUBE_MAP;
    };
    CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) {
        if (linkBaseTexture === undefined) {
            linkBaseTexture = this.linkBaseTexture;
        }
        if (!this.items[index]) {
            throw new Error("Index " + index + " is out of bounds");
        }
        if (!this.linkBaseTexture
            || baseTexture.parentTextureArray
            || Object.keys(baseTexture._glTextures).length > 0) {
            // copy mode
            if (baseTexture.resource) {
                this.addResourceAt(baseTexture.resource, index);
            }
            else {
                throw new Error("CubeResource does not support copying of renderTexture.");
            }
        }
        else {
            // link mode, the difficult one!
            baseTexture.target = constants_TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index;
            baseTexture.parentTextureArray = this.baseTexture;
            this.items[index] = baseTexture;
        }
        if (baseTexture.valid && !this.valid) {
            this.resize(baseTexture.realWidth, baseTexture.realHeight);
        }
        this.items[index] = baseTexture;
        return this;
    };
    /**
     * Upload the resource
     *
     * @returns {boolean} true is success
     */
    CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) {
        var dirty = this.itemDirtyIds;
        for (var i = 0; i < CubeResource.SIDES; i++) {
            var side = this.items[i];
            if (dirty[i] < side.dirtyId) {
                if (side.valid && side.resource) {
                    side.resource.upload(renderer, side, glTexture);
                    dirty[i] = side.dirtyId;
                }
                else if (dirty[i] < -1) {
                    // either item is not valid yet, either its a renderTexture
                    // allocate the memory
                    renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null);
                    dirty[i] = -1;
                }
            }
        }
        return true;
    };
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @return {boolean} `true` if source is an array of 6 elements
     */
    CubeResource.test = function (source) {
        return Array.isArray(source) && source.length === CubeResource.SIDES;
    };
    /** Number of texture sides to store for CubeResources. */
    CubeResource.SIDES = 6;
    return CubeResource;
}(AbstractMultiResource));

/**
 * Resource type for HTMLImageElement.
 *
 * @memberof PIXI
 */
var ImageResource = /** @class */ (function (_super) {
    core_extends(ImageResource, _super);
    /**
     * @param source - image source or URL
     * @param options
     * @param {boolean} [options.autoLoad=true] - start loading process
     * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create
     *        a bitmap before upload
     * @param {boolean} [options.crossorigin=true] - Load image using cross origin
     * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap
     */
    function ImageResource(source, options) {
        var _this = this;
        options = options || {};
        if (!(source instanceof HTMLImageElement)) {
            var imageElement = new Image();
            BaseImageResource.crossOrigin(imageElement, source, options.crossorigin);
            imageElement.src = source;
            source = imageElement;
        }
        _this = _super.call(this, source) || this;
        // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height
        // to non-zero values before its loading completes if images are in a cache.
        // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images.
        // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968).
        if (!source.complete && !!_this._width && !!_this._height) {
            _this._width = 0;
            _this._height = 0;
        }
        _this.url = source.src;
        _this._process = null;
        _this.preserveBitmap = false;
        _this.createBitmap = (options.createBitmap !== undefined
            ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap;
        _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null;
        _this.bitmap = null;
        _this._load = null;
        if (options.autoLoad !== false) {
            _this.load();
        }
        return _this;
    }
    /**
     * Returns a promise when image will be loaded and processed.
     *
     * @param createBitmap - whether process image into bitmap
     */
    ImageResource.prototype.load = function (createBitmap) {
        var _this = this;
        if (this._load) {
            return this._load;
        }
        if (createBitmap !== undefined) {
            this.createBitmap = createBitmap;
        }
        this._load = new Promise(function (resolve, reject) {
            var source = _this.source;
            _this.url = source.src;
            var completed = function () {
                if (_this.destroyed) {
                    return;
                }
                source.onload = null;
                source.onerror = null;
                _this.resize(source.width, source.height);
                _this._load = null;
                if (_this.createBitmap) {
                    resolve(_this.process());
                }
                else {
                    resolve(_this);
                }
            };
            if (source.complete && source.src) {
                completed();
            }
            else {
                source.onload = completed;
                source.onerror = function (event) {
                    // Avoids Promise freezing when resource broken
                    reject(event);
                    _this.onError.emit(event);
                };
            }
        });
        return this._load;
    };
    /**
     * Called when we need to convert image into BitmapImage.
     * Can be called multiple times, real promise is cached inside.
     *
     * @return - Cached promise to fill that bitmap
     */
    ImageResource.prototype.process = function () {
        var _this = this;
        var source = this.source;
        if (this._process !== null) {
            return this._process;
        }
        if (this.bitmap !== null || !globalThis.createImageBitmap) {
            return Promise.resolve(this);
        }
        var createImageBitmap = globalThis.createImageBitmap;
        var cors = !source.crossOrigin || source.crossOrigin === 'anonymous';
        this._process = fetch(source.src, {
            mode: cors ? 'cors' : 'no-cors'
        })
            .then(function (r) { return r.blob(); })
            .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, {
            premultiplyAlpha: _this.alphaMode === constants_ALPHA_MODES.UNPACK ? 'premultiply' : 'none',
        }); })
            .then(function (bitmap) {
            if (_this.destroyed) {
                return Promise.reject();
            }
            _this.bitmap = bitmap;
            _this.update();
            _this._process = null;
            return Promise.resolve(_this);
        });
        return this._process;
    };
    /**
     * Upload the image resource to GPU.
     *
     * @param renderer - Renderer to upload to
     * @param baseTexture - BaseTexture for this resource
     * @param glTexture - GLTexture to use
     * @returns {boolean} true is success
     */
    ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) {
        if (typeof this.alphaMode === 'number') {
            // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it
            baseTexture.alphaMode = this.alphaMode;
        }
        if (!this.createBitmap) {
            return _super.prototype.upload.call(this, renderer, baseTexture, glTexture);
        }
        if (!this.bitmap) {
            // yeah, ignore the output
            this.process();
            if (!this.bitmap) {
                return false;
            }
        }
        _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap);
        if (!this.preserveBitmap) {
            // checks if there are other renderers that possibly need this bitmap
            var flag = true;
            var glTextures = baseTexture._glTextures;
            for (var key in glTextures) {
                var otherTex = glTextures[key];
                if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                if (this.bitmap.close) {
                    this.bitmap.close();
                }
                this.bitmap = null;
            }
        }
        return true;
    };
    /** Destroys this resource. */
    ImageResource.prototype.dispose = function () {
        this.source.onload = null;
        this.source.onerror = null;
        _super.prototype.dispose.call(this);
        if (this.bitmap) {
            this.bitmap.close();
            this.bitmap = null;
        }
        this._process = null;
        this._load = null;
    };
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @return {boolean} `true` if source is string or HTMLImageElement
     */
    ImageResource.test = function (source) {
        return typeof source === 'string' || source instanceof HTMLImageElement;
    };
    return ImageResource;
}(BaseImageResource));

/**
 * Resource type for SVG elements and graphics.
 *
 * @memberof PIXI
 */
var SVGResource = /** @class */ (function (_super) {
    core_extends(SVGResource, _super);
    /**
     * @param sourceBase64 - Base64 encoded SVG element or URL for SVG file.
     * @param {object} [options] - Options to use
     * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by...
     * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified.
     * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified.
     * @param {boolean} [options.autoLoad=true] - Start loading right away.
     */
    function SVGResource(sourceBase64, options) {
        var _this = this;
        options = options || {};
        _this = _super.call(this, document.createElement('canvas')) || this;
        _this._width = 0;
        _this._height = 0;
        _this.svg = sourceBase64;
        _this.scale = options.scale || 1;
        _this._overrideWidth = options.width;
        _this._overrideHeight = options.height;
        _this._resolve = null;
        _this._crossorigin = options.crossorigin;
        _this._load = null;
        if (options.autoLoad !== false) {
            _this.load();
        }
        return _this;
    }
    SVGResource.prototype.load = function () {
        var _this = this;
        if (this._load) {
            return this._load;
        }
        this._load = new Promise(function (resolve) {
            // Save this until after load is finished
            _this._resolve = function () {
                _this.resize(_this.source.width, _this.source.height);
                resolve(_this);
            };
            // Convert SVG inline string to data-uri
            if (SVGResource.SVG_XML.test(_this.svg.trim())) {
                if (!btoa) {
                    throw new Error('Your browser doesn\'t support base64 conversions.');
                }
                _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg)));
            }
            _this._loadSvg();
        });
        return this._load;
    };
    /** Loads an SVG image from `imageUrl` or `data URL`. */
    SVGResource.prototype._loadSvg = function () {
        var _this = this;
        var tempImage = new Image();
        BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin);
        tempImage.src = this.svg;
        tempImage.onerror = function (event) {
            if (!_this._resolve) {
                return;
            }
            tempImage.onerror = null;
            _this.onError.emit(event);
        };
        tempImage.onload = function () {
            if (!_this._resolve) {
                return;
            }
            var svgWidth = tempImage.width;
            var svgHeight = tempImage.height;
            if (!svgWidth || !svgHeight) {
                throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');
            }
            // Set render size
            var width = svgWidth * _this.scale;
            var height = svgHeight * _this.scale;
            if (_this._overrideWidth || _this._overrideHeight) {
                width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth;
                height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight;
            }
            width = Math.round(width);
            height = Math.round(height);
            // Create a canvas element
            var canvas = _this.source;
            canvas.width = width;
            canvas.height = height;
            canvas._pixiId = "canvas_" + uid();
            // Draw the Svg to the canvas
            canvas
                .getContext('2d')
                .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height);
            _this._resolve();
            _this._resolve = null;
        };
    };
    /**
     * Get size from an svg string using a regular expression.
     *
     * @param svgString - a serialized svg element
     * @return - image extension
     */
    SVGResource.getSize = function (svgString) {
        var sizeMatch = SVGResource.SVG_SIZE.exec(svgString);
        var size = {};
        if (sizeMatch) {
            size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3]));
            size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7]));
        }
        return size;
    };
    /** Destroys this texture. */
    SVGResource.prototype.dispose = function () {
        _super.prototype.dispose.call(this);
        this._resolve = null;
        this._crossorigin = null;
    };
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @param {string} extension - The extension of source, if set
     * @return {boolean} - If the source is a SVG source or data file
     */
    SVGResource.test = function (source, extension) {
        // url file extension is SVG
        return extension === 'svg'
            // source is SVG data-uri
            || (typeof source === 'string' && (/^data:image\/svg\+xml(;(charset=utf8|utf8))?;base64/).test(source))
            // source is SVG inline
            || (typeof source === 'string' && SVGResource.SVG_XML.test(source));
    };
    /**
     * Regular expression for SVG XML document.
     *
     * @example &lt;?xml version="1.0" encoding="utf-8" ?&gt;&lt;!-- image/svg --&gt;&lt;svg
     * @readonly
     */
    SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m;
    /**
     * Regular expression for SVG size.
     *
     * @example &lt;svg width="100" height="100"&gt;&lt;/svg&gt;
     * @readonly
     */
    SVGResource.SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len
    return SVGResource;
}(BaseImageResource));

/**
 * Resource type for {@code HTMLVideoElement}.
 *
 * @memberof PIXI
 */
var VideoResource = /** @class */ (function (_super) {
    core_extends(VideoResource, _super);
    /**
     * @param {HTMLVideoElement|object|string|Array<string|object>} source - Video element to use.
     * @param {object} [options] - Options to use
     * @param {boolean} [options.autoLoad=true] - Start loading the video immediately
     * @param {boolean} [options.autoPlay=true] - Start playing video immediately
     * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video.
     * Leave at 0 to update at every render.
     * @param {boolean} [options.crossorigin=true] - Load image using cross origin
     */
    function VideoResource(source, options) {
        var _this = this;
        options = options || {};
        if (!(source instanceof HTMLVideoElement)) {
            var videoElement = document.createElement('video');
            // workaround for https://github.com/pixijs/pixi.js/issues/5996
            videoElement.setAttribute('preload', 'auto');
            videoElement.setAttribute('webkit-playsinline', '');
            videoElement.setAttribute('playsinline', '');
            if (typeof source === 'string') {
                source = [source];
            }
            var firstSrc = source[0].src || source[0];
            BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin);
            // array of objects or strings
            for (var i = 0; i < source.length; ++i) {
                var sourceElement = document.createElement('source');
                var _a = source[i], src = _a.src, mime = _a.mime;
                src = src || source[i];
                var baseSrc = src.split('?').shift().toLowerCase();
                var ext = baseSrc.slice(baseSrc.lastIndexOf('.') + 1);
                mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext;
                sourceElement.src = src;
                sourceElement.type = mime;
                videoElement.appendChild(sourceElement);
            }
            // Override the source
            source = videoElement;
        }
        _this = _super.call(this, source) || this;
        _this.noSubImage = true;
        _this._autoUpdate = true;
        _this._isConnectedToTicker = false;
        _this._updateFPS = options.updateFPS || 0;
        _this._msToNextUpdate = 0;
        _this.autoPlay = options.autoPlay !== false;
        _this._load = null;
        _this._resolve = null;
        // Bind for listeners
        _this._onCanPlay = _this._onCanPlay.bind(_this);
        _this._onError = _this._onError.bind(_this);
        if (options.autoLoad !== false) {
            _this.load();
        }
        return _this;
    }
    /**
     * Trigger updating of the texture.
     *
     * @param deltaTime - time delta since last tick
     */
    VideoResource.prototype.update = function (_deltaTime) {
        if (!this.destroyed) {
            // account for if video has had its playbackRate changed
            var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate;
            this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS);
            if (!this._updateFPS || this._msToNextUpdate <= 0) {
                _super.prototype.update.call(this);
                this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0;
            }
        }
    };
    /**
     * Start preloading the video resource.
     *
     * @return {Promise<void>} Handle the validate event
     */
    VideoResource.prototype.load = function () {
        var _this = this;
        if (this._load) {
            return this._load;
        }
        var source = this.source;
        if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA)
            && source.width && source.height) {
            source.complete = true;
        }
        source.addEventListener('play', this._onPlayStart.bind(this));
        source.addEventListener('pause', this._onPlayStop.bind(this));
        if (!this._isSourceReady()) {
            source.addEventListener('canplay', this._onCanPlay);
            source.addEventListener('canplaythrough', this._onCanPlay);
            source.addEventListener('error', this._onError, true);
        }
        else {
            this._onCanPlay();
        }
        this._load = new Promise(function (resolve) {
            if (_this.valid) {
                resolve(_this);
            }
            else {
                _this._resolve = resolve;
                source.load();
            }
        });
        return this._load;
    };
    /** Handle video error events. */
    VideoResource.prototype._onError = function (event) {
        this.source.removeEventListener('error', this._onError, true);
        this.onError.emit(event);
    };
    /**
     * Returns true if the underlying source is playing.
     *
     * @return - True if playing.
     */
    VideoResource.prototype._isSourcePlaying = function () {
        var source = this.source;
        return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2);
    };
    /**
     * Returns true if the underlying source is ready for playing.
     *
     * @return - True if ready.
     */
    VideoResource.prototype._isSourceReady = function () {
        var source = this.source;
        return source.readyState === 3 || source.readyState === 4;
    };
    /** Runs the update loop when the video is ready to play. */
    VideoResource.prototype._onPlayStart = function () {
        // Just in case the video has not received its can play even yet..
        if (!this.valid) {
            this._onCanPlay();
        }
        if (this.autoUpdate && !this._isConnectedToTicker) {
            Ticker.shared.add(this.update, this);
            this._isConnectedToTicker = true;
        }
    };
    /** Fired when a pause event is triggered, stops the update loop. */
    VideoResource.prototype._onPlayStop = function () {
        if (this._isConnectedToTicker) {
            Ticker.shared.remove(this.update, this);
            this._isConnectedToTicker = false;
        }
    };
    /** Fired when the video is loaded and ready to play. */
    VideoResource.prototype._onCanPlay = function () {
        var source = this.source;
        source.removeEventListener('canplay', this._onCanPlay);
        source.removeEventListener('canplaythrough', this._onCanPlay);
        var valid = this.valid;
        this.resize(source.videoWidth, source.videoHeight);
        // prevent multiple loaded dispatches..
        if (!valid && this._resolve) {
            this._resolve(this);
            this._resolve = null;
        }
        if (this._isSourcePlaying()) {
            this._onPlayStart();
        }
        else if (this.autoPlay) {
            source.play();
        }
    };
    /** Destroys this texture. */
    VideoResource.prototype.dispose = function () {
        if (this._isConnectedToTicker) {
            Ticker.shared.remove(this.update, this);
            this._isConnectedToTicker = false;
        }
        var source = this.source;
        if (source) {
            source.removeEventListener('error', this._onError, true);
            source.pause();
            source.src = '';
            source.load();
        }
        _super.prototype.dispose.call(this);
    };
    Object.defineProperty(VideoResource.prototype, "autoUpdate", {
        /** Should the base texture automatically update itself, set to true by default. */
        get: function () {
            return this._autoUpdate;
        },
        set: function (value) {
            if (value !== this._autoUpdate) {
                this._autoUpdate = value;
                if (!this._autoUpdate && this._isConnectedToTicker) {
                    Ticker.shared.remove(this.update, this);
                    this._isConnectedToTicker = false;
                }
                else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) {
                    Ticker.shared.add(this.update, this);
                    this._isConnectedToTicker = true;
                }
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VideoResource.prototype, "updateFPS", {
        /**
         * How many times a second to update the texture from the video. Leave at 0 to update at every render.
         * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
         */
        get: function () {
            return this._updateFPS;
        },
        set: function (value) {
            if (value !== this._updateFPS) {
                this._updateFPS = value;
            }
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @param {string} extension - The extension of source, if set
     * @return {boolean} `true` if video source
     */
    VideoResource.test = function (source, extension) {
        return (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement)
            || VideoResource.TYPES.indexOf(extension) > -1;
    };
    /**
     * List of common video file extensions supported by VideoResource.
     *
     * @readonly
     */
    VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov'];
    /**
     * Map of video MIME types that can't be directly derived from file extensions.
     *
     * @readonly
     */
    VideoResource.MIME_TYPES = {
        ogv: 'video/ogg',
        mov: 'video/quicktime',
        m4v: 'video/mp4',
    };
    return VideoResource;
}(BaseImageResource));

/**
 * Resource type for ImageBitmap.
 *
 * @memberof PIXI
 */
var ImageBitmapResource = /** @class */ (function (_super) {
    core_extends(ImageBitmapResource, _super);
    /**
     * @param source - Image element to use
     */
    // eslint-disable-next-line @typescript-eslint/no-useless-constructor
    function ImageBitmapResource(source) {
        return _super.call(this, source) || this;
    }
    /**
     * Used to auto-detect the type of resource.
     *
     * @param {*} source - The source object
     * @return {boolean} `true` if source is an ImageBitmap
     */
    ImageBitmapResource.test = function (source) {
        return !!globalThis.createImageBitmap && source instanceof ImageBitmap;
    };
    return ImageBitmapResource;
}(BaseImageResource));

INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource);

var _resources = {
    __proto__: null,
    Resource: Resource,
    BaseImageResource: BaseImageResource,
    INSTALLED: INSTALLED,
    autoDetectResource: autoDetectResource,
    AbstractMultiResource: AbstractMultiResource,
    ArrayResource: ArrayResource,
    BufferResource: BufferResource,
    CanvasResource: CanvasResource,
    CubeResource: CubeResource,
    ImageResource: ImageResource,
    SVGResource: SVGResource,
    VideoResource: VideoResource,
    ImageBitmapResource: ImageBitmapResource
};

/**
 * Resource type for DepthTexture.
 *
 * @memberof PIXI
 */
var DepthResource = /** @class */ (function (_super) {
    core_extends(DepthResource, _super);
    function DepthResource() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Upload the texture to the GPU.
     *
     * @param renderer - Upload to the renderer
     * @param baseTexture - Reference to parent texture
     * @param glTexture - glTexture
     * @return - true is success
     */
    DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) {
        var gl = renderer.gl;
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === constants_ALPHA_MODES.UNPACK);
        var width = baseTexture.realWidth;
        var height = baseTexture.realHeight;
        if (glTexture.width === width && glTexture.height === height) {
            gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data);
        }
        else {
            glTexture.width = width;
            glTexture.height = height;
            gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data);
        }
        return true;
    };
    return DepthResource;
}(BufferResource));

/**
 * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses
 * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer.
 *
 * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES.
 *
 * @memberof PIXI
 */
var Framebuffer = /** @class */ (function () {
    /**
     * @param width - Width of the frame buffer
     * @param height - Height of the frame buffer
     */
    function Framebuffer(width, height) {
        this.width = Math.round(width || 100);
        this.height = Math.round(height || 100);
        this.stencil = false;
        this.depth = false;
        this.dirtyId = 0;
        this.dirtyFormat = 0;
        this.dirtySize = 0;
        this.depthTexture = null;
        this.colorTextures = [];
        this.glFramebuffers = {};
        this.disposeRunner = new Runner('disposeFramebuffer');
        this.multisample = constants_MSAA_QUALITY.NONE;
    }
    Object.defineProperty(Framebuffer.prototype, "colorTexture", {
        /**
         * Reference to the colorTexture.
         *
         * @readonly
         */
        get: function () {
            return this.colorTextures[0];
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Add texture to the colorTexture array.
     *
     * @param index - Index of the array to add the texture to
     * @param texture - Texture to add to the array
     */
    Framebuffer.prototype.addColorTexture = function (index, texture) {
        if (index === void 0) { index = 0; }
        // TODO add some validation to the texture - same width / height etc?
        this.colorTextures[index] = texture || new BaseTexture(null, {
            scaleMode: constants_SCALE_MODES.NEAREST,
            resolution: 1,
            mipmap: constants_MIPMAP_MODES.OFF,
            width: this.width,
            height: this.height,
        });
        this.dirtyId++;
        this.dirtyFormat++;
        return this;
    };
    /**
     * Add a depth texture to the frame buffer.
     *
     * @param texture - Texture to add.
     */
    Framebuffer.prototype.addDepthTexture = function (texture) {
        /* eslint-disable max-len */
        this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), {
            scaleMode: constants_SCALE_MODES.NEAREST,
            resolution: 1,
            width: this.width,
            height: this.height,
            mipmap: constants_MIPMAP_MODES.OFF,
            format: constants_FORMATS.DEPTH_COMPONENT,
            type: constants_TYPES.UNSIGNED_SHORT,
        });
        this.dirtyId++;
        this.dirtyFormat++;
        return this;
    };
    /** Enable depth on the frame buffer. */
    Framebuffer.prototype.enableDepth = function () {
        this.depth = true;
        this.dirtyId++;
        this.dirtyFormat++;
        return this;
    };
    /** Enable stencil on the frame buffer. */
    Framebuffer.prototype.enableStencil = function () {
        this.stencil = true;
        this.dirtyId++;
        this.dirtyFormat++;
        return this;
    };
    /**
     * Resize the frame buffer
     *
     * @param width - Width of the frame buffer to resize to
     * @param height - Height of the frame buffer to resize to
     */
    Framebuffer.prototype.resize = function (width, height) {
        width = Math.round(width);
        height = Math.round(height);
        if (width === this.width && height === this.height)
            { return; }
        this.width = width;
        this.height = height;
        this.dirtyId++;
        this.dirtySize++;
        for (var i = 0; i < this.colorTextures.length; i++) {
            var texture = this.colorTextures[i];
            var resolution = texture.resolution;
            // take into account the fact the texture may have a different resolution..
            texture.setSize(width / resolution, height / resolution);
        }
        if (this.depthTexture) {
            var resolution = this.depthTexture.resolution;
            this.depthTexture.setSize(width / resolution, height / resolution);
        }
    };
    /** Disposes WebGL resources that are connected to this geometry. */
    Framebuffer.prototype.dispose = function () {
        this.disposeRunner.emit(this, false);
    };
    /** Destroys and removes the depth texture added to this framebuffer. */
    Framebuffer.prototype.destroyDepthTexture = function () {
        if (this.depthTexture) {
            this.depthTexture.destroy();
            this.depthTexture = null;
            ++this.dirtyId;
            ++this.dirtyFormat;
        }
    };
    return Framebuffer;
}());

/**
 * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
 *
 * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded
 * otherwise black rectangles will be drawn instead.
 *
 * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position
 * and rotation of the given Display Objects is ignored. For example:
 *
 * ```js
 * let renderer = PIXI.autoDetectRenderer();
 * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 });
 * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
 * let sprite = PIXI.Sprite.from("spinObj_01.png");
 *
 * sprite.position.x = 800/2;
 * sprite.position.y = 600/2;
 * sprite.anchor.x = 0.5;
 * sprite.anchor.y = 0.5;
 *
 * renderer.render(sprite, {renderTexture});
 * ```
 *
 * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0
 * you can clear the transform
 *
 * ```js
 *
 * sprite.setTransform()
 *
 * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 });
 * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
 *
 * renderer.render(sprite, {renderTexture});  // Renders to center of RenderTexture
 * ```
 *
 * @memberof PIXI
 */
var BaseRenderTexture = /** @class */ (function (_super) {
    core_extends(BaseRenderTexture, _super);
    /**
     * @param options
     * @param {number} [options.width=100] - The width of the base render texture.
     * @param {number} [options.height=100] - The height of the base render texture.
     * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES}
     *   for possible values.
     * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio
     *   of the texture being generated.
     * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer.
     */
    function BaseRenderTexture(options) {
        if (options === void 0) { options = {}; }
        var _this = this;
        if (typeof options === 'number') {
            /* eslint-disable prefer-rest-params */
            // Backward compatibility of signature
            var width = arguments[0];
            var height = arguments[1];
            var scaleMode = arguments[2];
            var resolution = arguments[3];
            options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution };
            /* eslint-enable prefer-rest-params */
        }
        options.width = options.width || 100;
        options.height = options.height || 100;
        options.multisample = options.multisample !== undefined ? options.multisample : constants_MSAA_QUALITY.NONE;
        _this = _super.call(this, null, options) || this;
        // Set defaults
        _this.mipmap = constants_MIPMAP_MODES.OFF;
        _this.valid = true;
        _this.clearColor = [0, 0, 0, 0];
        _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight)
            .addColorTexture(0, _this);
        _this.framebuffer.multisample = options.multisample;
        // TODO - could this be added the systems?
        _this.maskStack = [];
        _this.filterStack = [{}];
        return _this;
    }
    /**
     * Resizes the BaseRenderTexture.
     *
     * @param desiredWidth - The desired width to resize to.
     * @param desiredHeight - The desired height to resize to.
     */
    BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) {
        this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution);
        this.setRealSize(this.framebuffer.width, this.framebuffer.height);
    };
    /**
     * Frees the texture and framebuffer from WebGL memory without destroying this texture object.
     * This means you can still use the texture later which will upload it to GPU
     * memory again.
     *
     * @fires PIXI.BaseTexture#dispose
     */
    BaseRenderTexture.prototype.dispose = function () {
        this.framebuffer.dispose();
        _super.prototype.dispose.call(this);
    };
    /** Destroys this texture. */
    BaseRenderTexture.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        this.framebuffer.destroyDepthTexture();
        this.framebuffer = null;
    };
    return BaseRenderTexture;
}(BaseTexture));

/**
 * Stores a texture's frame in UV coordinates, in
 * which everything lies in the rectangle `[(0,0), (1,0),
 * (1,1), (0,1)]`.
 *
 * | Corner       | Coordinates |
 * |--------------|-------------|
 * | Top-Left     | `(x0,y0)`   |
 * | Top-Right    | `(x1,y1)`   |
 * | Bottom-Right | `(x2,y2)`   |
 * | Bottom-Left  | `(x3,y3)`   |
 *
 * @protected
 * @memberof PIXI
 */
var TextureUvs = /** @class */ (function () {
    function TextureUvs() {
        this.x0 = 0;
        this.y0 = 0;
        this.x1 = 1;
        this.y1 = 0;
        this.x2 = 1;
        this.y2 = 1;
        this.x3 = 0;
        this.y3 = 1;
        this.uvsFloat32 = new Float32Array(8);
    }
    /**
     * Sets the texture Uvs based on the given frame information.
     *
     * @protected
     * @param frame - The frame of the texture
     * @param baseFrame - The base frame of the texture
     * @param rotate - Rotation of frame, see {@link PIXI.groupD8}
     */
    TextureUvs.prototype.set = function (frame, baseFrame, rotate) {
        var tw = baseFrame.width;
        var th = baseFrame.height;
        if (rotate) {
            // width and height div 2 div baseFrame size
            var w2 = frame.width / 2 / tw;
            var h2 = frame.height / 2 / th;
            // coordinates of center
            var cX = (frame.x / tw) + w2;
            var cY = (frame.y / th) + h2;
            rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner
            this.x0 = cX + (w2 * groupD8.uX(rotate));
            this.y0 = cY + (h2 * groupD8.uY(rotate));
            rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise
            this.x1 = cX + (w2 * groupD8.uX(rotate));
            this.y1 = cY + (h2 * groupD8.uY(rotate));
            rotate = groupD8.add(rotate, 2);
            this.x2 = cX + (w2 * groupD8.uX(rotate));
            this.y2 = cY + (h2 * groupD8.uY(rotate));
            rotate = groupD8.add(rotate, 2);
            this.x3 = cX + (w2 * groupD8.uX(rotate));
            this.y3 = cY + (h2 * groupD8.uY(rotate));
        }
        else {
            this.x0 = frame.x / tw;
            this.y0 = frame.y / th;
            this.x1 = (frame.x + frame.width) / tw;
            this.y1 = frame.y / th;
            this.x2 = (frame.x + frame.width) / tw;
            this.y2 = (frame.y + frame.height) / th;
            this.x3 = frame.x / tw;
            this.y3 = (frame.y + frame.height) / th;
        }
        this.uvsFloat32[0] = this.x0;
        this.uvsFloat32[1] = this.y0;
        this.uvsFloat32[2] = this.x1;
        this.uvsFloat32[3] = this.y1;
        this.uvsFloat32[4] = this.x2;
        this.uvsFloat32[5] = this.y2;
        this.uvsFloat32[6] = this.x3;
        this.uvsFloat32[7] = this.y3;
    };
    TextureUvs.prototype.toString = function () {
        return "[@pixi/core:TextureUvs "
            + ("x0=" + this.x0 + " y0=" + this.y0 + " ")
            + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ")
            + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3)
            + "]";
    };
    return TextureUvs;
}());

var DEFAULT_UVS = new TextureUvs();
/**
 * A texture stores the information that represents an image or part of an image.
 *
 * It cannot be added to the display list directly; instead use it as the texture for a Sprite.
 * If no frame is provided for a texture, then the whole image is used.
 *
 * You can directly create a texture from an image and then reuse it multiple times like this :
 *
 * ```js
 * let texture = PIXI.Texture.from('assets/image.png');
 * let sprite1 = new PIXI.Sprite(texture);
 * let sprite2 = new PIXI.Sprite(texture);
 * ```
 *
 * If you didnt pass the texture frame to constructor, it enables `noFrame` mode:
 * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture.
 *
 * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing.
 * You can check for this by checking the sprite's _textureID property.
 * ```js
 * var texture = PIXI.Texture.from('assets/image.svg');
 * var sprite1 = new PIXI.Sprite(texture);
 * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file
 * ```
 * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068.
 *
 * @memberof PIXI
 * @typeParam R - The BaseTexture's Resource type.
 */
var Texture = /** @class */ (function (_super) {
    core_extends(Texture, _super);
    /**
     * @param baseTexture - The base texture source to create the texture from
     * @param frame - The rectangle frame of the texture to show
     * @param orig - The area of original texture
     * @param trim - Trimmed rectangle of original texture
     * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8}
     * @param anchor - Default anchor point used for sprite placement / rotation
     */
    function Texture(baseTexture, frame, orig, trim, rotate, anchor) {
        var _this = _super.call(this) || this;
        _this.noFrame = false;
        if (!frame) {
            _this.noFrame = true;
            frame = new Rectangle(0, 0, 1, 1);
        }
        if (baseTexture instanceof Texture) {
            baseTexture = baseTexture.baseTexture;
        }
        _this.baseTexture = baseTexture;
        _this._frame = frame;
        _this.trim = trim;
        _this.valid = false;
        _this._uvs = DEFAULT_UVS;
        _this.uvMatrix = null;
        _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1);
        _this._rotate = Number(rotate || 0);
        if (rotate === true) {
            // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures
            _this._rotate = 2;
        }
        else if (_this._rotate % 2 !== 0) {
            throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually');
        }
        _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0);
        _this._updateID = 0;
        _this.textureCacheIds = [];
        if (!baseTexture.valid) {
            baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);
        }
        else if (_this.noFrame) {
            // if there is no frame we should monitor for any base texture changes..
            if (baseTexture.valid) {
                _this.onBaseTextureUpdated(baseTexture);
            }
        }
        else {
            _this.frame = frame;
        }
        if (_this.noFrame) {
            baseTexture.on('update', _this.onBaseTextureUpdated, _this);
        }
        return _this;
    }
    /**
     * Updates this texture on the gpu.
     *
     * Calls the TextureResource update.
     *
     * If you adjusted `frame` manually, please call `updateUvs()` instead.
     */
    Texture.prototype.update = function () {
        if (this.baseTexture.resource) {
            this.baseTexture.resource.update();
        }
    };
    /**
     * Called when the base texture is updated
     *
     * @protected
     * @param baseTexture - The base texture.
     */
    Texture.prototype.onBaseTextureUpdated = function (baseTexture) {
        if (this.noFrame) {
            if (!this.baseTexture.valid) {
                return;
            }
            this._frame.width = baseTexture.width;
            this._frame.height = baseTexture.height;
            this.valid = true;
            this.updateUvs();
        }
        else {
            // TODO this code looks confusing.. boo to abusing getters and setters!
            // if user gave us frame that has bigger size than resized texture it can be a problem
            this.frame = this._frame;
        }
        this.emit('update', this);
    };
    /**
     * Destroys this texture
     *
     * @param [destroyBase=false] - Whether to destroy the base texture as well
     */
    Texture.prototype.destroy = function (destroyBase) {
        if (this.baseTexture) {
            if (destroyBase) {
                var resource = this.baseTexture.resource;
                // delete the texture if it exists in the texture cache..
                // this only needs to be removed if the base texture is actually destroyed too..
                if (resource && resource.url && TextureCache[resource.url]) {
                    Texture.removeFromCache(resource.url);
                }
                this.baseTexture.destroy();
            }
            this.baseTexture.off('loaded', this.onBaseTextureUpdated, this);
            this.baseTexture.off('update', this.onBaseTextureUpdated, this);
            this.baseTexture = null;
        }
        this._frame = null;
        this._uvs = null;
        this.trim = null;
        this.orig = null;
        this.valid = false;
        Texture.removeFromCache(this);
        this.textureCacheIds = null;
    };
    /**
     * Creates a new texture object that acts the same as this one.
     *
     * @return - The new texture
     */
    Texture.prototype.clone = function () {
        var clonedFrame = this._frame.clone();
        var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone();
        var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor);
        if (this.noFrame) {
            clonedTexture._frame = clonedFrame;
        }
        return clonedTexture;
    };
    /**
     * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture.
     * Call it after changing the frame
     */
    Texture.prototype.updateUvs = function () {
        if (this._uvs === DEFAULT_UVS) {
            this._uvs = new TextureUvs();
        }
        this._uvs.set(this._frame, this.baseTexture, this.rotate);
        this._updateID++;
    };
    /**
     * Helper function that creates a new Texture based on the source you provide.
     * The source can be - frame id, image url, video url, canvas element, video element, base texture
     *
     * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source -
     *        Source to create texture from
     * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
     * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
     * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}.
     * @return {PIXI.Texture} The newly created texture
     */
    Texture.from = function (source, options, strict) {
        if (options === void 0) { options = {}; }
        if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; }
        var isFrame = typeof source === 'string';
        var cacheId = null;
        if (isFrame) {
            cacheId = source;
        }
        else if (source instanceof BaseTexture) {
            if (!source.cacheId) {
                var prefix = (options && options.pixiIdPrefix) || 'pixiid';
                source.cacheId = prefix + "-" + uid();
                BaseTexture.addToCache(source, source.cacheId);
            }
            cacheId = source.cacheId;
        }
        else {
            if (!source._pixiId) {
                var prefix = (options && options.pixiIdPrefix) || 'pixiid';
                source._pixiId = prefix + "_" + uid();
            }
            cacheId = source._pixiId;
        }
        var texture = TextureCache[cacheId];
        // Strict-mode rejects invalid cacheIds
        if (isFrame && strict && !texture) {
            throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache.");
        }
        if (!texture && !(source instanceof BaseTexture)) {
            if (!options.resolution) {
                options.resolution = getResolutionOfUrl(source);
            }
            texture = new Texture(new BaseTexture(source, options));
            texture.baseTexture.cacheId = cacheId;
            BaseTexture.addToCache(texture.baseTexture, cacheId);
            Texture.addToCache(texture, cacheId);
        }
        else if (!texture && (source instanceof BaseTexture)) {
            texture = new Texture(source);
            Texture.addToCache(texture, cacheId);
        }
        // lets assume its a base texture!
        return texture;
    };
    /**
     * Useful for loading textures via URLs. Use instead of `Texture.from` because
     * it does a better job of handling failed URLs more effectively. This also ignores
     * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images.
     *
     * @param url - The remote URL to load.
     * @param options - Optional options to include
     * @return - A Promise that resolves to a Texture.
     */
    Texture.fromURL = function (url, options) {
        var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions);
        var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false);
        var resource = texture.baseTexture.resource;
        // The texture was already loaded
        if (texture.baseTexture.valid) {
            return Promise.resolve(texture);
        }
        // Manually load the texture, this should allow users to handle load errors
        return resource.load().then(function () { return Promise.resolve(texture); });
    };
    /**
     * Create a new Texture with a BufferResource from a Float32Array.
     * RGBA values are floats from 0 to 1.
     *
     * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data
     *        is provided, a new Float32Array is created.
     * @param width - Width of the resource
     * @param height - Height of the resource
     * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
     * @return - The resulting new BaseTexture
     */
    Texture.fromBuffer = function (buffer, width, height, options) {
        return new Texture(BaseTexture.fromBuffer(buffer, width, height, options));
    };
    /**
     * Create a texture from a source and add to the cache.
     *
     * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source.
     * @param imageUrl - File name of texture, for cache and resolving resolution.
     * @param name - Human readable name for the texture cache. If no name is
     *        specified, only `imageUrl` will be used as the cache ID.
     * @return - Output texture
     */
    Texture.fromLoader = function (source, imageUrl, name, options) {
        var baseTexture = new BaseTexture(source, Object.assign({
            scaleMode: settings.SCALE_MODE,
            resolution: getResolutionOfUrl(imageUrl),
        }, options));
        var resource = baseTexture.resource;
        if (resource instanceof ImageResource) {
            resource.url = imageUrl;
        }
        var texture = new Texture(baseTexture);
        // No name, use imageUrl instead
        if (!name) {
            name = imageUrl;
        }
        // lets also add the frame to pixi's global cache for 'fromLoader' function
        BaseTexture.addToCache(texture.baseTexture, name);
        Texture.addToCache(texture, name);
        // also add references by url if they are different.
        if (name !== imageUrl) {
            BaseTexture.addToCache(texture.baseTexture, imageUrl);
            Texture.addToCache(texture, imageUrl);
        }
        // Generally images are valid right away
        if (texture.baseTexture.valid) {
            return Promise.resolve(texture);
        }
        // SVG assets need to be parsed async, let's wait
        return new Promise(function (resolve) {
            texture.baseTexture.once('loaded', function () { return resolve(texture); });
        });
    };
    /**
     * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object.
     *
     * @param texture - The Texture to add to the cache.
     * @param id - The id that the Texture will be stored against.
     */
    Texture.addToCache = function (texture, id) {
        if (id) {
            if (texture.textureCacheIds.indexOf(id) === -1) {
                texture.textureCacheIds.push(id);
            }
            if (TextureCache[id]) {
                // eslint-disable-next-line no-console
                console.warn("Texture added to the cache with an id [" + id + "] that already had an entry");
            }
            TextureCache[id] = texture;
        }
    };
    /**
     * Remove a Texture from the global TextureCache.
     *
     * @param texture - id of a Texture to be removed, or a Texture instance itself
     * @return - The Texture that was removed
     */
    Texture.removeFromCache = function (texture) {
        if (typeof texture === 'string') {
            var textureFromCache = TextureCache[texture];
            if (textureFromCache) {
                var index = textureFromCache.textureCacheIds.indexOf(texture);
                if (index > -1) {
                    textureFromCache.textureCacheIds.splice(index, 1);
                }
                delete TextureCache[texture];
                return textureFromCache;
            }
        }
        else if (texture && texture.textureCacheIds) {
            for (var i = 0; i < texture.textureCacheIds.length; ++i) {
                // Check that texture matches the one being passed in before deleting it from the cache.
                if (TextureCache[texture.textureCacheIds[i]] === texture) {
                    delete TextureCache[texture.textureCacheIds[i]];
                }
            }
            texture.textureCacheIds.length = 0;
            return texture;
        }
        return null;
    };
    Object.defineProperty(Texture.prototype, "resolution", {
        /**
         * Returns resolution of baseTexture
         *
         * @readonly
         */
        get: function () {
            return this.baseTexture.resolution;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Texture.prototype, "frame", {
        /**
         * The frame specifies the region of the base texture that this texture uses.
         * Please call `updateUvs()` after you change coordinates of `frame` manually.
         */
        get: function () {
            return this._frame;
        },
        set: function (frame) {
            this._frame = frame;
            this.noFrame = false;
            var x = frame.x, y = frame.y, width = frame.width, height = frame.height;
            var xNotFit = x + width > this.baseTexture.width;
            var yNotFit = y + height > this.baseTexture.height;
            if (xNotFit || yNotFit) {
                var relationship = xNotFit && yNotFit ? 'and' : 'or';
                var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width;
                var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height;
                throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: '
                    + (errorX + " " + relationship + " " + errorY));
            }
            this.valid = width && height && this.baseTexture.valid;
            if (!this.trim && !this.rotate) {
                this.orig = frame;
            }
            if (this.valid) {
                this.updateUvs();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Texture.prototype, "rotate", {
        /**
         * Indicates whether the texture is rotated inside the atlas
         * set to 2 to compensate for texture packer rotation
         * set to 6 to compensate for spine packer rotation
         * can be used to rotate or mirror sprites
         * See {@link PIXI.groupD8} for explanation
         */
        get: function () {
            return this._rotate;
        },
        set: function (rotate) {
            this._rotate = rotate;
            if (this.valid) {
                this.updateUvs();
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Texture.prototype, "width", {
        /** The width of the Texture in pixels. */
        get: function () {
            return this.orig.width;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Texture.prototype, "height", {
        /** The height of the Texture in pixels. */
        get: function () {
            return this.orig.height;
        },
        enumerable: false,
        configurable: true
    });
    /** Utility function for BaseTexture|Texture cast. */
    Texture.prototype.castToBaseTexture = function () {
        return this.baseTexture;
    };
    return Texture;
}((eventemitter3_default())));
function createWhiteTexture() {
    var canvas = document.createElement('canvas');
    canvas.width = 16;
    canvas.height = 16;
    var context = canvas.getContext('2d');
    context.fillStyle = 'white';
    context.fillRect(0, 0, 16, 16);
    return new Texture(new BaseTexture(new CanvasResource(canvas)));
}
function removeAllHandlers(tex) {
    tex.destroy = function _emptyDestroy() { };
    tex.on = function _emptyOn() { };
    tex.once = function _emptyOnce() { };
    tex.emit = function _emptyEmit() { };
}
/**
 * An empty texture, used often to not have to create multiple empty textures.
 * Can not be destroyed.
 *
 * @static
 * @constant
 * @member {PIXI.Texture}
 */
Texture.EMPTY = new Texture(new BaseTexture());
removeAllHandlers(Texture.EMPTY);
removeAllHandlers(Texture.EMPTY.baseTexture);
/**
 * A white texture of 16x16 size, used for graphics and other things
 * Can not be destroyed.
 *
 * @static
 * @constant
 * @member {PIXI.Texture}
 */
Texture.WHITE = createWhiteTexture();
removeAllHandlers(Texture.WHITE);
removeAllHandlers(Texture.WHITE.baseTexture);

/**
 * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
 *
 * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded
 * otherwise black rectangles will be drawn instead.
 *
 * __Hint-2__: The actual memory allocation will happen on first render.
 * You shouldn't create renderTextures each frame just to delete them after, try to reuse them.
 *
 * A RenderTexture takes a snapshot of any Display Object given to its render method. For example:
 *
 * ```js
 * let renderer = PIXI.autoDetectRenderer();
 * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 });
 * let sprite = PIXI.Sprite.from("spinObj_01.png");
 *
 * sprite.position.x = 800/2;
 * sprite.position.y = 600/2;
 * sprite.anchor.x = 0.5;
 * sprite.anchor.y = 0.5;
 *
 * renderer.render(sprite, {renderTexture});
 * ```
 * Note that you should not create a new renderer, but reuse the same one as the rest of the application.
 *
 * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0
 * you can clear the transform
 *
 * ```js
 *
 * sprite.setTransform()
 *
 * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 });
 *
 * renderer.render(sprite, {renderTexture});  // Renders to center of RenderTexture
 * ```
 *
 * @memberof PIXI
 */
var RenderTexture = /** @class */ (function (_super) {
    core_extends(RenderTexture, _super);
    /**
     * @param baseRenderTexture - The base texture object that this texture uses.
     * @param frame - The rectangle frame of the texture to show.
     */
    function RenderTexture(baseRenderTexture, frame) {
        var _this = _super.call(this, baseRenderTexture, frame) || this;
        _this.valid = true;
        _this.filterFrame = null;
        _this.filterPoolKey = null;
        _this.updateUvs();
        return _this;
    }
    Object.defineProperty(RenderTexture.prototype, "framebuffer", {
        /**
         * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast.
         *
         * @readonly
         */
        get: function () {
            return this.baseTexture.framebuffer;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RenderTexture.prototype, "multisample", {
        /**
         * Shortcut to `this.framebuffer.multisample`.
         *
         * @default PIXI.MSAA_QUALITY.NONE
         */
        get: function () {
            return this.framebuffer.multisample;
        },
        set: function (value) {
            this.framebuffer.multisample = value;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Resizes the RenderTexture.
     *
     * @param desiredWidth - The desired width to resize to.
     * @param desiredHeight - The desired height to resize to.
     * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well?
     */
    RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) {
        if (resizeBaseTexture === void 0) { resizeBaseTexture = true; }
        var resolution = this.baseTexture.resolution;
        var width = Math.round(desiredWidth * resolution) / resolution;
        var height = Math.round(desiredHeight * resolution) / resolution;
        // TODO - could be not required..
        this.valid = (width > 0 && height > 0);
        this._frame.width = this.orig.width = width;
        this._frame.height = this.orig.height = height;
        if (resizeBaseTexture) {
            this.baseTexture.resize(width, height);
        }
        this.updateUvs();
    };
    /**
     * Changes the resolution of baseTexture, but does not change framebuffer size.
     *
     * @param resolution - The new resolution to apply to RenderTexture
     */
    RenderTexture.prototype.setResolution = function (resolution) {
        var baseTexture = this.baseTexture;
        if (baseTexture.resolution === resolution) {
            return;
        }
        baseTexture.setResolution(resolution);
        this.resize(baseTexture.width, baseTexture.height, false);
    };
    RenderTexture.create = function (options) {
        var arguments$1 = arguments;

        var rest = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            rest[_i - 1] = arguments$1[_i];
        }
        // @deprecated fallback, old-style: create(width, height, scaleMode, resolution)
        if (typeof options === 'number') {
            deprecation('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.');
            /* eslint-disable prefer-rest-params */
            options = {
                width: options,
                height: rest[0],
                scaleMode: rest[1],
                resolution: rest[2],
            };
            /* eslint-enable prefer-rest-params */
        }
        return new RenderTexture(new BaseRenderTexture(options));
    };
    return RenderTexture;
}(Texture));

/**
 * Texture pool, used by FilterSystem and plugins.
 *
 * Stores collection of temporary pow2 or screen-sized renderTextures
 *
 * If you use custom RenderTexturePool for your filters, you can use methods
 * `getFilterTexture` and `returnFilterTexture` same as in
 *
 * @memberof PIXI
 */
var RenderTexturePool = /** @class */ (function () {
    /**
     * @param textureOptions - options that will be passed to BaseRenderTexture constructor
     * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values.
     */
    function RenderTexturePool(textureOptions) {
        this.texturePool = {};
        this.textureOptions = textureOptions || {};
        this.enableFullScreen = false;
        this._pixelsWidth = 0;
        this._pixelsHeight = 0;
    }
    /**
     * Creates texture with params that were specified in pool constructor.
     *
     * @param realWidth - Width of texture in pixels.
     * @param realHeight - Height of texture in pixels.
     * @param multisample - Number of samples of the framebuffer.
     */
    RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) {
        if (multisample === void 0) { multisample = constants_MSAA_QUALITY.NONE; }
        var baseRenderTexture = new BaseRenderTexture(Object.assign({
            width: realWidth,
            height: realHeight,
            resolution: 1,
            multisample: multisample,
        }, this.textureOptions));
        return new RenderTexture(baseRenderTexture);
    };
    /**
     * Gets a Power-of-Two render texture or fullScreen texture
     *
     * @param minWidth - The minimum width of the render texture.
     * @param minHeight - The minimum height of the render texture.
     * @param resolution - The resolution of the render texture.
     * @param multisample - Number of samples of the render texture.
     * @return The new render texture.
     */
    RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) {
        if (resolution === void 0) { resolution = 1; }
        if (multisample === void 0) { multisample = constants_MSAA_QUALITY.NONE; }
        var key;
        minWidth = Math.ceil((minWidth * resolution) - 1e-6);
        minHeight = Math.ceil((minHeight * resolution) - 1e-6);
        if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) {
            minWidth = nextPow2(minWidth);
            minHeight = nextPow2(minHeight);
            key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0;
            if (multisample > 1) {
                key += multisample * 0x100000000;
            }
        }
        else {
            key = multisample > 1 ? -multisample : -1;
        }
        if (!this.texturePool[key]) {
            this.texturePool[key] = [];
        }
        var renderTexture = this.texturePool[key].pop();
        if (!renderTexture) {
            renderTexture = this.createTexture(minWidth, minHeight, multisample);
        }
        renderTexture.filterPoolKey = key;
        renderTexture.setResolution(resolution);
        return renderTexture;
    };
    /**
     * Gets extra texture of the same size as input renderTexture
     *
     * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)`
     *
     * @param input - renderTexture from which size and resolution will be copied
     * @param resolution - override resolution of the renderTexture
     *  It overrides, it does not multiply
     * @param multisample - number of samples of the renderTexture
     * @returns
     */
    RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) {
        var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || constants_MSAA_QUALITY.NONE);
        filterTexture.filterFrame = input.filterFrame;
        return filterTexture;
    };
    /**
     * Place a render texture back into the pool.
     *
     * @param renderTexture - The renderTexture to free
     */
    RenderTexturePool.prototype.returnTexture = function (renderTexture) {
        var key = renderTexture.filterPoolKey;
        renderTexture.filterFrame = null;
        this.texturePool[key].push(renderTexture);
    };
    /**
     * Alias for returnTexture, to be compliant with FilterSystem interface.
     *
     * @param renderTexture - The renderTexture to free
     */
    RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) {
        this.returnTexture(renderTexture);
    };
    /**
     * Clears the pool.
     *
     * @param destroyTextures - Destroy all stored textures.
     */
    RenderTexturePool.prototype.clear = function (destroyTextures) {
        destroyTextures = destroyTextures !== false;
        if (destroyTextures) {
            for (var i in this.texturePool) {
                var textures = this.texturePool[i];
                if (textures) {
                    for (var j = 0; j < textures.length; j++) {
                        textures[j].destroy(true);
                    }
                }
            }
        }
        this.texturePool = {};
    };
    /**
     * If screen size was changed, drops all screen-sized textures,
     * sets new screen size, sets `enableFullScreen` to true
     *
     * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen`
     *
     * @param size - Initial size of screen.
     */
    RenderTexturePool.prototype.setScreenSize = function (size) {
        if (size.width === this._pixelsWidth
            && size.height === this._pixelsHeight) {
            return;
        }
        this.enableFullScreen = size.width > 0 && size.height > 0;
        for (var i in this.texturePool) {
            if (!(Number(i) < 0)) {
                continue;
            }
            var textures = this.texturePool[i];
            if (textures) {
                for (var j = 0; j < textures.length; j++) {
                    textures[j].destroy(true);
                }
            }
            this.texturePool[i] = [];
        }
        this._pixelsWidth = size.width;
        this._pixelsHeight = size.height;
    };
    /**
     * Key that is used to store fullscreen renderTextures in a pool
     *
     * @constant
     */
    RenderTexturePool.SCREEN_KEY = -1;
    return RenderTexturePool;
}());

/* eslint-disable max-len */
/**
 * Holds the information for a single attribute structure required to render geometry.
 *
 * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer}
 * This can include anything from positions, uvs, normals, colors etc.
 *
 * @memberof PIXI
 */
var Attribute = /** @class */ (function () {
    /**
     * @param buffer - the id of the buffer that this attribute will look for
     * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2.
     * @param normalized - should the data be normalized.
     * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available
     * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
     * @param [start=0] - How far into the array to start reading values (used for interleaving data)
     * @param [instance=false] - Whether the geometry is instanced.
     */
    function Attribute(buffer, size, normalized, type, stride, start, instance) {
        if (size === void 0) { size = 0; }
        if (normalized === void 0) { normalized = false; }
        if (type === void 0) { type = constants_TYPES.FLOAT; }
        this.buffer = buffer;
        this.size = size;
        this.normalized = normalized;
        this.type = type;
        this.stride = stride;
        this.start = start;
        this.instance = instance;
    }
    /** Destroys the Attribute. */
    Attribute.prototype.destroy = function () {
        this.buffer = null;
    };
    /**
     * Helper function that creates an Attribute based on the information provided
     *
     * @param buffer - the id of the buffer that this attribute will look for
     * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
     * @param [normalized=false] - should the data be normalized.
     * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available
     * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
     * @returns - A new {@link PIXI.Attribute} based on the information provided
     */
    Attribute.from = function (buffer, size, normalized, type, stride) {
        return new Attribute(buffer, size, normalized, type, stride);
    };
    return Attribute;
}());

var UID = 0;
/**
 * A wrapper for data so that it can be used and uploaded by WebGL
 *
 * @memberof PIXI
 */
var Buffer = /** @class */ (function () {
    /**
     * @param {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} data - the data to store in the buffer.
     * @param _static - `true` for static buffer
     * @param index - `true` for index buffer
     */
    function Buffer(data, _static, index) {
        if (_static === void 0) { _static = true; }
        if (index === void 0) { index = false; }
        this.data = (data || new Float32Array(1));
        this._glBuffers = {};
        this._updateID = 0;
        this.index = index;
        this.static = _static;
        this.id = UID++;
        this.disposeRunner = new Runner('disposeBuffer');
    }
    // TODO could explore flagging only a partial upload?
    /**
     * Flags this buffer as requiring an upload to the GPU.
     * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView|number[]} [data] - the data to update in the buffer.
     */
    Buffer.prototype.update = function (data) {
        if (data instanceof Array) {
            data = new Float32Array(data);
        }
        this.data = data || this.data;
        this._updateID++;
    };
    /** Disposes WebGL resources that are connected to this geometry. */
    Buffer.prototype.dispose = function () {
        this.disposeRunner.emit(this, false);
    };
    /** Destroys the buffer. */
    Buffer.prototype.destroy = function () {
        this.dispose();
        this.data = null;
    };
    Object.defineProperty(Buffer.prototype, "index", {
        get: function () {
            return this.type === constants_BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
        },
        /**
         * Flags whether this is an index buffer.
         *
         * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make
         * the buffer of type `ARRAY_BUFFER`.
         *
         * For backwards compatibility.
         */
        set: function (value) {
            this.type = value ? constants_BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : constants_BUFFER_TYPE.ARRAY_BUFFER;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Helper function that creates a buffer based on an array or TypedArray
     *
     * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array.
     * @return - A new Buffer based on the data provided.
     */
    Buffer.from = function (data) {
        if (data instanceof Array) {
            data = new Float32Array(data);
        }
        return new Buffer(data);
    };
    return Buffer;
}());

/* eslint-disable object-shorthand */
var core_map = {
    Float32Array: Float32Array,
    Uint32Array: Uint32Array,
    Int32Array: Int32Array,
    Uint8Array: Uint8Array,
};
function core_interleaveTypedArrays(arrays, sizes) {
    var outSize = 0;
    var stride = 0;
    var views = {};
    for (var i = 0; i < arrays.length; i++) {
        stride += sizes[i];
        outSize += arrays[i].length;
    }
    var buffer = new ArrayBuffer(outSize * 4);
    var out = null;
    var littleOffset = 0;
    for (var i = 0; i < arrays.length; i++) {
        var size = sizes[i];
        var array = arrays[i];
        var type = getBufferType(array);
        if (!views[type]) {
            views[type] = new core_map[type](buffer);
        }
        out = views[type];
        for (var j = 0; j < array.length; j++) {
            var indexStart = ((j / size | 0) * stride) + littleOffset;
            var index = j % size;
            out[indexStart + index] = array[j];
        }
        littleOffset += size;
    }
    return new Float32Array(buffer);
}

var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 };
var UID$1 = 0;
/* eslint-disable object-shorthand */
var map$1 = {
    Float32Array: Float32Array,
    Uint32Array: Uint32Array,
    Int32Array: Int32Array,
    Uint8Array: Uint8Array,
    Uint16Array: Uint16Array,
};
/* eslint-disable max-len */
/**
 * The Geometry represents a model. It consists of two components:
 * - GeometryStyle - The structure of the model such as the attributes layout
 * - GeometryData - the data of the model - this consists of buffers.
 * This can include anything from positions, uvs, normals, colors etc.
 *
 * Geometry can be defined without passing in a style or data if required (thats how I prefer!)
 *
 * ```js
 * let geometry = new PIXI.Geometry();
 *
 * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);
 * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2)
 * geometry.addIndex([0,1,2,1,3,2])
 * ```
 *
 * @memberof PIXI
 */
var Geometry = /** @class */ (function () {
    /**
     * @param buffers - An array of buffers. optional.
     * @param attributes - Of the geometry, optional structure of the attributes layout
     */
    function Geometry(buffers, attributes) {
        if (buffers === void 0) { buffers = []; }
        if (attributes === void 0) { attributes = {}; }
        this.buffers = buffers;
        this.indexBuffer = null;
        this.attributes = attributes;
        this.glVertexArrayObjects = {};
        this.id = UID$1++;
        this.instanced = false;
        this.instanceCount = 1;
        this.disposeRunner = new Runner('disposeGeometry');
        this.refCount = 0;
    }
    /**
     *
     * Adds an attribute to the geometry
     * Note: `stride` and `start` should be `undefined` if you dont know them, not 0!
     *
     * @param id - the name of the attribute (matching up to a shader)
     * @param {PIXI.Buffer|number[]} buffer - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it.
     * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
     * @param normalized - should the data be normalized.
     * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available
     * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
     * @param [start=0] - How far into the array to start reading values (used for interleaving data)
     * @param instance - Instancing flag
     * @return - Returns self, useful for chaining.
     */
    Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) {
        if (size === void 0) { size = 0; }
        if (normalized === void 0) { normalized = false; }
        if (instance === void 0) { instance = false; }
        if (!buffer) {
            throw new Error('You must pass a buffer when creating an attribute');
        }
        // check if this is a buffer!
        if (!(buffer instanceof Buffer)) {
            // its an array!
            if (buffer instanceof Array) {
                buffer = new Float32Array(buffer);
            }
            buffer = new Buffer(buffer);
        }
        var ids = id.split('|');
        if (ids.length > 1) {
            for (var i = 0; i < ids.length; i++) {
                this.addAttribute(ids[i], buffer, size, normalized, type);
            }
            return this;
        }
        var bufferIndex = this.buffers.indexOf(buffer);
        if (bufferIndex === -1) {
            this.buffers.push(buffer);
            bufferIndex = this.buffers.length - 1;
        }
        this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance);
        // assuming that if there is instanced data then this will be drawn with instancing!
        this.instanced = this.instanced || instance;
        return this;
    };
    /**
     * Returns the requested attribute.
     *
     * @param id - The name of the attribute required
     * @return - The attribute requested.
     */
    Geometry.prototype.getAttribute = function (id) {
        return this.attributes[id];
    };
    /**
     * Returns the requested buffer.
     *
     * @param id - The name of the buffer required.
     * @return - The buffer requested.
     */
    Geometry.prototype.getBuffer = function (id) {
        return this.buffers[this.getAttribute(id).buffer];
    };
    /**
    *
    * Adds an index buffer to the geometry
    * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer.
    *
    * @param {PIXI.Buffer|number[]} [buffer] - The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it.
    * @return - Returns self, useful for chaining.
    */
    Geometry.prototype.addIndex = function (buffer) {
        if (!(buffer instanceof Buffer)) {
            // its an array!
            if (buffer instanceof Array) {
                buffer = new Uint16Array(buffer);
            }
            buffer = new Buffer(buffer);
        }
        buffer.type = constants_BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
        this.indexBuffer = buffer;
        if (this.buffers.indexOf(buffer) === -1) {
            this.buffers.push(buffer);
        }
        return this;
    };
    /**
     * Returns the index buffer
     *
     * @return - The index buffer.
     */
    Geometry.prototype.getIndex = function () {
        return this.indexBuffer;
    };
    /**
     * This function modifies the structure so that all current attributes become interleaved into a single buffer
     * This can be useful if your model remains static as it offers a little performance boost
     *
     * @return - Returns self, useful for chaining.
     */
    Geometry.prototype.interleave = function () {
        // a simple check to see if buffers are already interleaved..
        if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer))
            { return this; }
        // assume already that no buffers are interleaved
        var arrays = [];
        var sizes = [];
        var interleavedBuffer = new Buffer();
        var i;
        for (i in this.attributes) {
            var attribute = this.attributes[i];
            var buffer = this.buffers[attribute.buffer];
            arrays.push(buffer.data);
            sizes.push((attribute.size * byteSizeMap[attribute.type]) / 4);
            attribute.buffer = 0;
        }
        interleavedBuffer.data = core_interleaveTypedArrays(arrays, sizes);
        for (i = 0; i < this.buffers.length; i++) {
            if (this.buffers[i] !== this.indexBuffer) {
                this.buffers[i].destroy();
            }
        }
        this.buffers = [interleavedBuffer];
        if (this.indexBuffer) {
            this.buffers.push(this.indexBuffer);
        }
        return this;
    };
    /** Get the size of the geometries, in vertices. */
    Geometry.prototype.getSize = function () {
        for (var i in this.attributes) {
            var attribute = this.attributes[i];
            var buffer = this.buffers[attribute.buffer];
            return buffer.data.length / ((attribute.stride / 4) || attribute.size);
        }
        return 0;
    };
    /** Disposes WebGL resources that are connected to this geometry. */
    Geometry.prototype.dispose = function () {
        this.disposeRunner.emit(this, false);
    };
    /** Destroys the geometry. */
    Geometry.prototype.destroy = function () {
        this.dispose();
        this.buffers = null;
        this.indexBuffer = null;
        this.attributes = null;
    };
    /**
     * Returns a clone of the geometry.
     *
     * @returns - A new clone of this geometry.
     */
    Geometry.prototype.clone = function () {
        var geometry = new Geometry();
        for (var i = 0; i < this.buffers.length; i++) {
            geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0));
        }
        for (var i in this.attributes) {
            var attrib = this.attributes[i];
            geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance);
        }
        if (this.indexBuffer) {
            geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)];
            geometry.indexBuffer.type = constants_BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
        }
        return geometry;
    };
    /**
     * Merges an array of geometries into a new single one.
     *
     * Geometry attribute styles must match for this operation to work.
     *
     * @param geometries - array of geometries to merge
     * @return - Shiny new geometry!
     */
    Geometry.merge = function (geometries) {
        // todo add a geometry check!
        // also a size check.. cant be too big!]
        var geometryOut = new Geometry();
        var arrays = [];
        var sizes = [];
        var offsets = [];
        var geometry;
        // pass one.. get sizes..
        for (var i = 0; i < geometries.length; i++) {
            geometry = geometries[i];
            for (var j = 0; j < geometry.buffers.length; j++) {
                sizes[j] = sizes[j] || 0;
                sizes[j] += geometry.buffers[j].data.length;
                offsets[j] = 0;
            }
        }
        // build the correct size arrays..
        for (var i = 0; i < geometry.buffers.length; i++) {
            // TODO types!
            arrays[i] = new map$1[getBufferType(geometry.buffers[i].data)](sizes[i]);
            geometryOut.buffers[i] = new Buffer(arrays[i]);
        }
        // pass to set data..
        for (var i = 0; i < geometries.length; i++) {
            geometry = geometries[i];
            for (var j = 0; j < geometry.buffers.length; j++) {
                arrays[j].set(geometry.buffers[j].data, offsets[j]);
                offsets[j] += geometry.buffers[j].data.length;
            }
        }
        geometryOut.attributes = geometry.attributes;
        if (geometry.indexBuffer) {
            geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)];
            geometryOut.indexBuffer.type = constants_BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
            var offset = 0;
            var stride = 0;
            var offset2 = 0;
            var bufferIndexToCount = 0;
            // get a buffer
            for (var i = 0; i < geometry.buffers.length; i++) {
                if (geometry.buffers[i] !== geometry.indexBuffer) {
                    bufferIndexToCount = i;
                    break;
                }
            }
            // figure out the stride of one buffer..
            for (var i in geometry.attributes) {
                var attribute = geometry.attributes[i];
                if ((attribute.buffer | 0) === bufferIndexToCount) {
                    stride += ((attribute.size * byteSizeMap[attribute.type]) / 4);
                }
            }
            // time to off set all indexes..
            for (var i = 0; i < geometries.length; i++) {
                var indexBufferData = geometries[i].indexBuffer.data;
                for (var j = 0; j < indexBufferData.length; j++) {
                    geometryOut.indexBuffer.data[j + offset2] += offset;
                }
                offset += geometries[i].buffers[bufferIndexToCount].data.length / (stride);
                offset2 += indexBufferData.length;
            }
        }
        return geometryOut;
    };
    return Geometry;
}());

/**
 * Helper class to create a quad
 *
 * @memberof PIXI
 */
var Quad = /** @class */ (function (_super) {
    core_extends(Quad, _super);
    function Quad() {
        var _this = _super.call(this) || this;
        _this.addAttribute('aVertexPosition', new Float32Array([
            0, 0,
            1, 0,
            1, 1,
            0, 1 ]))
            .addIndex([0, 1, 3, 2]);
        return _this;
    }
    return Quad;
}(Geometry));

/**
 * Helper class to create a quad with uvs like in v4
 *
 * @memberof PIXI
 */
var QuadUv = /** @class */ (function (_super) {
    core_extends(QuadUv, _super);
    function QuadUv() {
        var _this = _super.call(this) || this;
        _this.vertices = new Float32Array([
            -1, -1,
            1, -1,
            1, 1,
            -1, 1 ]);
        _this.uvs = new Float32Array([
            0, 0,
            1, 0,
            1, 1,
            0, 1 ]);
        _this.vertexBuffer = new Buffer(_this.vertices);
        _this.uvBuffer = new Buffer(_this.uvs);
        _this.addAttribute('aVertexPosition', _this.vertexBuffer)
            .addAttribute('aTextureCoord', _this.uvBuffer)
            .addIndex([0, 1, 2, 0, 2, 3]);
        return _this;
    }
    /**
     * Maps two Rectangle to the quad.
     *
     * @param targetTextureFrame - The first rectangle
     * @param destinationFrame - The second rectangle
     * @return - Returns itself.
     */
    QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) {
        var x = 0; // destinationFrame.x / targetTextureFrame.width;
        var y = 0; // destinationFrame.y / targetTextureFrame.height;
        this.uvs[0] = x;
        this.uvs[1] = y;
        this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width);
        this.uvs[3] = y;
        this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width);
        this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height);
        this.uvs[6] = x;
        this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height);
        x = destinationFrame.x;
        y = destinationFrame.y;
        this.vertices[0] = x;
        this.vertices[1] = y;
        this.vertices[2] = x + destinationFrame.width;
        this.vertices[3] = y;
        this.vertices[4] = x + destinationFrame.width;
        this.vertices[5] = y + destinationFrame.height;
        this.vertices[6] = x;
        this.vertices[7] = y + destinationFrame.height;
        this.invalidate();
        return this;
    };
    /**
     * Legacy upload method, just marks buffers dirty.
     *
     * @returns - Returns itself.
     */
    QuadUv.prototype.invalidate = function () {
        this.vertexBuffer._updateID++;
        this.uvBuffer._updateID++;
        return this;
    };
    return QuadUv;
}(Geometry));

var UID$2 = 0;
/**
 * Uniform group holds uniform map and some ID's for work
 *
 * `UniformGroup` has two modes:
 *
 * 1: Normal mode
 * Normal mode will upload the uniforms with individual function calls as required
 *
 * 2: Uniform buffer mode
 * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or
 * or a generic object that PixiJS will automatically map to a buffer for you.
 * For maximum benefits, make Ubo UniformGroups static, and only update them each frame.
 *
 * Rules of UBOs:
 * - UBOs only work with WebGL2, so make sure you have a fallback!
 * - Only floats are supported (including vec[2,3,4], mat[2,3,4])
 * - Samplers cannot be used in ubo's (a GPU limitation)
 * - You must ensure that the object you pass in exactly matches in the shader ubo structure.
 * Otherwise, weirdness will ensue!
 * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader.
 *
 * ```
 * // ubo in shader:
 * uniform myCoolData { // declaring a ubo..
 * mat4 uCoolMatrix;
 * float uFloatyMcFloatFace
 *
 *
 * // a new uniform buffer object..
 * const myCoolData = new UniformBufferGroup({
 *   uCoolMatrix: new Matrix(),
 *   uFloatyMcFloatFace: 23,
 * }}
 *
 * // build a shader...
 * const shader = Shader.from(srcVert, srcFrag, {
 *   myCoolData // name matches the ubo name in the shader. will be processed accordingly.
 * })
 *
 *  ```
 *
 * @memberof PIXI
 */
var UniformGroup = /** @class */ (function () {
    /**
     * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer.
     * @param isStatic - Uniforms wont be changed after creation.
     * @param isUbo - If true, will treat this uniform group as a uniform buffer object.
     */
    function UniformGroup(uniforms, isStatic, isUbo) {
        this.group = true;
        // lets generate this when the shader ?
        this.syncUniforms = {};
        this.dirtyId = 0;
        this.id = UID$2++;
        this.static = !!isStatic;
        this.ubo = !!isUbo;
        if (uniforms instanceof Buffer) {
            this.buffer = uniforms;
            this.buffer.type = constants_BUFFER_TYPE.UNIFORM_BUFFER;
            this.autoManage = false;
            this.ubo = true;
        }
        else {
            this.uniforms = uniforms;
            if (this.ubo) {
                this.buffer = new Buffer(new Float32Array(1));
                this.buffer.type = constants_BUFFER_TYPE.UNIFORM_BUFFER;
                this.autoManage = true;
            }
        }
    }
    UniformGroup.prototype.update = function () {
        this.dirtyId++;
        if (!this.autoManage && this.buffer) {
            this.buffer.update();
        }
    };
    UniformGroup.prototype.add = function (name, uniforms, _static) {
        if (!this.ubo) {
            this.uniforms[name] = new UniformGroup(uniforms, _static);
        }
        else {
            // eslint-disable-next-line max-len
            throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them');
        }
    };
    UniformGroup.from = function (uniforms, _static, _ubo) {
        return new UniformGroup(uniforms, _static, _ubo);
    };
    /**
     * A short hand function for creating a static UBO UniformGroup.
     *
     * @param uniforms - the ubo item
     * @param _static - should this be updated each time it is used? defaults to true here!
     */
    UniformGroup.uboFrom = function (uniforms, _static) {
        return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true);
    };
    return UniformGroup;
}());

/**
 * System plugin to the renderer to manage filter states.
 *
 * @ignore
 */
var FilterState = /** @class */ (function () {
    function FilterState() {
        this.renderTexture = null;
        this.target = null;
        this.legacy = false;
        this.resolution = 1;
        this.multisample = constants_MSAA_QUALITY.NONE;
        // next three fields are created only for root
        // re-assigned for everything else
        this.sourceFrame = new Rectangle();
        this.destinationFrame = new Rectangle();
        this.bindingSourceFrame = new Rectangle();
        this.bindingDestinationFrame = new Rectangle();
        this.filters = [];
        this.transform = null;
    }
    /** Clears the state */
    FilterState.prototype.clear = function () {
        this.target = null;
        this.filters = null;
        this.renderTexture = null;
    };
    return FilterState;
}());

var core_tempPoints = [new Point(), new Point(), new Point(), new Point()];
var tempMatrix = new Matrix();
/**
 * System plugin to the renderer to manage filters.
 *
 * ## Pipeline
 *
 * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its
 * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target.
 *
 * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into
 * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called
 * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame`
 * in the final render-target.
 *
 * ## Usage
 *
 * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process:
 *
 * * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target.
 * * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents
 *      inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is
 *      illegal during an existing render cycle, and it may reset the filter system.
 * * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them
 *      serially and output to the bounds of the filter-target.
 *
 * @memberof PIXI
 */
var FilterSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this System works for.
     */
    function FilterSystem(renderer) {
        this.renderer = renderer;
        this.defaultFilterStack = [{}];
        this.texturePool = new RenderTexturePool();
        this.texturePool.setScreenSize(renderer.view);
        this.statePool = [];
        this.quad = new Quad();
        this.quadUv = new QuadUv();
        this.tempRect = new Rectangle();
        this.activeState = {};
        this.globalUniforms = new UniformGroup({
            outputFrame: new Rectangle(),
            inputSize: new Float32Array(4),
            inputPixel: new Float32Array(4),
            inputClamp: new Float32Array(4),
            resolution: 1,
            // legacy variables
            filterArea: new Float32Array(4),
            filterClamp: new Float32Array(4),
        }, true);
        this.forceClear = false;
        this.useMaxPadding = false;
    }
    /**
     * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an
     * input render-texture for the rest of the filtering pipeline.
     *
     * @param {PIXI.DisplayObject} target - The target of the filter to render.
     * @param filters - The filters to apply.
     */
    FilterSystem.prototype.push = function (target, filters) {
        var _a, _b;
        var renderer = this.renderer;
        var filterStack = this.defaultFilterStack;
        var state = this.statePool.pop() || new FilterState();
        var renderTextureSystem = this.renderer.renderTexture;
        var resolution = filters[0].resolution;
        var multisample = filters[0].multisample;
        var padding = filters[0].padding;
        var autoFit = filters[0].autoFit;
        // We don't know whether it's a legacy filter until it was bound for the first time,
        // therefore we have to assume that it is if legacy is undefined.
        var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true;
        for (var i = 1; i < filters.length; i++) {
            var filter = filters[i];
            // let's use the lowest resolution
            resolution = Math.min(resolution, filter.resolution);
            // let's use the lowest number of samples
            multisample = Math.min(multisample, filter.multisample);
            // figure out the padding required for filters
            padding = this.useMaxPadding
                // old behavior: use largest amount of padding!
                ? Math.max(padding, filter.padding)
                // new behavior: sum the padding
                : padding + filter.padding;
            // only auto fit if all filters are autofit
            autoFit = autoFit && filter.autoFit;
            legacy = legacy || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true);
        }
        if (filterStack.length === 1) {
            this.defaultFilterStack[0].renderTexture = renderTextureSystem.current;
        }
        filterStack.push(state);
        state.resolution = resolution;
        state.multisample = multisample;
        state.legacy = legacy;
        state.target = target;
        state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true));
        state.sourceFrame.pad(padding);
        if (autoFit) {
            var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame);
            // Project source frame into world space (if projection is applied)
            if (renderer.projection.transform) {
                this.transformAABB(tempMatrix.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected);
            }
            state.sourceFrame.fit(sourceFrameProjected);
        }
        // Round sourceFrame in screen space based on render-texture.
        this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform);
        state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample);
        state.filters = filters;
        state.destinationFrame.width = state.renderTexture.width;
        state.destinationFrame.height = state.renderTexture.height;
        var destinationFrame = this.tempRect;
        destinationFrame.x = 0;
        destinationFrame.y = 0;
        destinationFrame.width = state.sourceFrame.width;
        destinationFrame.height = state.sourceFrame.height;
        state.renderTexture.filterFrame = state.sourceFrame;
        state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame);
        state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame);
        state.transform = renderer.projection.transform;
        renderer.projection.transform = null;
        renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame);
        renderer.framebuffer.clear(0, 0, 0, 0);
    };
    /** Pops off the filter and applies it. */
    FilterSystem.prototype.pop = function () {
        var filterStack = this.defaultFilterStack;
        var state = filterStack.pop();
        var filters = state.filters;
        this.activeState = state;
        var globalUniforms = this.globalUniforms.uniforms;
        globalUniforms.outputFrame = state.sourceFrame;
        globalUniforms.resolution = state.resolution;
        var inputSize = globalUniforms.inputSize;
        var inputPixel = globalUniforms.inputPixel;
        var inputClamp = globalUniforms.inputClamp;
        inputSize[0] = state.destinationFrame.width;
        inputSize[1] = state.destinationFrame.height;
        inputSize[2] = 1.0 / inputSize[0];
        inputSize[3] = 1.0 / inputSize[1];
        inputPixel[0] = Math.round(inputSize[0] * state.resolution);
        inputPixel[1] = Math.round(inputSize[1] * state.resolution);
        inputPixel[2] = 1.0 / inputPixel[0];
        inputPixel[3] = 1.0 / inputPixel[1];
        inputClamp[0] = 0.5 * inputPixel[2];
        inputClamp[1] = 0.5 * inputPixel[3];
        inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]);
        inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]);
        // only update the rect if its legacy..
        if (state.legacy) {
            var filterArea = globalUniforms.filterArea;
            filterArea[0] = state.destinationFrame.width;
            filterArea[1] = state.destinationFrame.height;
            filterArea[2] = state.sourceFrame.x;
            filterArea[3] = state.sourceFrame.y;
            globalUniforms.filterClamp = globalUniforms.inputClamp;
        }
        this.globalUniforms.update();
        var lastState = filterStack[filterStack.length - 1];
        this.renderer.framebuffer.blit();
        if (filters.length === 1) {
            filters[0].apply(this, state.renderTexture, lastState.renderTexture, constants_CLEAR_MODES.BLEND, state);
            this.returnFilterTexture(state.renderTexture);
        }
        else {
            var flip = state.renderTexture;
            var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution);
            flop.filterFrame = flip.filterFrame;
            var i = 0;
            for (i = 0; i < filters.length - 1; ++i) {
                if (i === 1 && state.multisample > 1) {
                    flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution);
                    flop.filterFrame = flip.filterFrame;
                }
                filters[i].apply(this, flip, flop, constants_CLEAR_MODES.CLEAR, state);
                var t = flip;
                flip = flop;
                flop = t;
            }
            filters[i].apply(this, flip, lastState.renderTexture, constants_CLEAR_MODES.BLEND, state);
            if (i > 1 && state.multisample > 1) {
                this.returnFilterTexture(state.renderTexture);
            }
            this.returnFilterTexture(flip);
            this.returnFilterTexture(flop);
        }
        // lastState.renderTexture is blitted when lastState is popped
        state.clear();
        this.statePool.push(state);
    };
    /**
     * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds.
     *
     * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack
     * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES}
     */
    FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) {
        if (clearMode === void 0) { clearMode = constants_CLEAR_MODES.CLEAR; }
        var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state;
        if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) {
            // Restore projection transform if rendering into the output render-target.
            this.renderer.projection.transform = this.activeState.transform;
        }
        else {
            // Prevent projection within filtering pipeline.
            this.renderer.projection.transform = null;
        }
        if (filterTexture && filterTexture.filterFrame) {
            var destinationFrame = this.tempRect;
            destinationFrame.x = 0;
            destinationFrame.y = 0;
            destinationFrame.width = filterTexture.filterFrame.width;
            destinationFrame.height = filterTexture.filterFrame.height;
            renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame);
        }
        else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) {
            renderTextureSystem.bind(filterTexture);
        }
        else {
            // Restore binding for output render-target.
            this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame);
        }
        // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending
        // is stored in the 0th bit of the state.
        var autoClear = (stateSystem.stateId & 1) || this.forceClear;
        if (clearMode === constants_CLEAR_MODES.CLEAR
            || (clearMode === constants_CLEAR_MODES.BLIT && autoClear)) {
            // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering
            // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur)
            // instead of clamping their arithmetic.
            this.renderer.framebuffer.clear(0, 0, 0, 0);
        }
    };
    /**
     * Draws a filter using the default rendering process.
     *
     * This should be called only by {@link Filter#apply}.
     *
     * @param filter - The filter to draw.
     * @param input - The input render target.
     * @param output - The target to output to.
     * @param clearMode - Should the output be cleared before rendering to it
     */
    FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) {
        var renderer = this.renderer;
        // Set state before binding, so bindAndClear gets the blend mode.
        renderer.state.set(filter.state);
        this.bindAndClear(output, clearMode);
        // set the uniforms..
        filter.uniforms.uSampler = input;
        filter.uniforms.filterGlobals = this.globalUniforms;
        // TODO make it so that the order of this does not matter..
        // because it does at the moment cos of global uniforms.
        // they need to get resynced
        renderer.shader.bind(filter);
        // check to see if the filter is a legacy one..
        filter.legacy = !!filter.program.attributeData.aTextureCoord;
        if (filter.legacy) {
            this.quadUv.map(input._frame, input.filterFrame);
            renderer.geometry.bind(this.quadUv);
            renderer.geometry.draw(constants_DRAW_MODES.TRIANGLES);
        }
        else {
            renderer.geometry.bind(this.quad);
            renderer.geometry.draw(constants_DRAW_MODES.TRIANGLE_STRIP);
        }
    };
    /**
     * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
     *
     * Use `outputMatrix * vTextureCoord` in the shader.
     *
     * @param outputMatrix - The matrix to output to.
     * @param {PIXI.Sprite} sprite - The sprite to map to.
     * @return The mapped matrix.
     */
    FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) {
        var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame;
        var orig = sprite._texture.orig;
        var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y);
        var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX);
        worldTransform.invert();
        mappedMatrix.prepend(worldTransform);
        mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height);
        mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y);
        return mappedMatrix;
    };
    /** Destroys this Filter System. */
    FilterSystem.prototype.destroy = function () {
        this.renderer = null;
        // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem
        this.texturePool.clear(false);
    };
    /**
     * Gets a Power-of-Two render texture or fullScreen texture
     *
     * @param minWidth - The minimum width of the render texture in real pixels.
     * @param minHeight - The minimum height of the render texture in real pixels.
     * @param resolution - The resolution of the render texture.
     * @param multisample - Number of samples of the render texture.
     * @return - The new render texture.
     */
    FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) {
        if (resolution === void 0) { resolution = 1; }
        if (multisample === void 0) { multisample = constants_MSAA_QUALITY.NONE; }
        return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample);
    };
    /**
     * Gets extra render texture to use inside current filter
     * To be compliant with older filters, you can use params in any order
     *
     * @param input - renderTexture from which size and resolution will be copied
     * @param resolution - override resolution of the renderTexture
     * @param multisample - number of samples of the renderTexture
     */
    FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) {
        if (typeof input === 'number') {
            var swap = input;
            input = resolution;
            resolution = swap;
        }
        input = input || this.activeState.renderTexture;
        var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || constants_MSAA_QUALITY.NONE);
        filterTexture.filterFrame = input.filterFrame;
        return filterTexture;
    };
    /**
     * Frees a render texture back into the pool.
     *
     * @param renderTexture - The renderTarget to free
     */
    FilterSystem.prototype.returnFilterTexture = function (renderTexture) {
        this.texturePool.returnTexture(renderTexture);
    };
    /** Empties the texture pool. */
    FilterSystem.prototype.emptyPool = function () {
        this.texturePool.clear(true);
    };
    /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */
    FilterSystem.prototype.resize = function () {
        this.texturePool.setScreenSize(this.renderer.view);
    };
    /**
     * @param matrix - first param
     * @param rect - second param
     */
    FilterSystem.prototype.transformAABB = function (matrix, rect) {
        var lt = core_tempPoints[0];
        var lb = core_tempPoints[1];
        var rt = core_tempPoints[2];
        var rb = core_tempPoints[3];
        lt.set(rect.left, rect.top);
        lb.set(rect.left, rect.bottom);
        rt.set(rect.right, rect.top);
        rb.set(rect.right, rect.bottom);
        matrix.apply(lt, lt);
        matrix.apply(lb, lb);
        matrix.apply(rt, rt);
        matrix.apply(rb, rb);
        var x0 = Math.min(lt.x, lb.x, rt.x, rb.x);
        var y0 = Math.min(lt.y, lb.y, rt.y, rb.y);
        var x1 = Math.max(lt.x, lb.x, rt.x, rb.x);
        var y1 = Math.max(lt.y, lb.y, rt.y, rb.y);
        rect.x = x0;
        rect.y = y0;
        rect.width = x1 - x0;
        rect.height = y1 - y0;
    };
    FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) {
        if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) {
            return;
        }
        if (transform) {
            var a = transform.a, b = transform.b, c = transform.c, d = transform.d;
            // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation
            // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0).
            if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4)
                && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) {
                return;
            }
        }
        transform = transform ? tempMatrix.copyFrom(transform) : tempMatrix.identity();
        // Get forward transform from world space to screen space
        transform
            .translate(-bindingSourceFrame.x, -bindingSourceFrame.y)
            .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height)
            .translate(bindingDestinationFrame.x, bindingDestinationFrame.y);
        // Convert frame to screen space
        this.transformAABB(transform, frame);
        // Round frame in screen space
        frame.ceil(resolution);
        // Project back into world space.
        this.transformAABB(transform.invert(), frame);
    };
    return FilterSystem;
}());

/**
 * Base for a common object renderer that can be used as a
 * system renderer plugin.
 *
 * @memberof PIXI
 */
var ObjectRenderer = /** @class */ (function () {
    /**
     * @param renderer - The renderer this manager works for.
     */
    function ObjectRenderer(renderer) {
        this.renderer = renderer;
    }
    /**
     * Stub method that should be used to empty the current
     * batch by rendering objects now.
     */
    ObjectRenderer.prototype.flush = function () {
        // flush!
    };
    /**
     * Generic destruction method that frees all resources. This
     * should be called by subclasses.
     */
    ObjectRenderer.prototype.destroy = function () {
        this.renderer = null;
    };
    /**
     * Stub method that initializes any state required before
     * rendering starts. It is different from the `prerender`
     * signal, which occurs every frame, in that it is called
     * whenever an object requests _this_ renderer specifically.
     */
    ObjectRenderer.prototype.start = function () {
        // set the shader..
    };
    /**
     * Stops the renderer. It should free up any state and
     * become dormant.
     */
    ObjectRenderer.prototype.stop = function () {
        this.flush();
    };
    /**
     * Keeps the object to render. It doesn't have to be
     * rendered immediately.
     *
     * @param {PIXI.DisplayObject} object - The object to render.
     */
    ObjectRenderer.prototype.render = function (_object) {
        // render the object
    };
    return ObjectRenderer;
}());

/**
 * System plugin to the renderer to manage batching.
 *
 * @memberof PIXI
 */
var BatchSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this System works for.
     */
    function BatchSystem(renderer) {
        this.renderer = renderer;
        this.emptyRenderer = new ObjectRenderer(renderer);
        this.currentRenderer = this.emptyRenderer;
    }
    /**
     * Changes the current renderer to the one given in parameter
     *
     * @param objectRenderer - The object renderer to use.
     */
    BatchSystem.prototype.setObjectRenderer = function (objectRenderer) {
        if (this.currentRenderer === objectRenderer) {
            return;
        }
        this.currentRenderer.stop();
        this.currentRenderer = objectRenderer;
        this.currentRenderer.start();
    };
    /**
     * This should be called if you wish to do some custom rendering
     * It will basically render anything that may be batched up such as sprites
     */
    BatchSystem.prototype.flush = function () {
        this.setObjectRenderer(this.emptyRenderer);
    };
    /**
     * Reset the system to an empty renderer
     */
    BatchSystem.prototype.reset = function () {
        this.setObjectRenderer(this.emptyRenderer);
    };
    /**
     * Handy function for batch renderers: copies bound textures in first maxTextures locations to array
     * sets actual _batchLocation for them
     *
     * @param arr - arr copy destination
     * @param maxTextures - number of copied elements
     */
    BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) {
        var boundTextures = this.renderer.texture.boundTextures;
        for (var i = maxTextures - 1; i >= 0; --i) {
            arr[i] = boundTextures[i] || null;
            if (arr[i]) {
                arr[i]._batchLocation = i;
            }
        }
    };
    /**
     * Assigns batch locations to textures in array based on boundTextures state.
     * All textures in texArray should have `_batchEnabled = _batchId`,
     * and their count should be less than `maxTextures`.
     *
     * @param texArray - textures to bound
     * @param boundTextures - current state of bound textures
     * @param batchId - marker for _batchEnabled param of textures in texArray
     * @param maxTextures - number of texture locations to manipulate
     */
    BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) {
        var elements = texArray.elements, ids = texArray.ids, count = texArray.count;
        var j = 0;
        for (var i = 0; i < count; i++) {
            var tex = elements[i];
            var loc = tex._batchLocation;
            if (loc >= 0 && loc < maxTextures
                && boundTextures[loc] === tex) {
                ids[i] = loc;
                continue;
            }
            while (j < maxTextures) {
                var bound = boundTextures[j];
                if (bound && bound._batchEnabled === batchId
                    && bound._batchLocation === j) {
                    j++;
                    continue;
                }
                ids[i] = j;
                tex._batchLocation = j;
                boundTextures[j] = tex;
                break;
            }
        }
    };
    /**
     * @ignore
     */
    BatchSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return BatchSystem;
}());

var CONTEXT_UID_COUNTER = 0;
/**
 * System plugin to the renderer to manage the context.
 *
 * @memberof PIXI
 */
var ContextSystem = /** @class */ (function () {
    /** @param renderer - The renderer this System works for. */
    function ContextSystem(renderer) {
        this.renderer = renderer;
        this.webGLVersion = 1;
        this.extensions = {};
        this.supports = {
            uint32Indices: false,
        };
        // Bind functions
        this.handleContextLost = this.handleContextLost.bind(this);
        this.handleContextRestored = this.handleContextRestored.bind(this);
        renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false);
        renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false);
    }
    Object.defineProperty(ContextSystem.prototype, "isLost", {
        /**
         * `true` if the context is lost
         *
         * @readonly
         */
        get: function () {
            return (!this.gl || this.gl.isContextLost());
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Handles the context change event.
     *
     * @param {WebGLRenderingContext} gl - New WebGL context.
     */
    ContextSystem.prototype.contextChange = function (gl) {
        this.gl = gl;
        this.renderer.gl = gl;
        this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++;
        // restore a context if it was previously lost
        if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) {
            gl.getExtension('WEBGL_lose_context').restoreContext();
        }
    };
    /**
     * Initializes the context.
     *
     * @protected
     * @param {WebGLRenderingContext} gl - WebGL context
     */
    ContextSystem.prototype.initFromContext = function (gl) {
        this.gl = gl;
        this.validateContext(gl);
        this.renderer.gl = gl;
        this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++;
        this.renderer.runners.contextChange.emit(gl);
    };
    /**
     * Initialize from context options
     *
     * @protected
     * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
     * @param {object} options - context attributes
     */
    ContextSystem.prototype.initFromOptions = function (options) {
        var gl = this.createContext(this.renderer.view, options);
        this.initFromContext(gl);
    };
    /**
     * Helper class to create a WebGL Context
     *
     * @param canvas - the canvas element that we will get the context from
     * @param options - An options object that gets passed in to the canvas element containing the
     *    context attributes
     * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext
     * @return {WebGLRenderingContext} the WebGL context
     */
    ContextSystem.prototype.createContext = function (canvas, options) {
        var gl;
        if (settings.PREFER_ENV >= constants_ENV.WEBGL2) {
            gl = canvas.getContext('webgl2', options);
        }
        if (gl) {
            this.webGLVersion = 2;
        }
        else {
            this.webGLVersion = 1;
            gl = canvas.getContext('webgl', options)
                || canvas.getContext('experimental-webgl', options);
            if (!gl) {
                // fail, not able to get a context
                throw new Error('This browser does not support WebGL. Try using the canvas renderer');
            }
        }
        this.gl = gl;
        this.getExtensions();
        return this.gl;
    };
    /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */
    ContextSystem.prototype.getExtensions = function () {
        // time to set up default extensions that Pixi uses.
        var gl = this.gl;
        var common = {
            anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'),
            floatTextureLinear: gl.getExtension('OES_texture_float_linear'),
            s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'),
            s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'),
            etc: gl.getExtension('WEBGL_compressed_texture_etc'),
            etc1: gl.getExtension('WEBGL_compressed_texture_etc1'),
            pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc')
                || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
            atc: gl.getExtension('WEBGL_compressed_texture_atc'),
            astc: gl.getExtension('WEBGL_compressed_texture_astc')
        };
        if (this.webGLVersion === 1) {
            Object.assign(this.extensions, common, {
                drawBuffers: gl.getExtension('WEBGL_draw_buffers'),
                depthTexture: gl.getExtension('WEBGL_depth_texture'),
                loseContext: gl.getExtension('WEBGL_lose_context'),
                vertexArrayObject: gl.getExtension('OES_vertex_array_object')
                    || gl.getExtension('MOZ_OES_vertex_array_object')
                    || gl.getExtension('WEBKIT_OES_vertex_array_object'),
                uint32ElementIndex: gl.getExtension('OES_element_index_uint'),
                // Floats and half-floats
                floatTexture: gl.getExtension('OES_texture_float'),
                floatTextureLinear: gl.getExtension('OES_texture_float_linear'),
                textureHalfFloat: gl.getExtension('OES_texture_half_float'),
                textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'),
            });
        }
        else if (this.webGLVersion === 2) {
            Object.assign(this.extensions, common, {
                // Floats and half-floats
                colorBufferFloat: gl.getExtension('EXT_color_buffer_float')
            });
        }
    };
    /**
     * Handles a lost webgl context
     *
     * @param {WebGLContextEvent} event - The context lost event.
     */
    ContextSystem.prototype.handleContextLost = function (event) {
        event.preventDefault();
    };
    /** Handles a restored webgl context. */
    ContextSystem.prototype.handleContextRestored = function () {
        this.renderer.runners.contextChange.emit(this.gl);
    };
    ContextSystem.prototype.destroy = function () {
        var view = this.renderer.view;
        this.renderer = null;
        // remove listeners
        view.removeEventListener('webglcontextlost', this.handleContextLost);
        view.removeEventListener('webglcontextrestored', this.handleContextRestored);
        this.gl.useProgram(null);
        if (this.extensions.loseContext) {
            this.extensions.loseContext.loseContext();
        }
    };
    /** Handle the post-render runner event. */
    ContextSystem.prototype.postrender = function () {
        if (this.renderer.renderingToScreen) {
            this.gl.flush();
        }
    };
    /**
     * Validate context.
     *
     * @param {WebGLRenderingContext} gl - Render context.
     */
    ContextSystem.prototype.validateContext = function (gl) {
        var attributes = gl.getContextAttributes();
        var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext;
        if (isWebGl2) {
            this.webGLVersion = 2;
        }
        // this is going to be fairly simple for now.. but at least we have room to grow!
        if (!attributes.stencil) {
            /* eslint-disable max-len, no-console */
            console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly');
            /* eslint-enable max-len, no-console */
        }
        var hasuint32 = isWebGl2 || !!gl.getExtension('OES_element_index_uint');
        this.supports.uint32Indices = hasuint32;
        if (!hasuint32) {
            /* eslint-disable max-len, no-console */
            console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly');
            /* eslint-enable max-len, no-console */
        }
    };
    return ContextSystem;
}());

/**
 * Internal framebuffer for WebGL context.
 *
 * @memberof PIXI
 */
var GLFramebuffer = /** @class */ (function () {
    function GLFramebuffer(framebuffer) {
        this.framebuffer = framebuffer;
        this.stencil = null;
        this.dirtyId = -1;
        this.dirtyFormat = -1;
        this.dirtySize = -1;
        this.multisample = constants_MSAA_QUALITY.NONE;
        this.msaaBuffer = null;
        this.blitFramebuffer = null;
        this.mipLevel = 0;
    }
    return GLFramebuffer;
}());

var tempRectangle = new Rectangle();
/**
 * System plugin to the renderer to manage framebuffers.
 *
 * @memberof PIXI
 */
var FramebufferSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this System works for.
     */
    function FramebufferSystem(renderer) {
        this.renderer = renderer;
        this.managedFramebuffers = [];
        this.unknownFramebuffer = new Framebuffer(10, 10);
        this.msaaSamples = null;
    }
    /** Sets up the renderer context and necessary buffers. */
    FramebufferSystem.prototype.contextChange = function () {
        var gl = this.gl = this.renderer.gl;
        this.CONTEXT_UID = this.renderer.CONTEXT_UID;
        this.current = this.unknownFramebuffer;
        this.viewport = new Rectangle();
        this.hasMRT = true;
        this.writeDepthTexture = true;
        this.disposeAll(true);
        // webgl2
        if (this.renderer.context.webGLVersion === 1) {
            // webgl 1!
            var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers;
            var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture;
            if (settings.PREFER_ENV === constants_ENV.WEBGL_LEGACY) {
                nativeDrawBuffersExtension_1 = null;
                nativeDepthTextureExtension = null;
            }
            if (nativeDrawBuffersExtension_1) {
                gl.drawBuffers = function (activeTextures) {
                    return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures);
                };
            }
            else {
                this.hasMRT = false;
                gl.drawBuffers = function () {
                    // empty
                };
            }
            if (!nativeDepthTextureExtension) {
                this.writeDepthTexture = false;
            }
        }
        else {
            // WebGL2
            // cache possible MSAA samples
            this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES);
        }
    };
    /**
     * Bind a framebuffer.
     *
     * @param framebuffer
     * @param frame - frame, default is framebuffer size
     * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0
     */
    FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) {
        if (mipLevel === void 0) { mipLevel = 0; }
        var gl = this.gl;
        if (framebuffer) {
            // TODO caching layer!
            var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer);
            if (this.current !== framebuffer) {
                this.current = framebuffer;
                gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer);
            }
            // make sure all textures are unbound..
            if (fbo.mipLevel !== mipLevel) {
                framebuffer.dirtyId++;
                framebuffer.dirtyFormat++;
                fbo.mipLevel = mipLevel;
            }
            // now check for updates...
            if (fbo.dirtyId !== framebuffer.dirtyId) {
                fbo.dirtyId = framebuffer.dirtyId;
                if (fbo.dirtyFormat !== framebuffer.dirtyFormat) {
                    fbo.dirtyFormat = framebuffer.dirtyFormat;
                    fbo.dirtySize = framebuffer.dirtySize;
                    this.updateFramebuffer(framebuffer, mipLevel);
                }
                else if (fbo.dirtySize !== framebuffer.dirtySize) {
                    fbo.dirtySize = framebuffer.dirtySize;
                    this.resizeFramebuffer(framebuffer);
                }
            }
            for (var i = 0; i < framebuffer.colorTextures.length; i++) {
                var tex = framebuffer.colorTextures[i];
                this.renderer.texture.unbind(tex.parentTextureArray || tex);
            }
            if (framebuffer.depthTexture) {
                this.renderer.texture.unbind(framebuffer.depthTexture);
            }
            if (frame) {
                var mipWidth = (frame.width >> mipLevel);
                var mipHeight = (frame.height >> mipLevel);
                var scale = mipWidth / frame.width;
                this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight);
            }
            else {
                var mipWidth = (framebuffer.width >> mipLevel);
                var mipHeight = (framebuffer.height >> mipLevel);
                this.setViewport(0, 0, mipWidth, mipHeight);
            }
        }
        else {
            if (this.current) {
                this.current = null;
                gl.bindFramebuffer(gl.FRAMEBUFFER, null);
            }
            if (frame) {
                this.setViewport(frame.x, frame.y, frame.width, frame.height);
            }
            else {
                this.setViewport(0, 0, this.renderer.width, this.renderer.height);
            }
        }
    };
    /**
     * Set the WebGLRenderingContext's viewport.
     *
     * @param x - X position of viewport
     * @param y - Y position of viewport
     * @param width - Width of viewport
     * @param height - Height of viewport
     */
    FramebufferSystem.prototype.setViewport = function (x, y, width, height) {
        var v = this.viewport;
        x = Math.round(x);
        y = Math.round(y);
        width = Math.round(width);
        height = Math.round(height);
        if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) {
            v.x = x;
            v.y = y;
            v.width = width;
            v.height = height;
            this.gl.viewport(x, y, width, height);
        }
    };
    Object.defineProperty(FramebufferSystem.prototype, "size", {
        /**
         * Get the size of the current width and height. Returns object with `width` and `height` values.
         *
         * @readonly
         */
        get: function () {
            if (this.current) {
                // TODO store temp
                return { x: 0, y: 0, width: this.current.width, height: this.current.height };
            }
            return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height };
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Clear the color of the context
     *
     * @param r - Red value from 0 to 1
     * @param g - Green value from 0 to 1
     * @param b - Blue value from 0 to 1
     * @param a - Alpha value from 0 to 1
     * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks
     *  that indicate the buffers to be cleared, by default COLOR and DEPTH buffers.
     */
    FramebufferSystem.prototype.clear = function (r, g, b, a, mask) {
        if (mask === void 0) { mask = constants_BUFFER_BITS.COLOR | constants_BUFFER_BITS.DEPTH; }
        var gl = this.gl;
        // TODO clear color can be set only one right?
        gl.clearColor(r, g, b, a);
        gl.clear(mask);
    };
    /**
     * Initialize framebuffer for this context
     *
     * @protected
     * @param framebuffer
     * @returns - created GLFramebuffer
     */
    FramebufferSystem.prototype.initFramebuffer = function (framebuffer) {
        var gl = this.gl;
        var fbo = new GLFramebuffer(gl.createFramebuffer());
        fbo.multisample = this.detectSamples(framebuffer.multisample);
        framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo;
        this.managedFramebuffers.push(framebuffer);
        framebuffer.disposeRunner.add(this);
        return fbo;
    };
    /**
     * Resize the framebuffer
     *
     * @protected
     */
    FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) {
        var gl = this.gl;
        var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
        if (fbo.msaaBuffer) {
            gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer);
            gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height);
        }
        if (fbo.stencil) {
            gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
            if (fbo.msaaBuffer) {
                gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height);
            }
            else {
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
            }
        }
        var colorTextures = framebuffer.colorTextures;
        var count = colorTextures.length;
        if (!gl.drawBuffers) {
            count = Math.min(count, 1);
        }
        for (var i = 0; i < count; i++) {
            var texture = colorTextures[i];
            var parentTexture = texture.parentTextureArray || texture;
            this.renderer.texture.bind(parentTexture, 0);
        }
        if (framebuffer.depthTexture && this.writeDepthTexture) {
            this.renderer.texture.bind(framebuffer.depthTexture, 0);
        }
    };
    /**
     * Update the framebuffer
     *
     * @protected
     */
    FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) {
        var gl = this.gl;
        var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
        // bind the color texture
        var colorTextures = framebuffer.colorTextures;
        var count = colorTextures.length;
        if (!gl.drawBuffers) {
            count = Math.min(count, 1);
        }
        if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) {
            fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer();
            gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer);
            gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height);
            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer);
        }
        else if (fbo.msaaBuffer) {
            gl.deleteRenderbuffer(fbo.msaaBuffer);
            fbo.msaaBuffer = null;
            if (fbo.blitFramebuffer) {
                fbo.blitFramebuffer.dispose();
                fbo.blitFramebuffer = null;
            }
        }
        var activeTextures = [];
        for (var i = 0; i < count; i++) {
            var texture = colorTextures[i];
            var parentTexture = texture.parentTextureArray || texture;
            this.renderer.texture.bind(parentTexture, 0);
            if (i === 0 && fbo.msaaBuffer) {
                continue;
            }
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel);
            activeTextures.push(gl.COLOR_ATTACHMENT0 + i);
        }
        if (activeTextures.length > 1) {
            gl.drawBuffers(activeTextures);
        }
        if (framebuffer.depthTexture) {
            var writeDepthTexture = this.writeDepthTexture;
            if (writeDepthTexture) {
                var depthTexture = framebuffer.depthTexture;
                this.renderer.texture.bind(depthTexture, 0);
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel);
            }
        }
        if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) {
            fbo.stencil = fbo.stencil || gl.createRenderbuffer();
            gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
            if (fbo.msaaBuffer) {
                gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height);
            }
            else {
                gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
            }
            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil);
        }
        else if (fbo.stencil) {
            gl.deleteRenderbuffer(fbo.stencil);
            fbo.stencil = null;
        }
    };
    /** Returns true if the frame buffer can be multisampled. */
    FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) {
        return this.renderer.context.webGLVersion !== 1
            && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture;
    };
    /**
     * Detects number of samples that is not more than a param but as close to it as possible
     *
     * @param samples - number of samples
     * @returns - recommended number of samples
     */
    FramebufferSystem.prototype.detectSamples = function (samples) {
        var msaaSamples = this.msaaSamples;
        var res = constants_MSAA_QUALITY.NONE;
        if (samples <= 1 || msaaSamples === null) {
            return res;
        }
        for (var i = 0; i < msaaSamples.length; i++) {
            if (msaaSamples[i] <= samples) {
                res = msaaSamples[i];
                break;
            }
        }
        if (res === 1) {
            res = constants_MSAA_QUALITY.NONE;
        }
        return res;
    };
    /**
     * Only works with WebGL2
     *
     * blits framebuffer to another of the same or bigger size
     * after that target framebuffer is bound
     *
     * Fails with WebGL warning if blits multisample framebuffer to different size
     *
     * @param framebuffer - by default it blits "into itself", from renderBuffer to texture.
     * @param sourcePixels - source rectangle in pixels
     * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels
     */
    FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) {
        var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
        if (renderer.context.webGLVersion !== 2) {
            return;
        }
        if (!current) {
            return;
        }
        var fbo = current.glFramebuffers[CONTEXT_UID];
        if (!fbo) {
            return;
        }
        if (!framebuffer) {
            if (!fbo.msaaBuffer) {
                return;
            }
            var colorTexture = current.colorTextures[0];
            if (!colorTexture) {
                return;
            }
            if (!fbo.blitFramebuffer) {
                fbo.blitFramebuffer = new Framebuffer(current.width, current.height);
                fbo.blitFramebuffer.addColorTexture(0, colorTexture);
            }
            framebuffer = fbo.blitFramebuffer;
            if (framebuffer.colorTextures[0] !== colorTexture) {
                framebuffer.colorTextures[0] = colorTexture;
                framebuffer.dirtyId++;
                framebuffer.dirtyFormat++;
            }
            if (framebuffer.width !== current.width || framebuffer.height !== current.height) {
                framebuffer.width = current.width;
                framebuffer.height = current.height;
                framebuffer.dirtyId++;
                framebuffer.dirtySize++;
            }
        }
        if (!sourcePixels) {
            sourcePixels = tempRectangle;
            sourcePixels.width = current.width;
            sourcePixels.height = current.height;
        }
        if (!destPixels) {
            destPixels = sourcePixels;
        }
        var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height;
        this.bind(framebuffer);
        gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer);
        gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR);
    };
    /**
     * Disposes framebuffer.
     *
     * @param framebuffer - framebuffer that has to be disposed of
     * @param contextLost - If context was lost, we suppress all delete function calls
     */
    FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) {
        var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
        var gl = this.gl;
        if (!fbo) {
            return;
        }
        delete framebuffer.glFramebuffers[this.CONTEXT_UID];
        var index = this.managedFramebuffers.indexOf(framebuffer);
        if (index >= 0) {
            this.managedFramebuffers.splice(index, 1);
        }
        framebuffer.disposeRunner.remove(this);
        if (!contextLost) {
            gl.deleteFramebuffer(fbo.framebuffer);
            if (fbo.msaaBuffer) {
                gl.deleteRenderbuffer(fbo.msaaBuffer);
            }
            if (fbo.stencil) {
                gl.deleteRenderbuffer(fbo.stencil);
            }
        }
        if (fbo.blitFramebuffer) {
            fbo.blitFramebuffer.dispose();
        }
    };
    /**
     * Disposes all framebuffers, but not textures bound to them.
     *
     * @param [contextLost=false] - If context was lost, we suppress all delete function calls
     */
    FramebufferSystem.prototype.disposeAll = function (contextLost) {
        var list = this.managedFramebuffers;
        this.managedFramebuffers = [];
        for (var i = 0; i < list.length; i++) {
            this.disposeFramebuffer(list[i], contextLost);
        }
    };
    /**
     * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before.
     * Used by MaskSystem, when its time to use stencil mask for Graphics element.
     *
     * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind.
     *
     * @private
     */
    FramebufferSystem.prototype.forceStencil = function () {
        var framebuffer = this.current;
        if (!framebuffer) {
            return;
        }
        var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
        if (!fbo || fbo.stencil) {
            return;
        }
        framebuffer.stencil = true;
        var w = framebuffer.width;
        var h = framebuffer.height;
        var gl = this.gl;
        var stencil = gl.createRenderbuffer();
        gl.bindRenderbuffer(gl.RENDERBUFFER, stencil);
        if (fbo.msaaBuffer) {
            gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h);
        }
        else {
            gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h);
        }
        fbo.stencil = stencil;
        gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil);
    };
    /**
     * Resets framebuffer stored state, binds screen framebuffer.
     *
     * Should be called before renderTexture reset().
     */
    FramebufferSystem.prototype.reset = function () {
        this.current = this.unknownFramebuffer;
        this.viewport = new Rectangle();
    };
    FramebufferSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return FramebufferSystem;
}());

var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 };
/**
 * System plugin to the renderer to manage geometry.
 *
 * @memberof PIXI
 */
var GeometrySystem = /** @class */ (function () {
    /** @param renderer - The renderer this System works for. */
    function GeometrySystem(renderer) {
        this.renderer = renderer;
        this._activeGeometry = null;
        this._activeVao = null;
        this.hasVao = true;
        this.hasInstance = true;
        this.canUseUInt32ElementIndex = false;
        this.managedGeometries = {};
    }
    /** Sets up the renderer context and necessary buffers. */
    GeometrySystem.prototype.contextChange = function () {
        this.disposeAll(true);
        var gl = this.gl = this.renderer.gl;
        var context = this.renderer.context;
        this.CONTEXT_UID = this.renderer.CONTEXT_UID;
        // webgl2
        if (context.webGLVersion !== 2) {
            // webgl 1!
            var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject;
            if (settings.PREFER_ENV === constants_ENV.WEBGL_LEGACY) {
                nativeVaoExtension_1 = null;
            }
            if (nativeVaoExtension_1) {
                gl.createVertexArray = function () {
                    return nativeVaoExtension_1.createVertexArrayOES();
                };
                gl.bindVertexArray = function (vao) {
                    return nativeVaoExtension_1.bindVertexArrayOES(vao);
                };
                gl.deleteVertexArray = function (vao) {
                    return nativeVaoExtension_1.deleteVertexArrayOES(vao);
                };
            }
            else {
                this.hasVao = false;
                gl.createVertexArray = function () {
                    return null;
                };
                gl.bindVertexArray = function () {
                    return null;
                };
                gl.deleteVertexArray = function () {
                    return null;
                };
            }
        }
        if (context.webGLVersion !== 2) {
            var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays');
            if (instanceExt_1) {
                gl.vertexAttribDivisor = function (a, b) {
                    return instanceExt_1.vertexAttribDivisorANGLE(a, b);
                };
                gl.drawElementsInstanced = function (a, b, c, d, e) {
                    return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e);
                };
                gl.drawArraysInstanced = function (a, b, c, d) {
                    return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d);
                };
            }
            else {
                this.hasInstance = false;
            }
        }
        this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex;
    };
    /**
     * Binds geometry so that is can be drawn. Creating a Vao if required
     *
     * @param geometry - Instance of geometry to bind.
     * @param shader - Instance of shader to use vao for.
     */
    GeometrySystem.prototype.bind = function (geometry, shader) {
        shader = shader || this.renderer.shader.shader;
        var gl = this.gl;
        // not sure the best way to address this..
        // currently different shaders require different VAOs for the same geometry
        // Still mulling over the best way to solve this one..
        // will likely need to modify the shader attribute locations at run time!
        var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID];
        var incRefCount = false;
        if (!vaos) {
            this.managedGeometries[geometry.id] = geometry;
            geometry.disposeRunner.add(this);
            geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {};
            incRefCount = true;
        }
        var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount);
        this._activeGeometry = geometry;
        if (this._activeVao !== vao) {
            this._activeVao = vao;
            if (this.hasVao) {
                gl.bindVertexArray(vao);
            }
            else {
                this.activateVao(geometry, shader.program);
            }
        }
        // TODO - optimise later!
        // don't need to loop through if nothing changed!
        // maybe look to add an 'autoupdate' to geometry?
        this.updateBuffers();
    };
    /** Reset and unbind any active VAO and geometry. */
    GeometrySystem.prototype.reset = function () {
        this.unbind();
    };
    /** Update buffers of the currently bound geometry. */
    GeometrySystem.prototype.updateBuffers = function () {
        var geometry = this._activeGeometry;
        var bufferSystem = this.renderer.buffer;
        for (var i = 0; i < geometry.buffers.length; i++) {
            var buffer = geometry.buffers[i];
            bufferSystem.update(buffer);
        }
    };
    /**
     * Check compatibility between a geometry and a program
     *
     * @param geometry - Geometry instance.
     * @param program - Program instance.
     */
    GeometrySystem.prototype.checkCompatibility = function (geometry, program) {
        // geometry must have at least all the attributes that the shader requires.
        var geometryAttributes = geometry.attributes;
        var shaderAttributes = program.attributeData;
        for (var j in shaderAttributes) {
            if (!geometryAttributes[j]) {
                throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute");
            }
        }
    };
    /**
     * Takes a geometry and program and generates a unique signature for them.
     *
     * @param geometry - To get signature from.
     * @param program - To test geometry against.
     * @return - Unique signature of the geometry and program
     */
    GeometrySystem.prototype.getSignature = function (geometry, program) {
        var attribs = geometry.attributes;
        var shaderAttributes = program.attributeData;
        var strings = ['g', geometry.id];
        for (var i in attribs) {
            if (shaderAttributes[i]) {
                strings.push(i, shaderAttributes[i].location);
            }
        }
        return strings.join('-');
    };
    /**
     * Creates or gets Vao with the same structure as the geometry and stores it on the geometry.
     * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the
     * attribute locations.
     *
     * @param geometry - Instance of geometry to to generate Vao for.
     * @param shader - Instance of the shader.
     * @param incRefCount - Increment refCount of all geometry buffers.
     */
    GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) {
        if (incRefCount === void 0) { incRefCount = true; }
        var gl = this.gl;
        var CONTEXT_UID = this.CONTEXT_UID;
        var bufferSystem = this.renderer.buffer;
        var program = shader.program;
        if (!program.glPrograms[CONTEXT_UID]) {
            this.renderer.shader.generateProgram(shader);
        }
        this.checkCompatibility(geometry, program);
        var signature = this.getSignature(geometry, program);
        var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID];
        var vao = vaoObjectHash[signature];
        if (vao) {
            // this will give us easy access to the vao
            vaoObjectHash[program.id] = vao;
            return vao;
        }
        var buffers = geometry.buffers;
        var attributes = geometry.attributes;
        var tempStride = {};
        var tempStart = {};
        for (var j in buffers) {
            tempStride[j] = 0;
            tempStart[j] = 0;
        }
        for (var j in attributes) {
            if (!attributes[j].size && program.attributeData[j]) {
                attributes[j].size = program.attributeData[j].size;
            }
            else if (!attributes[j].size) {
                console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line
            }
            tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap$1[attributes[j].type];
        }
        for (var j in attributes) {
            var attribute = attributes[j];
            var attribSize = attribute.size;
            if (attribute.stride === undefined) {
                if (tempStride[attribute.buffer] === attribSize * byteSizeMap$1[attribute.type]) {
                    attribute.stride = 0;
                }
                else {
                    attribute.stride = tempStride[attribute.buffer];
                }
            }
            if (attribute.start === undefined) {
                attribute.start = tempStart[attribute.buffer];
                tempStart[attribute.buffer] += attribSize * byteSizeMap$1[attribute.type];
            }
        }
        vao = gl.createVertexArray();
        gl.bindVertexArray(vao);
        // first update - and create the buffers!
        // only create a gl buffer if it actually gets
        for (var i = 0; i < buffers.length; i++) {
            var buffer = buffers[i];
            bufferSystem.bind(buffer);
            if (incRefCount) {
                buffer._glBuffers[CONTEXT_UID].refCount++;
            }
        }
        // TODO - maybe make this a data object?
        // lets wait to see if we need to first!
        this.activateVao(geometry, program);
        this._activeVao = vao;
        // add it to the cache!
        vaoObjectHash[program.id] = vao;
        vaoObjectHash[signature] = vao;
        return vao;
    };
    /**
     * Disposes geometry.
     *
     * @param geometry - Geometry with buffers. Only VAO will be disposed
     * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray
     */
    GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) {
        var _a;
        if (!this.managedGeometries[geometry.id]) {
            return;
        }
        delete this.managedGeometries[geometry.id];
        var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID];
        var gl = this.gl;
        var buffers = geometry.buffers;
        var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer;
        geometry.disposeRunner.remove(this);
        if (!vaos) {
            return;
        }
        // bufferSystem may have already been destroyed..
        // if this is the case, there is no need to destroy the geometry buffers...
        // they already have been!
        if (bufferSystem) {
            for (var i = 0; i < buffers.length; i++) {
                var buf = buffers[i]._glBuffers[this.CONTEXT_UID];
                // my be null as context may have changed right before the dispose is called
                if (buf) {
                    buf.refCount--;
                    if (buf.refCount === 0 && !contextLost) {
                        bufferSystem.dispose(buffers[i], contextLost);
                    }
                }
            }
        }
        if (!contextLost) {
            for (var vaoId in vaos) {
                // delete only signatures, everything else are copies
                if (vaoId[0] === 'g') {
                    var vao = vaos[vaoId];
                    if (this._activeVao === vao) {
                        this.unbind();
                    }
                    gl.deleteVertexArray(vao);
                }
            }
        }
        delete geometry.glVertexArrayObjects[this.CONTEXT_UID];
    };
    /**
     * Dispose all WebGL resources of all managed geometries.
     *
     * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls
     */
    GeometrySystem.prototype.disposeAll = function (contextLost) {
        var all = Object.keys(this.managedGeometries);
        for (var i = 0; i < all.length; i++) {
            this.disposeGeometry(this.managedGeometries[all[i]], contextLost);
        }
    };
    /**
     * Activate vertex array object.
     *
     * @param geometry - Geometry instance.
     * @param program - Shader program instance.
     */
    GeometrySystem.prototype.activateVao = function (geometry, program) {
        var gl = this.gl;
        var CONTEXT_UID = this.CONTEXT_UID;
        var bufferSystem = this.renderer.buffer;
        var buffers = geometry.buffers;
        var attributes = geometry.attributes;
        if (geometry.indexBuffer) {
            // first update the index buffer if we have one..
            bufferSystem.bind(geometry.indexBuffer);
        }
        var lastBuffer = null;
        // add a new one!
        for (var j in attributes) {
            var attribute = attributes[j];
            var buffer = buffers[attribute.buffer];
            var glBuffer = buffer._glBuffers[CONTEXT_UID];
            if (program.attributeData[j]) {
                if (lastBuffer !== glBuffer) {
                    bufferSystem.bind(buffer);
                    lastBuffer = glBuffer;
                }
                var location = program.attributeData[j].location;
                // TODO introduce state again
                // we can optimise this for older devices that have no VAOs
                gl.enableVertexAttribArray(location);
                gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start);
                if (attribute.instance) {
                    // TODO calculate instance count based of this...
                    if (this.hasInstance) {
                        gl.vertexAttribDivisor(location, 1);
                    }
                    else {
                        throw new Error('geometry error, GPU Instancing is not supported on this device');
                    }
                }
            }
        }
    };
    /**
     * Draws the currently bound geometry.
     *
     * @param type - The type primitive to render.
     * @param size - The number of elements to be rendered. If not specified, all vertices after the
     *  starting vertex will be drawn.
     * @param start - The starting vertex in the geometry to start drawing from. If not specified,
     *  drawing will start from the first vertex.
     * @param instanceCount - The number of instances of the set of elements to execute. If not specified,
     *  all instances will be drawn.
     */
    GeometrySystem.prototype.draw = function (type, size, start, instanceCount) {
        var gl = this.gl;
        var geometry = this._activeGeometry;
        // TODO.. this should not change so maybe cache the function?
        if (geometry.indexBuffer) {
            var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT;
            var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT;
            if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) {
                if (geometry.instanced) {
                    /* eslint-disable max-len */
                    gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1);
                    /* eslint-enable max-len */
                }
                else {
                    /* eslint-disable max-len */
                    gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize);
                    /* eslint-enable max-len */
                }
            }
            else {
                console.warn('unsupported index buffer type: uint32');
            }
        }
        else if (geometry.instanced) {
            // TODO need a better way to calculate size..
            gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1);
        }
        else {
            gl.drawArrays(type, start, size || geometry.getSize());
        }
        return this;
    };
    /** Unbind/reset everything. */
    GeometrySystem.prototype.unbind = function () {
        this.gl.bindVertexArray(null);
        this._activeVao = null;
        this._activeGeometry = null;
    };
    GeometrySystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return GeometrySystem;
}());

/**
 * Component for masked elements.
 *
 * Holds mask mode and temporary data about current mask.
 *
 * @memberof PIXI
 */
var MaskData = /** @class */ (function () {
    /**
     * Create MaskData
     *
     * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask
     */
    function MaskData(maskObject) {
        if (maskObject === void 0) { maskObject = null; }
        this.type = constants_MASK_TYPES.NONE;
        this.autoDetect = true;
        this.maskObject = maskObject || null;
        this.pooled = false;
        this.isMaskData = true;
        this.resolution = null;
        this.multisample = settings.FILTER_MULTISAMPLE;
        this.enabled = true;
        this._filters = null;
        this._stencilCounter = 0;
        this._scissorCounter = 0;
        this._scissorRect = null;
        this._scissorRectLocal = null;
        this._target = null;
    }
    Object.defineProperty(MaskData.prototype, "filter", {
        /**
         * The sprite mask filter.
         * If set to `null`, the default sprite mask filter is used.
         * @default null
         */
        get: function () {
            return this._filters ? this._filters[0] : null;
        },
        set: function (value) {
            if (value) {
                if (this._filters) {
                    this._filters[0] = value;
                }
                else {
                    this._filters = [value];
                }
            }
            else {
                this._filters = null;
            }
        },
        enumerable: false,
        configurable: true
    });
    /** Resets the mask data after popMask(). */
    MaskData.prototype.reset = function () {
        if (this.pooled) {
            this.maskObject = null;
            this.type = constants_MASK_TYPES.NONE;
            this.autoDetect = true;
        }
        this._target = null;
        this._scissorRectLocal = null;
    };
    /** Copies counters from maskData above, called from pushMask(). */
    MaskData.prototype.copyCountersOrReset = function (maskAbove) {
        if (maskAbove) {
            this._stencilCounter = maskAbove._stencilCounter;
            this._scissorCounter = maskAbove._scissorCounter;
            this._scissorRect = maskAbove._scissorRect;
        }
        else {
            this._stencilCounter = 0;
            this._scissorCounter = 0;
            this._scissorRect = null;
        }
    };
    return MaskData;
}());

/**
 * @private
 * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram}
 * @param {Number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
 * @param {string} src - The vertex shader source as an array of strings.
 * @return {WebGLShader} the shader
 */
function compileShader(gl, type, src) {
    var shader = gl.createShader(type);
    gl.shaderSource(shader, src);
    gl.compileShader(shader);
    return shader;
}

/**
 * will log a shader error highlighting the lines with the error
 * also will add numbers along the side.
 *
 * @param gl - the WebGLContext
 * @param shader - the shader to log errors for
 */
function logPrettyShaderError(gl, shader) {
    var shaderSrc = gl.getShaderSource(shader)
        .split('\n')
        .map(function (line, index) { return index + ": " + line; });
    var shaderLog = gl.getShaderInfoLog(shader);
    var splitShader = shaderLog.split('\n');
    var dedupe = {};
    var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); })
        .filter(function (n) {
        if (n && !dedupe[n]) {
            dedupe[n] = true;
            return true;
        }
        return false;
    });
    var logArgs = [''];
    lineNumbers.forEach(function (number) {
        shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c";
        logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px');
    });
    var fragmentSourceToLog = shaderSrc
        .join('\n');
    logArgs[0] = fragmentSourceToLog;
    console.error(shaderLog);
    // eslint-disable-next-line no-console
    console.groupCollapsed('click to view full shader code');
    console.warn.apply(console, logArgs);
    // eslint-disable-next-line no-console
    console.groupEnd();
}
/**
 *
 * logs out any program errors
 *
 * @param gl - The current WebGL context
 * @param program - the WebGL program to display errors for
 * @param vertexShader  - the fragment WebGL shader program
 * @param fragmentShader - the vertex WebGL shader program
 */
function logProgramError(gl, program, vertexShader, fragmentShader) {
    // if linking fails, then log and cleanup
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
            logPrettyShaderError(gl, vertexShader);
        }
        if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
            logPrettyShaderError(gl, fragmentShader);
        }
        console.error('PixiJS Error: Could not initialize shader.');
        // if there is a program info log, log it
        if (gl.getProgramInfoLog(program) !== '') {
            console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program));
        }
    }
}

function booleanArray(size) {
    var array = new Array(size);
    for (var i = 0; i < array.length; i++) {
        array[i] = false;
    }
    return array;
}
/**
 * @method defaultValue
 * @memberof PIXI.glCore.shader
 * @param {string} type - Type of value
 * @param {number} size
 * @private
 */
function defaultValue(type, size) {
    switch (type) {
        case 'float':
            return 0;
        case 'vec2':
            return new Float32Array(2 * size);
        case 'vec3':
            return new Float32Array(3 * size);
        case 'vec4':
            return new Float32Array(4 * size);
        case 'int':
        case 'uint':
        case 'sampler2D':
        case 'sampler2DArray':
            return 0;
        case 'ivec2':
            return new Int32Array(2 * size);
        case 'ivec3':
            return new Int32Array(3 * size);
        case 'ivec4':
            return new Int32Array(4 * size);
        case 'uvec2':
            return new Uint32Array(2 * size);
        case 'uvec3':
            return new Uint32Array(3 * size);
        case 'uvec4':
            return new Uint32Array(4 * size);
        case 'bool':
            return false;
        case 'bvec2':
            return booleanArray(2 * size);
        case 'bvec3':
            return booleanArray(3 * size);
        case 'bvec4':
            return booleanArray(4 * size);
        case 'mat2':
            return new Float32Array([1, 0,
                0, 1]);
        case 'mat3':
            return new Float32Array([1, 0, 0,
                0, 1, 0,
                0, 0, 1]);
        case 'mat4':
            return new Float32Array([1, 0, 0, 0,
                0, 1, 0, 0,
                0, 0, 1, 0,
                0, 0, 0, 1]);
    }
    return null;
}

var unknownContext = {};
var context = unknownContext;
/**
 * returns a little WebGL context to use for program inspection.
 *
 * @static
 * @private
 * @returns {WebGLRenderingContext} a gl context to test with
 */
function getTestContext() {
    if (context === unknownContext || (context && context.isContextLost())) {
        var canvas = document.createElement('canvas');
        var gl = void 0;
        if (settings.PREFER_ENV >= constants_ENV.WEBGL2) {
            gl = canvas.getContext('webgl2', {});
        }
        if (!gl) {
            gl = canvas.getContext('webgl', {})
                || canvas.getContext('experimental-webgl', {});
            if (!gl) {
                // fail, not able to get a context
                gl = null;
            }
            else {
                // for shader testing..
                gl.getExtension('WEBGL_draw_buffers');
            }
        }
        context = gl;
    }
    return context;
}

var maxFragmentPrecision;
function getMaxFragmentPrecision() {
    if (!maxFragmentPrecision) {
        maxFragmentPrecision = constants_PRECISION.MEDIUM;
        var gl = getTestContext();
        if (gl) {
            if (gl.getShaderPrecisionFormat) {
                var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
                maxFragmentPrecision = shaderFragment.precision ? constants_PRECISION.HIGH : constants_PRECISION.MEDIUM;
            }
        }
    }
    return maxFragmentPrecision;
}

/**
 * Sets the float precision on the shader, ensuring the device supports the request precision.
 * If the precision is already present, it just ensures that the device is able to handle it.
 *
 * @private
 * @param {string} src - The shader source
 * @param {PIXI.PRECISION} requestedPrecision - The request float precision of the shader.
 * @param {PIXI.PRECISION} maxSupportedPrecision - The maximum precision the shader supports.
 *
 * @return {string} modified shader source
 */
function setPrecision(src, requestedPrecision, maxSupportedPrecision) {
    if (src.substring(0, 9) !== 'precision') {
        // no precision supplied, so PixiJS will add the requested level.
        var precision = requestedPrecision;
        // If highp is requested but not supported, downgrade precision to a level all devices support.
        if (requestedPrecision === constants_PRECISION.HIGH && maxSupportedPrecision !== constants_PRECISION.HIGH) {
            precision = constants_PRECISION.MEDIUM;
        }
        return "precision " + precision + " float;\n" + src;
    }
    else if (maxSupportedPrecision !== constants_PRECISION.HIGH && src.substring(0, 15) === 'precision highp') {
        // precision was supplied, but at a level this device does not support, so downgrading to mediump.
        return src.replace('precision highp', 'precision mediump');
    }
    return src;
}

var GLSL_TO_SIZE = {
    float: 1,
    vec2: 2,
    vec3: 3,
    vec4: 4,
    int: 1,
    ivec2: 2,
    ivec3: 3,
    ivec4: 4,
    uint: 1,
    uvec2: 2,
    uvec3: 3,
    uvec4: 4,
    bool: 1,
    bvec2: 2,
    bvec3: 3,
    bvec4: 4,
    mat2: 4,
    mat3: 9,
    mat4: 16,
    sampler2D: 1,
};
/**
 * @private
 * @method mapSize
 * @memberof PIXI.glCore.shader
 * @param {String} type
 * @return {Number}
 */
function mapSize(type) {
    return GLSL_TO_SIZE[type];
}

var GL_TABLE = null;
var GL_TO_GLSL_TYPES = {
    FLOAT: 'float',
    FLOAT_VEC2: 'vec2',
    FLOAT_VEC3: 'vec3',
    FLOAT_VEC4: 'vec4',
    INT: 'int',
    INT_VEC2: 'ivec2',
    INT_VEC3: 'ivec3',
    INT_VEC4: 'ivec4',
    UNSIGNED_INT: 'uint',
    UNSIGNED_INT_VEC2: 'uvec2',
    UNSIGNED_INT_VEC3: 'uvec3',
    UNSIGNED_INT_VEC4: 'uvec4',
    BOOL: 'bool',
    BOOL_VEC2: 'bvec2',
    BOOL_VEC3: 'bvec3',
    BOOL_VEC4: 'bvec4',
    FLOAT_MAT2: 'mat2',
    FLOAT_MAT3: 'mat3',
    FLOAT_MAT4: 'mat4',
    SAMPLER_2D: 'sampler2D',
    INT_SAMPLER_2D: 'sampler2D',
    UNSIGNED_INT_SAMPLER_2D: 'sampler2D',
    SAMPLER_CUBE: 'samplerCube',
    INT_SAMPLER_CUBE: 'samplerCube',
    UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube',
    SAMPLER_2D_ARRAY: 'sampler2DArray',
    INT_SAMPLER_2D_ARRAY: 'sampler2DArray',
    UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray',
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function mapType(gl, type) {
    if (!GL_TABLE) {
        var typeNames = Object.keys(GL_TO_GLSL_TYPES);
        GL_TABLE = {};
        for (var i = 0; i < typeNames.length; ++i) {
            var tn = typeNames[i];
            GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
        }
    }
    return GL_TABLE[type];
}

/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
// Parsers, each one of these will take a look at the type of shader property and uniform.
// if they pass the test function then the code function is called that returns a the shader upload code for that uniform.
// Shader upload code is automagically generated with these parsers.
// If no parser is valid then the default upload functions are used.
// exposing Parsers means that custom upload logic can be added to pixi's shaders.
// A good example would be a pixi rectangle can be directly set on a uniform.
// If the shader sees it it knows how to upload the rectangle structure as a vec4
// format is as follows:
//
// {
//     test: (data, uniform) => {} <--- test is this code should be used for this uniform
//     code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform
//     codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the
//                                         uniform to a uniform buffer
// }
var uniformParsers = [
    // a float cache layer
    {
        test: function (data) {
            return data.type === 'float' && data.size === 1;
        },
        code: function (name) {
            return "\n            if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n            {\n                ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n                gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n            }\n            ";
        },
    },
    // handling samplers
    {
        test: function (data) {
            // eslint-disable-next-line max-len
            return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray;
        },
        code: function (name) { return "t = syncData.textureCount++;\n\n            renderer.texture.bind(uv[\"" + name + "\"], t);\n\n            if(ud[\"" + name + "\"].value !== t)\n            {\n                ud[\"" + name + "\"].value = t;\n                gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n            }"; },
    },
    // uploading pixi matrix object to mat3
    {
        test: function (data, uniform) {
            return data.type === 'mat3' && data.size === 1 && uniform.a !== undefined;
        },
        code: function (name) {
            // TODO and some smart caching dirty ids here!
            return "\n            gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n            ";
        },
        codeUbo: function (name) {
            return "\n                var " + name + "_matrix = uv." + name + ".toArray(true);\n\n                data[offset] = " + name + "_matrix[0];\n                data[offset+1] = " + name + "_matrix[1];\n                data[offset+2] = " + name + "_matrix[2];\n        \n                data[offset + 4] = " + name + "_matrix[3];\n                data[offset + 5] = " + name + "_matrix[4];\n                data[offset + 6] = " + name + "_matrix[5];\n        \n                data[offset + 8] = " + name + "_matrix[6];\n                data[offset + 9] = " + name + "_matrix[7];\n                data[offset + 10] = " + name + "_matrix[8];\n            ";
        },
    },
    // uploading a pixi point as a vec2 with caching layer
    {
        test: function (data, uniform) {
            return data.type === 'vec2' && data.size === 1 && uniform.x !== undefined;
        },
        code: function (name) {
            return "\n                cv = ud[\"" + name + "\"].value;\n                v = uv[\"" + name + "\"];\n\n                if(cv[0] !== v.x || cv[1] !== v.y)\n                {\n                    cv[0] = v.x;\n                    cv[1] = v.y;\n                    gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n                }";
        },
        codeUbo: function (name) {
            return "\n                v = uv." + name + ";\n\n                data[offset] = v.x;\n                data[offset+1] = v.y;\n            ";
        }
    },
    // caching layer for a vec2
    {
        test: function (data) {
            return data.type === 'vec2' && data.size === 1;
        },
        code: function (name) {
            return "\n                cv = ud[\"" + name + "\"].value;\n                v = uv[\"" + name + "\"];\n\n                if(cv[0] !== v[0] || cv[1] !== v[1])\n                {\n                    cv[0] = v[0];\n                    cv[1] = v[1];\n                    gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n                }\n            ";
        },
    },
    // upload a pixi rectangle as a vec4 with caching layer
    {
        test: function (data, uniform) {
            return data.type === 'vec4' && data.size === 1 && uniform.width !== undefined;
        },
        code: function (name) {
            return "\n                cv = ud[\"" + name + "\"].value;\n                v = uv[\"" + name + "\"];\n\n                if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n                {\n                    cv[0] = v.x;\n                    cv[1] = v.y;\n                    cv[2] = v.width;\n                    cv[3] = v.height;\n                    gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n                }";
        },
        codeUbo: function (name) {
            return "\n                    v = uv." + name + ";\n\n                    data[offset] = v.x;\n                    data[offset+1] = v.y;\n                    data[offset+2] = v.width;\n                    data[offset+3] = v.height;\n                ";
        }
    },
    // a caching layer for vec4 uploading
    {
        test: function (data) {
            return data.type === 'vec4' && data.size === 1;
        },
        code: function (name) {
            return "\n                cv = ud[\"" + name + "\"].value;\n                v = uv[\"" + name + "\"];\n\n                if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n                {\n                    cv[0] = v[0];\n                    cv[1] = v[1];\n                    cv[2] = v[2];\n                    cv[3] = v[3];\n\n                    gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n                }";
        },
    } ];

// cu = Cached value's uniform data field
// cv = Cached value
// v = value to upload
// ud = uniformData
// uv = uniformValue
// l = location
var GLSL_TO_SINGLE_SETTERS_CACHED = {
    float: "\n    if (cv !== v)\n    {\n        cu.value = v;\n        gl.uniform1f(location, v);\n    }",
    vec2: "\n    if (cv[0] !== v[0] || cv[1] !== v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2f(location, v[0], v[1])\n    }",
    vec3: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n\n        gl.uniform3f(location, v[0], v[1], v[2])\n    }",
    vec4: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n        cv[3] = v[3];\n\n        gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n    }",
    int: "\n    if (cv !== v)\n    {\n        cu.value = v;\n\n        gl.uniform1i(location, v);\n    }",
    ivec2: "\n    if (cv[0] !== v[0] || cv[1] !== v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2i(location, v[0], v[1]);\n    }",
    ivec3: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n\n        gl.uniform3i(location, v[0], v[1], v[2]);\n    }",
    ivec4: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n        cv[3] = v[3];\n\n        gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n    }",
    uint: "\n    if (cv !== v)\n    {\n        cu.value = v;\n\n        gl.uniform1ui(location, v);\n    }",
    uvec2: "\n    if (cv[0] !== v[0] || cv[1] !== v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2ui(location, v[0], v[1]);\n    }",
    uvec3: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n\n        gl.uniform3ui(location, v[0], v[1], v[2]);\n    }",
    uvec4: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n        cv[3] = v[3];\n\n        gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n    }",
    bool: "\n    if (cv !== v)\n    {\n        cu.value = v;\n        gl.uniform1i(location, v);\n    }",
    bvec2: "\n    if (cv[0] != v[0] || cv[1] != v[1])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n\n        gl.uniform2i(location, v[0], v[1]);\n    }",
    bvec3: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n\n        gl.uniform3i(location, v[0], v[1], v[2]);\n    }",
    bvec4: "\n    if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n    {\n        cv[0] = v[0];\n        cv[1] = v[1];\n        cv[2] = v[2];\n        cv[3] = v[3];\n\n        gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n    }",
    mat2: 'gl.uniformMatrix2fv(location, false, v)',
    mat3: 'gl.uniformMatrix3fv(location, false, v)',
    mat4: 'gl.uniformMatrix4fv(location, false, v)',
    sampler2D: 'gl.uniform1i(location, v)',
    samplerCube: 'gl.uniform1i(location, v)',
    sampler2DArray: 'gl.uniform1i(location, v)',
};
var GLSL_TO_ARRAY_SETTERS = {
    float: "gl.uniform1fv(location, v)",
    vec2: "gl.uniform2fv(location, v)",
    vec3: "gl.uniform3fv(location, v)",
    vec4: 'gl.uniform4fv(location, v)',
    mat4: 'gl.uniformMatrix4fv(location, false, v)',
    mat3: 'gl.uniformMatrix3fv(location, false, v)',
    mat2: 'gl.uniformMatrix2fv(location, false, v)',
    int: 'gl.uniform1iv(location, v)',
    ivec2: 'gl.uniform2iv(location, v)',
    ivec3: 'gl.uniform3iv(location, v)',
    ivec4: 'gl.uniform4iv(location, v)',
    uint: 'gl.uniform1uiv(location, v)',
    uvec2: 'gl.uniform2uiv(location, v)',
    uvec3: 'gl.uniform3uiv(location, v)',
    uvec4: 'gl.uniform4uiv(location, v)',
    bool: 'gl.uniform1iv(location, v)',
    bvec2: 'gl.uniform2iv(location, v)',
    bvec3: 'gl.uniform3iv(location, v)',
    bvec4: 'gl.uniform4iv(location, v)',
    sampler2D: 'gl.uniform1iv(location, v)',
    samplerCube: 'gl.uniform1iv(location, v)',
    sampler2DArray: 'gl.uniform1iv(location, v)',
};
function generateUniformsSync(group, uniformData) {
    var _a;
    var funcFragments = ["\n        var v = null;\n        var cv = null;\n        var cu = null;\n        var t = 0;\n        var gl = renderer.gl;\n    "];
    for (var i in group.uniforms) {
        var data = uniformData[i];
        if (!data) {
            if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) {
                if (group.uniforms[i].ubo) {
                    funcFragments.push("\n                        renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n                    ");
                }
                else {
                    funcFragments.push("\n                        renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n                    ");
                }
            }
            continue;
        }
        var uniform = group.uniforms[i];
        var parsed = false;
        for (var j = 0; j < uniformParsers.length; j++) {
            if (uniformParsers[j].test(data, uniform)) {
                funcFragments.push(uniformParsers[j].code(i, uniform));
                parsed = true;
                break;
            }
        }
        if (!parsed) {
            var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS;
            var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location");
            funcFragments.push("\n            cu = ud[\"" + i + "\"];\n            cv = cu.value;\n            v = uv[\"" + i + "\"];\n            " + template + ";");
        }
    }
    /*
     * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly
     * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used
     * no matter which group is being used
     *
     */
    // eslint-disable-next-line no-new-func
    return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n'));
}

var fragTemplate = [
    'precision mediump float;',
    'void main(void){',
    'float test = 0.1;',
    '%forloop%',
    'gl_FragColor = vec4(0.0);',
    '}' ].join('\n');
function generateIfTestSrc(maxIfs) {
    var src = '';
    for (var i = 0; i < maxIfs; ++i) {
        if (i > 0) {
            src += '\nelse ';
        }
        if (i < maxIfs - 1) {
            src += "if(test == " + i + ".0){}";
        }
    }
    return src;
}
function checkMaxIfStatementsInShader(maxIfs, gl) {
    if (maxIfs === 0) {
        throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`');
    }
    var shader = gl.createShader(gl.FRAGMENT_SHADER);
    while (true) // eslint-disable-line no-constant-condition
     {
        var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs));
        gl.shaderSource(shader, fragmentSrc);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            maxIfs = (maxIfs / 2) | 0;
        }
        else {
            // valid!
            break;
        }
    }
    return maxIfs;
}

// Cache the result to prevent running this over and over
var unsafeEval;
/**
 * Not all platforms allow to generate function code (e.g., `new Function`).
 * this provides the platform-level detection.
 *
 * @private
 * @returns {boolean}
 */
function unsafeEvalSupported() {
    if (typeof unsafeEval === 'boolean') {
        return unsafeEval;
    }
    try {
        /* eslint-disable no-new-func */
        var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;');
        /* eslint-enable no-new-func */
        unsafeEval = func({ a: 'b' }, 'a', 'b') === true;
    }
    catch (e) {
        unsafeEval = false;
    }
    return unsafeEval;
}

var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n   gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}";

var defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n   gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n   vTextureCoord = aTextureCoord;\n}\n";

var UID$3 = 0;
var nameCache = {};
/**
 * Helper class to create a shader program.
 *
 * @memberof PIXI
 */
var Program = /** @class */ (function () {
    /**
     * @param vertexSrc - The source of the vertex shader.
     * @param fragmentSrc - The source of the fragment shader.
     * @param name - Name for shader
     */
    function Program(vertexSrc, fragmentSrc, name) {
        if (name === void 0) { name = 'pixi-shader'; }
        this.id = UID$3++;
        this.vertexSrc = vertexSrc || Program.defaultVertexSrc;
        this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc;
        this.vertexSrc = this.vertexSrc.trim();
        this.fragmentSrc = this.fragmentSrc.trim();
        if (this.vertexSrc.substring(0, 8) !== '#version') {
            name = name.replace(/\s+/g, '-');
            if (nameCache[name]) {
                nameCache[name]++;
                name += "-" + nameCache[name];
            }
            else {
                nameCache[name] = 1;
            }
            this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc;
            this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc;
            this.vertexSrc = setPrecision(this.vertexSrc, settings.PRECISION_VERTEX, constants_PRECISION.HIGH);
            this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision());
        }
        // currently this does not extract structs only default types
        // this is where we store shader references..
        this.glPrograms = {};
        this.syncUniforms = null;
    }
    Object.defineProperty(Program, "defaultVertexSrc", {
        /**
         * The default vertex shader source.
         *
         * @constant
         */
        get: function () {
            return defaultVertex;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Program, "defaultFragmentSrc", {
        /**
         * The default fragment shader source.
         *
         * @constant
         */
        get: function () {
            return defaultFragment;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * A short hand function to create a program based of a vertex and fragment shader.
     *
     * This method will also check to see if there is a cached program.
     *
     * @param vertexSrc - The source of the vertex shader.
     * @param fragmentSrc - The source of the fragment shader.
     * @param name - Name for shader
     * @returns A shiny new PixiJS shader program!
     */
    Program.from = function (vertexSrc, fragmentSrc, name) {
        var key = vertexSrc + fragmentSrc;
        var program = ProgramCache[key];
        if (!program) {
            ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name);
        }
        return program;
    };
    return Program;
}());

/**
 * A helper class for shaders.
 *
 * @memberof PIXI
 */
var Shader = /** @class */ (function () {
    /**
     * @param program - The program the shader will use.
     * @param uniforms - Custom uniforms to use to augment the built-in ones.
     */
    function Shader(program, uniforms) {
        /**
         * Used internally to bind uniform buffer objects.
         * @ignore
         */
        this.uniformBindCount = 0;
        this.program = program;
        // lets see whats been passed in
        // uniforms should be converted to a uniform group
        if (uniforms) {
            if (uniforms instanceof UniformGroup) {
                this.uniformGroup = uniforms;
            }
            else {
                this.uniformGroup = new UniformGroup(uniforms);
            }
        }
        else {
            this.uniformGroup = new UniformGroup({});
        }
    }
    // TODO move to shader system..
    Shader.prototype.checkUniformExists = function (name, group) {
        if (group.uniforms[name]) {
            return true;
        }
        for (var i in group.uniforms) {
            var uniform = group.uniforms[i];
            if (uniform.group) {
                if (this.checkUniformExists(name, uniform)) {
                    return true;
                }
            }
        }
        return false;
    };
    Shader.prototype.destroy = function () {
        // usage count on programs?
        // remove if not used!
        this.uniformGroup = null;
    };
    Object.defineProperty(Shader.prototype, "uniforms", {
        /**
         * Shader uniform values, shortcut for `uniformGroup.uniforms`.
         *
         * @readonly
         */
        get: function () {
            return this.uniformGroup.uniforms;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * A short hand function to create a shader based of a vertex and fragment shader.
     *
     * @param vertexSrc - The source of the vertex shader.
     * @param fragmentSrc - The source of the fragment shader.
     * @param uniforms - Custom uniforms to use to augment the built-in ones.
     * @returns A shiny new PixiJS shader!
     */
    Shader.from = function (vertexSrc, fragmentSrc, uniforms) {
        var program = Program.from(vertexSrc, fragmentSrc);
        return new Shader(program, uniforms);
    };
    return Shader;
}());

/* eslint-disable max-len */
var BLEND = 0;
var OFFSET = 1;
var CULLING = 2;
var DEPTH_TEST = 3;
var WINDING = 4;
var DEPTH_MASK = 5;
/**
 * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}.
 *
 * Each mesh rendered may require WebGL to be in a different state.
 * For example you may want different blend mode or to enable polygon offsets
 *
 * @memberof PIXI
 */
var State = /** @class */ (function () {
    function State() {
        this.data = 0;
        this.blendMode = constants_BLEND_MODES.NORMAL;
        this.polygonOffset = 0;
        this.blend = true;
        this.depthMask = true;
        //  this.depthTest = true;
    }
    Object.defineProperty(State.prototype, "blend", {
        /**
         * Activates blending of the computed fragment color values.
         *
         * @default true
         */
        get: function () {
            return !!(this.data & (1 << BLEND));
        },
        set: function (value) {
            if (!!(this.data & (1 << BLEND)) !== value) {
                this.data ^= (1 << BLEND);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "offsets", {
        /**
         * Activates adding an offset to depth values of polygon's fragments
         *
         * @default false
         */
        get: function () {
            return !!(this.data & (1 << OFFSET));
        },
        set: function (value) {
            if (!!(this.data & (1 << OFFSET)) !== value) {
                this.data ^= (1 << OFFSET);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "culling", {
        /**
         * Activates culling of polygons.
         *
         * @default false
         */
        get: function () {
            return !!(this.data & (1 << CULLING));
        },
        set: function (value) {
            if (!!(this.data & (1 << CULLING)) !== value) {
                this.data ^= (1 << CULLING);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "depthTest", {
        /**
         * Activates depth comparisons and updates to the depth buffer.
         *
         * @default false
         */
        get: function () {
            return !!(this.data & (1 << DEPTH_TEST));
        },
        set: function (value) {
            if (!!(this.data & (1 << DEPTH_TEST)) !== value) {
                this.data ^= (1 << DEPTH_TEST);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "depthMask", {
        /**
         * Enables or disables writing to the depth buffer.
         *
         * @default true
         */
        get: function () {
            return !!(this.data & (1 << DEPTH_MASK));
        },
        set: function (value) {
            if (!!(this.data & (1 << DEPTH_MASK)) !== value) {
                this.data ^= (1 << DEPTH_MASK);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "clockwiseFrontFace", {
        /**
         * Specifies whether or not front or back-facing polygons can be culled.
         *
         * @default false
         */
        get: function () {
            return !!(this.data & (1 << WINDING));
        },
        set: function (value) {
            if (!!(this.data & (1 << WINDING)) !== value) {
                this.data ^= (1 << WINDING);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "blendMode", {
        /**
         * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
         * Setting this mode to anything other than NO_BLEND will automatically switch blending on.
         *
         * @default PIXI.BLEND_MODES.NORMAL
         */
        get: function () {
            return this._blendMode;
        },
        set: function (value) {
            this.blend = (value !== constants_BLEND_MODES.NONE);
            this._blendMode = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "polygonOffset", {
        /**
         * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill.
         *
         * @default 0
         */
        get: function () {
            return this._polygonOffset;
        },
        set: function (value) {
            this.offsets = !!value;
            this._polygonOffset = value;
        },
        enumerable: false,
        configurable: true
    });
    State.prototype.toString = function () {
        return "[@pixi/core:State "
            + ("blendMode=" + this.blendMode + " ")
            + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ")
            + ("culling=" + this.culling + " ")
            + ("depthMask=" + this.depthMask + " ")
            + ("polygonOffset=" + this.polygonOffset)
            + "]";
    };
    State.for2d = function () {
        var state = new State();
        state.depthTest = false;
        state.blend = true;
        return state;
    };
    return State;
}());

var defaultVertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n    vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n    return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n    return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n    gl_Position = filterVertexPosition();\n    vTextureCoord = filterTextureCoord();\n}\n";

var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n   gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n";

/**
 * A filter is a special shader that applies post-processing effects to an input texture and writes into an output
 * render-target.
 *
 * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the
 * {@link PIXI.filters.BlurFilter BlurFilter}.
 *
 * ### Usage
 * Filters can be applied to any DisplayObject or Container.
 * PixiJS' `FilterSystem` renders the container into temporary Framebuffer,
 * then filter renders it to the screen.
 * Multiple filters can be added to the `filters` array property and stacked on each other.
 *
 * ```
 * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 });
 * const container = new PIXI.Container();
 * container.filters = [filter];
 * ```
 *
 * ### Previous Version Differences
 *
 * In PixiJS **v3**, a filter was always applied to _whole screen_.
 *
 * In PixiJS **v4**, a filter can be applied _only part of the screen_.
 * Developers had to create a set of uniforms to deal with coordinates.
 *
 * In PixiJS **v5** combines _both approaches_.
 * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers,
 * bringing those extra uniforms into account.
 *
 * Also be aware that we have changed default vertex shader, please consult
 * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}.
 *
 * ### Frames
 *
 * The following table summarizes the coordinate spaces used in the filtering pipeline:
 *
 * <table>
 * <thead>
 *   <tr>
 *     <th>Coordinate Space</th>
 *     <th>Description</th>
 *   </tr>
 * </thead>
 * <tbody>
 *   <tr>
 *     <td>Texture Coordinates</td>
 *     <td>
 *         The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along
 *         both axes.
 *     </td>
 *   </tr>
 *   <tr>
 *     <td>World Space</td>
 *     <td>
 *         A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space).
 *     </td>
 *   </tr>
 *   <tr>
 *     <td>Physical Pixels</td>
 *     <td>
 *         This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture
 *         coordinates by the dimensions of the texture.
 *     </td>
 *   </tr>
 * </tbody>
 * </table>
 *
 * ### Built-in Uniforms
 *
 * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`,
 * and `projectionMatrix` uniform maps it to the gl viewport.
 *
 * **uSampler**
 *
 * The most important uniform is the input texture that container was rendered into.
 * _Important note: as with all Framebuffers in PixiJS, both input and output are
 * premultiplied by alpha._
 *
 * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`.
 * Use it to sample the input.
 *
 * ```
 * const fragment = `
 * varying vec2 vTextureCoord;
 * uniform sampler2D uSampler;
 * void main(void)
 * {
 *    gl_FragColor = texture2D(uSampler, vTextureCoord);
 * }
 * `;
 *
 * const myFilter = new PIXI.Filter(null, fragment);
 * ```
 *
 * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}.
 *
 * **outputFrame**
 *
 * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates.
 * It's the same as `renderer.screen` for a fullscreen filter.
 * Only a part of  `outputFrame.zw` size of temporary Framebuffer is used,
 * `(0, 0, outputFrame.width, outputFrame.height)`,
 *
 * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute.
 * To calculate vertex position in screen space using normalized (0-1) space:
 *
 * ```
 * vec4 filterVertexPosition( void )
 * {
 *     vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;
 *     return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
 * }
 * ```
 *
 * **inputSize**
 *
 * Temporary framebuffer is different, it can be either the size of screen, either power-of-two.
 * The `inputSize.xy` are size of temporary framebuffer that holds input.
 * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader.
 *
 * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter.
 *
 * To calculate input normalized coordinate, you have to map it to filter normalized space.
 * Multiply by `outputFrame.zw` to get input coordinate.
 * Divide by `inputSize.xy` to get input normalized coordinate.
 *
 * ```
 * vec2 filterTextureCoord( void )
 * {
 *     return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy
 * }
 * ```
 * **resolution**
 *
 * The `resolution` is the ratio of screen (CSS) pixels to real pixels.
 *
 * **inputPixel**
 *
 * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution`
 * `inputPixel.zw` is inverted `inputPixel.xy`.
 *
 * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}.
 *
 * **inputClamp**
 *
 * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour.
 * For displacements, coordinates has to be clamped.
 *
 * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer
 * `inputClamp.zw` is bottom-right pixel center.
 *
 * ```
 * vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw))
 * ```
 * OR
 * ```
 * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw))
 * ```
 *
 * ### Additional Information
 *
 * Complete documentation on Filter usage is located in the
 * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}.
 *
 * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded
 * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository.
 *
 * @memberof PIXI
 */
var Filter = /** @class */ (function (_super) {
    core_extends(Filter, _super);
    /**
     * @param vertexSrc - The source of the vertex shader.
     * @param fragmentSrc - The source of the fragment shader.
     * @param uniforms - Custom uniforms to use to augment the built-in ones.
     */
    function Filter(vertexSrc, fragmentSrc, uniforms) {
        var _this = this;
        var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc);
        _this = _super.call(this, program, uniforms) || this;
        _this.padding = 0;
        _this.resolution = settings.FILTER_RESOLUTION;
        _this.multisample = settings.FILTER_MULTISAMPLE;
        _this.enabled = true;
        _this.autoFit = true;
        _this.state = new State();
        return _this;
    }
    /**
     * Applies the filter
     *
     * @param {PIXI.FilterSystem} filterManager - The renderer to retrieve the filter from
     * @param {PIXI.RenderTexture} input - The input render target.
     * @param {PIXI.RenderTexture} output - The target to output to.
     * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it.
     * @param {object} [currentState] - It's current state of filter.
     *        There are some useful properties in the currentState :
     *        target, filters, sourceFrame, destinationFrame, renderTarget, resolution
     */
    Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) {
        // do as you please!
        filterManager.applyFilter(this, input, output, clearMode);
        // or just do a regular render..
    };
    Object.defineProperty(Filter.prototype, "blendMode", {
        /**
         * Sets the blend mode of the filter.
         *
         * @default PIXI.BLEND_MODES.NORMAL
         */
        get: function () {
            return this.state.blendMode;
        },
        set: function (value) {
            this.state.blendMode = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Filter.prototype, "resolution", {
        /**
         * The resolution of the filter. Setting this to be lower will lower the quality but
         * increase the performance of the filter.
         */
        get: function () {
            return this._resolution;
        },
        set: function (value) {
            this._resolution = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Filter, "defaultVertexSrc", {
        /**
         * The default vertex shader source
         *
         * @constant
         */
        get: function () {
            return defaultVertex$1;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Filter, "defaultFragmentSrc", {
        /**
         * The default fragment shader source
         *
         * @constant
         */
        get: function () {
            return defaultFragment$1;
        },
        enumerable: false,
        configurable: true
    });
    return Filter;
}(Shader));

var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = aTextureCoord;\n    vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0)  ).xy;\n}\n";

var fragment = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n    float clip = step(3.5,\n        step(maskClamp.x, vMaskCoord.x) +\n        step(maskClamp.y, vMaskCoord.y) +\n        step(vMaskCoord.x, maskClamp.z) +\n        step(vMaskCoord.y, maskClamp.w));\n\n    vec4 original = texture2D(uSampler, vTextureCoord);\n    vec4 masky = texture2D(mask, vMaskCoord);\n    float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n    original *= (alphaMul * masky.r * alpha * clip);\n\n    gl_FragColor = original;\n}\n";

var tempMat = new Matrix();
/**
 * Class controls uv mapping from Texture normal space to BaseTexture normal space.
 *
 * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite.
 *
 * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture.
 * If you want to add support for texture region of certain feature or filter, that's what you're looking for.
 *
 * Takes track of Texture changes through `_lastTextureID` private field.
 * Use `update()` method call to track it from outside.
 *
 * @see PIXI.Texture
 * @see PIXI.Mesh
 * @see PIXI.TilingSprite
 * @memberof PIXI
 */
var TextureMatrix = /** @class */ (function () {
    /**
     * @param texture - observed texture
     * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
     */
    function TextureMatrix(texture, clampMargin) {
        this._texture = texture;
        this.mapCoord = new Matrix();
        this.uClampFrame = new Float32Array(4);
        this.uClampOffset = new Float32Array(2);
        this._textureID = -1;
        this._updateID = 0;
        this.clampOffset = 0;
        this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin;
        this.isSimple = false;
    }
    Object.defineProperty(TextureMatrix.prototype, "texture", {
        /** Texture property. */
        get: function () {
            return this._texture;
        },
        set: function (value) {
            this._texture = value;
            this._textureID = -1;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Multiplies uvs array to transform
     *
     * @param uvs - mesh uvs
     * @param [out=uvs] - output
     * @returns - output
     */
    TextureMatrix.prototype.multiplyUvs = function (uvs, out) {
        if (out === undefined) {
            out = uvs;
        }
        var mat = this.mapCoord;
        for (var i = 0; i < uvs.length; i += 2) {
            var x = uvs[i];
            var y = uvs[i + 1];
            out[i] = (x * mat.a) + (y * mat.c) + mat.tx;
            out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty;
        }
        return out;
    };
    /**
     * Updates matrices if texture was changed.
     *
     * @param [forceUpdate=false] - if true, matrices will be updated any case
     * @returns - Whether or not it was updated
     */
    TextureMatrix.prototype.update = function (forceUpdate) {
        var tex = this._texture;
        if (!tex || !tex.valid) {
            return false;
        }
        if (!forceUpdate
            && this._textureID === tex._updateID) {
            return false;
        }
        this._textureID = tex._updateID;
        this._updateID++;
        var uvs = tex._uvs;
        this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0);
        var orig = tex.orig;
        var trim = tex.trim;
        if (trim) {
            tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height);
            this.mapCoord.append(tempMat);
        }
        var texBase = tex.baseTexture;
        var frame = this.uClampFrame;
        var margin = this.clampMargin / texBase.resolution;
        var offset = this.clampOffset;
        frame[0] = (tex._frame.x + margin + offset) / texBase.width;
        frame[1] = (tex._frame.y + margin + offset) / texBase.height;
        frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width;
        frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height;
        this.uClampOffset[0] = offset / texBase.realWidth;
        this.uClampOffset[1] = offset / texBase.realHeight;
        this.isSimple = tex._frame.width === texBase.width
            && tex._frame.height === texBase.height
            && tex.rotate === 0;
        return true;
    };
    return TextureMatrix;
}());

/**
 * This handles a Sprite acting as a mask, as opposed to a Graphic.
 *
 * WebGL only.
 *
 * @memberof PIXI
 */
var SpriteMaskFilter = /** @class */ (function (_super) {
    core_extends(SpriteMaskFilter, _super);
    /** @ignore */
    function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) {
        var _this = this;
        var sprite = null;
        if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) {
            sprite = vertexSrc;
            vertexSrc = undefined;
            fragmentSrc = undefined;
            uniforms = undefined;
        }
        _this = _super.call(this, vertexSrc || vertex, fragmentSrc || fragment, uniforms) || this;
        _this.maskSprite = sprite;
        _this.maskMatrix = new Matrix();
        return _this;
    }
    Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", {
        /**
         * Sprite mask
         *
         * @type {PIXI.DisplayObject}
         */
        get: function () {
            return this._maskSprite;
        },
        set: function (value) {
            this._maskSprite = value;
            if (this._maskSprite) {
                this._maskSprite.renderable = false;
            }
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Applies the filter
     *
     * @param filterManager - The renderer to retrieve the filter from
     * @param input - The input render target.
     * @param output - The target to output to.
     * @param clearMode - Should the output be cleared before rendering to it.
     */
    SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) {
        var maskSprite = this._maskSprite;
        var tex = maskSprite._texture;
        if (!tex.valid) {
            return;
        }
        if (!tex.uvMatrix) {
            // margin = 0.0, let it bleed a bit, shader code becomes easier
            // assuming that atlas textures were made with 1-pixel padding
            tex.uvMatrix = new TextureMatrix(tex, 0.0);
        }
        tex.uvMatrix.update();
        this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0;
        this.uniforms.mask = tex;
        // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend`
        this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite)
            .prepend(tex.uvMatrix.mapCoord);
        this.uniforms.alpha = maskSprite.worldAlpha;
        this.uniforms.maskClamp = tex.uvMatrix.uClampFrame;
        filterManager.applyFilter(this, input, output, clearMode);
    };
    return SpriteMaskFilter;
}(Filter));

/**
 * System plugin to the renderer to manage masks.
 *
 * There are three built-in types of masking:
 * * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is
 *  the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular.
 * * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil
 *  buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does
 *  cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks.
 * * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's
 *  texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this
 *  type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins.
 *
 * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics`
 * object with just a rectangle drawn.
 *
 * ## Mask Stacks
 *
 * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask
 * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e.
 * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target.
 *
 * @memberof PIXI
 */
var MaskSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this System works for.
     */
    function MaskSystem(renderer) {
        this.renderer = renderer;
        this.enableScissor = true;
        this.alphaMaskPool = [];
        this.maskDataPool = [];
        this.maskStack = [];
        this.alphaMaskIndex = 0;
    }
    /**
     * Changes the mask stack that is used by this System.
     *
     * @param maskStack - The mask stack
     */
    MaskSystem.prototype.setMaskStack = function (maskStack) {
        this.maskStack = maskStack;
        this.renderer.scissor.setMaskStack(maskStack);
        this.renderer.stencil.setMaskStack(maskStack);
    };
    /**
     * Enables the mask and appends it to the current mask stack.
     *
     * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked.
     *
     * @param {PIXI.DisplayObject} target - Display Object to push the mask to
     * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskData - The masking data.
     */
    MaskSystem.prototype.push = function (target, maskDataOrTarget) {
        var maskData = maskDataOrTarget;
        if (!maskData.isMaskData) {
            var d = this.maskDataPool.pop() || new MaskData();
            d.pooled = true;
            d.maskObject = maskDataOrTarget;
            maskData = d;
        }
        var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null;
        maskData.copyCountersOrReset(maskAbove);
        if (maskData.autoDetect) {
            this.detect(maskData);
        }
        maskData._target = target;
        if (maskData.type !== constants_MASK_TYPES.SPRITE) {
            this.maskStack.push(maskData);
        }
        if (maskData.enabled) {
            switch (maskData.type) {
                case constants_MASK_TYPES.SCISSOR:
                    this.renderer.scissor.push(maskData);
                    break;
                case constants_MASK_TYPES.STENCIL:
                    this.renderer.stencil.push(maskData);
                    break;
                case constants_MASK_TYPES.SPRITE:
                    maskData.copyCountersOrReset(null);
                    this.pushSpriteMask(maskData);
                    break;
            }
        }
        if (maskData.type === constants_MASK_TYPES.SPRITE) {
            this.maskStack.push(maskData);
        }
    };
    /**
     * Removes the last mask from the mask stack and doesn't return it.
     *
     * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed.
     *
     * @param {PIXI.DisplayObject} target - Display Object to pop the mask from
     */
    MaskSystem.prototype.pop = function (target) {
        var maskData = this.maskStack.pop();
        if (!maskData || maskData._target !== target) {
            // TODO: add an assert when we have it
            return;
        }
        if (maskData.enabled) {
            switch (maskData.type) {
                case constants_MASK_TYPES.SCISSOR:
                    this.renderer.scissor.pop();
                    break;
                case constants_MASK_TYPES.STENCIL:
                    this.renderer.stencil.pop(maskData.maskObject);
                    break;
                case constants_MASK_TYPES.SPRITE:
                    this.popSpriteMask(maskData);
                    break;
            }
        }
        maskData.reset();
        if (maskData.pooled) {
            this.maskDataPool.push(maskData);
        }
        if (this.maskStack.length !== 0) {
            var maskCurrent = this.maskStack[this.maskStack.length - 1];
            if (maskCurrent.type === constants_MASK_TYPES.SPRITE && maskCurrent._filters) {
                maskCurrent._filters[0].maskSprite = maskCurrent.maskObject;
            }
        }
    };
    /** Sets type of MaskData based on its maskObject. */
    MaskSystem.prototype.detect = function (maskData) {
        var maskObject = maskData.maskObject;
        if (maskObject.isSprite) {
            maskData.type = constants_MASK_TYPES.SPRITE;
        }
        else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) {
            maskData.type = constants_MASK_TYPES.SCISSOR;
        }
        else {
            maskData.type = constants_MASK_TYPES.STENCIL;
        }
    };
    /**
     * Applies the Mask and adds it to the current filter stack.
     *
     * @param maskData - Sprite to be used as the mask.
     */
    MaskSystem.prototype.pushSpriteMask = function (maskData) {
        var _a, _b;
        var maskObject = maskData.maskObject;
        var target = maskData._target;
        var alphaMaskFilter = maskData._filters;
        if (!alphaMaskFilter) {
            alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex];
            if (!alphaMaskFilter) {
                alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()];
            }
        }
        var renderer = this.renderer;
        var renderTextureSystem = renderer.renderTexture;
        var resolution;
        var multisample;
        if (renderTextureSystem.current) {
            var renderTexture = renderTextureSystem.current;
            resolution = maskData.resolution || renderTexture.resolution;
            multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample;
        }
        else {
            resolution = maskData.resolution || renderer.resolution;
            multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample;
        }
        alphaMaskFilter[0].resolution = resolution;
        alphaMaskFilter[0].multisample = multisample;
        alphaMaskFilter[0].maskSprite = maskObject;
        var stashFilterArea = target.filterArea;
        target.filterArea = maskObject.getBounds(true);
        renderer.filter.push(target, alphaMaskFilter);
        target.filterArea = stashFilterArea;
        if (!maskData._filters) {
            this.alphaMaskIndex++;
        }
    };
    /**
     * Removes the last filter from the filter stack and doesn't return it.
     *
     * @param maskData - Sprite to be used as the mask.
     */
    MaskSystem.prototype.popSpriteMask = function (maskData) {
        this.renderer.filter.pop();
        if (maskData._filters) {
            maskData._filters[0].maskSprite = null;
        }
        else {
            this.alphaMaskIndex--;
            this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null;
        }
    };
    MaskSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return MaskSystem;
}());

/**
 * System plugin to the renderer to manage specific types of masking operations.
 *
 * @memberof PIXI
 */
var AbstractMaskSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this System works for.
     */
    function AbstractMaskSystem(renderer) {
        this.renderer = renderer;
        this.maskStack = [];
        this.glConst = 0;
    }
    /** Gets count of masks of certain type. */
    AbstractMaskSystem.prototype.getStackLength = function () {
        return this.maskStack.length;
    };
    /**
     * Changes the mask stack that is used by this System.
     *
     * @param {PIXI.MaskData[]} maskStack - The mask stack
     */
    AbstractMaskSystem.prototype.setMaskStack = function (maskStack) {
        var gl = this.renderer.gl;
        var curStackLen = this.getStackLength();
        this.maskStack = maskStack;
        var newStackLen = this.getStackLength();
        if (newStackLen !== curStackLen) {
            if (newStackLen === 0) {
                gl.disable(this.glConst);
            }
            else {
                gl.enable(this.glConst);
                this._useCurrent();
            }
        }
    };
    /**
     * Setup renderer to use the current mask data.
     * @private
     */
    AbstractMaskSystem.prototype._useCurrent = function () {
        // OVERWRITE;
    };
    /** Destroys the mask stack. */
    AbstractMaskSystem.prototype.destroy = function () {
        this.renderer = null;
        this.maskStack = null;
    };
    return AbstractMaskSystem;
}());

var tempMatrix$1 = new Matrix();
/**
 * System plugin to the renderer to manage scissor masking.
 *
 * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer
 * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically
 * by this system.
 *
 * @memberof PIXI
 */
var ScissorSystem = /** @class */ (function (_super) {
    core_extends(ScissorSystem, _super);
    /**
     * @param {PIXI.Renderer} renderer - The renderer this System works for.
     */
    function ScissorSystem(renderer) {
        var _this = _super.call(this, renderer) || this;
        _this.glConst = WebGLRenderingContext.SCISSOR_TEST;
        return _this;
    }
    ScissorSystem.prototype.getStackLength = function () {
        var maskData = this.maskStack[this.maskStack.length - 1];
        if (maskData) {
            return maskData._scissorCounter;
        }
        return 0;
    };
    /**
     * evaluates _boundsTransformed, _scissorRect for MaskData
     * @param maskData
     */
    ScissorSystem.prototype.calcScissorRect = function (maskData) {
        if (maskData._scissorRectLocal) {
            return;
        }
        var prevData = maskData._scissorRect;
        var maskObject = maskData.maskObject;
        var renderer = this.renderer;
        var renderTextureSystem = renderer.renderTexture;
        maskObject.renderable = true;
        var rect = maskObject.getBounds();
        this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform);
        maskObject.renderable = false;
        if (prevData) {
            rect.fit(prevData);
        }
        maskData._scissorRectLocal = rect;
    };
    ScissorSystem.isMatrixRotated = function (matrix) {
        if (!matrix) {
            return false;
        }
        var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d;
        // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation
        // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0).
        return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4)
            && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4));
    };
    /**
     * Test, whether the object can be scissor mask with current renderer projection.
     * Calls "calcScissorRect()" if its true.
     * @param maskData mask data
     * @returns whether Whether the object can be scissor mask
     */
    ScissorSystem.prototype.testScissor = function (maskData) {
        var maskObject = maskData.maskObject;
        if (!maskObject.isFastRect || !maskObject.isFastRect()) {
            return false;
        }
        if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) {
            return false;
        }
        if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) {
            return false;
        }
        this.calcScissorRect(maskData);
        var rect = maskData._scissorRectLocal;
        return rect.width > 0 && rect.height > 0;
    };
    ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) {
        if (ScissorSystem.isMatrixRotated(transform)) {
            return;
        }
        transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity();
        // Get forward transform from world space to screen space
        transform
            .translate(-bindingSourceFrame.x, -bindingSourceFrame.y)
            .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height)
            .translate(bindingDestinationFrame.x, bindingDestinationFrame.y);
        // Convert frame to screen space
        this.renderer.filter.transformAABB(transform, frame);
        frame.fit(bindingDestinationFrame);
        frame.x = Math.round(frame.x * resolution);
        frame.y = Math.round(frame.y * resolution);
        frame.width = Math.round(frame.width * resolution);
        frame.height = Math.round(frame.height * resolution);
    };
    /**
     * Applies the Mask and adds it to the current stencil stack.
     *
     * @author alvin
     * @param maskData - The mask data.
     */
    ScissorSystem.prototype.push = function (maskData) {
        if (!maskData._scissorRectLocal) {
            this.calcScissorRect(maskData);
        }
        var gl = this.renderer.gl;
        if (!maskData._scissorRect) {
            gl.enable(gl.SCISSOR_TEST);
        }
        maskData._scissorCounter++;
        maskData._scissorRect = maskData._scissorRectLocal;
        this._useCurrent();
    };
    /**
     * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the
     * last mask in the stack.
     *
     * This can also be called when you directly modify the scissor box and want to restore PixiJS state.
     */
    ScissorSystem.prototype.pop = function () {
        var gl = this.renderer.gl;
        if (this.getStackLength() > 0) {
            this._useCurrent();
        }
        else {
            gl.disable(gl.SCISSOR_TEST);
        }
    };
    /**
     * Setup renderer to use the current scissor data.
     * @private
     */
    ScissorSystem.prototype._useCurrent = function () {
        var rect = this.maskStack[this.maskStack.length - 1]._scissorRect;
        var y;
        if (this.renderer.renderTexture.current) {
            y = rect.y;
        }
        else {
            // flipY. In future we'll have it over renderTextures as an option
            y = this.renderer.height - rect.height - rect.y;
        }
        this.renderer.gl.scissor(rect.x, y, rect.width, rect.height);
    };
    return ScissorSystem;
}(AbstractMaskSystem));

/**
 * System plugin to the renderer to manage stencils (used for masks).
 *
 * @memberof PIXI
 */
var StencilSystem = /** @class */ (function (_super) {
    core_extends(StencilSystem, _super);
    /**
     * @param renderer - The renderer this System works for.
     */
    function StencilSystem(renderer) {
        var _this = _super.call(this, renderer) || this;
        _this.glConst = WebGLRenderingContext.STENCIL_TEST;
        return _this;
    }
    StencilSystem.prototype.getStackLength = function () {
        var maskData = this.maskStack[this.maskStack.length - 1];
        if (maskData) {
            return maskData._stencilCounter;
        }
        return 0;
    };
    /**
     * Applies the Mask and adds it to the current stencil stack.
     *
     * @param maskData - The mask data
     */
    StencilSystem.prototype.push = function (maskData) {
        var maskObject = maskData.maskObject;
        var gl = this.renderer.gl;
        var prevMaskCount = maskData._stencilCounter;
        if (prevMaskCount === 0) {
            // force use stencil texture in current framebuffer
            this.renderer.framebuffer.forceStencil();
            gl.clearStencil(0);
            gl.clear(gl.STENCIL_BUFFER_BIT);
            gl.enable(gl.STENCIL_TEST);
        }
        maskData._stencilCounter++;
        // Increment the reference stencil value where the new mask overlaps with the old ones.
        gl.colorMask(false, false, false, false);
        gl.stencilFunc(gl.EQUAL, prevMaskCount, 0xFFFFFFFF);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
        maskObject.renderable = true;
        maskObject.render(this.renderer);
        this.renderer.batch.flush();
        maskObject.renderable = false;
        this._useCurrent();
    };
    /**
     * Pops stencil mask. MaskData is already removed from stack
     *
     * @param {PIXI.DisplayObject} maskObject - object of popped mask data
     */
    StencilSystem.prototype.pop = function (maskObject) {
        var gl = this.renderer.gl;
        if (this.getStackLength() === 0) {
            // the stack is empty!
            gl.disable(gl.STENCIL_TEST);
        }
        else {
            // Decrement the reference stencil value where the popped mask overlaps with the other ones
            gl.colorMask(false, false, false, false);
            gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
            maskObject.renderable = true;
            maskObject.render(this.renderer);
            this.renderer.batch.flush();
            maskObject.renderable = false;
            this._useCurrent();
        }
    };
    /**
     * Setup renderer to use the current stencil data.
     * @private
     */
    StencilSystem.prototype._useCurrent = function () {
        var gl = this.renderer.gl;
        gl.colorMask(true, true, true, true);
        gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
    };
    return StencilSystem;
}(AbstractMaskSystem));

/**
 * System plugin to the renderer to manage the projection matrix.
 *
 * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to
 * normalized device coordinates.
 *
 * @memberof PIXI
 */
var ProjectionSystem = /** @class */ (function () {
    /** @param renderer - The renderer this System works for. */
    function ProjectionSystem(renderer) {
        this.renderer = renderer;
        this.destinationFrame = null;
        this.sourceFrame = null;
        this.defaultFrame = null;
        this.projectionMatrix = new Matrix();
        this.transform = null;
    }
    /**
     * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided.
     *
     * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because
     * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates.
     *
     * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected
     * that you dirty the current bindings when calling this manually.
     *
     * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas,
     *  the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left.
     * @param sourceFrame - The rectangle in world space that contains the contents being rendered.
     * @param resolution - The resolution of the render-target, which is the ratio of
     *  world-space (or CSS) pixels to physical pixels.
     * @param root - Whether the render-target is the screen. This is required because rendering to textures
     *  is y-flipped (i.e. upside down relative to the screen).
     */
    ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) {
        this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame;
        this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame;
        // Calculate object-space to clip-space projection
        this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root);
        if (this.transform) {
            this.projectionMatrix.append(this.transform);
        }
        var renderer = this.renderer;
        renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix;
        renderer.globalUniforms.update();
        // this will work for now
        // but would be sweet to stick and even on the global uniforms..
        if (renderer.shader.shader) {
            renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals);
        }
    };
    /**
     * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`.
     *
     * @param destinationFrame - The destination frame in the render-target.
     * @param sourceFrame - The source frame in world space.
     * @param resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels.
     * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection
     *  is y-flipped.
     */
    ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) {
        var pm = this.projectionMatrix;
        var sign = !root ? 1 : -1;
        pm.identity();
        pm.a = (1 / sourceFrame.width * 2);
        pm.d = sign * (1 / sourceFrame.height * 2);
        pm.tx = -1 - (sourceFrame.x * pm.a);
        pm.ty = -sign - (sourceFrame.y * pm.d);
    };
    /**
     * Sets the transform of the active render target to the given matrix.
     *
     * @param matrix - The transformation matrix
     */
    ProjectionSystem.prototype.setTransform = function (_matrix) {
        // this._activeRenderTarget.transform = matrix;
    };
    ProjectionSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return ProjectionSystem;
}());

// Temporary rectangle for assigned sourceFrame or destinationFrame
var tempRect = new Rectangle();
// Temporary rectangle for renderTexture destinationFrame
var tempRect2 = new Rectangle();
/* eslint-disable max-len */
/**
 * System plugin to the renderer to manage render textures.
 *
 * Should be added after FramebufferSystem
 *
 * ### Frames
 *
 * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different
 * coordinate spaces used:
 *
 * | Frame                  | Description                                                      | Coordinate System                                       |
 * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- |
 * | sourceFrame            | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left             |
 * | destinationFrame       | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left.  |
 * | viewportFrame          | The framebuffer viewport corresponding to the destination-frame  | **Window Coordinates**: The origin is always on the bottom-left. |
 *
 * @memberof PIXI
 */
var RenderTextureSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this System works for.
     */
    function RenderTextureSystem(renderer) {
        this.renderer = renderer;
        this.clearColor = renderer._backgroundColorRgba;
        this.defaultMaskStack = [];
        this.current = null;
        this.sourceFrame = new Rectangle();
        this.destinationFrame = new Rectangle();
        this.viewportFrame = new Rectangle();
    }
    /**
     * Bind the current render texture.
     *
     * @param renderTexture - RenderTexture to bind, by default its `null` - the screen.
     * @param sourceFrame - Part of world that is mapped to the renderTexture.
     * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame.
     */
    RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) {
        if (renderTexture === void 0) { renderTexture = null; }
        var renderer = this.renderer;
        this.current = renderTexture;
        var baseTexture;
        var framebuffer;
        var resolution;
        if (renderTexture) {
            baseTexture = renderTexture.baseTexture;
            resolution = baseTexture.resolution;
            if (!sourceFrame) {
                tempRect.width = renderTexture.frame.width;
                tempRect.height = renderTexture.frame.height;
                sourceFrame = tempRect;
            }
            if (!destinationFrame) {
                tempRect2.x = renderTexture.frame.x;
                tempRect2.y = renderTexture.frame.y;
                tempRect2.width = sourceFrame.width;
                tempRect2.height = sourceFrame.height;
                destinationFrame = tempRect2;
            }
            framebuffer = baseTexture.framebuffer;
        }
        else {
            resolution = renderer.resolution;
            if (!sourceFrame) {
                tempRect.width = renderer.screen.width;
                tempRect.height = renderer.screen.height;
                sourceFrame = tempRect;
            }
            if (!destinationFrame) {
                destinationFrame = tempRect;
                destinationFrame.width = sourceFrame.width;
                destinationFrame.height = sourceFrame.height;
            }
        }
        var viewportFrame = this.viewportFrame;
        viewportFrame.x = destinationFrame.x * resolution;
        viewportFrame.y = destinationFrame.y * resolution;
        viewportFrame.width = destinationFrame.width * resolution;
        viewportFrame.height = destinationFrame.height * resolution;
        if (!renderTexture) {
            viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height);
        }
        viewportFrame.ceil();
        this.renderer.framebuffer.bind(framebuffer, viewportFrame);
        this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer);
        if (renderTexture) {
            this.renderer.mask.setMaskStack(baseTexture.maskStack);
        }
        else {
            this.renderer.mask.setMaskStack(this.defaultMaskStack);
        }
        this.sourceFrame.copyFrom(sourceFrame);
        this.destinationFrame.copyFrom(destinationFrame);
    };
    /**
     * Erases the render texture and fills the drawing area with a colour.
     *
     * @param clearColor - The color as rgba, default to use the renderer backgroundColor
     * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks
     *  that indicate the buffers to be cleared, by default COLOR and DEPTH buffers.
     */
    RenderTextureSystem.prototype.clear = function (clearColor, mask) {
        if (this.current) {
            clearColor = clearColor || this.current.baseTexture.clearColor;
        }
        else {
            clearColor = clearColor || this.clearColor;
        }
        var destinationFrame = this.destinationFrame;
        var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen;
        var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height;
        if (clearMask) {
            var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
            x = Math.round(x);
            y = Math.round(y);
            width = Math.round(width);
            height = Math.round(height);
            // TODO: ScissorSystem should cache whether the scissor test is enabled or not.
            this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);
            this.renderer.gl.scissor(x, y, width, height);
        }
        this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask);
        if (clearMask) {
            // Restore the scissor box
            this.renderer.scissor.pop();
        }
    };
    RenderTextureSystem.prototype.resize = function () {
        // resize the root only!
        this.bind(null);
    };
    /** Resets render-texture state. */
    RenderTextureSystem.prototype.reset = function () {
        this.bind(null);
    };
    RenderTextureSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return RenderTextureSystem;
}());

function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) {
    _renderer.buffer.update(buffer);
}
// cv = CachedValue
// v = value
// ud = uniformData
// uv = uniformValue
// l = location
var UBO_TO_SINGLE_SETTERS = {
    float: "\n        data[offset] = v;\n    ",
    vec2: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n    ",
    vec3: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n        data[offset+2] = v[2];\n\n    ",
    vec4: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n        data[offset+2] = v[2];\n        data[offset+3] = v[3];\n    ",
    mat2: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n\n        data[offset+4] = v[2];\n        data[offset+5] = v[3];\n    ",
    mat3: "\n        data[offset] = v[0];\n        data[offset+1] = v[1];\n        data[offset+2] = v[2];\n\n        data[offset + 4] = v[3];\n        data[offset + 5] = v[4];\n        data[offset + 6] = v[5];\n\n        data[offset + 8] = v[6];\n        data[offset + 9] = v[7];\n        data[offset + 10] = v[8];\n    ",
    mat4: "\n        for(var i = 0; i < 16; i++)\n        {\n            data[offset + i] = v[i];\n        }\n    "
};
var GLSL_TO_STD40_SIZE = {
    float: 4,
    vec2: 8,
    vec3: 12,
    vec4: 16,
    int: 4,
    ivec2: 8,
    ivec3: 12,
    ivec4: 16,
    uint: 4,
    uvec2: 8,
    uvec3: 12,
    uvec4: 16,
    bool: 4,
    bvec2: 8,
    bvec3: 12,
    bvec4: 16,
    mat2: 16 * 2,
    mat3: 16 * 3,
    mat4: 16 * 4,
};
/**
 * @ignore
 *
 * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js
 * rewrote it, but this was a great starting point to get a solid understanding of whats going on :)
 *
 * @param uniformData
 */
function createUBOElements(uniformData) {
    var uboElements = uniformData.map(function (data) {
        return ({
            data: data,
            offset: 0,
            dataLen: 0,
            dirty: 0
        });
    });
    var size = 0;
    var chunkSize = 0;
    var offset = 0;
    for (var i = 0; i < uboElements.length; i++) {
        var uboElement = uboElements[i];
        size = GLSL_TO_STD40_SIZE[uboElement.data.type];
        if (uboElement.data.size > 1) {
            size = Math.max(size, 16) * uboElement.data.size;
        }
        uboElement.dataLen = size;
        // add some size offset..
        // must align to the nearest 16 bytes or internally nearest round size
        if (chunkSize % size !== 0 && chunkSize < 16) {
            // diff required to line up..
            var lineUpValue = (chunkSize % size) % 16;
            chunkSize += lineUpValue;
            offset += lineUpValue;
        }
        if ((chunkSize + size) > 16) {
            offset = Math.ceil(offset / 16) * 16;
            uboElement.offset = offset;
            offset += size;
            chunkSize = size;
        }
        else {
            uboElement.offset = offset;
            chunkSize += size;
            offset += size;
        }
    }
    offset = Math.ceil(offset / 16) * 16;
    return { uboElements: uboElements, size: offset };
}
function getUBOData(uniforms, uniformData) {
    var usedUniformDatas = [];
    // build..
    for (var i in uniforms) {
        if (uniformData[i]) {
            usedUniformDatas.push(uniformData[i]);
        }
    }
    // sort them out by index!
    usedUniformDatas.sort(function (a, b) { return a.index - b.index; });
    return usedUniformDatas;
}
function generateUniformBufferSync(group, uniformData) {
    if (!group.autoManage) {
        // if the group is nott automatically managed, we don't need to generate a special function for it...
        return { size: 0, syncFunc: uboUpdate };
    }
    var usedUniformDatas = getUBOData(group.uniforms, uniformData);
    var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size;
    var funcFragments = ["\n    var v = null;\n    var v2 = null;\n    var cv = null;\n    var t = 0;\n    var gl = renderer.gl\n    var index = 0;\n    var data = buffer.data;\n    "];
    for (var i = 0; i < uboElements.length; i++) {
        var uboElement = uboElements[i];
        var uniform = group.uniforms[uboElement.data.name];
        var name = uboElement.data.name;
        var parsed = false;
        for (var j = 0; j < uniformParsers.length; j++) {
            var uniformParser = uniformParsers[j];
            if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) {
                funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform));
                parsed = true;
                break;
            }
        }
        if (!parsed) {
            if (uboElement.data.size > 1) {
                var size_1 = mapSize(uboElement.data.type);
                var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1);
                var elementSize = size_1 / rowSize;
                var remainder = (4 - (elementSize % 4)) % 4;
                funcFragments.push("\n                cv = ud." + name + ".value;\n                v = uv." + name + ";\n                offset = " + uboElement.offset / 4 + ";\n\n                t = 0;\n\n                for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n                {\n                    for(var j = 0; j < " + elementSize + "; j++)\n                    {\n                        data[offset++] = v[t++];\n                    }\n                    offset += " + remainder + ";\n                }\n\n                ");
            }
            else {
                var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type];
                funcFragments.push("\n                cv = ud." + name + ".value;\n                v = uv." + name + ";\n                offset = " + uboElement.offset / 4 + ";\n                " + template + ";\n                ");
            }
        }
    }
    funcFragments.push("\n       renderer.buffer.update(buffer);\n    ");
    return {
        size: size,
        // eslint-disable-next-line no-new-func
        syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n'))
    };
}

/**
 * @private
 */
var IGLUniformData = /** @class */ (function () {
    function IGLUniformData() {
    }
    return IGLUniformData;
}());
/**
 * Helper class to create a WebGL Program
 *
 * @memberof PIXI
 */
var GLProgram = /** @class */ (function () {
    /**
     * Makes a new Pixi program.
     *
     * @param program - webgl program
     * @param uniformData - uniforms
     */
    function GLProgram(program, uniformData) {
        this.program = program;
        this.uniformData = uniformData;
        this.uniformGroups = {};
        this.uniformDirtyGroups = {};
        this.uniformBufferBindings = {};
    }
    /** Destroys this program. */
    GLProgram.prototype.destroy = function () {
        this.uniformData = null;
        this.uniformGroups = null;
        this.uniformDirtyGroups = null;
        this.uniformBufferBindings = null;
        this.program = null;
    };
    return GLProgram;
}());

/**
 * returns the attribute data from the program
 * @private
 *
 * @param {WebGLProgram} [program] - the WebGL program
 * @param {WebGLRenderingContext} [gl] - the WebGL context
 *
 * @returns {object} the attribute data for this program
 */
function getAttributeData(program, gl) {
    var attributes = {};
    var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
    for (var i = 0; i < totalAttributes; i++) {
        var attribData = gl.getActiveAttrib(program, i);
        if (attribData.name.indexOf('gl_') === 0) {
            continue;
        }
        var type = mapType(gl, attribData.type);
        var data = {
            type: type,
            name: attribData.name,
            size: mapSize(type),
            location: gl.getAttribLocation(program, attribData.name),
        };
        attributes[attribData.name] = data;
    }
    return attributes;
}

/**
 * returns the uniform data from the program
 * @private
 *
 * @param program - the webgl program
 * @param gl - the WebGL context
 *
 * @returns {object} the uniform data for this program
 */
function getUniformData(program, gl) {
    var uniforms = {};
    var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
    for (var i = 0; i < totalUniforms; i++) {
        var uniformData = gl.getActiveUniform(program, i);
        var name = uniformData.name.replace(/\[.*?\]$/, '');
        var isArray = !!(uniformData.name.match(/\[.*?\]$/));
        var type = mapType(gl, uniformData.type);
        uniforms[name] = {
            name: name,
            index: i,
            type: type,
            size: uniformData.size,
            isArray: isArray,
            value: defaultValue(type, uniformData.size),
        };
    }
    return uniforms;
}

/**
 * generates a WebGL Program object from a high level Pixi Program.
 *
 * @param gl - a rendering context on which to generate the program
 * @param program - the high level Pixi Program.
 */
function generateProgram(gl, program) {
    var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc);
    var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc);
    var webGLProgram = gl.createProgram();
    gl.attachShader(webGLProgram, glVertShader);
    gl.attachShader(webGLProgram, glFragShader);
    gl.linkProgram(webGLProgram);
    if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) {
        logProgramError(gl, webGLProgram, glVertShader, glFragShader);
    }
    program.attributeData = getAttributeData(webGLProgram, gl);
    program.uniformData = getUniformData(webGLProgram, gl);
    // GLSL 1.00: bind attributes sorted by name in ascending order
    // GLSL 3.00: don't change the attribute locations that where chosen by the compiler
    //            or assigned by the layout specifier in the shader source code
    if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) {
        var keys = Object.keys(program.attributeData);
        keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow
        for (var i = 0; i < keys.length; i++) {
            program.attributeData[keys[i]].location = i;
            gl.bindAttribLocation(webGLProgram, i, keys[i]);
        }
        gl.linkProgram(webGLProgram);
    }
    gl.deleteShader(glVertShader);
    gl.deleteShader(glFragShader);
    var uniformData = {};
    for (var i in program.uniformData) {
        var data = program.uniformData[i];
        uniformData[i] = {
            location: gl.getUniformLocation(webGLProgram, i),
            value: defaultValue(data.type, data.size),
        };
    }
    var glProgram = new GLProgram(webGLProgram, uniformData);
    return glProgram;
}

var UID$4 = 0;
// default sync data so we don't create a new one each time!
var defaultSyncData = { textureCount: 0, uboCount: 0 };
/**
 * System plugin to the renderer to manage shaders.
 *
 * @memberof PIXI
 */
var ShaderSystem = /** @class */ (function () {
    /** @param renderer - The renderer this System works for. */
    function ShaderSystem(renderer) {
        this.destroyed = false;
        this.renderer = renderer;
        // Validation check that this environment support `new Function`
        this.systemCheck();
        this.gl = null;
        this.shader = null;
        this.program = null;
        this.cache = {};
        this._uboCache = {};
        this.id = UID$4++;
    }
    /**
     * Overrideable function by `@pixi/unsafe-eval` to silence
     * throwing an error if platform doesn't support unsafe-evals.
     *
     * @private
     */
    ShaderSystem.prototype.systemCheck = function () {
        if (!unsafeEvalSupported()) {
            throw new Error('Current environment does not allow unsafe-eval, '
                + 'please use @pixi/unsafe-eval module to enable support.');
        }
    };
    ShaderSystem.prototype.contextChange = function (gl) {
        this.gl = gl;
        this.reset();
    };
    /**
     * Changes the current shader to the one given in parameter.
     *
     * @param shader - the new shader
     * @param dontSync - false if the shader should automatically sync its uniforms.
     * @returns the glProgram that belongs to the shader.
     */
    ShaderSystem.prototype.bind = function (shader, dontSync) {
        shader.uniforms.globals = this.renderer.globalUniforms;
        var program = shader.program;
        var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader);
        this.shader = shader;
        // TODO - some current Pixi plugins bypass this.. so it not safe to use yet..
        if (this.program !== program) {
            this.program = program;
            this.gl.useProgram(glProgram.program);
        }
        if (!dontSync) {
            defaultSyncData.textureCount = 0;
            defaultSyncData.uboCount = 0;
            this.syncUniformGroup(shader.uniformGroup, defaultSyncData);
        }
        return glProgram;
    };
    /**
     * Uploads the uniforms values to the currently bound shader.
     *
     * @param uniforms - the uniforms values that be applied to the current shader
     */
    ShaderSystem.prototype.setUniforms = function (uniforms) {
        var shader = this.shader.program;
        var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID];
        shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer);
    };
    /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
    /**
     * Syncs uniforms on the group
     *
     * @param group - the uniform group to sync
     * @param syncData - this is data that is passed to the sync function and any nested sync functions
     */
    ShaderSystem.prototype.syncUniformGroup = function (group, syncData) {
        var glProgram = this.getGlProgram();
        if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) {
            glProgram.uniformDirtyGroups[group.id] = group.dirtyId;
            this.syncUniforms(group, glProgram, syncData);
        }
    };
    /**
     * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead.
     */
    ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) {
        var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group);
        syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData);
    };
    ShaderSystem.prototype.createSyncGroups = function (group) {
        var id = this.getSignature(group, this.shader.program.uniformData, 'u');
        if (!this.cache[id]) {
            this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData);
        }
        group.syncUniforms[this.shader.program.id] = this.cache[id];
        return group.syncUniforms[this.shader.program.id];
    };
    /**
     * Syncs uniform buffers
     *
     * @param group - the uniform buffer group to sync
     * @param name - the name of the uniform buffer
     */
    ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) {
        var glProgram = this.getGlProgram();
        if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) {
            group.dirtyId = 0;
            var syncFunc = glProgram.uniformGroups[group.id]
                || this.createSyncBufferGroup(group, glProgram, name);
            // TODO wrap update in a cache??
            group.buffer.update();
            syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer);
        }
        this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]);
    };
    /**
     * Will create a function that uploads a uniform buffer using the STD140 standard.
     * The upload function will then be cached for future calls
     * If a group is manually managed, then a simple upload function is generated
     *
     * @param group - the uniform buffer group to sync
     * @param glProgram - the gl program to attach the uniform bindings to
     * @param name - the name of the uniform buffer (must exist on the shader)
     */
    ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) {
        var gl = this.renderer.gl;
        this.renderer.buffer.bind(group.buffer);
        // bind them...
        var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name);
        glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount;
        gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount);
        this.shader.uniformBindCount++;
        var id = this.getSignature(group, this.shader.program.uniformData, 'ubo');
        var uboData = this._uboCache[id];
        if (!uboData) {
            uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData);
        }
        if (group.autoManage) {
            var data = new Float32Array(uboData.size / 4);
            group.buffer.update(data);
        }
        glProgram.uniformGroups[group.id] = uboData.syncFunc;
        return glProgram.uniformGroups[group.id];
    };
    /**
     * Takes a uniform group and data and generates a unique signature for them.
     *
     * @param group - The uniform group to get signature of
     * @param uniformData - Uniform information generated by the shader
     * @returns Unique signature of the uniform group
     */
    ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) {
        var uniforms = group.uniforms;
        var strings = [preFix + "-"];
        for (var i in uniforms) {
            strings.push(i);
            if (uniformData[i]) {
                strings.push(uniformData[i].type);
            }
        }
        return strings.join('-');
    };
    /**
     * Returns the underlying GLShade rof the currently bound shader.
     *
     * This can be handy for when you to have a little more control over the setting of your uniforms.
     *
     * @return The glProgram for the currently bound Shader for this context
     */
    ShaderSystem.prototype.getGlProgram = function () {
        if (this.shader) {
            return this.shader.program.glPrograms[this.renderer.CONTEXT_UID];
        }
        return null;
    };
    /**
     * Generates a glProgram version of the Shader provided.
     *
     * @param shader - The shader that the glProgram will be based on.
     * @return A shiny new glProgram!
     */
    ShaderSystem.prototype.generateProgram = function (shader) {
        var gl = this.gl;
        var program = shader.program;
        var glProgram = generateProgram(gl, program);
        program.glPrograms[this.renderer.CONTEXT_UID] = glProgram;
        return glProgram;
    };
    /** Resets ShaderSystem state, does not affect WebGL state. */
    ShaderSystem.prototype.reset = function () {
        this.program = null;
        this.shader = null;
    };
    /** Destroys this System and removes all its textures. */
    ShaderSystem.prototype.destroy = function () {
        this.renderer = null;
        // TODO implement destroy method for ShaderSystem
        this.destroyed = true;
    };
    return ShaderSystem;
}());

/**
 * Maps gl blend combinations to WebGL.
 *
 * @memberof PIXI
 * @function mapWebGLBlendModesToPixi
 * @private
 * @param {WebGLRenderingContext} gl - The rendering context.
 * @param {number[][]} [array=[]] - The array to output into.
 * @return {number[][]} Mapped modes.
 */
function mapWebGLBlendModesToPixi(gl, array) {
    if (array === void 0) { array = []; }
    // TODO - premultiply alpha would be different.
    // add a boolean for that!
    array[constants_BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.ADD] = [gl.ONE, gl.ONE];
    array[constants_BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.NONE] = [0, 0];
    // not-premultiplied blend modes
    array[constants_BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE];
    array[constants_BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
    // composite operations
    array[constants_BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO];
    array[constants_BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO];
    array[constants_BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE];
    array[constants_BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA];
    array[constants_BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA];
    array[constants_BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA];
    array[constants_BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
    // SUBTRACT from flash
    array[constants_BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD];
    return array;
}

var BLEND$1 = 0;
var OFFSET$1 = 1;
var CULLING$1 = 2;
var DEPTH_TEST$1 = 3;
var WINDING$1 = 4;
var DEPTH_MASK$1 = 5;
/**
 * System plugin to the renderer to manage WebGL state machines.
 *
 * @memberof PIXI
 */
var StateSystem = /** @class */ (function () {
    function StateSystem() {
        this.gl = null;
        this.stateId = 0;
        this.polygonOffset = 0;
        this.blendMode = constants_BLEND_MODES.NONE;
        this._blendEq = false;
        // map functions for when we set state..
        this.map = [];
        this.map[BLEND$1] = this.setBlend;
        this.map[OFFSET$1] = this.setOffset;
        this.map[CULLING$1] = this.setCullFace;
        this.map[DEPTH_TEST$1] = this.setDepthTest;
        this.map[WINDING$1] = this.setFrontFace;
        this.map[DEPTH_MASK$1] = this.setDepthMask;
        this.checks = [];
        this.defaultState = new State();
        this.defaultState.blend = true;
    }
    StateSystem.prototype.contextChange = function (gl) {
        this.gl = gl;
        this.blendModes = mapWebGLBlendModesToPixi(gl);
        this.set(this.defaultState);
        this.reset();
    };
    /**
     * Sets the current state
     *
     * @param {*} state - The state to set.
     */
    StateSystem.prototype.set = function (state) {
        state = state || this.defaultState;
        // TODO maybe to an object check? ( this.state === state )?
        if (this.stateId !== state.data) {
            var diff = this.stateId ^ state.data;
            var i = 0;
            // order from least to most common
            while (diff) {
                if (diff & 1) {
                    // state change!
                    this.map[i].call(this, !!(state.data & (1 << i)));
                }
                diff = diff >> 1;
                i++;
            }
            this.stateId = state.data;
        }
        // based on the above settings we check for specific modes..
        // for example if blend is active we check and set the blend modes
        // or of polygon offset is active we check the poly depth.
        for (var i = 0; i < this.checks.length; i++) {
            this.checks[i](this, state);
        }
    };
    /**
     * Sets the state, when previous state is unknown.
     *
     * @param {*} state - The state to set
     */
    StateSystem.prototype.forceState = function (state) {
        state = state || this.defaultState;
        for (var i = 0; i < this.map.length; i++) {
            this.map[i].call(this, !!(state.data & (1 << i)));
        }
        for (var i = 0; i < this.checks.length; i++) {
            this.checks[i](this, state);
        }
        this.stateId = state.data;
    };
    /**
     * Sets whether to enable or disable blending.
     *
     * @param value - Turn on or off WebGl blending.
     */
    StateSystem.prototype.setBlend = function (value) {
        this.updateCheck(StateSystem.checkBlendMode, value);
        this.gl[value ? 'enable' : 'disable'](this.gl.BLEND);
    };
    /**
     * Sets whether to enable or disable polygon offset fill.
     *
     * @param value - Turn on or off webgl polygon offset testing.
     */
    StateSystem.prototype.setOffset = function (value) {
        this.updateCheck(StateSystem.checkPolygonOffset, value);
        this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL);
    };
    /**
     * Sets whether to enable or disable depth test.
     *
     * @param value - Turn on or off webgl depth testing.
     */
    StateSystem.prototype.setDepthTest = function (value) {
        this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST);
    };
    /**
     * Sets whether to enable or disable depth mask.
     *
     * @param value - Turn on or off webgl depth mask.
     */
    StateSystem.prototype.setDepthMask = function (value) {
        this.gl.depthMask(value);
    };
    /**
     * Sets whether to enable or disable cull face.
     *
     * @param {boolean} value - Turn on or off webgl cull face.
     */
    StateSystem.prototype.setCullFace = function (value) {
        this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE);
    };
    /**
     * Sets the gl front face.
     *
     * @param {boolean} value - true is clockwise and false is counter-clockwise
     */
    StateSystem.prototype.setFrontFace = function (value) {
        this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']);
    };
    /**
     * Sets the blend mode.
     *
     * @param {number} value - The blend mode to set to.
     */
    StateSystem.prototype.setBlendMode = function (value) {
        if (value === this.blendMode) {
            return;
        }
        this.blendMode = value;
        var mode = this.blendModes[value];
        var gl = this.gl;
        if (mode.length === 2) {
            gl.blendFunc(mode[0], mode[1]);
        }
        else {
            gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]);
        }
        if (mode.length === 6) {
            this._blendEq = true;
            gl.blendEquationSeparate(mode[4], mode[5]);
        }
        else if (this._blendEq) {
            this._blendEq = false;
            gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
        }
    };
    /**
     * Sets the polygon offset.
     *
     * @param {number} value - the polygon offset
     * @param {number} scale - the polygon offset scale
     */
    StateSystem.prototype.setPolygonOffset = function (value, scale) {
        this.gl.polygonOffset(value, scale);
    };
    // used
    /** Resets all the logic and disables the VAOs. */
    StateSystem.prototype.reset = function () {
        this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
        this.forceState(this.defaultState);
        this._blendEq = true;
        this.blendMode = -1;
        this.setBlendMode(0);
    };
    /**
     * Checks to see which updates should be checked based on which settings have been activated.
     *
     * For example, if blend is enabled then we should check the blend modes each time the state is changed
     * or if polygon fill is activated then we need to check if the polygon offset changes.
     * The idea is that we only check what we have too.
     *
     * @param func - the checking function to add or remove
     * @param value - should the check function be added or removed.
     */
    StateSystem.prototype.updateCheck = function (func, value) {
        var index = this.checks.indexOf(func);
        if (value && index === -1) {
            this.checks.push(func);
        }
        else if (!value && index !== -1) {
            this.checks.splice(index, 1);
        }
    };
    /**
     * A private little wrapper function that we call to check the blend mode.
     *
     * @param System - the System to perform the state check on
     * @param state - the state that the blendMode will pulled from
     */
    StateSystem.checkBlendMode = function (system, state) {
        system.setBlendMode(state.blendMode);
    };
    /**
     * A private little wrapper function that we call to check the polygon offset.
     *
     * @param System - the System to perform the state check on
     * @param state - the state that the blendMode will pulled from
     */
    StateSystem.checkPolygonOffset = function (system, state) {
        system.setPolygonOffset(1, state.polygonOffset);
    };
    /**
     * @ignore
     */
    StateSystem.prototype.destroy = function () {
        this.gl = null;
    };
    return StateSystem;
}());

/**
 * System plugin to the renderer to manage texture garbage collection on the GPU,
 * ensuring that it does not get clogged up with textures that are no longer being used.
 *
 * @memberof PIXI
 */
var TextureGCSystem = /** @class */ (function () {
    /** @param renderer - The renderer this System works for. */
    function TextureGCSystem(renderer) {
        this.renderer = renderer;
        this.count = 0;
        this.checkCount = 0;
        this.maxIdle = settings.GC_MAX_IDLE;
        this.checkCountMax = settings.GC_MAX_CHECK_COUNT;
        this.mode = settings.GC_MODE;
    }
    /**
     * Checks to see when the last time a texture was used
     * if the texture has not been used for a specified amount of time it will be removed from the GPU
     */
    TextureGCSystem.prototype.postrender = function () {
        if (!this.renderer.renderingToScreen) {
            return;
        }
        this.count++;
        if (this.mode === constants_GC_MODES.MANUAL) {
            return;
        }
        this.checkCount++;
        if (this.checkCount > this.checkCountMax) {
            this.checkCount = 0;
            this.run();
        }
    };
    /**
     * Checks to see when the last time a texture was used
     * if the texture has not been used for a specified amount of time it will be removed from the GPU
     */
    TextureGCSystem.prototype.run = function () {
        var tm = this.renderer.texture;
        var managedTextures = tm.managedTextures;
        var wasRemoved = false;
        for (var i = 0; i < managedTextures.length; i++) {
            var texture = managedTextures[i];
            // only supports non generated textures at the moment!
            if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) {
                tm.destroyTexture(texture, true);
                managedTextures[i] = null;
                wasRemoved = true;
            }
        }
        if (wasRemoved) {
            var j = 0;
            for (var i = 0; i < managedTextures.length; i++) {
                if (managedTextures[i] !== null) {
                    managedTextures[j++] = managedTextures[i];
                }
            }
            managedTextures.length = j;
        }
    };
    /**
     * Removes all the textures within the specified displayObject and its children from the GPU
     *
     * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from.
     */
    TextureGCSystem.prototype.unload = function (displayObject) {
        var tm = this.renderer.texture;
        var texture = displayObject._texture;
        // only destroy non generated textures
        if (texture && !texture.framebuffer) {
            tm.destroyTexture(texture);
        }
        for (var i = displayObject.children.length - 1; i >= 0; i--) {
            this.unload(displayObject.children[i]);
        }
    };
    TextureGCSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return TextureGCSystem;
}());

/**
 * Returns a lookup table that maps each type-format pair to a compatible internal format.
 *
 * @memberof PIXI
 * @function mapTypeAndFormatToInternalFormat
 * @private
 * @param {WebGLRenderingContext} gl - The rendering context.
 * @return {{ [type: number]: { [format: number]: number } }} Lookup table.
 */
function mapTypeAndFormatToInternalFormat(gl) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
    var table;
    if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) {
        table = (_a = {},
            _a[constants_TYPES.UNSIGNED_BYTE] = (_b = {},
                _b[constants_FORMATS.RGBA] = gl.RGBA8,
                _b[constants_FORMATS.RGB] = gl.RGB8,
                _b[constants_FORMATS.RG] = gl.RG8,
                _b[constants_FORMATS.RED] = gl.R8,
                _b[constants_FORMATS.RGBA_INTEGER] = gl.RGBA8UI,
                _b[constants_FORMATS.RGB_INTEGER] = gl.RGB8UI,
                _b[constants_FORMATS.RG_INTEGER] = gl.RG8UI,
                _b[constants_FORMATS.RED_INTEGER] = gl.R8UI,
                _b[constants_FORMATS.ALPHA] = gl.ALPHA,
                _b[constants_FORMATS.LUMINANCE] = gl.LUMINANCE,
                _b[constants_FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA,
                _b),
            _a[constants_TYPES.BYTE] = (_c = {},
                _c[constants_FORMATS.RGBA] = gl.RGBA8_SNORM,
                _c[constants_FORMATS.RGB] = gl.RGB8_SNORM,
                _c[constants_FORMATS.RG] = gl.RG8_SNORM,
                _c[constants_FORMATS.RED] = gl.R8_SNORM,
                _c[constants_FORMATS.RGBA_INTEGER] = gl.RGBA8I,
                _c[constants_FORMATS.RGB_INTEGER] = gl.RGB8I,
                _c[constants_FORMATS.RG_INTEGER] = gl.RG8I,
                _c[constants_FORMATS.RED_INTEGER] = gl.R8I,
                _c),
            _a[constants_TYPES.UNSIGNED_SHORT] = (_d = {},
                _d[constants_FORMATS.RGBA_INTEGER] = gl.RGBA16UI,
                _d[constants_FORMATS.RGB_INTEGER] = gl.RGB16UI,
                _d[constants_FORMATS.RG_INTEGER] = gl.RG16UI,
                _d[constants_FORMATS.RED_INTEGER] = gl.R16UI,
                _d[constants_FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16,
                _d),
            _a[constants_TYPES.SHORT] = (_e = {},
                _e[constants_FORMATS.RGBA_INTEGER] = gl.RGBA16I,
                _e[constants_FORMATS.RGB_INTEGER] = gl.RGB16I,
                _e[constants_FORMATS.RG_INTEGER] = gl.RG16I,
                _e[constants_FORMATS.RED_INTEGER] = gl.R16I,
                _e),
            _a[constants_TYPES.UNSIGNED_INT] = (_f = {},
                _f[constants_FORMATS.RGBA_INTEGER] = gl.RGBA32UI,
                _f[constants_FORMATS.RGB_INTEGER] = gl.RGB32UI,
                _f[constants_FORMATS.RG_INTEGER] = gl.RG32UI,
                _f[constants_FORMATS.RED_INTEGER] = gl.R32UI,
                _f[constants_FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24,
                _f),
            _a[constants_TYPES.INT] = (_g = {},
                _g[constants_FORMATS.RGBA_INTEGER] = gl.RGBA32I,
                _g[constants_FORMATS.RGB_INTEGER] = gl.RGB32I,
                _g[constants_FORMATS.RG_INTEGER] = gl.RG32I,
                _g[constants_FORMATS.RED_INTEGER] = gl.R32I,
                _g),
            _a[constants_TYPES.FLOAT] = (_h = {},
                _h[constants_FORMATS.RGBA] = gl.RGBA32F,
                _h[constants_FORMATS.RGB] = gl.RGB32F,
                _h[constants_FORMATS.RG] = gl.RG32F,
                _h[constants_FORMATS.RED] = gl.R32F,
                _h[constants_FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F,
                _h),
            _a[constants_TYPES.HALF_FLOAT] = (_j = {},
                _j[constants_FORMATS.RGBA] = gl.RGBA16F,
                _j[constants_FORMATS.RGB] = gl.RGB16F,
                _j[constants_FORMATS.RG] = gl.RG16F,
                _j[constants_FORMATS.RED] = gl.R16F,
                _j),
            _a[constants_TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {},
                _k[constants_FORMATS.RGB] = gl.RGB565,
                _k),
            _a[constants_TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {},
                _l[constants_FORMATS.RGBA] = gl.RGBA4,
                _l),
            _a[constants_TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {},
                _m[constants_FORMATS.RGBA] = gl.RGB5_A1,
                _m),
            _a[constants_TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {},
                _o[constants_FORMATS.RGBA] = gl.RGB10_A2,
                _o[constants_FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI,
                _o),
            _a[constants_TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {},
                _p[constants_FORMATS.RGB] = gl.R11F_G11F_B10F,
                _p),
            _a[constants_TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {},
                _q[constants_FORMATS.RGB] = gl.RGB9_E5,
                _q),
            _a[constants_TYPES.UNSIGNED_INT_24_8] = (_r = {},
                _r[constants_FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8,
                _r),
            _a[constants_TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {},
                _s[constants_FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8,
                _s),
            _a);
    }
    else {
        table = (_t = {},
            _t[constants_TYPES.UNSIGNED_BYTE] = (_u = {},
                _u[constants_FORMATS.RGBA] = gl.RGBA,
                _u[constants_FORMATS.RGB] = gl.RGB,
                _u[constants_FORMATS.ALPHA] = gl.ALPHA,
                _u[constants_FORMATS.LUMINANCE] = gl.LUMINANCE,
                _u[constants_FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA,
                _u),
            _t[constants_TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {},
                _v[constants_FORMATS.RGB] = gl.RGB,
                _v),
            _t[constants_TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {},
                _w[constants_FORMATS.RGBA] = gl.RGBA,
                _w),
            _t[constants_TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {},
                _x[constants_FORMATS.RGBA] = gl.RGBA,
                _x),
            _t);
    }
    return table;
}

/**
 * Internal texture for WebGL context.
 *
 * @memberof PIXI
 */
var GLTexture = /** @class */ (function () {
    function GLTexture(texture) {
        this.texture = texture;
        this.width = -1;
        this.height = -1;
        this.dirtyId = -1;
        this.dirtyStyleId = -1;
        this.mipmap = false;
        this.wrapMode = 33071;
        this.type = constants_TYPES.UNSIGNED_BYTE;
        this.internalFormat = constants_FORMATS.RGBA;
        this.samplerType = 0;
    }
    return GLTexture;
}());

/**
 * System plugin to the renderer to manage textures.
 *
 * @memberof PIXI
 */
var TextureSystem = /** @class */ (function () {
    /**
     * @param renderer - The renderer this system works for.
     */
    function TextureSystem(renderer) {
        this.renderer = renderer;
        // TODO set to max textures...
        this.boundTextures = [];
        this.currentLocation = -1;
        this.managedTextures = [];
        this._unknownBoundTextures = false;
        this.unknownTexture = new BaseTexture();
        this.hasIntegerTextures = false;
    }
    /** Sets up the renderer context and necessary buffers. */
    TextureSystem.prototype.contextChange = function () {
        var gl = this.gl = this.renderer.gl;
        this.CONTEXT_UID = this.renderer.CONTEXT_UID;
        this.webGLVersion = this.renderer.context.webGLVersion;
        this.internalFormats = mapTypeAndFormatToInternalFormat(gl);
        var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
        this.boundTextures.length = maxTextures;
        for (var i = 0; i < maxTextures; i++) {
            this.boundTextures[i] = null;
        }
        // TODO move this.. to a nice make empty textures class..
        this.emptyTextures = {};
        var emptyTexture2D = new GLTexture(gl.createTexture());
        gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
        this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D;
        this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture());
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture);
        for (var i = 0; i < 6; i++) {
            gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
        }
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        for (var i = 0; i < this.boundTextures.length; i++) {
            this.bind(null, i);
        }
    };
    /**
     * Bind a texture to a specific location
     *
     * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)`
     *
     * @param texture_ - Texture to bind
     * @param [location=0] - Location to bind at
     */
    TextureSystem.prototype.bind = function (texture, location) {
        if (location === void 0) { location = 0; }
        var gl = this.gl;
        texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture();
        // cannot bind partial texture
        // TODO: report a warning
        if (texture && texture.valid && !texture.parentTextureArray) {
            texture.touched = this.renderer.textureGC.count;
            var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture);
            if (this.boundTextures[location] !== texture) {
                if (this.currentLocation !== location) {
                    this.currentLocation = location;
                    gl.activeTexture(gl.TEXTURE0 + location);
                }
                gl.bindTexture(texture.target, glTexture.texture);
            }
            if (glTexture.dirtyId !== texture.dirtyId) {
                if (this.currentLocation !== location) {
                    this.currentLocation = location;
                    gl.activeTexture(gl.TEXTURE0 + location);
                }
                this.updateTexture(texture);
            }
            this.boundTextures[location] = texture;
        }
        else {
            if (this.currentLocation !== location) {
                this.currentLocation = location;
                gl.activeTexture(gl.TEXTURE0 + location);
            }
            gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture);
            this.boundTextures[location] = null;
        }
    };
    /**
     * Resets texture location and bound textures
     *
     * Actual `bind(null, i)` calls will be performed at next `unbind()` call
     */
    TextureSystem.prototype.reset = function () {
        this._unknownBoundTextures = true;
        this.hasIntegerTextures = false;
        this.currentLocation = -1;
        for (var i = 0; i < this.boundTextures.length; i++) {
            this.boundTextures[i] = this.unknownTexture;
        }
    };
    /**
     * Unbind a texture.
     *
     * @param texture - Texture to bind
     */
    TextureSystem.prototype.unbind = function (texture) {
        var _a = this, gl = _a.gl, boundTextures = _a.boundTextures;
        if (this._unknownBoundTextures) {
            this._unknownBoundTextures = false;
            // someone changed webGL state,
            // we have to be sure that our texture does not appear in multi-texture renderer samplers
            for (var i = 0; i < boundTextures.length; i++) {
                if (boundTextures[i] === this.unknownTexture) {
                    this.bind(null, i);
                }
            }
        }
        for (var i = 0; i < boundTextures.length; i++) {
            if (boundTextures[i] === texture) {
                if (this.currentLocation !== i) {
                    gl.activeTexture(gl.TEXTURE0 + i);
                    this.currentLocation = i;
                }
                gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture);
                boundTextures[i] = null;
            }
        }
    };
    /**
     * Ensures that current boundTextures all have FLOAT sampler type,
     * see {@link PIXI.SAMPLER_TYPES} for explanation.
     *
     * @param maxTextures - number of locations to check
     */
    TextureSystem.prototype.ensureSamplerType = function (maxTextures) {
        var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID;
        if (!hasIntegerTextures) {
            return;
        }
        for (var i = maxTextures - 1; i >= 0; --i) {
            var tex = boundTextures[i];
            if (tex) {
                var glTexture = tex._glTextures[CONTEXT_UID];
                if (glTexture.samplerType !== constants_SAMPLER_TYPES.FLOAT) {
                    this.renderer.texture.unbind(tex);
                }
            }
        }
    };
    /**
     * Initialize a texture
     *
     * @private
     * @param texture - Texture to initialize
     */
    TextureSystem.prototype.initTexture = function (texture) {
        var glTexture = new GLTexture(this.gl.createTexture());
        // guarantee an update..
        glTexture.dirtyId = -1;
        texture._glTextures[this.CONTEXT_UID] = glTexture;
        this.managedTextures.push(texture);
        texture.on('dispose', this.destroyTexture, this);
        return glTexture;
    };
    TextureSystem.prototype.initTextureType = function (texture, glTexture) {
        var _a, _b;
        glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format;
        if (this.webGLVersion === 2 && texture.type === constants_TYPES.HALF_FLOAT) {
            // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES
            // we have to convert it to WebGL HALF_FLOAT
            glTexture.type = this.gl.HALF_FLOAT;
        }
        else {
            glTexture.type = texture.type;
        }
    };
    /**
     * Update a texture
     *
     * @private
     * @param {PIXI.BaseTexture} texture - Texture to initialize
     */
    TextureSystem.prototype.updateTexture = function (texture) {
        var glTexture = texture._glTextures[this.CONTEXT_UID];
        if (!glTexture) {
            return;
        }
        var renderer = this.renderer;
        this.initTextureType(texture, glTexture);
        if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) {
            // texture is uploaded, dont do anything!
            if (glTexture.samplerType !== constants_SAMPLER_TYPES.FLOAT) {
                this.hasIntegerTextures = true;
            }
        }
        else {
            // default, renderTexture-like logic
            var width = texture.realWidth;
            var height = texture.realHeight;
            var gl = renderer.gl;
            if (glTexture.width !== width
                || glTexture.height !== height
                || glTexture.dirtyId < 0) {
                glTexture.width = width;
                glTexture.height = height;
                gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null);
            }
        }
        // lets only update what changes..
        if (texture.dirtyStyleId !== glTexture.dirtyStyleId) {
            this.updateTextureStyle(texture);
        }
        glTexture.dirtyId = texture.dirtyId;
    };
    /**
     * Deletes the texture from WebGL
     *
     * @private
     * @param texture_ - the texture to destroy
     * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
     */
    TextureSystem.prototype.destroyTexture = function (texture, skipRemove) {
        var gl = this.gl;
        texture = texture.castToBaseTexture();
        if (texture._glTextures[this.CONTEXT_UID]) {
            this.unbind(texture);
            gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture);
            texture.off('dispose', this.destroyTexture, this);
            delete texture._glTextures[this.CONTEXT_UID];
            if (!skipRemove) {
                var i = this.managedTextures.indexOf(texture);
                if (i !== -1) {
                    removeItems(this.managedTextures, i, 1);
                }
            }
        }
    };
    /**
     * Update texture style such as mipmap flag
     *
     * @private
     * @param {PIXI.BaseTexture} texture - Texture to update
     */
    TextureSystem.prototype.updateTextureStyle = function (texture) {
        var glTexture = texture._glTextures[this.CONTEXT_UID];
        if (!glTexture) {
            return;
        }
        if ((texture.mipmap === constants_MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) {
            glTexture.mipmap = false;
        }
        else {
            glTexture.mipmap = texture.mipmap >= 1;
        }
        if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) {
            glTexture.wrapMode = constants_WRAP_MODES.CLAMP;
        }
        else {
            glTexture.wrapMode = texture.wrapMode;
        }
        if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) ;
        else {
            this.setStyle(texture, glTexture);
        }
        glTexture.dirtyStyleId = texture.dirtyStyleId;
    };
    /**
     * Set style for texture
     *
     * @private
     * @param texture - Texture to update
     * @param glTexture
     */
    TextureSystem.prototype.setStyle = function (texture, glTexture) {
        var gl = this.gl;
        if (glTexture.mipmap && texture.mipmap !== constants_MIPMAP_MODES.ON_MANUAL) {
            gl.generateMipmap(texture.target);
        }
        gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode);
        gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode);
        if (glTexture.mipmap) {
            /* eslint-disable max-len */
            gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === constants_SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
            /* eslint-disable max-len */
            var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering;
            if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === constants_SCALE_MODES.LINEAR) {
                var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT));
                gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level);
            }
        }
        else {
            gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === constants_SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST);
        }
        gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === constants_SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST);
    };
    TextureSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    return TextureSystem;
}());



var _systems = {
    __proto__: null,
    FilterSystem: FilterSystem,
    BatchSystem: BatchSystem,
    ContextSystem: ContextSystem,
    FramebufferSystem: FramebufferSystem,
    GeometrySystem: GeometrySystem,
    MaskSystem: MaskSystem,
    ScissorSystem: ScissorSystem,
    StencilSystem: StencilSystem,
    ProjectionSystem: ProjectionSystem,
    RenderTextureSystem: RenderTextureSystem,
    ShaderSystem: ShaderSystem,
    StateSystem: StateSystem,
    TextureGCSystem: TextureGCSystem,
    TextureSystem: TextureSystem
};

var tempMatrix$2 = new Matrix();
/**
 * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer}
 * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene.
 *
 * @abstract
 * @class
 * @extends PIXI.utils.EventEmitter
 * @memberof PIXI
 */
var AbstractRenderer = /** @class */ (function (_super) {
    core_extends(AbstractRenderer, _super);
    /**
     * @param system - The name of the system this renderer is for.
     * @param [options] - The optional renderer parameters.
     * @param {number} [options.width=800] - The width of the screen.
     * @param {number} [options.height=600] - The height of the screen.
     * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional.
     * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
     *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
     *   canvas needs to be opaque, possibly for performance reasons on some older devices.
     * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for
     *   resolutions other than 1.
     * @param {boolean} [options.antialias=false] - Sets antialias
     * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
     * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation,
     *  enable this if you need to call toDataUrl on the WebGL context.
     * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or
     *      not before the new render pass.
     * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
     *  (shown if not transparent).
     * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
     */
    function AbstractRenderer(type, options) {
        if (type === void 0) { type = constants_RENDERER_TYPE.UNKNOWN; }
        var _this = _super.call(this) || this;
        // Add the default render options
        options = Object.assign({}, settings.RENDER_OPTIONS, options);
        /**
         * The supplied constructor options.
         *
         * @member {Object}
         * @readOnly
         */
        _this.options = options;
        /**
         * The type of the renderer.
         *
         * @member {number}
         * @default PIXI.RENDERER_TYPE.UNKNOWN
         * @see PIXI.RENDERER_TYPE
         */
        _this.type = type;
        /**
         * Measurements of the screen. (0, 0, screenWidth, screenHeight).
         *
         * Its safe to use as filterArea or hitArea for the whole stage.
         *
         * @member {PIXI.Rectangle}
         */
        _this.screen = new Rectangle(0, 0, options.width, options.height);
        /**
         * The canvas element that everything is drawn to.
         *
         * @member {HTMLCanvasElement}
         */
        _this.view = options.view || document.createElement('canvas');
        /**
         * The resolution / device pixel ratio of the renderer.
         *
         * @member {number}
         * @default PIXI.settings.RESOLUTION
         */
        _this.resolution = options.resolution || settings.RESOLUTION;
        /**
         * Pass-thru setting for the canvas' context `alpha` property. This is typically
         * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`.
         *
         * @member {boolean}
         */
        _this.useContextAlpha = options.useContextAlpha;
        /**
         * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically.
         *
         * @member {boolean}
         */
        _this.autoDensity = !!options.autoDensity;
        /**
         * The value of the preserveDrawingBuffer flag affects whether or not the contents of
         * the stencil buffer is retained after rendering.
         *
         * @member {boolean}
         */
        _this.preserveDrawingBuffer = options.preserveDrawingBuffer;
        /**
         * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
         * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every
         * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect
         * to clear the canvas every frame. Disable this by setting this to false. For example, if
         * your game has a canvas filling background image you often don't need this set.
         *
         * @member {boolean}
         * @default
         */
        _this.clearBeforeRender = options.clearBeforeRender;
        /**
         * The background color as a number.
         *
         * @member {number}
         * @protected
         */
        _this._backgroundColor = 0x000000;
        /**
         * The background color as an [R, G, B, A] array.
         *
         * @member {number[]}
         * @protected
         */
        _this._backgroundColorRgba = [0, 0, 0, 1];
        /**
         * The background color as a string.
         *
         * @member {string}
         * @protected
         */
        _this._backgroundColorString = '#000000';
        _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter
        _this.backgroundAlpha = options.backgroundAlpha;
        // @deprecated
        if (options.transparent !== undefined) {
            deprecation('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.');
            _this.useContextAlpha = options.transparent;
            _this.backgroundAlpha = options.transparent ? 0 : 1;
        }
        /**
         * The last root object that the renderer tried to render.
         *
         * @member {PIXI.DisplayObject}
         * @protected
         */
        _this._lastObjectRendered = null;
        /**
         * Collection of plugins.
         * @readonly
         * @member {object}
         */
        _this.plugins = {};
        return _this;
    }
    /**
     * Initialize the plugins.
     *
     * @protected
     * @param {object} staticMap - The dictionary of statically saved plugins.
     */
    AbstractRenderer.prototype.initPlugins = function (staticMap) {
        for (var o in staticMap) {
            this.plugins[o] = new (staticMap[o])(this);
        }
    };
    Object.defineProperty(AbstractRenderer.prototype, "width", {
        /**
         * Same as view.width, actual number of pixels in the canvas by horizontal.
         *
         * @member {number}
         * @readonly
         * @default 800
         */
        get: function () {
            return this.view.width;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AbstractRenderer.prototype, "height", {
        /**
         * Same as view.height, actual number of pixels in the canvas by vertical.
         *
         * @member {number}
         * @readonly
         * @default 600
         */
        get: function () {
            return this.view.height;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Resizes the screen and canvas as close as possible to the specified width and height.
     * Canvas dimensions are multiplied by resolution and rounded to the nearest integers.
     * The new canvas dimensions divided by the resolution become the new screen dimensions.
     *
     * @param desiredScreenWidth - The desired width of the screen.
     * @param desiredScreenHeight - The desired height of the screen.
     */
    AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) {
        this.view.width = Math.round(desiredScreenWidth * this.resolution);
        this.view.height = Math.round(desiredScreenHeight * this.resolution);
        var screenWidth = this.view.width / this.resolution;
        var screenHeight = this.view.height / this.resolution;
        this.screen.width = screenWidth;
        this.screen.height = screenHeight;
        if (this.autoDensity) {
            this.view.style.width = screenWidth + "px";
            this.view.style.height = screenHeight + "px";
        }
        /**
         * Fired after view has been resized.
         *
         * @event PIXI.Renderer#resize
         * @param {number} screenWidth - The new width of the screen.
         * @param {number} screenHeight - The new height of the screen.
         */
        this.emit('resize', screenWidth, screenHeight);
    };
    /**
     * @ignore
     */
    AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) {
        if (options === void 0) { options = {}; }
        // @deprecated parameters spread, use options instead
        if (typeof options === 'number') {
            deprecation('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.');
            options = { scaleMode: options, resolution: resolution, region: region };
        }
        var manualRegion = options.region, textureOptions = __rest(options, ["region"]);
        region = manualRegion || displayObject.getLocalBounds(null, true);
        // minimum texture size is 1x1, 0x0 will throw an error
        if (region.width === 0)
            { region.width = 1; }
        if (region.height === 0)
            { region.height = 1; }
        var renderTexture = RenderTexture.create(__assign({ width: region.width, height: region.height }, textureOptions));
        tempMatrix$2.tx = -region.x;
        tempMatrix$2.ty = -region.y;
        this.render(displayObject, {
            renderTexture: renderTexture,
            clear: false,
            transform: tempMatrix$2,
            skipUpdateTransform: !!displayObject.parent
        });
        return renderTexture;
    };
    /**
     * Removes everything from the renderer and optionally removes the Canvas DOM element.
     *
     * @param [removeView=false] - Removes the Canvas element from the DOM.
     */
    AbstractRenderer.prototype.destroy = function (removeView) {
        for (var o in this.plugins) {
            this.plugins[o].destroy();
            this.plugins[o] = null;
        }
        if (removeView && this.view.parentNode) {
            this.view.parentNode.removeChild(this.view);
        }
        var thisAny = this;
        // null-ing all objects, that's a tradition!
        thisAny.plugins = null;
        thisAny.type = constants_RENDERER_TYPE.UNKNOWN;
        thisAny.view = null;
        thisAny.screen = null;
        thisAny._tempDisplayObjectParent = null;
        thisAny.options = null;
        this._backgroundColorRgba = null;
        this._backgroundColorString = null;
        this._lastObjectRendered = null;
    };
    Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", {
        /**
         * The background color to fill if not transparent
         *
         * @member {number}
         */
        get: function () {
            return this._backgroundColor;
        },
        set: function (value) {
            this._backgroundColor = value;
            this._backgroundColorString = hex2string(value);
            hex2rgb(value, this._backgroundColorRgba);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", {
        /**
         * The background color alpha. Setting this to 0 will make the canvas transparent.
         *
         * @member {number}
         */
        get: function () {
            return this._backgroundColorRgba[3];
        },
        set: function (value) {
            this._backgroundColorRgba[3] = value;
        },
        enumerable: false,
        configurable: true
    });
    return AbstractRenderer;
}((eventemitter3_default())));

var GLBuffer = /** @class */ (function () {
    function GLBuffer(buffer) {
        this.buffer = buffer || null;
        this.updateID = -1;
        this.byteLength = -1;
        this.refCount = 0;
    }
    return GLBuffer;
}());

/**
 * System plugin to the renderer to manage buffers.
 *
 * WebGL uses Buffers as a way to store objects to the GPU.
 * This system makes working with them a lot easier.
 *
 * Buffers are used in three main places in WebGL
 * - geometry information
 * - Uniform information (via uniform buffer objects - a WebGL 2 only feature)
 * - Transform feedback information. (WebGL 2 only feature)
 *
 * This system will handle the binding of buffers to the GPU as well as uploading
 * them. With this system, you never need to work directly with GPU buffers, but instead work with
 * the PIXI.Buffer class.
 *
 *
 * @class
 * @memberof PIXI
 */
var BufferSystem = /** @class */ (function () {
    /**
     * @param {PIXI.Renderer} renderer - The renderer this System works for.
     */
    function BufferSystem(renderer) {
        this.renderer = renderer;
        this.managedBuffers = {};
        this.boundBufferBases = {};
    }
    /**
     * @ignore
     */
    BufferSystem.prototype.destroy = function () {
        this.renderer = null;
    };
    /**
     * Sets up the renderer context and necessary buffers.
     */
    BufferSystem.prototype.contextChange = function () {
        this.disposeAll(true);
        this.gl = this.renderer.gl;
        // TODO fill out...
        this.CONTEXT_UID = this.renderer.CONTEXT_UID;
    };
    /**
     * This binds specified buffer. On first run, it will create the webGL buffers for the context too
     *
     * @param buffer - the buffer to bind to the renderer
     */
    BufferSystem.prototype.bind = function (buffer) {
        var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
        var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
        gl.bindBuffer(buffer.type, glBuffer.buffer);
    };
    /**
     * Binds an uniform buffer to at the given index.
     *
     * A cache is used so a buffer will not be bound again if already bound.
     *
     * @param buffer - the buffer to bind
     * @param index - the base index to bind it to.
     */
    BufferSystem.prototype.bindBufferBase = function (buffer, index) {
        var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
        if (this.boundBufferBases[index] !== buffer) {
            var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
            this.boundBufferBases[index] = buffer;
            gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer);
        }
    };
    /**
     * Binds a buffer whilst also binding its range.
     * This will make the buffer start from the offset supplied rather than 0 when it is read.
     *
     * @param buffer - the buffer to bind
     * @param index - the base index to bind at, defaults to 0
     * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc
     */
    BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) {
        var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
        offset = offset || 0;
        var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
        gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256);
    };
    /**
     * Will ensure the data in the buffer is uploaded to the GPU.
     *
     * @param {PIXI.Buffer} buffer - the buffer to update
     */
    BufferSystem.prototype.update = function (buffer) {
        var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
        var glBuffer = buffer._glBuffers[CONTEXT_UID];
        if (buffer._updateID === glBuffer.updateID) {
            return;
        }
        glBuffer.updateID = buffer._updateID;
        gl.bindBuffer(buffer.type, glBuffer.buffer);
        if (glBuffer.byteLength >= buffer.data.byteLength) {
            // offset is always zero for now!
            gl.bufferSubData(buffer.type, 0, buffer.data);
        }
        else {
            var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW;
            glBuffer.byteLength = buffer.data.byteLength;
            gl.bufferData(buffer.type, buffer.data, drawType);
        }
    };
    /**
     * Disposes buffer
     * @param {PIXI.Buffer} buffer - buffer with data
     * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray
     */
    BufferSystem.prototype.dispose = function (buffer, contextLost) {
        if (!this.managedBuffers[buffer.id]) {
            return;
        }
        delete this.managedBuffers[buffer.id];
        var glBuffer = buffer._glBuffers[this.CONTEXT_UID];
        var gl = this.gl;
        buffer.disposeRunner.remove(this);
        if (!glBuffer) {
            return;
        }
        if (!contextLost) {
            gl.deleteBuffer(glBuffer.buffer);
        }
        delete buffer._glBuffers[this.CONTEXT_UID];
    };
    /**
     * dispose all WebGL resources of all managed buffers
     * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls
     */
    BufferSystem.prototype.disposeAll = function (contextLost) {
        var all = Object.keys(this.managedBuffers);
        for (var i = 0; i < all.length; i++) {
            this.dispose(this.managedBuffers[all[i]], contextLost);
        }
    };
    /**
     * creates and attaches a GLBuffer object tied to the current context.
     * @protected
     */
    BufferSystem.prototype.createGLBuffer = function (buffer) {
        var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl;
        buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer());
        this.managedBuffers[buffer.id] = buffer;
        buffer.disposeRunner.add(this);
        return buffer._glBuffers[CONTEXT_UID];
    };
    return BufferSystem;
}());

/**
 * The Renderer draws the scene and all its content onto a WebGL enabled canvas.
 *
 * This renderer should be used for browsers that support WebGL.
 *
 * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds.
 * Don't forget to add the view to your DOM or you will not see anything!
 *
 * Renderer is composed of systems that manage specific tasks. The following systems are added by default
 * whenever you create a renderer:
 *
 * | System                               | Description                                                                   |
 * | ------------------------------------ | ----------------------------------------------------------------------------- |
 * | {@link PIXI.BatchSystem}             | This manages object renderers that defer rendering until a flush.             |
 * | {@link PIXI.ContextSystem}           | This manages the WebGL context and extensions.                                |
 * | {@link PIXI.EventSystem}             | This manages UI events.                                                       |
 * | {@link PIXI.FilterSystem}            | This manages the filtering pipeline for post-processing effects.              |
 * | {@link PIXI.FramebufferSystem}       | This manages framebuffers, which are used for offscreen rendering.            |
 * | {@link PIXI.GeometrySystem}          | This manages geometries & buffers, which are used to draw object meshes.      |
 * | {@link PIXI.MaskSystem}              | This manages masking operations.                                              |
 * | {@link PIXI.ProjectionSystem}        | This manages the `projectionMatrix`, used by shaders to get NDC coordinates.  |
 * | {@link PIXI.RenderTextureSystem}     | This manages render-textures, which are an abstraction over framebuffers.     |
 * | {@link PIXI.ScissorSystem}           | This handles scissor masking, and is used internally by {@link MaskSystem}    |
 * | {@link PIXI.ShaderSystem}            | This manages shaders, programs that run on the GPU to calculate 'em pixels.   |
 * | {@link PIXI.StateSystem}             | This manages the WebGL state variables like blend mode, depth testing, etc.   |
 * | {@link PIXI.StencilSystem}           | This handles stencil masking, and is used internally by {@link MaskSystem}    |
 * | {@link PIXI.TextureSystem}           | This manages textures and their resources on the GPU.                         |
 * | {@link PIXI.TextureGCSystem}         | This will automatically remove textures from the GPU if they are not used.    |
 *
 * The breadth of the API surface provided by the renderer is contained within these systems.
 *
 * @memberof PIXI
 */
var Renderer = /** @class */ (function (_super) {
    core_extends(Renderer, _super);
    /**
     * @param [options] - The optional renderer parameters.
     * @param {number} [options.width=800] - The width of the screen.
     * @param {number} [options.height=600] - The height of the screen.
     * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional.
     * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
     *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
     *   canvas needs to be opaque, possibly for performance reasons on some older devices.
     * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for
     *   resolutions other than 1.
     * @param {boolean} [options.antialias=false] - Sets antialias. If not available natively then FXAA
     *  antialiasing is used.
     * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
     * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear
     *  the canvas or not before the new render pass. If you wish to set this to false, you *must* set
     *  preserveDrawingBuffer to `true`.
     * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation,
     *  enable this if you need to call toDataUrl on the WebGL context.
     * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
     *  (shown if not transparent).
     * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
     * @param {string} [options.powerPreference] - Parameter passed to WebGL context, set to "high-performance"
     *  for devices with dual graphics card.
     * @param {object} [options.context] - If WebGL context already exists, all parameters must be taken from it.
     */
    function Renderer(options) {
        var _this = _super.call(this, constants_RENDERER_TYPE.WEBGL, options) || this;
        // the options will have been modified here in the super constructor with pixi's default settings..
        options = _this.options;
        _this.gl = null;
        _this.CONTEXT_UID = 0;
        _this.runners = {
            destroy: new Runner('destroy'),
            contextChange: new Runner('contextChange'),
            reset: new Runner('reset'),
            update: new Runner('update'),
            postrender: new Runner('postrender'),
            prerender: new Runner('prerender'),
            resize: new Runner('resize'),
        };
        _this.runners.contextChange.add(_this);
        _this.globalUniforms = new UniformGroup({
            projectionMatrix: new Matrix(),
        }, true);
        _this.addSystem(MaskSystem, 'mask')
            .addSystem(ContextSystem, 'context')
            .addSystem(StateSystem, 'state')
            .addSystem(ShaderSystem, 'shader')
            .addSystem(TextureSystem, 'texture')
            .addSystem(BufferSystem, 'buffer')
            .addSystem(GeometrySystem, 'geometry')
            .addSystem(FramebufferSystem, 'framebuffer')
            .addSystem(ScissorSystem, 'scissor')
            .addSystem(StencilSystem, 'stencil')
            .addSystem(ProjectionSystem, 'projection')
            .addSystem(TextureGCSystem, 'textureGC')
            .addSystem(FilterSystem, 'filter')
            .addSystem(RenderTextureSystem, 'renderTexture')
            .addSystem(BatchSystem, 'batch');
        _this.initPlugins(Renderer.__plugins);
        _this.multisample = undefined;
        /*
         * The options passed in to create a new WebGL context.
         */
        if (options.context) {
            _this.context.initFromContext(options.context);
        }
        else {
            _this.context.initFromOptions({
                alpha: !!_this.useContextAlpha,
                antialias: options.antialias,
                premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied',
                stencil: true,
                preserveDrawingBuffer: options.preserveDrawingBuffer,
                powerPreference: _this.options.powerPreference,
            });
        }
        _this.renderingToScreen = true;
        sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1');
        _this.resize(_this.options.width, _this.options.height);
        return _this;
    }
    /**
     * Create renderer if WebGL is available. Overrideable
     * by the **@pixi/canvas-renderer** package to allow fallback.
     * throws error if WebGL is not available.
     *
     * @private
     */
    Renderer.create = function (options) {
        if (isWebGLSupported()) {
            return new Renderer(options);
        }
        throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.');
    };
    Renderer.prototype.contextChange = function () {
        var gl = this.gl;
        var samples;
        if (this.context.webGLVersion === 1) {
            var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
            gl.bindFramebuffer(gl.FRAMEBUFFER, null);
            samples = gl.getParameter(gl.SAMPLES);
            gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        }
        else {
            var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
            gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
            samples = gl.getParameter(gl.SAMPLES);
            gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer);
        }
        if (samples >= constants_MSAA_QUALITY.HIGH) {
            this.multisample = constants_MSAA_QUALITY.HIGH;
        }
        else if (samples >= constants_MSAA_QUALITY.MEDIUM) {
            this.multisample = constants_MSAA_QUALITY.MEDIUM;
        }
        else if (samples >= constants_MSAA_QUALITY.LOW) {
            this.multisample = constants_MSAA_QUALITY.LOW;
        }
        else {
            this.multisample = constants_MSAA_QUALITY.NONE;
        }
    };
    /**
     * Add a new system to the renderer.
     *
     * @param ClassRef - Class reference
     * @param name - Property name for system, if not specified
     *        will use a static `name` property on the class itself. This
     *        name will be assigned as s property on the Renderer so make
     *        sure it doesn't collide with properties on Renderer.
     * @return Return instance of renderer
     */
    Renderer.prototype.addSystem = function (ClassRef, name) {
        var system = new ClassRef(this);
        if (this[name]) {
            throw new Error("Whoops! The name \"" + name + "\" is already in use");
        }
        this[name] = system;
        for (var i in this.runners) {
            this.runners[i].add(system);
        }
        /**
         * Fired after rendering finishes.
         *
         * @event PIXI.Renderer#postrender
         */
        /**
         * Fired before rendering starts.
         *
         * @event PIXI.Renderer#prerender
         */
        /**
         * Fired when the WebGL context is set.
         *
         * @event PIXI.Renderer#context
         * @param {WebGLRenderingContext} gl - WebGL context.
         */
        return this;
    };
    /**
     * @ignore
     */
    Renderer.prototype.render = function (displayObject, options) {
        var renderTexture;
        var clear;
        var transform;
        var skipUpdateTransform;
        if (options) {
            if (options instanceof RenderTexture) {
                deprecation('6.0.0', 'Renderer#render arguments changed, use options instead.');
                /* eslint-disable prefer-rest-params */
                renderTexture = options;
                clear = arguments[2];
                transform = arguments[3];
                skipUpdateTransform = arguments[4];
                /* eslint-enable prefer-rest-params */
            }
            else {
                renderTexture = options.renderTexture;
                clear = options.clear;
                transform = options.transform;
                skipUpdateTransform = options.skipUpdateTransform;
            }
        }
        // can be handy to know!
        this.renderingToScreen = !renderTexture;
        this.runners.prerender.emit();
        this.emit('prerender');
        // apply a transform at a GPU level
        this.projection.transform = transform;
        // no point rendering if our context has been blown up!
        if (this.context.isLost) {
            return;
        }
        if (!renderTexture) {
            this._lastObjectRendered = displayObject;
        }
        if (!skipUpdateTransform) {
            // update the scene graph
            var cacheParent = displayObject.enableTempParent();
            displayObject.updateTransform();
            displayObject.disableTempParent(cacheParent);
            // displayObject.hitArea = //TODO add a temp hit area
        }
        this.renderTexture.bind(renderTexture);
        this.batch.currentRenderer.start();
        if (clear !== undefined ? clear : this.clearBeforeRender) {
            this.renderTexture.clear();
        }
        displayObject.render(this);
        // apply transform..
        this.batch.currentRenderer.flush();
        if (renderTexture) {
            renderTexture.baseTexture.update();
        }
        this.runners.postrender.emit();
        // reset transform after render
        this.projection.transform = null;
        this.emit('postrender');
    };
    /**
     * @override
     * @ignore
     */
    Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) {
        if (options === void 0) { options = {}; }
        var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region);
        this.framebuffer.blit();
        return renderTexture;
    };
    /**
     * Resizes the WebGL view to the specified width and height.
     *
     * @param desiredScreenWidth - The desired width of the screen.
     * @param desiredScreenHeight - The desired height of the screen.
     */
    Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) {
        _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight);
        this.runners.resize.emit(this.screen.height, this.screen.width);
    };
    /**
     * Resets the WebGL state so you can render things however you fancy!
     *
     * @return Returns itself.
     */
    Renderer.prototype.reset = function () {
        this.runners.reset.emit();
        return this;
    };
    /** Clear the frame buffer. */
    Renderer.prototype.clear = function () {
        this.renderTexture.bind();
        this.renderTexture.clear();
    };
    /**
     * Removes everything from the renderer (event listeners, spritebatch, etc...)
     *
     * @param [removeView=false] - Removes the Canvas element from the DOM.
     *  See: https://github.com/pixijs/pixi.js/issues/2233
     */
    Renderer.prototype.destroy = function (removeView) {
        this.runners.destroy.emit();
        for (var r in this.runners) {
            this.runners[r].destroy();
        }
        // call base destroy
        _super.prototype.destroy.call(this, removeView);
        // TODO nullify all the managers..
        this.gl = null;
    };
    Object.defineProperty(Renderer.prototype, "extract", {
        /**
         * Please use `plugins.extract` instead.
         * @member {PIXI.Extract} extract
         * @deprecated since 6.0.0
         * @readonly
         */
        get: function () {
            deprecation('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.');
            return this.plugins.extract;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Adds a plugin to the renderer.
     *
     * @param pluginName - The name of the plugin.
     * @param ctor - The constructor function or class for the plugin.
     */
    Renderer.registerPlugin = function (pluginName, ctor) {
        Renderer.__plugins = Renderer.__plugins || {};
        Renderer.__plugins[pluginName] = ctor;
    };
    return Renderer;
}(AbstractRenderer));

/**
 * This helper function will automatically detect which renderer you should be using.
 * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by
 * the browser then this function will return a canvas renderer
 *
 * @memberof PIXI
 * @function autoDetectRenderer
 * @param {object} [options] - The optional renderer parameters
 * @param {number} [options.width=800] - the width of the renderers view
 * @param {number} [options.height=600] - the height of the renderers view
 * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
 * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
 *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
 *   canvas needs to be opaque, possibly for performance reasons on some older devices.
 * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for
 *   resolutions other than 1
 * @param {boolean} [options.antialias=false] - sets antialias
 * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you
 *  need to call toDataUrl on the webgl context
 * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
 *  (shown if not transparent).
 * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
 * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or
 *   not before the new render pass.
 * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
 * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this
 *   option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise
 *   it is ignored.
 * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance"
 *  for devices with dual graphics card **webgl only**
 * @return {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer
 */
function autoDetectRenderer(options) {
    return Renderer.create(options);
}

var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n    vTextureCoord = aTextureCoord;\n}";

var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n    vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n    return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n    return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n    gl_Position = filterVertexPosition();\n    vTextureCoord = filterTextureCoord();\n}\n";

/**
 * Default vertex shader
 * @memberof PIXI
 * @member {string} defaultVertex
 */
/**
 * Default filter vertex shader
 * @memberof PIXI
 * @member {string} defaultFilterVertex
 */
// NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types
// of defaultVertex, defaultFilterVertex.
var defaultVertex$2 = $defaultVertex;
var defaultFilterVertex = $defaultFilterVertex;

/**
 * Use the ISystem interface instead.
 * @deprecated since 6.1.0
 * @memberof PIXI
 */
var System = /** @class */ (function () {
    /**
     * @param renderer - Reference to Renderer
     */
    function System(renderer) {
        deprecation('6.1.0', 'System class is deprecated, implemement ISystem interface instead.');
        this.renderer = renderer;
    }
    /** Destroy and don't use after this. */
    System.prototype.destroy = function () {
        this.renderer = null;
    };
    return System;
}());

/**
 * Used by the batcher to draw batches.
 * Each one of these contains all information required to draw a bound geometry.
 *
 * @memberof PIXI
 */
var BatchDrawCall = /** @class */ (function () {
    function BatchDrawCall() {
        this.texArray = null;
        this.blend = 0;
        this.type = constants_DRAW_MODES.TRIANGLES;
        this.start = 0;
        this.size = 0;
        this.data = null;
    }
    return BatchDrawCall;
}());

/**
 * Used by the batcher to build texture batches.
 * Holds list of textures and their respective locations.
 *
 * @memberof PIXI
 */
var BatchTextureArray = /** @class */ (function () {
    function BatchTextureArray() {
        this.elements = [];
        this.ids = [];
        this.count = 0;
    }
    BatchTextureArray.prototype.clear = function () {
        for (var i = 0; i < this.count; i++) {
            this.elements[i] = null;
        }
        this.count = 0;
    };
    return BatchTextureArray;
}());

/**
 * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand.
 *
 * @memberof PIXI
 */
var ViewableBuffer = /** @class */ (function () {
    function ViewableBuffer(sizeOrBuffer) {
        if (typeof sizeOrBuffer === 'number') {
            this.rawBinaryData = new ArrayBuffer(sizeOrBuffer);
        }
        else if (sizeOrBuffer instanceof Uint8Array) {
            this.rawBinaryData = sizeOrBuffer.buffer;
        }
        else {
            this.rawBinaryData = sizeOrBuffer;
        }
        this.uint32View = new Uint32Array(this.rawBinaryData);
        this.float32View = new Float32Array(this.rawBinaryData);
    }
    Object.defineProperty(ViewableBuffer.prototype, "int8View", {
        /** View on the raw binary data as a `Int8Array`. */
        get: function () {
            if (!this._int8View) {
                this._int8View = new Int8Array(this.rawBinaryData);
            }
            return this._int8View;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ViewableBuffer.prototype, "uint8View", {
        /** View on the raw binary data as a `Uint8Array`. */
        get: function () {
            if (!this._uint8View) {
                this._uint8View = new Uint8Array(this.rawBinaryData);
            }
            return this._uint8View;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ViewableBuffer.prototype, "int16View", {
        /**  View on the raw binary data as a `Int16Array`. */
        get: function () {
            if (!this._int16View) {
                this._int16View = new Int16Array(this.rawBinaryData);
            }
            return this._int16View;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ViewableBuffer.prototype, "uint16View", {
        /** View on the raw binary data as a `Uint16Array`. */
        get: function () {
            if (!this._uint16View) {
                this._uint16View = new Uint16Array(this.rawBinaryData);
            }
            return this._uint16View;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ViewableBuffer.prototype, "int32View", {
        /** View on the raw binary data as a `Int32Array`. */
        get: function () {
            if (!this._int32View) {
                this._int32View = new Int32Array(this.rawBinaryData);
            }
            return this._int32View;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Returns the view of the given type.
     *
     * @param type - One of `int8`, `uint8`, `int16`,
     *    `uint16`, `int32`, `uint32`, and `float32`.
     * @return - typed array of given type
     */
    ViewableBuffer.prototype.view = function (type) {
        return this[type + "View"];
    };
    /** Destroys all buffer references. Do not use after calling this. */
    ViewableBuffer.prototype.destroy = function () {
        this.rawBinaryData = null;
        this._int8View = null;
        this._uint8View = null;
        this._int16View = null;
        this._uint16View = null;
        this._int32View = null;
        this.uint32View = null;
        this.float32View = null;
    };
    ViewableBuffer.sizeOf = function (type) {
        switch (type) {
            case 'int8':
            case 'uint8':
                return 1;
            case 'int16':
            case 'uint16':
                return 2;
            case 'int32':
            case 'uint32':
            case 'float32':
                return 4;
            default:
                throw new Error(type + " isn't a valid view type");
        }
    };
    return ViewableBuffer;
}());

/**
 * Renderer dedicated to drawing and batching sprites.
 *
 * This is the default batch renderer. It buffers objects
 * with texture-based geometries and renders them in
 * batches. It uploads multiple textures to the GPU to
 * reduce to the number of draw calls.
 *
 * @memberof PIXI
 */
var AbstractBatchRenderer = /** @class */ (function (_super) {
    core_extends(AbstractBatchRenderer, _super);
    /**
     * This will hook onto the renderer's `contextChange`
     * and `prerender` signals.
     *
     * @param {PIXI.Renderer} renderer - The renderer this works for.
     */
    function AbstractBatchRenderer(renderer) {
        var _this = _super.call(this, renderer) || this;
        _this.shaderGenerator = null;
        _this.geometryClass = null;
        _this.vertexSize = null;
        _this.state = State.for2d();
        _this.size = settings.SPRITE_BATCH_SIZE * 4;
        _this._vertexCount = 0;
        _this._indexCount = 0;
        _this._bufferedElements = [];
        _this._bufferedTextures = [];
        _this._bufferSize = 0;
        _this._shader = null;
        _this._packedGeometries = [];
        _this._packedGeometryPoolSize = 2;
        _this._flushId = 0;
        _this._aBuffers = {};
        _this._iBuffers = {};
        _this.MAX_TEXTURES = 1;
        _this.renderer.on('prerender', _this.onPrerender, _this);
        renderer.runners.contextChange.add(_this);
        _this._dcIndex = 0;
        _this._aIndex = 0;
        _this._iIndex = 0;
        _this._attributeBuffer = null;
        _this._indexBuffer = null;
        _this._tempBoundTextures = [];
        return _this;
    }
    /**
     * Handles the `contextChange` signal.
     *
     * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool.
     */
    AbstractBatchRenderer.prototype.contextChange = function () {
        var gl = this.renderer.gl;
        if (settings.PREFER_ENV === constants_ENV.WEBGL_LEGACY) {
            this.MAX_TEXTURES = 1;
        }
        else {
            // step 1: first check max textures the GPU can handle.
            this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.SPRITE_MAX_TEXTURES);
            // step 2: check the maximum number of if statements the shader can have too..
            this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl);
        }
        this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES);
        // we use the second shader as the first one depending on your browser
        // may omit aTextureId as it is not used by the shader so is optimized out.
        for (var i = 0; i < this._packedGeometryPoolSize; i++) {
            /* eslint-disable max-len */
            this._packedGeometries[i] = new (this.geometryClass)();
        }
        this.initFlushBuffers();
    };
    /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */
    AbstractBatchRenderer.prototype.initFlushBuffers = function () {
        var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool;
        // max draw calls
        var MAX_SPRITES = this.size / 4;
        // max texture arrays
        var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1;
        while (_drawCallPool.length < MAX_SPRITES) {
            _drawCallPool.push(new BatchDrawCall());
        }
        while (_textureArrayPool.length < MAX_TA) {
            _textureArrayPool.push(new BatchTextureArray());
        }
        for (var i = 0; i < this.MAX_TEXTURES; i++) {
            this._tempBoundTextures[i] = null;
        }
    };
    /**
     * Handles the `prerender` signal.
     *
     * It ensures that flushes start from the first geometry object again.
     */
    AbstractBatchRenderer.prototype.onPrerender = function () {
        this._flushId = 0;
    };
    /**
     * Buffers the "batchable" object. It need not be rendered immediately.
     *
     * @param {PIXI.DisplayObject} element - the element to render when
     *    using this renderer
     */
    AbstractBatchRenderer.prototype.render = function (element) {
        if (!element._texture.valid) {
            return;
        }
        if (this._vertexCount + (element.vertexData.length / 2) > this.size) {
            this.flush();
        }
        this._vertexCount += element.vertexData.length / 2;
        this._indexCount += element.indices.length;
        this._bufferedTextures[this._bufferSize] = element._texture.baseTexture;
        this._bufferedElements[this._bufferSize++] = element;
    };
    AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () {
        var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES;
        var textureArrays = AbstractBatchRenderer._textureArrayPool;
        var batch = this.renderer.batch;
        var boundTextures = this._tempBoundTextures;
        var touch = this.renderer.textureGC.count;
        var TICK = ++BaseTexture._globalBatch;
        var countTexArrays = 0;
        var texArray = textureArrays[0];
        var start = 0;
        batch.copyBoundTextures(boundTextures, MAX_TEXTURES);
        for (var i = 0; i < this._bufferSize; ++i) {
            var tex = textures[i];
            textures[i] = null;
            if (tex._batchEnabled === TICK) {
                continue;
            }
            if (texArray.count >= MAX_TEXTURES) {
                batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES);
                this.buildDrawCalls(texArray, start, i);
                start = i;
                texArray = textureArrays[++countTexArrays];
                ++TICK;
            }
            tex._batchEnabled = TICK;
            tex.touched = touch;
            texArray.elements[texArray.count++] = tex;
        }
        if (texArray.count > 0) {
            batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES);
            this.buildDrawCalls(texArray, start, this._bufferSize);
            ++countTexArrays;
            ++TICK;
        }
        // Clean-up
        for (var i = 0; i < boundTextures.length; i++) {
            boundTextures[i] = null;
        }
        BaseTexture._globalBatch = TICK;
    };
    /** Populating drawcalls for rendering */
    AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) {
        var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize;
        var drawCalls = AbstractBatchRenderer._drawCallPool;
        var dcIndex = this._dcIndex;
        var aIndex = this._aIndex;
        var iIndex = this._iIndex;
        var drawCall = drawCalls[dcIndex];
        drawCall.start = this._iIndex;
        drawCall.texArray = texArray;
        for (var i = start; i < finish; ++i) {
            var sprite = elements[i];
            var tex = sprite._texture.baseTexture;
            var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode];
            elements[i] = null;
            if (start < i && drawCall.blend !== spriteBlendMode) {
                drawCall.size = iIndex - drawCall.start;
                start = i;
                drawCall = drawCalls[++dcIndex];
                drawCall.texArray = texArray;
                drawCall.start = iIndex;
            }
            this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex);
            aIndex += sprite.vertexData.length / 2 * vertexSize;
            iIndex += sprite.indices.length;
            drawCall.blend = spriteBlendMode;
        }
        if (start < finish) {
            drawCall.size = iIndex - drawCall.start;
            ++dcIndex;
        }
        this._dcIndex = dcIndex;
        this._aIndex = aIndex;
        this._iIndex = iIndex;
    };
    /** Bind textures for current rendering */
    AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) {
        var textureSystem = this.renderer.texture;
        for (var j = 0; j < texArray.count; j++) {
            textureSystem.bind(texArray.elements[j], texArray.ids[j]);
            texArray.elements[j] = null;
        }
        texArray.count = 0;
    };
    AbstractBatchRenderer.prototype.updateGeometry = function () {
        var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer;
        if (!settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't
            like uploads to the same buffer in a single frame. */
            if (this._packedGeometryPoolSize <= this._flushId) {
                this._packedGeometryPoolSize++;
                packedGeometries[this._flushId] = new (this.geometryClass)();
            }
            packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData);
            packedGeometries[this._flushId]._indexBuffer.update(indexBuffer);
            this.renderer.geometry.bind(packedGeometries[this._flushId]);
            this.renderer.geometry.updateBuffers();
            this._flushId++;
        }
        else {
            // lets use the faster option, always use buffer number 0
            packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData);
            packedGeometries[this._flushId]._indexBuffer.update(indexBuffer);
            this.renderer.geometry.updateBuffers();
        }
    };
    AbstractBatchRenderer.prototype.drawBatches = function () {
        var dcCount = this._dcIndex;
        var _a = this.renderer, gl = _a.gl, stateSystem = _a.state;
        var drawCalls = AbstractBatchRenderer._drawCallPool;
        var curTexArray = null;
        // Upload textures and do the draw calls
        for (var i = 0; i < dcCount; i++) {
            var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend;
            if (curTexArray !== texArray) {
                curTexArray = texArray;
                this.bindAndClearTexArray(texArray);
            }
            this.state.blendMode = blend;
            stateSystem.set(this.state);
            gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2);
        }
    };
    /** Renders the content _now_ and empties the current batch. */
    AbstractBatchRenderer.prototype.flush = function () {
        if (this._vertexCount === 0) {
            return;
        }
        this._attributeBuffer = this.getAttributeBuffer(this._vertexCount);
        this._indexBuffer = this.getIndexBuffer(this._indexCount);
        this._aIndex = 0;
        this._iIndex = 0;
        this._dcIndex = 0;
        this.buildTexturesAndDrawCalls();
        this.updateGeometry();
        this.drawBatches();
        // reset elements buffer for the next flush
        this._bufferSize = 0;
        this._vertexCount = 0;
        this._indexCount = 0;
    };
    /** Starts a new sprite batch. */
    AbstractBatchRenderer.prototype.start = function () {
        this.renderer.state.set(this.state);
        this.renderer.texture.ensureSamplerType(this.MAX_TEXTURES);
        this.renderer.shader.bind(this._shader);
        if (settings.CAN_UPLOAD_SAME_BUFFER) {
            // bind buffer #0, we don't need others
            this.renderer.geometry.bind(this._packedGeometries[this._flushId]);
        }
    };
    /** Stops and flushes the current batch. */
    AbstractBatchRenderer.prototype.stop = function () {
        this.flush();
    };
    /** Destroys this `AbstractBatchRenderer`. It cannot be used again. */
    AbstractBatchRenderer.prototype.destroy = function () {
        for (var i = 0; i < this._packedGeometryPoolSize; i++) {
            if (this._packedGeometries[i]) {
                this._packedGeometries[i].destroy();
            }
        }
        this.renderer.off('prerender', this.onPrerender, this);
        this._aBuffers = null;
        this._iBuffers = null;
        this._packedGeometries = null;
        this._attributeBuffer = null;
        this._indexBuffer = null;
        if (this._shader) {
            this._shader.destroy();
            this._shader = null;
        }
        _super.prototype.destroy.call(this);
    };
    /**
     * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats.
     *
     * @param size - minimum capacity required
     * @return - buffer than can hold atleast `size` floats
     */
    AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) {
        // 8 vertices is enough for 2 quads
        var roundedP2 = nextPow2(Math.ceil(size / 8));
        var roundedSizeIndex = log2(roundedP2);
        var roundedSize = roundedP2 * 8;
        if (this._aBuffers.length <= roundedSizeIndex) {
            this._iBuffers.length = roundedSizeIndex + 1;
        }
        var buffer = this._aBuffers[roundedSize];
        if (!buffer) {
            this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4);
        }
        return buffer;
    };
    /**
     * Fetches an index buffer from `this._iBuffers` that can
     * have at least `size` capacity.
     *
     * @param size - minimum required capacity
     * @return - buffer that can fit `size` indices.
     */
    AbstractBatchRenderer.prototype.getIndexBuffer = function (size) {
        // 12 indices is enough for 2 quads
        var roundedP2 = nextPow2(Math.ceil(size / 12));
        var roundedSizeIndex = log2(roundedP2);
        var roundedSize = roundedP2 * 12;
        if (this._iBuffers.length <= roundedSizeIndex) {
            this._iBuffers.length = roundedSizeIndex + 1;
        }
        var buffer = this._iBuffers[roundedSizeIndex];
        if (!buffer) {
            this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize);
        }
        return buffer;
    };
    /**
     * Takes the four batching parameters of `element`, interleaves
     * and pushes them into the batching attribute/index buffers given.
     *
     * It uses these properties: `vertexData` `uvs`, `textureId` and
     * `indicies`. It also uses the "tint" of the base-texture, if
     * present.
     *
     * @param {PIXI.DisplayObject} element - element being rendered
     * @param attributeBuffer - attribute buffer.
     * @param indexBuffer - index buffer
     * @param aIndex - number of floats already in the attribute buffer
     * @param iIndex - number of indices already in `indexBuffer`
     */
    AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) {
        var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View;
        var packedVertices = aIndex / this.vertexSize;
        var uvs = element.uvs;
        var indicies = element.indices;
        var vertexData = element.vertexData;
        var textureId = element._texture.baseTexture._batchLocation;
        var alpha = Math.min(element.worldAlpha, 1.0);
        var argb = (alpha < 1.0
            && element._texture.baseTexture.alphaMode)
            ? premultiplyTint(element._tintRGB, alpha)
            : element._tintRGB + (alpha * 255 << 24);
        // lets not worry about tint! for now..
        for (var i = 0; i < vertexData.length; i += 2) {
            float32View[aIndex++] = vertexData[i];
            float32View[aIndex++] = vertexData[i + 1];
            float32View[aIndex++] = uvs[i];
            float32View[aIndex++] = uvs[i + 1];
            uint32View[aIndex++] = argb;
            float32View[aIndex++] = textureId;
        }
        for (var i = 0; i < indicies.length; i++) {
            indexBuffer[iIndex++] = packedVertices + indicies[i];
        }
    };
    /**
     * Pool of `BatchDrawCall` objects that `flush` used
     * to create "batches" of the objects being rendered.
     *
     * These are never re-allocated again.
     * Shared between all batch renderers because it can be only one "flush" working at the moment.
     *
     * @member {PIXI.BatchDrawCall[]}
     */
    AbstractBatchRenderer._drawCallPool = [];
    /**
     * Pool of `BatchDrawCall` objects that `flush` used
     * to create "batches" of the objects being rendered.
     *
     * These are never re-allocated again.
     * Shared between all batch renderers because it can be only one "flush" working at the moment.
     *
     * @member {PIXI.BatchTextureArray[]}
     */
    AbstractBatchRenderer._textureArrayPool = [];
    return AbstractBatchRenderer;
}(ObjectRenderer));

/**
 * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer
 *
 * @memberof PIXI
 */
var BatchShaderGenerator = /** @class */ (function () {
    /**
     * @param vertexSrc - Vertex shader
     * @param fragTemplate - Fragment shader template
     */
    function BatchShaderGenerator(vertexSrc, fragTemplate) {
        this.vertexSrc = vertexSrc;
        this.fragTemplate = fragTemplate;
        this.programCache = {};
        this.defaultGroupCache = {};
        if (fragTemplate.indexOf('%count%') < 0) {
            throw new Error('Fragment template must contain "%count%".');
        }
        if (fragTemplate.indexOf('%forloop%') < 0) {
            throw new Error('Fragment template must contain "%forloop%".');
        }
    }
    BatchShaderGenerator.prototype.generateShader = function (maxTextures) {
        if (!this.programCache[maxTextures]) {
            var sampleValues = new Int32Array(maxTextures);
            for (var i = 0; i < maxTextures; i++) {
                sampleValues[i] = i;
            }
            this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true);
            var fragmentSrc = this.fragTemplate;
            fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures);
            fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures));
            this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc);
        }
        var uniforms = {
            tint: new Float32Array([1, 1, 1, 1]),
            translationMatrix: new Matrix(),
            default: this.defaultGroupCache[maxTextures],
        };
        return new Shader(this.programCache[maxTextures], uniforms);
    };
    BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) {
        var src = '';
        src += '\n';
        src += '\n';
        for (var i = 0; i < maxTextures; i++) {
            if (i > 0) {
                src += '\nelse ';
            }
            if (i < maxTextures - 1) {
                src += "if(vTextureId < " + i + ".5)";
            }
            src += '\n{';
            src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);";
            src += '\n}';
        }
        src += '\n';
        src += '\n';
        return src;
    };
    return BatchShaderGenerator;
}());

/**
 * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects).
 *
 * @memberof PIXI
 */
var BatchGeometry = /** @class */ (function (_super) {
    core_extends(BatchGeometry, _super);
    /**
     * @param {boolean} [_static=false] - Optimization flag, where `false`
     *        is updated every frame, `true` doesn't change frame-to-frame.
     */
    function BatchGeometry(_static) {
        if (_static === void 0) { _static = false; }
        var _this = _super.call(this) || this;
        _this._buffer = new Buffer(null, _static, false);
        _this._indexBuffer = new Buffer(null, _static, true);
        _this.addAttribute('aVertexPosition', _this._buffer, 2, false, constants_TYPES.FLOAT)
            .addAttribute('aTextureCoord', _this._buffer, 2, false, constants_TYPES.FLOAT)
            .addAttribute('aColor', _this._buffer, 4, true, constants_TYPES.UNSIGNED_BYTE)
            .addAttribute('aTextureId', _this._buffer, 1, true, constants_TYPES.FLOAT)
            .addIndex(_this._indexBuffer);
        return _this;
    }
    return BatchGeometry;
}(Geometry));

var defaultVertex$3 = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = aTextureCoord;\n    vTextureId = aTextureId;\n    vColor = aColor * tint;\n}\n";

var defaultFragment$2 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n    vec4 color;\n    %forloop%\n    gl_FragColor = color * vColor;\n}\n";

/** @memberof PIXI */
var BatchPluginFactory = /** @class */ (function () {
    function BatchPluginFactory() {
    }
    /**
     * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way
     * to extend BatchRenderer with all the necessary pieces.
     * @example
     * const fragment = `
     * varying vec2 vTextureCoord;
     * varying vec4 vColor;
     * varying float vTextureId;
     * uniform sampler2D uSamplers[%count%];
     *
     * void main(void){
     *     vec4 color;
     *     %forloop%
     *     gl_FragColor = vColor * vec4(color.a - color.rgb, color.a);
     * }
     * `;
     * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment });
     * PIXI.Renderer.registerPlugin('invert', InvertBatchRenderer);
     * const sprite = new PIXI.Sprite();
     * sprite.pluginName = 'invert';
     *
     * @param {object} [options]
     * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source
     * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template
     * @param {number} [options.vertexSize=6] - Vertex size
     * @param {object} [options.geometryClass=PIXI.BatchGeometry]
     * @return {*} New batch renderer plugin
     */
    BatchPluginFactory.create = function (options) {
        var _a = Object.assign({
            vertex: defaultVertex$3,
            fragment: defaultFragment$2,
            geometryClass: BatchGeometry,
            vertexSize: 6,
        }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass;
        return /** @class */ (function (_super) {
            core_extends(BatchPlugin, _super);
            function BatchPlugin(renderer) {
                var _this = _super.call(this, renderer) || this;
                _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment);
                _this.geometryClass = geometryClass;
                _this.vertexSize = vertexSize;
                return _this;
            }
            return BatchPlugin;
        }(AbstractBatchRenderer));
    };
    Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", {
        /**
         * The default vertex shader source
         *
         * @readonly
         */
        get: function () {
            return defaultVertex$3;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", {
        /**
         * The default fragment shader source
         *
         * @readonly
         */
        get: function () {
            return defaultFragment$2;
        },
        enumerable: false,
        configurable: true
    });
    return BatchPluginFactory;
}());
// Setup the default BatchRenderer plugin, this is what
// we'll actually export at the root level
var BatchRenderer = BatchPluginFactory.create();

/**
 * @memberof PIXI
 * @namespace resources
 * @see PIXI
 * @deprecated since 6.0.0
 */
var resources = {};
var _loop_1 = function (name) {
    Object.defineProperty(resources, name, {
        get: function () {
            deprecation('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name);
            return _resources[name];
        },
    });
};
for (var core_name in _resources) {
    _loop_1(core_name);
}
/**
 * @memberof PIXI
 * @namespace systems
 * @see PIXI
 * @deprecated since 6.0.0
 */
var systems = {};
var _loop_2 = function (name) {
    Object.defineProperty(systems, name, {
        get: function () {
            deprecation('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name);
            return _systems[name];
        },
    });
};
for (var core_name in _systems) {
    _loop_2(core_name);
}


//# sourceMappingURL=core.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/app/dist/esm/app.js
/*!
 * @pixi/app - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/app is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */



/**
 * Convenience class to create a new PIXI application.
 *
 * This class automatically creates the renderer, ticker and root container.
 *
 * @example
 * // Create the application
 * const app = new PIXI.Application();
 *
 * // Add the view to the DOM
 * document.body.appendChild(app.view);
 *
 * // ex, add display objects
 * app.stage.addChild(PIXI.Sprite.from('something.png'));
 *
 * @class
 * @memberof PIXI
 */
var Application = /** @class */ (function () {
    /**
     * @param {object} [options] - The optional renderer parameters.
     * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction.
     *     **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set
     *     options.sharedTicker to true in case that it is already started. Stop it by your own.
     * @param {number} [options.width=800] - The width of the renderers view.
     * @param {number} [options.height=600] - The height of the renderers view.
     * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional.
     * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property.
     *   If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the
     *   canvas needs to be opaque, possibly for performance reasons on some older devices.
     * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for
     *   resolutions other than 1.
     * @param {boolean} [options.antialias=false] - Sets antialias
     * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you
     *  need to call toDataUrl on the WebGL context.
     * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer.
     * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this
     *   option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise
     *   it is ignored.
     * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
     *  (shown if not transparent).
     * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque).
     * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or
     *   not before the new render pass.
     * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance"
     *  for devices with dual graphics card. **(WebGL only)**.
     * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker.
     *  If set to false, you cannot register a handler to occur before anything that runs on the shared ticker.
     *  The system ticker will always run before both the shared ticker and the app ticker.
     * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader.
     * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to.
     */
    function Application(options) {
        var _this = this;
        /**
         * The root display container that's rendered.
         * @member {PIXI.Container}
         */
        this.stage = new Container();
        // The default options
        options = Object.assign({
            forceCanvas: false,
        }, options);
        this.renderer = autoDetectRenderer(options);
        // install plugins here
        Application._plugins.forEach(function (plugin) {
            plugin.init.call(_this, options);
        });
    }
    /**
     * Register a middleware plugin for the application
     * @static
     * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
     */
    Application.registerPlugin = function (plugin) {
        Application._plugins.push(plugin);
    };
    /**
     * Render the current stage.
     */
    Application.prototype.render = function () {
        this.renderer.render(this.stage);
    };
    Object.defineProperty(Application.prototype, "view", {
        /**
         * Reference to the renderer's canvas element.
         * @member {HTMLCanvasElement}
         * @readonly
         */
        get: function () {
            return this.renderer.view;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Application.prototype, "screen", {
        /**
         * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
         * @member {PIXI.Rectangle}
         * @readonly
         */
        get: function () {
            return this.renderer.screen;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Destroy and don't use after this.
     * @param {Boolean} [removeView=false] - Automatically remove canvas from DOM.
     * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
     *  method called as well. 'stageOptions' will be passed on to those calls.
     * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
     *  to true. Should it destroy the texture of the child sprite
     * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
     *  to true. Should it destroy the base texture of the child sprite
     */
    Application.prototype.destroy = function (removeView, stageOptions) {
        var _this = this;
        // Destroy plugins in the opposite order
        // which they were constructed
        var plugins = Application._plugins.slice(0);
        plugins.reverse();
        plugins.forEach(function (plugin) {
            plugin.destroy.call(_this);
        });
        this.stage.destroy(stageOptions);
        this.stage = null;
        this.renderer.destroy(removeView);
        this.renderer = null;
    };
    /** Collection of installed plugins. */
    Application._plugins = [];
    return Application;
}());

/**
 * Middleware for for Application's resize functionality
 * @private
 * @class
 */
var ResizePlugin = /** @class */ (function () {
    function ResizePlugin() {
    }
    /**
     * Initialize the plugin with scope of application instance
     * @static
     * @private
     * @param {object} [options] - See application options
     */
    ResizePlugin.init = function (options) {
        var _this = this;
        Object.defineProperty(this, 'resizeTo', 
        /**
         * The HTML element or window to automatically resize the
         * renderer's view element to match width and height.
         * @member {Window|HTMLElement}
         * @name resizeTo
         * @memberof PIXI.Application#
         */
        {
            set: function (dom) {
                globalThis.removeEventListener('resize', this.queueResize);
                this._resizeTo = dom;
                if (dom) {
                    globalThis.addEventListener('resize', this.queueResize);
                    this.resize();
                }
            },
            get: function () {
                return this._resizeTo;
            },
        });
        /**
         * Resize is throttled, so it's safe to call this multiple times per frame and it'll
         * only be called once.
         *
         * @memberof PIXI.Application#
         * @method queueResize
         * @private
         */
        this.queueResize = function () {
            if (!_this._resizeTo) {
                return;
            }
            _this.cancelResize();
            // // Throttle resize events per raf
            _this._resizeId = requestAnimationFrame(function () { return _this.resize(); });
        };
        /**
         * Cancel the resize queue.
         *
         * @memberof PIXI.Application#
         * @method cancelResize
         * @private
         */
        this.cancelResize = function () {
            if (_this._resizeId) {
                cancelAnimationFrame(_this._resizeId);
                _this._resizeId = null;
            }
        };
        /**
         * Execute an immediate resize on the renderer, this is not
         * throttled and can be expensive to call many times in a row.
         * Will resize only if `resizeTo` property is set.
         *
         * @memberof PIXI.Application#
         * @method resize
         */
        this.resize = function () {
            if (!_this._resizeTo) {
                return;
            }
            // clear queue resize
            _this.cancelResize();
            var width;
            var height;
            // Resize to the window
            if (_this._resizeTo === globalThis.window) {
                width = globalThis.innerWidth;
                height = globalThis.innerHeight;
            }
            // Resize to other HTML entities
            else {
                var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight;
                width = clientWidth;
                height = clientHeight;
            }
            _this.renderer.resize(width, height);
        };
        // On resize
        this._resizeId = null;
        this._resizeTo = null;
        this.resizeTo = options.resizeTo || null;
    };
    /**
     * Clean up the ticker, scoped to application
     *
     * @static
     * @private
     */
    ResizePlugin.destroy = function () {
        globalThis.removeEventListener('resize', this.queueResize);
        this.cancelResize();
        this.cancelResize = null;
        this.queueResize = null;
        this.resizeTo = null;
        this.resize = null;
    };
    return ResizePlugin;
}());

Application.registerPlugin(ResizePlugin);


//# sourceMappingURL=app.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/extract/dist/esm/extract.js
/*!
 * @pixi/extract - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/extract is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */




var TEMP_RECT = new Rectangle();
var BYTES_PER_PIXEL = 4;
/**
 * This class provides renderer-specific plugins for exporting content from a renderer.
 * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels).
 *
 * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property.
 * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}.
 *
 * @example
 * // Create a new app (will auto-add extract plugin to renderer)
 * const app = new PIXI.Application();
 *
 * // Draw a red circle
 * const graphics = new PIXI.Graphics()
 *     .beginFill(0xFF0000)
 *     .drawCircle(0, 0, 50);
 *
 * // Render the graphics as an HTMLImageElement
 * const image = app.renderer.plugins.extract.image(graphics);
 * document.body.appendChild(image);
 *
 * @memberof PIXI
 */
var Extract = /** @class */ (function () {
    /**
     * @param renderer - A reference to the current renderer
     */
    function Extract(renderer) {
        this.renderer = renderer;
    }
    /**
     * Will return a HTML Image of the target
     *
     * @param target - A displayObject or renderTexture
     *  to convert. If left empty will use the main renderer
     * @param format - Image format, e.g. "image/jpeg" or "image/webp".
     * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92.
     * @return - HTML Image of the target
     */
    Extract.prototype.image = function (target, format, quality) {
        var image = new Image();
        image.src = this.base64(target, format, quality);
        return image;
    };
    /**
     * Will return a base64 encoded string of this target. It works by calling
     *  `Extract.getCanvas` and then running toDataURL on that.
     *
     * @param target - A displayObject or renderTexture
     *  to convert. If left empty will use the main renderer
     * @param format - Image format, e.g. "image/jpeg" or "image/webp".
     * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92.
     * @return - A base64 encoded string of the texture.
     */
    Extract.prototype.base64 = function (target, format, quality) {
        return this.canvas(target).toDataURL(format, quality);
    };
    /**
     * Creates a Canvas element, renders this target to it and then returns it.
     *
     * @param target - A displayObject or renderTexture
     *  to convert. If left empty will use the main renderer
     * @return - A Canvas element with the texture rendered on.
     */
    Extract.prototype.canvas = function (target) {
        var renderer = this.renderer;
        var resolution;
        var frame;
        var flipY = false;
        var renderTexture;
        var generated = false;
        if (target) {
            if (target instanceof RenderTexture) {
                renderTexture = target;
            }
            else {
                renderTexture = this.renderer.generateTexture(target);
                generated = true;
            }
        }
        if (renderTexture) {
            resolution = renderTexture.baseTexture.resolution;
            frame = renderTexture.frame;
            flipY = false;
            renderer.renderTexture.bind(renderTexture);
        }
        else {
            resolution = this.renderer.resolution;
            flipY = true;
            frame = TEMP_RECT;
            frame.width = this.renderer.width;
            frame.height = this.renderer.height;
            renderer.renderTexture.bind(null);
        }
        var width = Math.floor((frame.width * resolution) + 1e-4);
        var height = Math.floor((frame.height * resolution) + 1e-4);
        var canvasBuffer = new CanvasRenderTarget(width, height, 1);
        var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height);
        // read pixels to the array
        var gl = renderer.gl;
        gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels);
        // add the pixels to the canvas
        var canvasData = canvasBuffer.context.getImageData(0, 0, width, height);
        Extract.arrayPostDivide(webglPixels, canvasData.data);
        canvasBuffer.context.putImageData(canvasData, 0, 0);
        // pulling pixels
        if (flipY) {
            var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1);
            target_1.context.scale(1, -1);
            // we can't render to itself because we should be empty before render.
            target_1.context.drawImage(canvasBuffer.canvas, 0, -height);
            canvasBuffer.destroy();
            canvasBuffer = target_1;
        }
        if (generated) {
            renderTexture.destroy(true);
        }
        // send the canvas back..
        return canvasBuffer.canvas;
    };
    /**
     * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA
     * order, with integer values between 0 and 255 (included).
     *
     * @param target - A displayObject or renderTexture
     *  to convert. If left empty will use the main renderer
     * @return - One-dimensional array containing the pixel data of the entire texture
     */
    Extract.prototype.pixels = function (target) {
        var renderer = this.renderer;
        var resolution;
        var frame;
        var renderTexture;
        var generated = false;
        if (target) {
            if (target instanceof RenderTexture) {
                renderTexture = target;
            }
            else {
                renderTexture = this.renderer.generateTexture(target);
                generated = true;
            }
        }
        if (renderTexture) {
            resolution = renderTexture.baseTexture.resolution;
            frame = renderTexture.frame;
            // bind the buffer
            renderer.renderTexture.bind(renderTexture);
        }
        else {
            resolution = renderer.resolution;
            frame = TEMP_RECT;
            frame.width = renderer.width;
            frame.height = renderer.height;
            renderer.renderTexture.bind(null);
        }
        var width = frame.width * resolution;
        var height = frame.height * resolution;
        var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height);
        // read pixels to the array
        var gl = renderer.gl;
        gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels);
        if (generated) {
            renderTexture.destroy(true);
        }
        Extract.arrayPostDivide(webglPixels, webglPixels);
        return webglPixels;
    };
    /** Destroys the extract. */
    Extract.prototype.destroy = function () {
        this.renderer = null;
    };
    /**
     * Takes premultiplied pixel data and produces regular pixel data
     *
     * @private
     * @param pixels - array of pixel data
     * @param out - output array
     */
    Extract.arrayPostDivide = function (pixels, out) {
        for (var i = 0; i < pixels.length; i += 4) {
            var alpha = out[i + 3] = pixels[i + 3];
            if (alpha !== 0) {
                out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0));
                out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0));
                out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0));
            }
            else {
                out[i] = pixels[i];
                out[i + 1] = pixels[i + 1];
                out[i + 2] = pixels[i + 2];
            }
        }
    };
    return Extract;
}());


//# sourceMappingURL=extract.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/loaders/dist/esm/loaders.js
/*!
 * @pixi/loaders - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/loaders is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/* jshint -W097 */
/**
 * @memberof PIXI
 */
var SignalBinding = /** @class */ (function () {
    /**
     * SignalBinding constructor.
     * @constructs SignalBinding
     * @param {Function} fn - Event handler to be called.
     * @param {Boolean} [once=false] - Should this listener be removed after dispatch
     * @param {object} [thisArg] - The context of the callback function.
     * @api private
     */
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    function SignalBinding(fn, once, thisArg) {
        if (once === void 0) { once = false; }
        this._fn = fn;
        this._once = once;
        this._thisArg = thisArg;
        this._next = this._prev = this._owner = null;
    }
    SignalBinding.prototype.detach = function () {
        if (this._owner === null)
            { return false; }
        this._owner.detach(this);
        return true;
    };
    return SignalBinding;
}());
/**
 * @private
 */
function _addSignalBinding(self, node) {
    if (!self._head) {
        self._head = node;
        self._tail = node;
    }
    else {
        self._tail._next = node;
        node._prev = self._tail;
        self._tail = node;
    }
    node._owner = self;
    return node;
}
/**
 * @memberof PIXI
 */
var Signal = /** @class */ (function () {
    /**
     * MiniSignal constructor.
     * @example
     * let mySignal = new Signal();
     * let binding = mySignal.add(onSignal);
     * mySignal.dispatch('foo', 'bar');
     * mySignal.detach(binding);
     */
    function Signal() {
        this._head = this._tail = undefined;
    }
    /**
     * Return an array of attached SignalBinding.
     *
     * @param {Boolean} [exists=false] - We only need to know if there are handlers.
     * @returns {PIXI.SignalBinding[]|Boolean} Array of attached SignalBinding or Boolean if called with exists = true
     * @api public
     */
    Signal.prototype.handlers = function (exists) {
        if (exists === void 0) { exists = false; }
        var node = this._head;
        if (exists)
            { return !!node; }
        var ee = [];
        while (node) {
            ee.push(node);
            node = node._next;
        }
        return ee;
    };
    /**
     * Return true if node is a SignalBinding attached to this MiniSignal
     *
     * @param {PIXI.SignalBinding} node - Node to check.
     * @returns {Boolean} True if node is attache to mini-signal
     */
    Signal.prototype.has = function (node) {
        if (!(node instanceof SignalBinding)) {
            throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.');
        }
        return node._owner === this;
    };
    /**
     * Dispaches a signal to all registered listeners.
     *
     * @returns {Boolean} Indication if we've emitted an event.
     */
    Signal.prototype.dispatch = function () {
        var arguments$1 = arguments;

        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments$1[_i];
        }
        var node = this._head;
        if (!node)
            { return false; }
        while (node) {
            if (node._once)
                { this.detach(node); }
            node._fn.apply(node._thisArg, args);
            node = node._next;
        }
        return true;
    };
    /**
     * Register a new listener.
     *
     * @param {Function} fn - Callback function.
     * @param {object} [thisArg] - The context of the callback function.
     * @returns {PIXI.SignalBinding} The SignalBinding node that was added.
     */
    Signal.prototype.add = function (fn, thisArg) {
        if (thisArg === void 0) { thisArg = null; }
        if (typeof fn !== 'function') {
            throw new Error('MiniSignal#add(): First arg must be a Function.');
        }
        return _addSignalBinding(this, new SignalBinding(fn, false, thisArg));
    };
    /**
     * Register a new listener that will be executed only once.
     *
     * @param {Function} fn - Callback function.
     * @param {object} [thisArg] - The context of the callback function.
     * @returns {PIXI.SignalBinding} The SignalBinding node that was added.
     */
    Signal.prototype.once = function (fn, thisArg) {
        if (thisArg === void 0) { thisArg = null; }
        if (typeof fn !== 'function') {
            throw new Error('MiniSignal#once(): First arg must be a Function.');
        }
        return _addSignalBinding(this, new SignalBinding(fn, true, thisArg));
    };
    /**
     * Remove binding object.
     *
     * @param {PIXI.SignalBinding} node - The binding node that will be removed.
     * @returns {Signal} The instance on which this method was called.
     * @api public */
    Signal.prototype.detach = function (node) {
        if (!(node instanceof SignalBinding)) {
            throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.');
        }
        if (node._owner !== this)
            { return this; } // todo: or error?
        if (node._prev)
            { node._prev._next = node._next; }
        if (node._next)
            { node._next._prev = node._prev; }
        if (node === this._head) { // first node
            this._head = node._next;
            if (node._next === null) {
                this._tail = null;
            }
        }
        else if (node === this._tail) { // last node
            this._tail = node._prev;
            this._tail._next = null;
        }
        node._owner = null;
        return this;
    };
    /**
     * Detach all listeners.
     *
     * @returns {Signal} The instance on which this method was called.
     */
    Signal.prototype.detachAll = function () {
        var node = this._head;
        if (!node)
            { return this; }
        this._head = this._tail = null;
        while (node) {
            node._owner = null;
            node = node._next;
        }
        return this;
    };
    return Signal;
}());

/**
 * function from npm package `parseUri`, converted to TS to avoid leftpad incident
 * @param {string} str
 * @param [opts] - options
 * @param {boolean} [opts.strictMode] - type of parser
 */
function parseUri(str, opts) {
    opts = opts || {};
    var o = {
        // eslint-disable-next-line max-len
        key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'],
        q: {
            name: 'queryKey',
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {
            // eslint-disable-next-line max-len
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            // eslint-disable-next-line max-len
            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
        }
    };
    var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str);
    var uri = {};
    var i = 14;
    while (i--)
        { uri[o.key[i]] = m[i] || ''; }
    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function (_t0, t1, t2) {
        if (t1)
            { uri[o.q.name][t1] = t2; }
    });
    return uri;
}

// tests if CORS is supported in XHR, if not we need to use XDR
var useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest())));
var loaders_tempAnchor = null;
// some status constants
var STATUS_NONE = 0;
var STATUS_OK = 200;
var STATUS_EMPTY = 204;
var STATUS_IE_BUG_EMPTY = 1223;
var STATUS_TYPE_OK = 2;
// noop
function _noop() { }
/**
 * Quick helper to set a value on one of the extension maps. Ensures there is no
 * dot at the start of the extension.
 *
 * @ignore
 * @param map - The map to set on.
 * @param extname - The extension (or key) to set.
 * @param val - The value to set.
 */
function setExtMap(map, extname, val) {
    if (extname && extname.indexOf('.') === 0) {
        extname = extname.substring(1);
    }
    if (!extname) {
        return;
    }
    map[extname] = val;
}
/**
 * Quick helper to get string xhr type.
 *
 * @ignore
 * @param xhr - The request to check.
 * @return The type.
 */
function reqType(xhr) {
    return xhr.toString().replace('object ', '');
}
/**
 * Manages the state and loading of a resource and all child resources.
 *
 * Can be extended in `GlobalMixins.LoaderResource`.
 *
 * @memberof PIXI
 */
var LoaderResource = /** @class */ (function () {
    /**
     * @param {string} name - The name of the resource to load.
     * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass
     *      an array of sources.
     * @param {object} [options] - The options for the load.
     * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to
     *      determine automatically.
     * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes
     *      longer than this time it is cancelled and the load is considered a failure. If this value is
     *      set to `0` then there is no explicit timeout.
     * @param {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource
     *      be loaded?
     * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How
     *      should the data being loaded be interpreted when using XHR?
     * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware
     *      and the Resource object.
     */
    function LoaderResource(name, url, options) {
        /**
         * The `dequeue` method that will be used a storage place for the async queue dequeue method
         * used privately by the loader.
         *
         * @private
         * @member {function}
         */
        this._dequeue = _noop;
        /**
         * Used a storage place for the on load binding used privately by the loader.
         *
         * @private
         * @member {function}
         */
        this._onLoadBinding = null;
        /**
         * The timer for element loads to check if they timeout.
         *
         * @private
         */
        this._elementTimer = 0;
        /**
         * The `complete` function bound to this resource's context.
         *
         * @private
         * @type {function}
         */
        this._boundComplete = null;
        /**
         * The `_onError` function bound to this resource's context.
         *
         * @private
         * @type {function}
         */
        this._boundOnError = null;
        /**
         * The `_onProgress` function bound to this resource's context.
         *
         * @private
         * @type {function}
         */
        this._boundOnProgress = null;
        /**
         * The `_onTimeout` function bound to this resource's context.
         *
         * @private
         * @type {function}
         */
        this._boundOnTimeout = null;
        this._boundXhrOnError = null;
        this._boundXhrOnTimeout = null;
        this._boundXhrOnAbort = null;
        this._boundXhrOnLoad = null;
        if (typeof name !== 'string' || typeof url !== 'string') {
            throw new Error('Both name and url are required for constructing a resource.');
        }
        options = options || {};
        this._flags = 0;
        // set data url flag, needs to be set early for some _determineX checks to work.
        this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0);
        this.name = name;
        this.url = url;
        this.extension = this._getExtension();
        this.data = null;
        this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin;
        this.timeout = options.timeout || 0;
        this.loadType = options.loadType || this._determineLoadType();
        // The type used to load the resource via XHR. If unset, determined automatically.
        this.xhrType = options.xhrType;
        // Extra info for middleware, and controlling specifics about how the resource loads.
        // Note that if you pass in a `loadElement`, the Resource class takes ownership of it.
        // Meaning it will modify it as it sees fit.
        this.metadata = options.metadata || {};
        // The error that occurred while loading (if any).
        this.error = null;
        // The XHR object that was used to load this resource. This is only set
        // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`.
        this.xhr = null;
        // The child resources this resource owns.
        this.children = [];
        // The resource type.
        this.type = LoaderResource.TYPE.UNKNOWN;
        // The progress chunk owned by this resource.
        this.progressChunk = 0;
        // The `dequeue` method that will be used a storage place for the async queue dequeue method
        // used privately by the loader.
        this._dequeue = _noop;
        // Used a storage place for the on load binding used privately by the loader.
        this._onLoadBinding = null;
        // The timer for element loads to check if they timeout.
        this._elementTimer = 0;
        this._boundComplete = this.complete.bind(this);
        this._boundOnError = this._onError.bind(this);
        this._boundOnProgress = this._onProgress.bind(this);
        this._boundOnTimeout = this._onTimeout.bind(this);
        // xhr callbacks
        this._boundXhrOnError = this._xhrOnError.bind(this);
        this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this);
        this._boundXhrOnAbort = this._xhrOnAbort.bind(this);
        this._boundXhrOnLoad = this._xhrOnLoad.bind(this);
        // Dispatched when the resource beings to load.
        this.onStart = new Signal();
        // Dispatched each time progress of this resource load updates.
        // Not all resources types and loader systems can support this event
        // so sometimes it may not be available. If the resource
        // is being loaded on a modern browser, using XHR, and the remote server
        // properly sets Content-Length headers, then this will be available.
        this.onProgress = new Signal();
        // Dispatched once this resource has loaded, if there was an error it will
        // be in the `error` property.
        this.onComplete = new Signal();
        // Dispatched after this resource has had all the *after* middleware run on it.
        this.onAfterMiddleware = new Signal();
    }
    /**
     * Sets the load type to be used for a specific extension.
     *
     * @static
     * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
     * @param {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to.
     */
    LoaderResource.setExtensionLoadType = function (extname, loadType) {
        setExtMap(LoaderResource._loadTypeMap, extname, loadType);
    };
    /**
     * Sets the load type to be used for a specific extension.
     *
     * @static
     * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
     * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
     */
    LoaderResource.setExtensionXhrType = function (extname, xhrType) {
        setExtMap(LoaderResource._xhrTypeMap, extname, xhrType);
    };
    Object.defineProperty(LoaderResource.prototype, "isDataUrl", {
        /**
         * When the resource starts to load.
         *
         * @memberof PIXI.LoaderResource
         * @callback OnStartSignal
         * @param {Resource} resource - The resource that the event happened on.
         */
        /**
         * When the resource reports loading progress.
         *
         * @memberof PIXI.LoaderResource
         * @callback OnProgressSignal
         * @param {Resource} resource - The resource that the event happened on.
         * @param {number} percentage - The progress of the load in the range [0, 1].
         */
        /**
         * When the resource finishes loading.
         *
         * @memberof PIXI.LoaderResource
         * @callback OnCompleteSignal
         * @param {Resource} resource - The resource that the event happened on.
         */
        /**
         * @memberof PIXI.LoaderResource
         * @typedef {object} IMetadata
         * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The
         *      element to use for loading, instead of creating one.
         * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This
         *      is useful if you want to pass in a `loadElement` that you already added load sources to.
         * @property {string|string[]} [mimeType] - The mime type to use for the source element
         *      of a video/audio elment. If the urls are an array, you can pass this as an array as well
         *      where each index is the mime type to use for the corresponding url index.
         */
        /**
         * Stores whether or not this url is a data url.
         *
         * @readonly
         * @member {boolean}
         */
        get: function () {
            return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(LoaderResource.prototype, "isComplete", {
        /**
         * Describes if this resource has finished loading. Is true when the resource has completely
         * loaded.
         *
         * @readonly
         * @member {boolean}
         */
        get: function () {
            return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(LoaderResource.prototype, "isLoading", {
        /**
         * Describes if this resource is currently loading. Is true when the resource starts loading,
         * and is false again when complete.
         *
         * @readonly
         * @member {boolean}
         */
        get: function () {
            return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Marks the resource as complete.
     *
     */
    LoaderResource.prototype.complete = function () {
        this._clearEvents();
        this._finish();
    };
    /**
     * Aborts the loading of this resource, with an optional message.
     *
     * @param {string} message - The message to use for the error
     */
    LoaderResource.prototype.abort = function (message) {
        // abort can be called multiple times, ignore subsequent calls.
        if (this.error) {
            return;
        }
        // store error
        this.error = new Error(message);
        // clear events before calling aborts
        this._clearEvents();
        // abort the actual loading
        if (this.xhr) {
            this.xhr.abort();
        }
        else if (this.xdr) {
            this.xdr.abort();
        }
        else if (this.data) {
            // single source
            if (this.data.src) {
                this.data.src = LoaderResource.EMPTY_GIF;
            }
            // multi-source
            else {
                while (this.data.firstChild) {
                    this.data.removeChild(this.data.firstChild);
                }
            }
        }
        // done now.
        this._finish();
    };
    /**
     * Kicks off loading of this resource. This method is asynchronous.
     *
     * @param {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded.
     */
    LoaderResource.prototype.load = function (cb) {
        var _this = this;
        if (this.isLoading) {
            return;
        }
        if (this.isComplete) {
            if (cb) {
                setTimeout(function () { return cb(_this); }, 1);
            }
            return;
        }
        else if (cb) {
            this.onComplete.once(cb);
        }
        this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, true);
        this.onStart.dispatch(this);
        // if unset, determine the value
        if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') {
            this.crossOrigin = this._determineCrossOrigin(this.url);
        }
        switch (this.loadType) {
            case LoaderResource.LOAD_TYPE.IMAGE:
                this.type = LoaderResource.TYPE.IMAGE;
                this._loadElement('image');
                break;
            case LoaderResource.LOAD_TYPE.AUDIO:
                this.type = LoaderResource.TYPE.AUDIO;
                this._loadSourceElement('audio');
                break;
            case LoaderResource.LOAD_TYPE.VIDEO:
                this.type = LoaderResource.TYPE.VIDEO;
                this._loadSourceElement('video');
                break;
            case LoaderResource.LOAD_TYPE.XHR:
            /* falls through */
            default:
                if (useXdr && this.crossOrigin) {
                    this._loadXdr();
                }
                else {
                    this._loadXhr();
                }
                break;
        }
    };
    /**
     * Checks if the flag is set.
     *
     * @param flag - The flag to check.
     * @return True if the flag is set.
     */
    LoaderResource.prototype._hasFlag = function (flag) {
        return (this._flags & flag) !== 0;
    };
    /**
     * (Un)Sets the flag.
     *
     * @param flag - The flag to (un)set.
     * @param value - Whether to set or (un)set the flag.
     */
    LoaderResource.prototype._setFlag = function (flag, value) {
        this._flags = value ? (this._flags | flag) : (this._flags & ~flag);
    };
    /**
     * Clears all the events from the underlying loading source.
     */
    LoaderResource.prototype._clearEvents = function () {
        clearTimeout(this._elementTimer);
        if (this.data && this.data.removeEventListener) {
            this.data.removeEventListener('error', this._boundOnError, false);
            this.data.removeEventListener('load', this._boundComplete, false);
            this.data.removeEventListener('progress', this._boundOnProgress, false);
            this.data.removeEventListener('canplaythrough', this._boundComplete, false);
        }
        if (this.xhr) {
            if (this.xhr.removeEventListener) {
                this.xhr.removeEventListener('error', this._boundXhrOnError, false);
                this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false);
                this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false);
                this.xhr.removeEventListener('progress', this._boundOnProgress, false);
                this.xhr.removeEventListener('load', this._boundXhrOnLoad, false);
            }
            else {
                this.xhr.onerror = null;
                this.xhr.ontimeout = null;
                this.xhr.onprogress = null;
                this.xhr.onload = null;
            }
        }
    };
    /**
     * Finalizes the load.
     */
    LoaderResource.prototype._finish = function () {
        if (this.isComplete) {
            throw new Error('Complete called again for an already completed resource.');
        }
        this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true);
        this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false);
        this.onComplete.dispatch(this);
    };
    /**
     * Loads this resources using an element that has a single source,
     * like an HTMLImageElement.
     * @private
     * @param type - The type of element to use.
     */
    LoaderResource.prototype._loadElement = function (type) {
        if (this.metadata.loadElement) {
            this.data = this.metadata.loadElement;
        }
        else if (type === 'image' && typeof globalThis.Image !== 'undefined') {
            this.data = new Image();
        }
        else {
            this.data = document.createElement(type);
        }
        if (this.crossOrigin) {
            this.data.crossOrigin = this.crossOrigin;
        }
        if (!this.metadata.skipSource) {
            this.data.src = this.url;
        }
        this.data.addEventListener('error', this._boundOnError, false);
        this.data.addEventListener('load', this._boundComplete, false);
        this.data.addEventListener('progress', this._boundOnProgress, false);
        if (this.timeout) {
            this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
        }
    };
    /**
     * Loads this resources using an element that has multiple sources,
     * like an HTMLAudioElement or HTMLVideoElement.
     * @param type - The type of element to use.
     */
    LoaderResource.prototype._loadSourceElement = function (type) {
        if (this.metadata.loadElement) {
            this.data = this.metadata.loadElement;
        }
        else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') {
            this.data = new Audio();
        }
        else {
            this.data = document.createElement(type);
        }
        if (this.data === null) {
            this.abort("Unsupported element: " + type);
            return;
        }
        if (this.crossOrigin) {
            this.data.crossOrigin = this.crossOrigin;
        }
        if (!this.metadata.skipSource) {
            // support for CocoonJS Canvas+ runtime, lacks document.createElement('source')
            if (navigator.isCocoonJS) {
                this.data.src = Array.isArray(this.url) ? this.url[0] : this.url;
            }
            else if (Array.isArray(this.url)) {
                var mimeTypes = this.metadata.mimeType;
                for (var i = 0; i < this.url.length; ++i) {
                    this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes));
                }
            }
            else {
                var mimeTypes = this.metadata.mimeType;
                this.data.appendChild(this._createSource(type, this.url, Array.isArray(mimeTypes) ? mimeTypes[0] : mimeTypes));
            }
        }
        this.data.addEventListener('error', this._boundOnError, false);
        this.data.addEventListener('load', this._boundComplete, false);
        this.data.addEventListener('progress', this._boundOnProgress, false);
        this.data.addEventListener('canplaythrough', this._boundComplete, false);
        this.data.load();
        if (this.timeout) {
            this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
        }
    };
    /**
     * Loads this resources using an XMLHttpRequest.
     */
    LoaderResource.prototype._loadXhr = function () {
        // if unset, determine the value
        if (typeof this.xhrType !== 'string') {
            this.xhrType = this._determineXhrType();
        }
        var xhr = this.xhr = new XMLHttpRequest();
        // send credentials when crossOrigin with credentials requested
        if (this.crossOrigin === 'use-credentials') {
            xhr.withCredentials = true;
        }
        // set the request type and url
        xhr.open('GET', this.url, true);
        xhr.timeout = this.timeout;
        // load json as text and parse it ourselves. We do this because some browsers
        // *cough* safari *cough* can't deal with it.
        if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON
            || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) {
            xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT;
        }
        else {
            xhr.responseType = this.xhrType;
        }
        xhr.addEventListener('error', this._boundXhrOnError, false);
        xhr.addEventListener('timeout', this._boundXhrOnTimeout, false);
        xhr.addEventListener('abort', this._boundXhrOnAbort, false);
        xhr.addEventListener('progress', this._boundOnProgress, false);
        xhr.addEventListener('load', this._boundXhrOnLoad, false);
        xhr.send();
    };
    /**
     * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross).
     */
    LoaderResource.prototype._loadXdr = function () {
        // if unset, determine the value
        if (typeof this.xhrType !== 'string') {
            this.xhrType = this._determineXhrType();
        }
        var xdr = this.xhr = new globalThis.XDomainRequest(); // eslint-disable-line no-undef
        // XDomainRequest has a few quirks. Occasionally it will abort requests
        // A way to avoid this is to make sure ALL callbacks are set even if not used
        // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
        xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9
        xdr.onerror = this._boundXhrOnError;
        xdr.ontimeout = this._boundXhrOnTimeout;
        xdr.onprogress = this._boundOnProgress;
        xdr.onload = this._boundXhrOnLoad;
        xdr.open('GET', this.url, true);
        // Note: The xdr.send() call is wrapped in a timeout to prevent an
        // issue with the interface where some requests are lost if multiple
        // XDomainRequests are being sent at the same time.
        // Some info here: https://github.com/photonstorm/phaser/issues/1248
        setTimeout(function () { return xdr.send(); }, 1);
    };
    /**
     * Creates a source used in loading via an element.
     * @param type - The element type (video or audio).
     * @param url - The source URL to load from.
     * @param [mime] - The mime type of the video
     * @return The source element.
     */
    LoaderResource.prototype._createSource = function (type, url, mime) {
        if (!mime) {
            mime = type + "/" + this._getExtension(url);
        }
        var source = document.createElement('source');
        source.src = url;
        source.type = mime;
        return source;
    };
    /**
     * Called if a load errors out.
     *
     * @param event - The error event from the element that emits it.
     */
    LoaderResource.prototype._onError = function (event) {
        this.abort("Failed to load element using: " + event.target.nodeName);
    };
    /**
     * Called if a load progress event fires for an element or xhr/xdr.
     * @param event - Progress event.
     */
    LoaderResource.prototype._onProgress = function (event) {
        if (event && event.lengthComputable) {
            this.onProgress.dispatch(this, event.loaded / event.total);
        }
    };
    /**
     * Called if a timeout event fires for an element.
     */
    LoaderResource.prototype._onTimeout = function () {
        this.abort("Load timed out.");
    };
    /**
     * Called if an error event fires for xhr/xdr.
     */
    LoaderResource.prototype._xhrOnError = function () {
        var xhr = this.xhr;
        this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\"");
    };
    /**
     * Called if an error event fires for xhr/xdr.
     */
    LoaderResource.prototype._xhrOnTimeout = function () {
        var xhr = this.xhr;
        this.abort(reqType(xhr) + " Request timed out.");
    };
    /**
     * Called if an abort event fires for xhr/xdr.
     */
    LoaderResource.prototype._xhrOnAbort = function () {
        var xhr = this.xhr;
        this.abort(reqType(xhr) + " Request was aborted by the user.");
    };
    /**
     * Called when data successfully loads from an xhr/xdr request.
     */
    LoaderResource.prototype._xhrOnLoad = function () {
        var xhr = this.xhr;
        var text = '';
        var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200.
        // responseText is accessible only if responseType is '' or 'text' and on older browsers
        if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') {
            text = xhr.responseText;
        }
        // status can be 0 when using the `file://` protocol so we also check if a response is set.
        // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request.
        if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.XHR_RESPONSE_TYPE.BUFFER)) {
            status = STATUS_OK;
        }
        // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
        else if (status === STATUS_IE_BUG_EMPTY) {
            status = STATUS_EMPTY;
        }
        var statusType = (status / 100) | 0;
        if (statusType === STATUS_TYPE_OK) {
            // if text, just return it
            if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) {
                this.data = text;
                this.type = LoaderResource.TYPE.TEXT;
            }
            // if json, parse into json object
            else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) {
                try {
                    this.data = JSON.parse(text);
                    this.type = LoaderResource.TYPE.JSON;
                }
                catch (e) {
                    this.abort("Error trying to parse loaded json: " + e);
                    return;
                }
            }
            // if xml, parse into an xml document or div element
            else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) {
                try {
                    if (globalThis.DOMParser) {
                        var domparser = new DOMParser();
                        this.data = domparser.parseFromString(text, 'text/xml');
                    }
                    else {
                        var div = document.createElement('div');
                        div.innerHTML = text;
                        this.data = div;
                    }
                    this.type = LoaderResource.TYPE.XML;
                }
                catch (e$1) {
                    this.abort("Error trying to parse loaded xml: " + e$1);
                    return;
                }
            }
            // other types just return the response
            else {
                this.data = xhr.response || text;
            }
        }
        else {
            this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL);
            return;
        }
        this.complete();
    };
    /**
     * Sets the `crossOrigin` property for this resource based on if the url
     * for this resource is cross-origin. If crossOrigin was manually set, this
     * function does nothing.
     * @private
     * @param url - The url to test.
     * @param [loc=globalThis.location] - The location object to test against.
     * @return The crossOrigin value to use (or empty string for none).
     */
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    LoaderResource.prototype._determineCrossOrigin = function (url, loc) {
        // data: and javascript: urls are considered same-origin
        if (url.indexOf('data:') === 0) {
            return '';
        }
        // A sandboxed iframe without the 'allow-same-origin' attribute will have a special
        // origin designed not to match globalThis.location.origin, and will always require
        // crossOrigin requests regardless of whether the location matches.
        if (globalThis.origin !== globalThis.location.origin) {
            return 'anonymous';
        }
        // default is globalThis.location
        loc = loc || globalThis.location;
        if (!loaders_tempAnchor) {
            loaders_tempAnchor = document.createElement('a');
        }
        // let the browser determine the full href for the url of this resource and then
        // parse with the node url lib, we can't use the properties of the anchor element
        // because they don't work in IE9 :(
        loaders_tempAnchor.href = url;
        var parsedUrl = parseUri(loaders_tempAnchor.href, { strictMode: true });
        var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port);
        var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : '';
        // if cross origin
        if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) {
            return 'anonymous';
        }
        return '';
    };
    /**
     * Determines the responseType of an XHR request based on the extension of the
     * resource being loaded.
     *
     * @private
     * @return {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use.
     */
    LoaderResource.prototype._determineXhrType = function () {
        return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT;
    };
    /**
     * Determines the loadType of a resource based on the extension of the
     * resource being loaded.
     *
     * @private
     * @return {PIXI.LoaderResource.LOAD_TYPE} The loadType to use.
     */
    LoaderResource.prototype._determineLoadType = function () {
        return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR;
    };
    /**
     * Extracts the extension (sans '.') of the file being loaded by the resource.
     *
     * @param [url] - url to parse, `this.url` by default.
     * @return The extension.
     */
    LoaderResource.prototype._getExtension = function (url) {
        if (url === void 0) { url = this.url; }
        var ext = '';
        if (this.isDataUrl) {
            var slashIndex = url.indexOf('/');
            ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex));
        }
        else {
            var queryStart = url.indexOf('?');
            var hashStart = url.indexOf('#');
            var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length);
            url = url.substring(0, index);
            ext = url.substring(url.lastIndexOf('.') + 1);
        }
        return ext.toLowerCase();
    };
    /**
     * Determines the mime type of an XHR request based on the responseType of
     * resource being loaded.
     *
     * @param type - The type to get a mime type for.
     * @private
     * @return The mime type to use.
     */
    LoaderResource.prototype._getMimeFromXhrType = function (type) {
        switch (type) {
            case LoaderResource.XHR_RESPONSE_TYPE.BUFFER:
                return 'application/octet-binary';
            case LoaderResource.XHR_RESPONSE_TYPE.BLOB:
                return 'application/blob';
            case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT:
                return 'application/xml';
            case LoaderResource.XHR_RESPONSE_TYPE.JSON:
                return 'application/json';
            case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT:
            case LoaderResource.XHR_RESPONSE_TYPE.TEXT:
            /* falls through */
            default:
                return 'text/plain';
        }
    };
    return LoaderResource;
}());
// eslint-disable-next-line @typescript-eslint/no-namespace
(function (LoaderResource) {
    /**
     * The types of resources a resource could represent.
     *
     * @static
     * @readonly
     * @enum {number}
     * @memberof PIXI.LoaderResource
     */
    var STATUS_FLAGS;
    (function (STATUS_FLAGS) {
        /** None */
        STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE";
        /** Data URL */
        STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL";
        /** Complete */
        STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE";
        /** Loading */
        STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING";
    })(STATUS_FLAGS = LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {}));
    /**
     * The types of resources a resource could represent.
     *
     * @static
     * @readonly
     * @enum {number}
     * @memberof PIXI.LoaderResource
     */
    var TYPE;
    (function (TYPE) {
        /** Unknown */
        TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN";
        /** JSON */
        TYPE[TYPE["JSON"] = 1] = "JSON";
        /** XML */
        TYPE[TYPE["XML"] = 2] = "XML";
        /** Image */
        TYPE[TYPE["IMAGE"] = 3] = "IMAGE";
        /** Audio */
        TYPE[TYPE["AUDIO"] = 4] = "AUDIO";
        /** Video */
        TYPE[TYPE["VIDEO"] = 5] = "VIDEO";
        /** Plain text */
        TYPE[TYPE["TEXT"] = 6] = "TEXT";
    })(TYPE = LoaderResource.TYPE || (LoaderResource.TYPE = {}));
    /**
     * The types of loading a resource can use.
     *
     * @static
     * @readonly
     * @enum {number}
     * @memberof PIXI.LoaderResource
     */
    var LOAD_TYPE;
    (function (LOAD_TYPE) {
        /** Uses XMLHttpRequest to load the resource. */
        LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR";
        /** Uses an `Image` object to load the resource. */
        LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE";
        /** Uses an `Audio` object to load the resource. */
        LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO";
        /** Uses a `Video` object to load the resource. */
        LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO";
    })(LOAD_TYPE = LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {}));
    /**
     * The XHR ready states, used internally.
     *
     * @static
     * @readonly
     * @enum {string}
     * @memberof PIXI.LoaderResource
     */
    var XHR_RESPONSE_TYPE;
    (function (XHR_RESPONSE_TYPE) {
        /** string */
        XHR_RESPONSE_TYPE["DEFAULT"] = "text";
        /** ArrayBuffer */
        XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer";
        /** Blob */
        XHR_RESPONSE_TYPE["BLOB"] = "blob";
        /** Document */
        XHR_RESPONSE_TYPE["DOCUMENT"] = "document";
        /** Object */
        XHR_RESPONSE_TYPE["JSON"] = "json";
        /** String */
        XHR_RESPONSE_TYPE["TEXT"] = "text";
    })(XHR_RESPONSE_TYPE = LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {}));
    LoaderResource._loadTypeMap = {
        // images
        gif: LoaderResource.LOAD_TYPE.IMAGE,
        png: LoaderResource.LOAD_TYPE.IMAGE,
        bmp: LoaderResource.LOAD_TYPE.IMAGE,
        jpg: LoaderResource.LOAD_TYPE.IMAGE,
        jpeg: LoaderResource.LOAD_TYPE.IMAGE,
        tif: LoaderResource.LOAD_TYPE.IMAGE,
        tiff: LoaderResource.LOAD_TYPE.IMAGE,
        webp: LoaderResource.LOAD_TYPE.IMAGE,
        tga: LoaderResource.LOAD_TYPE.IMAGE,
        svg: LoaderResource.LOAD_TYPE.IMAGE,
        'svg+xml': LoaderResource.LOAD_TYPE.IMAGE,
        // audio
        mp3: LoaderResource.LOAD_TYPE.AUDIO,
        ogg: LoaderResource.LOAD_TYPE.AUDIO,
        wav: LoaderResource.LOAD_TYPE.AUDIO,
        // videos
        mp4: LoaderResource.LOAD_TYPE.VIDEO,
        webm: LoaderResource.LOAD_TYPE.VIDEO,
    };
    LoaderResource._xhrTypeMap = {
        // xml
        xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        svg: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
        // Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
        // this should probably be fine.
        tsx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
        // images
        gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        png: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
        // json
        json: LoaderResource.XHR_RESPONSE_TYPE.JSON,
        // text
        text: LoaderResource.XHR_RESPONSE_TYPE.TEXT,
        txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT,
        // fonts
        ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER,
        otf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER,
    };
    // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif
    LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
})(LoaderResource || (LoaderResource = {}));

/**
 * Smaller version of the async library constructs.
 * @ignore
 */
function _noop$1() {
}
/**
 * Ensures a function is only called once.
 * @ignore
 * @param {function} fn - The function to wrap.
 * @return {function} The wrapping function.
 */
function onlyOnce(fn) {
    return function onceWrapper() {
        var arguments$1 = arguments;

        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments$1[_i];
        }
        if (fn === null) {
            throw new Error('Callback was already called.');
        }
        var callFn = fn;
        fn = null;
        callFn.apply(this, args);
    };
}
/**
 * @private
 * @memberof PIXI
 */
var AsyncQueueItem = /** @class */ (function () {
    /**
     * @private
     */
    function AsyncQueueItem(data, callback) {
        this.data = data;
        this.callback = callback;
    }
    return AsyncQueueItem;
}());
/**
 * @private
 * @memberof PIXI
 */
var AsyncQueue = /** @class */ (function () {
    /**
     * @private
     */
    function AsyncQueue(worker, concurrency) {
        var _this = this;
        if (concurrency === void 0) { concurrency = 1; }
        this.workers = 0;
        this.saturated = _noop$1;
        this.unsaturated = _noop$1;
        this.empty = _noop$1;
        this.drain = _noop$1;
        this.error = _noop$1;
        this.started = false;
        this.paused = false;
        this._tasks = [];
        this._insert = function (data, insertAtFront, callback) {
            if (callback && typeof callback !== 'function') {
                throw new Error('task callback must be a function');
            }
            _this.started = true;
            // eslint-disable-next-line no-eq-null,eqeqeq
            if (data == null && _this.idle()) {
                // call drain immediately if there are no tasks
                setTimeout(function () { return _this.drain(); }, 1);
                return;
            }
            var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop$1);
            if (insertAtFront) {
                _this._tasks.unshift(item);
            }
            else {
                _this._tasks.push(item);
            }
            setTimeout(_this.process, 1);
        };
        this.process = function () {
            while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) {
                var task = _this._tasks.shift();
                if (_this._tasks.length === 0) {
                    _this.empty();
                }
                _this.workers += 1;
                if (_this.workers === _this.concurrency) {
                    _this.saturated();
                }
                _this._worker(task.data, onlyOnce(_this._next(task)));
            }
        };
        this._worker = worker;
        if (concurrency === 0) {
            throw new Error('Concurrency must not be zero');
        }
        this.concurrency = concurrency;
        this.buffer = concurrency / 4.0;
    }
    /**
     * @private
     */
    AsyncQueue.prototype._next = function (task) {
        var _this = this;
        return function () {
            var arguments$1 = arguments;

            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments$1[_i];
            }
            _this.workers -= 1;
            task.callback.apply(task, args);
            // eslint-disable-next-line no-eq-null,eqeqeq
            if (args[0] != null) {
                _this.error(args[0], task.data);
            }
            if (_this.workers <= (_this.concurrency - _this.buffer)) {
                _this.unsaturated();
            }
            if (_this.idle()) {
                _this.drain();
            }
            _this.process();
        };
    };
    // That was in object
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    AsyncQueue.prototype.push = function (data, callback) {
        this._insert(data, false, callback);
    };
    AsyncQueue.prototype.kill = function () {
        this.workers = 0;
        this.drain = _noop$1;
        this.started = false;
        this._tasks = [];
    };
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    AsyncQueue.prototype.unshift = function (data, callback) {
        this._insert(data, true, callback);
    };
    AsyncQueue.prototype.length = function () {
        return this._tasks.length;
    };
    AsyncQueue.prototype.running = function () {
        return this.workers;
    };
    AsyncQueue.prototype.idle = function () {
        return this._tasks.length + this.workers === 0;
    };
    AsyncQueue.prototype.pause = function () {
        if (this.paused === true) {
            return;
        }
        this.paused = true;
    };
    AsyncQueue.prototype.resume = function () {
        if (this.paused === false) {
            return;
        }
        this.paused = false;
        // Need to call this.process once per concurrent
        // worker to preserve full concurrency after pause
        for (var w = 1; w <= this.concurrency; w++) {
            this.process();
        }
    };
    /**
     * Iterates an array in series.
     *
     * @param {Array.<*>} array - Array to iterate.
     * @param {function} iterator - Function to call for each element.
     * @param {function} callback - Function to call when done, or on error.
     * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1.
     */
    AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) {
        var i = 0;
        var len = array.length;
        function next(err) {
            if (err || i === len) {
                if (callback) {
                    callback(err);
                }
                return;
            }
            if (deferNext) {
                setTimeout(function () {
                    iterator(array[i++], next);
                }, 1);
            }
            else {
                iterator(array[i++], next);
            }
        }
        next();
    };
    /**
     * Async queue implementation,
     *
     * @param {function} worker - The worker function to call for each task.
     * @param {number} concurrency - How many workers to run in parrallel.
     * @return {*} The async queue object.
     */
    AsyncQueue.queue = function (worker, concurrency) {
        return new AsyncQueue(worker, concurrency);
    };
    return AsyncQueue;
}());

// some constants
var MAX_PROGRESS = 100;
var rgxExtractUrlHash = /(#[\w-]+)?$/;
/**
 * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader
 *
 * ```js
 * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use.
 * // or
 * const loader = new PIXI.Loader(); // You can also create your own if you want
 *
 * const sprites = {};
 *
 * // Chainable `add` to enqueue a resource
 * loader.add('bunny', 'data/bunny.png')
 *       .add('spaceship', 'assets/spritesheet.json');
 * loader.add('scoreFont', 'assets/score.fnt');
 *
 * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource.
 * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc).
 * loader.pre(cachingMiddleware);
 *
 * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource.
 * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc).
 * loader.use(parsingMiddleware);
 *
 * // The `load` method loads the queue of resources, and calls the passed in callback called once all
 * // resources have loaded.
 * loader.load((loader, resources) => {
 *     // resources is an object where the key is the name of the resource loaded and the value is the resource object.
 *     // They have a couple default properties:
 *     // - `url`: The URL that the resource was loaded from
 *     // - `error`: The error that happened when trying to load (if any)
 *     // - `data`: The raw data that was loaded
 *     // also may contain other properties based on the middleware that runs.
 *     sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture);
 *     sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture);
 *     sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture);
 * });
 *
 * // throughout the process multiple signals can be dispatched.
 * loader.onProgress.add(() => {}); // called once per loaded/errored file
 * loader.onError.add(() => {}); // called once per errored file
 * loader.onLoad.add(() => {}); // called once per loaded file
 * loader.onComplete.add(() => {}); // called once when the queued resources all load.
 * ```
 *
 * @memberof PIXI
 */
var Loader = /** @class */ (function () {
    /**
     * @param baseUrl - The base url for all resources loaded by this loader.
     * @param concurrency - The number of resources to load concurrently.
     */
    function Loader(baseUrl, concurrency) {
        var _this = this;
        if (baseUrl === void 0) { baseUrl = ''; }
        if (concurrency === void 0) { concurrency = 10; }
        /**
         * The progress percent of the loader going through the queue.
         */
        this.progress = 0;
        /**
         * Loading state of the loader, true if it is currently loading resources.
         */
        this.loading = false;
        /**
         * A querystring to append to every URL added to the loader.
         *
         * This should be a valid query string *without* the question-mark (`?`). The loader will
         * also *not* escape values for you. Make sure to escape your parameters with
         * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property.
         *
         * @example
         * const loader = new Loader();
         *
         * loader.defaultQueryString = 'user=me&password=secret';
         *
         * // This will request 'image.png?user=me&password=secret'
         * loader.add('image.png').load();
         *
         * loader.reset();
         *
         * // This will request 'image.png?v=1&user=me&password=secret'
         * loader.add('iamge.png?v=1').load();
         */
        this.defaultQueryString = '';
        /**
         * The middleware to run before loading each resource.
         */
        this._beforeMiddleware = [];
        /**
         * The middleware to run after loading each resource.
         */
        this._afterMiddleware = [];
        /**
         * The tracks the resources we are currently completing parsing for.
         */
        this._resourcesParsing = [];
        /**
         * The `_loadResource` function bound with this object context.
         *
         * @param r - The resource to load
         * @param d - The dequeue function
         */
        this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); };
        /**
         * All the resources for this loader keyed by name.
         */
        this.resources = {};
        this.baseUrl = baseUrl;
        this._beforeMiddleware = [];
        this._afterMiddleware = [];
        this._resourcesParsing = [];
        this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); };
        this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency);
        this._queue.pause();
        this.resources = {};
        this.onProgress = new Signal();
        this.onError = new Signal();
        this.onLoad = new Signal();
        this.onStart = new Signal();
        this.onComplete = new Signal();
        for (var i = 0; i < Loader._plugins.length; ++i) {
            var plugin = Loader._plugins[i];
            var pre = plugin.pre, use = plugin.use;
            if (pre) {
                this.pre(pre);
            }
            if (use) {
                this.use(use);
            }
        }
        this._protected = false;
    }
    /**
     * Same as add, params have strict order
     *
     * @private
     * @param name - The name of the resource to load.
     * @param url - The url for this resource, relative to the baseUrl of this loader.
     * @param options - The options for the load.
     * @param callback - Function to call when this specific resource completes loading.
     * @return The loader itself.
     */
    Loader.prototype._add = function (name, url, options, callback) {
        // if loading already you can only add resources that have a parent.
        if (this.loading && (!options || !options.parentResource)) {
            throw new Error('Cannot add resources while the loader is running.');
        }
        // check if resource already exists.
        if (this.resources[name]) {
            throw new Error("Resource named \"" + name + "\" already exists.");
        }
        // add base url if this isn't an absolute url
        url = this._prepareUrl(url);
        // create the store the resource
        this.resources[name] = new LoaderResource(name, url, options);
        if (typeof callback === 'function') {
            this.resources[name].onAfterMiddleware.once(callback);
        }
        // if actively loading, make sure to adjust progress chunks for that parent and its children
        if (this.loading) {
            var parent = options.parentResource;
            var incompleteChildren = [];
            for (var i = 0; i < parent.children.length; ++i) {
                if (!parent.children[i].isComplete) {
                    incompleteChildren.push(parent.children[i]);
                }
            }
            var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
            var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
            parent.children.push(this.resources[name]);
            parent.progressChunk = eachChunk;
            for (var i = 0; i < incompleteChildren.length; ++i) {
                incompleteChildren[i].progressChunk = eachChunk;
            }
            this.resources[name].progressChunk = eachChunk;
        }
        // add the resource to the queue
        this._queue.push(this.resources[name]);
        return this;
    };
    /* eslint-enable require-jsdoc,valid-jsdoc */
    /**
     * Sets up a middleware function that will run *before* the
     * resource is loaded.
     *
     * @param fn - The middleware function to register.
     * @return The loader itself.
     */
    Loader.prototype.pre = function (fn) {
        this._beforeMiddleware.push(fn);
        return this;
    };
    /**
     * Sets up a middleware function that will run *after* the
     * resource is loaded.
     *
     * @param fn - The middleware function to register.
     * @return The loader itself.
     */
    Loader.prototype.use = function (fn) {
        this._afterMiddleware.push(fn);
        return this;
    };
    /**
     * Resets the queue of the loader to prepare for a new load.
     *
     * @return The loader itself.
     */
    Loader.prototype.reset = function () {
        this.progress = 0;
        this.loading = false;
        this._queue.kill();
        this._queue.pause();
        // abort all resource loads
        for (var k in this.resources) {
            var res = this.resources[k];
            if (res._onLoadBinding) {
                res._onLoadBinding.detach();
            }
            if (res.isLoading) {
                res.abort('loader reset');
            }
        }
        this.resources = {};
        return this;
    };
    /**
     * Starts loading the queued resources.
     * @param cb - Optional callback that will be bound to the `complete` event.
     * @return The loader itself.
     */
    Loader.prototype.load = function (cb) {
        // register complete callback if they pass one
        if (typeof cb === 'function') {
            this.onComplete.once(cb);
        }
        // if the queue has already started we are done here
        if (this.loading) {
            return this;
        }
        if (this._queue.idle()) {
            this._onStart();
            this._onComplete();
        }
        else {
            // distribute progress chunks
            var numTasks = this._queue._tasks.length;
            var chunk = MAX_PROGRESS / numTasks;
            for (var i = 0; i < this._queue._tasks.length; ++i) {
                this._queue._tasks[i].data.progressChunk = chunk;
            }
            // notify we are starting
            this._onStart();
            // start loading
            this._queue.resume();
        }
        return this;
    };
    Object.defineProperty(Loader.prototype, "concurrency", {
        /**
         * The number of resources to load concurrently.
         *
         * @default 10
         */
        get: function () {
            return this._queue.concurrency;
        },
        set: function (concurrency) {
            this._queue.concurrency = concurrency;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Prepares a url for usage based on the configuration of this object
     * @param url - The url to prepare.
     * @return The prepared url.
     */
    Loader.prototype._prepareUrl = function (url) {
        var parsedUrl = parseUri(url, { strictMode: true });
        var result;
        // absolute url, just use it as is.
        if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) {
            result = url;
        }
        // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween
        else if (this.baseUrl.length
            && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1
            && url.charAt(0) !== '/') {
            result = this.baseUrl + "/" + url;
        }
        else {
            result = this.baseUrl + url;
        }
        // if we need to add a default querystring, there is a bit more work
        if (this.defaultQueryString) {
            var hash = rgxExtractUrlHash.exec(result)[0];
            result = result.slice(0, result.length - hash.length);
            if (result.indexOf('?') !== -1) {
                result += "&" + this.defaultQueryString;
            }
            else {
                result += "?" + this.defaultQueryString;
            }
            result += hash;
        }
        return result;
    };
    /**
     * Loads a single resource.
     *
     * @param resource - The resource to load.
     * @param dequeue - The function to call when we need to dequeue this item.
     */
    Loader.prototype._loadResource = function (resource, dequeue) {
        var _this = this;
        resource._dequeue = dequeue;
        // run before middleware
        AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) {
            fn.call(_this, resource, function () {
                // if the before middleware marks the resource as complete,
                // break and don't process any more before middleware
                next(resource.isComplete ? {} : null);
            });
        }, function () {
            if (resource.isComplete) {
                _this._onLoad(resource);
            }
            else {
                resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this);
                resource.load();
            }
        }, true);
    };
    /**
     * Called once loading has started.
     */
    Loader.prototype._onStart = function () {
        this.progress = 0;
        this.loading = true;
        this.onStart.dispatch(this);
    };
    /**
     * Called once each resource has loaded.
     */
    Loader.prototype._onComplete = function () {
        this.progress = MAX_PROGRESS;
        this.loading = false;
        this.onComplete.dispatch(this, this.resources);
    };
    /**
     * Called each time a resources is loaded.
     * @param resource - The resource that was loaded
     */
    Loader.prototype._onLoad = function (resource) {
        var _this = this;
        resource._onLoadBinding = null;
        // remove this resource from the async queue, and add it to our list of resources that are being parsed
        this._resourcesParsing.push(resource);
        resource._dequeue();
        // run all the after middleware for this resource
        AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) {
            fn.call(_this, resource, next);
        }, function () {
            resource.onAfterMiddleware.dispatch(resource);
            _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk);
            _this.onProgress.dispatch(_this, resource);
            if (resource.error) {
                _this.onError.dispatch(resource.error, _this, resource);
            }
            else {
                _this.onLoad.dispatch(_this, resource);
            }
            _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1);
            // do completion check
            if (_this._queue.idle() && _this._resourcesParsing.length === 0) {
                _this._onComplete();
            }
        }, true);
    };
    /**
     * Destroy the loader, removes references.
     */
    Loader.prototype.destroy = function () {
        if (!this._protected) {
            this.reset();
        }
    };
    Object.defineProperty(Loader, "shared", {
        /**
         * A premade instance of the loader that can be used to load resources.
         */
        get: function () {
            var shared = Loader._shared;
            if (!shared) {
                shared = new Loader();
                shared._protected = true;
                Loader._shared = shared;
            }
            return shared;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Adds a Loader plugin for the global shared loader and all
     * new Loader instances created.
     *
     * @param plugin - The plugin to add
     * @return Reference to PIXI.Loader for chaining
     */
    Loader.registerPlugin = function (plugin) {
        Loader._plugins.push(plugin);
        if (plugin.add) {
            plugin.add();
        }
        return Loader;
    };
    Loader._plugins = [];
    return Loader;
}());
Loader.prototype.add = function add(name, url, options, callback) {
    // special case of an array of objects or urls
    if (Array.isArray(name)) {
        for (var i = 0; i < name.length; ++i) {
            this.add(name[i]);
        }
        return this;
    }
    // if an object is passed instead of params
    if (typeof name === 'object') {
        options = name;
        callback = url || options.callback || options.onComplete;
        url = options.url;
        name = options.name || options.key || options.url;
    }
    // case where no name is passed shift all args over by one.
    if (typeof url !== 'string') {
        callback = options;
        options = url;
        url = name;
    }
    // now that we shifted make sure we have a proper url.
    if (typeof url !== 'string') {
        throw new Error('No url passed to add resource to loader.');
    }
    // options are optional so people might pass a function and no options
    if (typeof options === 'function') {
        callback = options;
        options = null;
    }
    return this._add(name, url, options, callback);
};

/**
 * Application plugin for supporting loader option. Installing the LoaderPlugin
 * is not necessary if using **pixi.js** or **pixi.js-legacy**.
 * @example
 * import {AppLoaderPlugin} from '@pixi/loaders';
 * import {Application} from '@pixi/app';
 * Application.registerPlugin(AppLoaderPlugin);
 * @memberof PIXI
 */
var AppLoaderPlugin = /** @class */ (function () {
    function AppLoaderPlugin() {
    }
    /**
     * Called on application constructor
     *
     * @private
     */
    AppLoaderPlugin.init = function (options) {
        options = Object.assign({
            sharedLoader: false,
        }, options);
        this.loader = options.sharedLoader ? Loader.shared : new Loader();
    };
    /**
     * Called when application destroyed
     *
     * @private
     */
    AppLoaderPlugin.destroy = function () {
        if (this.loader) {
            this.loader.destroy();
            this.loader = null;
        }
    };
    return AppLoaderPlugin;
}());

/**
 * Loader plugin for handling Texture resources.
 *
 * @memberof PIXI
 */
var TextureLoader = /** @class */ (function () {
    function TextureLoader() {
    }
    /**
     * Handle SVG elements a text, render with SVGResource.
     */
    TextureLoader.add = function () {
        LoaderResource.setExtensionLoadType('svg', LoaderResource.LOAD_TYPE.XHR);
        LoaderResource.setExtensionXhrType('svg', LoaderResource.XHR_RESPONSE_TYPE.TEXT);
    };
    /**
     * Called after a resource is loaded.
     * @see PIXI.Loader.loaderMiddleware
     * @param resource
     * @param {function} next
     */
    TextureLoader.use = function (resource, next) {
        // create a new texture if the data is an Image object
        if (resource.data && (resource.type === LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) {
            var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata;
            Texture.fromLoader(data, url, name, metadata).then(function (texture) {
                resource.texture = texture;
                next();
            })
                // TODO: handle errors in Texture.fromLoader
                // so we can pass them to the Loader
                .catch(next);
        }
        else {
            next();
        }
    };
    return TextureLoader;
}());

var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
/**
 * Encodes binary into base64.
 *
 * @function encodeBinary
 * @param {string} input - The input data to encode.
 * @returns {string} The encoded base64 string
 */
function encodeBinary(input) {
    var output = '';
    var inx = 0;
    while (inx < input.length) {
        // Fill byte buffer array
        var bytebuffer = [0, 0, 0];
        var encodedCharIndexes = [0, 0, 0, 0];
        for (var jnx = 0; jnx < bytebuffer.length; ++jnx) {
            if (inx < input.length) {
                // throw away high-order byte, as documented at:
                // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
                bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff;
            }
            else {
                bytebuffer[jnx] = 0;
            }
        }
        // Get each encoded character, 6 bits at a time
        // index 1: first 6 bits
        encodedCharIndexes[0] = bytebuffer[0] >> 2;
        // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
        encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4);
        // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
        encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
        // index 3: forth 6 bits (6 least significant bits from input byte 3)
        encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
        // Determine whether padding happened, and adjust accordingly
        var paddingBytes = inx - (input.length - 1);
        switch (paddingBytes) {
            case 2:
                // Set last 2 characters to padding char
                encodedCharIndexes[3] = 64;
                encodedCharIndexes[2] = 64;
                break;
            case 1:
                // Set last character to padding char
                encodedCharIndexes[3] = 64;
                break;
        }
        // Now we will grab each appropriate character out of our keystring
        // based on our index array and append it to the output string
        for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) {
            output += _keyStr.charAt(encodedCharIndexes[jnx]);
        }
    }
    return output;
}

var Url = self.URL || self.webkitURL;
/**
 * A middleware for transforming XHR loaded Blobs into more useful objects
 *
 * @ignore
 * @function parsing
 * @example
 * import { Loader, middleware } from 'resource-loader';
 * const loader = new Loader();
 * loader.use(middleware.parsing);
 * @param resource - Current Resource
 * @param next - Callback when complete
 */
function parsing(resource, next) {
    if (!resource.data) {
        next();
        return;
    }
    // if this was an XHR load of a blob
    if (resource.xhr && resource.xhrType === LoaderResource.XHR_RESPONSE_TYPE.BLOB) {
        // if there is no blob support we probably got a binary string back
        if (!self.Blob || typeof resource.data === 'string') {
            var type = resource.xhr.getResponseHeader('content-type');
            // this is an image, convert the binary string into a data url
            if (type && type.indexOf('image') === 0) {
                resource.data = new Image();
                resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText);
                resource.type = LoaderResource.TYPE.IMAGE;
                // wait until the image loads and then callback
                resource.data.onload = function () {
                    resource.data.onload = null;
                    next();
                };
                // next will be called on load
                return;
            }
        }
        // if content type says this is an image, then we should transform the blob into an Image object
        else if (resource.data.type.indexOf('image') === 0) {
            var src_1 = Url.createObjectURL(resource.data);
            resource.blob = resource.data;
            resource.data = new Image();
            resource.data.src = src_1;
            resource.type = LoaderResource.TYPE.IMAGE;
            // cleanup the no longer used blob after the image loads
            // TODO: Is this correct? Will the image be invalid after revoking?
            resource.data.onload = function () {
                Url.revokeObjectURL(src_1);
                resource.data.onload = null;
                next();
            };
            // next will be called on load.
            return;
        }
    }
    next();
}

// parse any blob into more usable objects (e.g. Image)
Loader.registerPlugin({ use: parsing });
// parse any Image objects into textures
Loader.registerPlugin(TextureLoader);


//# sourceMappingURL=loaders.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/compressed-textures/dist/esm/compressed-textures.js
/*!
 * @pixi/compressed-textures - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/compressed-textures is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */





var _a;
/**
 * WebGL internal formats, including compressed texture formats provided by extensions
 *
 * @memberof PIXI
 * @static
 * @name INTERNAL_FORMATS
 * @enum {number}
 * @property {number} COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0
 * @property {number} COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1
 * @property {number} COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2
 * @property {number} COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3
 * @property {number} COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917
 * @property {number} COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918
 * @property {number} COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919
 * @property {number} COMPRESSED_SRGB_S3TC_DXT1_EXT=35916
 * @property {number} COMPRESSED_R11_EAC=0x9270
 * @property {number} COMPRESSED_SIGNED_R11_EAC=0x9271
 * @property {number} COMPRESSED_RG11_EAC=0x9272
 * @property {number} COMPRESSED_SIGNED_RG11_EAC=0x9273
 * @property {number} COMPRESSED_RGB8_ETC2=0x9274
 * @property {number} COMPRESSED_RGBA8_ETC2_EAC=0x9278
 * @property {number} COMPRESSED_SRGB8_ETC2=0x9275
 * @property {number} COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279
 * @property {number} COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276
 * @property {number} COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277
 * @property {number} COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00
 * @property {number} COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02
 * @property {number} COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01
 * @property {number} COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03
 * @property {number} COMPRESSED_RGB_ETC1_WEBGL=0x8D64
 * @property {number} COMPRESSED_RGB_ATC_WEBGL=0x8C92
 * @property {number} COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92
 * @property {number} COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE
 */
var INTERNAL_FORMATS;
(function (INTERNAL_FORMATS) {
    // WEBGL_compressed_texture_s3tc
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
    // WEBGL_compressed_texture_s3tc_srgb
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
    // WEBGL_compressed_texture_etc
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
    // WEBGL_compressed_texture_pvrtc
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
    // WEBGL_compressed_texture_etc1
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
    // WEBGL_compressed_texture_atc
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL";
    INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL";
})(INTERNAL_FORMATS || (INTERNAL_FORMATS = {}));
/**
 * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by
 * each texel.
 *
 * @memberof PIXI
 * @static
 * @ignore
 */
var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a = {},
    // WEBGL_compressed_texture_s3tc
    _a[INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1,
    // WEBGL_compressed_texture_s3tc
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1,
    // WEBGL_compressed_texture_etc
    _a[INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5,
    // WEBGL_compressed_texture_pvrtc
    _a[INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25,
    // WEBGL_compressed_texture_etc1
    _a[INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5,
    // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt
    // WEBGL_compressed_texture_atc
    _a[INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1,
    _a[INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1,
    _a);

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var compressed_textures_extendStatics = function(d, b) {
    compressed_textures_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return compressed_textures_extendStatics(d, b);
};

function compressed_textures_extends(d, b) {
    compressed_textures_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

function __awaiter(thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) { throw new TypeError("Generator is already executing."); }
        while (_) { try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; }
            if (y = 0, t) { op = [op[0] & 2, t.value]; }
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) { _.ops.pop(); }
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } }
        if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true };
    }
}

/**
 * Resource that fetches texture data over the network and stores it in a buffer.
 *
 * @class
 * @extends PIXI.Resource
 * @memberof PIXI
 */
var BlobResource = /** @class */ (function (_super) {
    compressed_textures_extends(BlobResource, _super);
    /**
     * @param {string} url - the URL of the texture file
     * @param {boolean}[autoLoad] - whether to fetch the data immediately;
     *  you can fetch it later via {@link BlobResource#load}
     */
    function BlobResource(source, options) {
        if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; }
        var _this = this;
        var origin;
        var data;
        if (typeof source === 'string') {
            origin = source;
            data = new Uint8Array();
        }
        else {
            origin = null;
            data = source;
        }
        _this = _super.call(this, data, options) || this;
        /**
         * The URL of the texture file
         * @member {string}
         */
        _this.origin = origin;
        /**
         * The viewable buffer on the data
         * @member {ViewableBuffer}
         */
        // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative
        _this.buffer = data ? new ViewableBuffer(data) : null;
        // Allow autoLoad = "undefined" still load the resource by default
        if (_this.origin && options.autoLoad !== false) {
            _this.load();
        }
        if (data && data.length) {
            _this.loaded = true;
            _this.onBlobLoaded(_this.buffer.rawBinaryData);
        }
        return _this;
    }
    BlobResource.prototype.onBlobLoaded = function (_data) {
        // TODO: Override this method
    };
    /**
     * Loads the blob
     */
    BlobResource.prototype.load = function () {
        return __awaiter(this, void 0, Promise, function () {
            var response, blob, arrayBuffer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, fetch(this.origin)];
                    case 1:
                        response = _a.sent();
                        return [4 /*yield*/, response.blob()];
                    case 2:
                        blob = _a.sent();
                        return [4 /*yield*/, blob.arrayBuffer()];
                    case 3:
                        arrayBuffer = _a.sent();
                        this.data = new Uint32Array(arrayBuffer);
                        this.buffer = new ViewableBuffer(arrayBuffer);
                        this.loaded = true;
                        this.onBlobLoaded(arrayBuffer);
                        this.update();
                        return [2 /*return*/, this];
                }
            });
        });
    };
    return BlobResource;
}(BufferResource));

/**
 * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC.
 *
 * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in
 * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store
 * more detail in the same amount of memory.
 *
 * For most developers, container file formats are a better abstraction instead of directly handling raw texture
 * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}):
 *
 * * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader}
 * * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats.
 *  See {@link PIXI.KTXLoader}.
 * * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded
 *  to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed
 *  format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to
 *  use these files. See {@link PIXI.BasisLoader}.
 *
 * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that
 * they be used instead.
 *
 * ## Working directly with CompressedTextureResource
 *
 * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing
 * the raw texture data (with no file headers!):
 *
 * ```js
 * // The resource backing the texture data for your textures.
 * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file
 * //   format such as KTX, DDS, or BASIS.
 * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", {
 *   format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
 *   width: 256,
 *   height: 256
 * });
 *
 * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API.
 * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM });
 *
 * // Create a Texture to add to the TextureCache
 * const texture = new PIXI.Texture(baseTexture);
 *
 * // Add baseTexture & texture to the global texture cache
 * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5");
 * PIXI.Texture.addToCache(texture, "bunny.dxt5");
 * ```
 *
 * @memberof PIXI
 */
var CompressedTextureResource = /** @class */ (function (_super) {
    compressed_textures_extends(CompressedTextureResource, _super);
    /**
     * @param source - the buffer/URL holding the compressed texture data
     * @param options
     * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format
     * @param {number} options.width - the image width in pixels.
     * @param {number} options.height - the image height in pixels.
     * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0.
     * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you
     *      to pass `null` for `source`, for cases where each level is stored in non-contiguous memory.
     */
    function CompressedTextureResource(source, options) {
        var _this = _super.call(this, source, options) || this;
        _this.format = options.format;
        _this.levels = options.levels || 1;
        _this._width = options.width;
        _this._height = options.height;
        _this._extension = CompressedTextureResource._formatToExtension(_this.format);
        if (options.levelBuffers || _this.buffer) {
            // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array
            _this._levelBuffers = options.levelBuffers
                || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode
                _this.width, _this.height);
        }
        return _this;
    }
    /**
     * @override
     * @param renderer - A reference to the current renderer
     * @param _texture - the texture
     * @param _glTexture - texture instance for this webgl context
     */
    CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) {
        var gl = renderer.gl;
        var extension = renderer.context.extensions[this._extension];
        if (!extension) {
            throw new Error(this._extension + " textures are not supported on the current machine");
        }
        if (!this._levelBuffers) {
            // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly!
            return false;
        }
        for (var i = 0, j = this.levels; i < j; i++) {
            var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer;
            gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer);
        }
        return true;
    };
    /** @protected */
    CompressedTextureResource.prototype.onBlobLoaded = function () {
        this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode
        this.width, this.height);
    };
    /**
     * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format
     *
     * @private
     * @param format - the compression format to get the extension for.
     */
    CompressedTextureResource._formatToExtension = function (format) {
        if (format >= 0x83F0 && format <= 0x83F3) {
            return 's3tc';
        }
        else if (format >= 0x9270 && format <= 0x9279) {
            return 'etc';
        }
        else if (format >= 0x8C00 && format <= 0x8C03) {
            return 'pvrtc';
        }
        else if (format >= 0x8D64) {
            return 'etc1';
        }
        else if (format >= 0x8C92 && format <= 0x87EE) {
            return 'atc';
        }
        throw new Error('Invalid (compressed) texture format given!');
    };
    /**
     * Pre-creates buffer views for each mipmap level
     *
     * @private
     * @param buffer -
     * @param format - compression formats
     * @param levels - mipmap levels
     * @param blockWidth -
     * @param blockHeight -
     * @param imageWidth - width of the image in pixels
     * @param imageHeight - height of the image in pixels
     */
    CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) {
        // The byte-size of the first level buffer
        var buffers = new Array(levels);
        var offset = buffer.byteOffset;
        var levelWidth = imageWidth;
        var levelHeight = imageHeight;
        var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1);
        var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1);
        var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format];
        for (var i = 0; i < levels; i++) {
            buffers[i] = {
                levelID: i,
                levelWidth: levels > 1 ? levelWidth : alignedLevelWidth,
                levelHeight: levels > 1 ? levelHeight : alignedLevelHeight,
                levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize)
            };
            offset += levelSize;
            // Calculate levelBuffer dimensions for next iteration
            levelWidth = (levelWidth >> 1) || 1;
            levelHeight = (levelHeight >> 1) || 1;
            alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1);
            alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1);
            levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format];
        }
        return buffers;
    };
    return CompressedTextureResource;
}(BlobResource));

/* eslint-enable camelcase */
/**
 * Loader plugin for handling compressed textures for all platforms.
 *
 * @class
 * @memberof PIXI
 * @implements PIXI.ILoaderPlugin
 */
var CompressedTextureLoader = /** @class */ (function () {
    function CompressedTextureLoader() {
    }
    /**
     * Called after a compressed-textures manifest is loaded.
     *
     * This will then load the correct compression format for the device. Your manifest should adhere
     * to the following schema:
     *
     * ```js
     * import { INTERNAL_FORMATS } from '@pixi/constants';
     *
     * type CompressedTextureManifest = {
     *  textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>,
     *  cacheID: string;
     * };
     * ```
     *
     * This is an example of a .json manifest file
     *
     * ```json
     * {
     *   "cacheID":"asset",
     *   "textures":[
     *     { "src":"asset.fallback.png" },
     *     { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" },
     *     { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" },
     *     { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" }
     *   ]
     * }
     * ```
     */
    CompressedTextureLoader.use = function (resource, next) {
        var data = resource.data;
        var loader = this;
        if (resource.type === LoaderResource.TYPE.JSON
            && data
            && data.cacheID
            && data.textures) {
            var textures = data.textures;
            var textureURL = void 0;
            var fallbackURL = void 0;
            // Search for an extension that holds one the formats
            for (var i = 0, j = textures.length; i < j; i++) {
                var texture = textures[i];
                var url_1 = texture.src;
                var format = texture.format;
                if (!format) {
                    fallbackURL = url_1;
                }
                if (CompressedTextureLoader.textureFormats[format]) {
                    textureURL = url_1;
                    break;
                }
            }
            textureURL = textureURL || fallbackURL;
            // Make sure we have a URL
            if (!textureURL) {
                next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback"));
                return;
            }
            if (textureURL === resource.url) {
                // Prevent infinite loops
                next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL'));
                return;
            }
            var loadOptions = {
                crossOrigin: resource.crossOrigin,
                metadata: resource.metadata.imageMetadata,
                parentResource: resource
            };
            var resourcePath = utils_url.resolve(resource.url.replace(loader.baseUrl, ''), textureURL);
            var resourceName = data.cacheID;
            // The appropriate loader should register the texture
            loader.add(resourceName, resourcePath, loadOptions, function (res) {
                if (res.error) {
                    next(res.error);
                    return;
                }
                var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b;
                // Make sure texture/textures is assigned to parent resource
                Object.assign(resource, { texture: texture, textures: textures });
                // Pass along any error
                next();
            });
        }
        else {
            next();
        }
    };
    /**
     * Detects the available compressed texture extensions on the device.
     * @ignore
     */
    CompressedTextureLoader.add = function () {
        // Auto-detect WebGL compressed-texture extensions
        var canvas = document.createElement('canvas');
        var gl = canvas.getContext('webgl');
        if (!gl) {
            console.warn('WebGL not available for compressed textures. Silently failing.');
            return;
        }
        var extensions = {
            s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'),
            s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'),
            etc: gl.getExtension('WEBGL_compressed_texture_etc'),
            etc1: gl.getExtension('WEBGL_compressed_texture_etc1'),
            pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc')
                || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
            atc: gl.getExtension('WEBGL_compressed_texture_atc'),
            astc: gl.getExtension('WEBGL_compressed_texture_astc')
        };
        CompressedTextureLoader.textureExtensions = extensions;
        CompressedTextureLoader.textureFormats = {};
        // Assign all available compressed-texture formats
        for (var extensionName in extensions) {
            var extension = extensions[extensionName];
            if (!extension) {
                continue;
            }
            Object.assign(CompressedTextureLoader.textureFormats, Object.getPrototypeOf(extension));
        }
    };
    return CompressedTextureLoader;
}());

/**
 * Creates base-textures and textures for each compressed-texture resource and adds them into the global
 * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the
 * form `${url}-i`.
 *
 * @param url - the original address of the resources
 * @param resources - the resources backing texture data
 * @ignore
 */
function registerCompressedTextures(url, resources, metadata) {
    var result = {
        textures: {},
        texture: null,
    };
    if (!resources) {
        return result;
    }
    var textures = resources.map(function (resource) {
        return (new Texture(new BaseTexture(resource, Object.assign({
            mipmap: constants_MIPMAP_MODES.OFF,
            alphaMode: constants_ALPHA_MODES.NO_PREMULTIPLIED_ALPHA
        }, metadata))));
    });
    textures.forEach(function (texture, i) {
        var baseTexture = texture.baseTexture;
        var cacheID = url + "-" + (i + 1);
        BaseTexture.addToCache(baseTexture, cacheID);
        Texture.addToCache(texture, cacheID);
        if (i === 0) {
            BaseTexture.addToCache(baseTexture, url);
            Texture.addToCache(texture, url);
            result.texture = texture;
        }
        result.textures[cacheID] = texture;
    });
    return result;
}

var _a$1, _b;
// Set DDS files to be loaded as an ArrayBuffer
LoaderResource.setExtensionXhrType('dds', LoaderResource.XHR_RESPONSE_TYPE.BUFFER);
var DDS_MAGIC_SIZE = 4;
var DDS_HEADER_SIZE = 124;
var DDS_HEADER_PF_SIZE = 32;
var DDS_HEADER_DX10_SIZE = 20;
// DDS file format magic word
var DDS_MAGIC = 0x20534444;
/**
 * DWORD offsets of the DDS file header fields (relative to file start).
 *
 * @ignore
 */
var DDS_FIELDS = {
    SIZE: 1,
    FLAGS: 2,
    HEIGHT: 3,
    WIDTH: 4,
    MIPMAP_COUNT: 7,
    PIXEL_FORMAT: 19,
};
/**
 * DWORD offsets of the DDS PIXEL_FORMAT fields.
 *
 * @ignore
 */
var DDS_PF_FIELDS = {
    SIZE: 0,
    FLAGS: 1,
    FOURCC: 2,
    RGB_BITCOUNT: 3,
    R_BIT_MASK: 4,
    G_BIT_MASK: 5,
    B_BIT_MASK: 6,
    A_BIT_MASK: 7
};
/**
 * DWORD offsets of the DDS_HEADER_DX10 fields.
 *
 * @ignore
 */
var DDS_DX10_FIELDS = {
    DXGI_FORMAT: 0,
    RESOURCE_DIMENSION: 1,
    MISC_FLAG: 2,
    ARRAY_SIZE: 3,
    MISC_FLAGS2: 4
};
/**
 * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format
 * @ignore
 */
// This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining
// ones to their correct value)
var DXGI_FORMAT;
(function (DXGI_FORMAT) {
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE";
    DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT";
})(DXGI_FORMAT || (DXGI_FORMAT = {}));
/**
 * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION}
 *
 * @ignore
 */
var D3D10_RESOURCE_DIMENSION;
(function (D3D10_RESOURCE_DIMENSION) {
    D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D";
    D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D";
    D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D";
})(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {}));
var PF_FLAGS = 1;
// PIXEL_FORMAT flags
var DDPF_ALPHA = 0x2;
var DDPF_FOURCC = 0x4;
var DDPF_RGB = 0x40;
var DDPF_YUV = 0x200;
var DDPF_LUMINANCE = 0x20000;
// Four character codes for DXTn formats
var FOURCC_DXT1 = 0x31545844;
var FOURCC_DXT3 = 0x33545844;
var FOURCC_DXT5 = 0x35545844;
var FOURCC_DX10 = 0x30315844;
// Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG)
var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4;
/**
 * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}).
 *
 * @ignore
 */
var FOURCC_TO_FORMAT = (_a$1 = {},
    _a$1[FOURCC_DXT1] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
    _a$1[FOURCC_DXT3] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
    _a$1[FOURCC_DXT5] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
    _a$1);
/**
 * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS})
 *
 * @ignore
 */
var DXGI_TO_FORMAT = (_b = {},
    // WEBGL_compressed_texture_s3tc
    _b[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
    // WEBGL_compressed_texture_s3tc_srgb
    _b[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,
    _b[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT,
    _b);
/**
 * @class
 * @memberof PIXI
 * @implements PIXI.ILoaderPlugin
 * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide
 */
var DDSLoader = /** @class */ (function () {
    function DDSLoader() {
    }
    /**
     * Registers a DDS compressed texture
     * @see PIXI.Loader.loaderMiddleware
     * @param resource - loader resource that is checked to see if it is a DDS file
     * @param next - callback Function to call when done
     */
    DDSLoader.use = function (resource, next) {
        if (resource.extension === 'dds' && resource.data) {
            try {
                Object.assign(resource, registerCompressedTextures(resource.name || resource.url, DDSLoader.parse(resource.data), resource.metadata));
            }
            catch (err) {
                next(err);
                return;
            }
        }
        next();
    };
    /** Parses the DDS file header, generates base-textures, and puts them into the texture cache. */
    DDSLoader.parse = function (arrayBuffer) {
        var data = new Uint32Array(arrayBuffer);
        var magicWord = data[0];
        if (magicWord !== DDS_MAGIC) {
            throw new Error('Invalid DDS file magic word');
        }
        var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT);
        // DDS header fields
        var height = header[DDS_FIELDS.HEIGHT];
        var width = header[DDS_FIELDS.WIDTH];
        var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT];
        // PIXEL_FORMAT fields
        var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT);
        var formatFlags = pixelFormat[PF_FLAGS];
        // File contains compressed texture(s)
        if (formatFlags & DDPF_FOURCC) {
            var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC];
            // File contains one DXTn compressed texture
            if (fourCC !== FOURCC_DX10) {
                var internalFormat_1 = FOURCC_TO_FORMAT[fourCC];
                var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE;
                var texData = new Uint8Array(arrayBuffer, dataOffset_1);
                var resource = new CompressedTextureResource(texData, {
                    format: internalFormat_1,
                    width: width,
                    height: height,
                    levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us!
                });
                return [resource];
            }
            // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER
            var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE;
            var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT);
            var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT];
            var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION];
            var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG];
            var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE];
            // Map dxgiFormat to PIXI.INTERNAL_FORMATS
            var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat];
            if (internalFormat_2 === undefined) {
                throw new Error("DDSLoader cannot parse texture data with DXGI format " + dxgiFormat);
            }
            if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) {
                // FIXME: Anybody excited about cubemap compressed textures?
                throw new Error('DDSLoader does not support cubemap textures');
            }
            if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) {
                // FIXME: Anybody excited about 3D compressed textures?
                throw new Error('DDSLoader does not supported 3D texture data');
            }
            // Uint8Array buffers of image data, including all mipmap levels in each image
            var imageBuffers = new Array();
            var dataOffset = DDS_MAGIC_SIZE
                + DDS_HEADER_SIZE
                + DDS_HEADER_DX10_SIZE;
            if (arraySize === 1) {
                // No need bothering with the imageSize calculation!
                imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset));
            }
            else {
                // Calculate imageSize for each texture, and then locate each image's texture data
                var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2];
                var imageSize = 0;
                var levelWidth = width;
                var levelHeight = height;
                for (var i = 0; i < mipmapCount; i++) {
                    var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3);
                    var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3);
                    var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize;
                    imageSize += levelSize;
                    levelWidth = levelWidth >>> 1;
                    levelHeight = levelHeight >>> 1;
                }
                var imageOffset = dataOffset;
                // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^)
                for (var i = 0; i < arraySize; i++) {
                    imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize));
                    imageOffset += imageSize;
                }
            }
            // Uint8Array -> CompressedTextureResource, and we're done!
            return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, {
                format: internalFormat_2,
                width: width,
                height: height,
                levels: mipmapCount
            }); });
        }
        if (formatFlags & DDPF_RGB) {
            // FIXME: We might want to allow uncompressed *.dds files?
            throw new Error('DDSLoader does not support uncompressed texture data.');
        }
        if (formatFlags & DDPF_YUV) {
            // FIXME: Does anybody need this feature?
            throw new Error('DDSLoader does not supported YUV uncompressed texture data.');
        }
        if (formatFlags & DDPF_LUMINANCE) {
            // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort!
            throw new Error('DDSLoader does not support single-channel (lumninance) texture data!');
        }
        if (formatFlags & DDPF_ALPHA) {
            // FIXME: I'm tired! See above =)
            throw new Error('DDSLoader does not support single-channel (alpha) texture data!');
        }
        throw new Error('DDSLoader failed to load a texture file due to an unknown reason!');
    };
    return DDSLoader;
}());

var _a$2, _b$1, _c;
// Set KTX files to be loaded as an ArrayBuffer
LoaderResource.setExtensionXhrType('ktx', LoaderResource.XHR_RESPONSE_TYPE.BUFFER);
/**
 * The 12-byte KTX file identifier
 *
 * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1
 * @ignore
 */
var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A];
/**
 * The value stored in the "endianness" field.
 *
 * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2
 * @ignore
 */
var ENDIANNESS = 0x04030201;
/**
 * Byte offsets of the KTX file header fields
 *
 * @ignore
 */
var KTX_FIELDS = {
    FILE_IDENTIFIER: 0,
    ENDIANNESS: 12,
    GL_TYPE: 16,
    GL_TYPE_SIZE: 20,
    GL_FORMAT: 24,
    GL_INTERNAL_FORMAT: 28,
    GL_BASE_INTERNAL_FORMAT: 32,
    PIXEL_WIDTH: 36,
    PIXEL_HEIGHT: 40,
    PIXEL_DEPTH: 44,
    NUMBER_OF_ARRAY_ELEMENTS: 48,
    NUMBER_OF_FACES: 52,
    NUMBER_OF_MIPMAP_LEVELS: 56,
    BYTES_OF_KEY_VALUE_DATA: 60
};
/**
 * Byte size of the file header fields in {@code KTX_FIELDS}
 *
 * @ignore
 */
var FILE_HEADER_SIZE = 64;
/**
 * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields.
 *
 * @ignore
 */
var TYPES_TO_BYTES_PER_COMPONENT = (_a$2 = {},
    _a$2[constants_TYPES.UNSIGNED_BYTE] = 1,
    _a$2[constants_TYPES.UNSIGNED_SHORT] = 2,
    _a$2[constants_TYPES.INT] = 4,
    _a$2[constants_TYPES.UNSIGNED_INT] = 4,
    _a$2[constants_TYPES.FLOAT] = 4,
    _a$2[constants_TYPES.HALF_FLOAT] = 8,
    _a$2);
/**
 * Number of components in each {@link PIXI.FORMATS}
 *
 * @ignore
 */
var FORMATS_TO_COMPONENTS = (_b$1 = {},
    _b$1[constants_FORMATS.RGBA] = 4,
    _b$1[constants_FORMATS.RGB] = 3,
    _b$1[constants_FORMATS.RG] = 2,
    _b$1[constants_FORMATS.RED] = 1,
    _b$1[constants_FORMATS.LUMINANCE] = 1,
    _b$1[constants_FORMATS.LUMINANCE_ALPHA] = 2,
    _b$1[constants_FORMATS.ALPHA] = 1,
    _b$1);
/**
 * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES}
 *
 * @ignore
 */
var TYPES_TO_BYTES_PER_PIXEL = (_c = {},
    _c[constants_TYPES.UNSIGNED_SHORT_4_4_4_4] = 2,
    _c[constants_TYPES.UNSIGNED_SHORT_5_5_5_1] = 2,
    _c[constants_TYPES.UNSIGNED_SHORT_5_6_5] = 2,
    _c);
/**
 * Loader plugin for handling KTX texture container files.
 *
 * This KTX loader does not currently support the following features:
 * * cube textures
 * * 3D textures
 * * vendor-specific key/value data parsing
 * * endianness conversion for big-endian machines
 * * embedded *.basis files
 *
 * It does supports the following features:
 * * multiple textures per file
 * * mipmapping (only for compressed formats)
 *
 * @class
 * @memberof PIXI
 * @implements PIXI.ILoaderPlugin
 */
var KTXLoader = /** @class */ (function () {
    function KTXLoader() {
    }
    /**
     * Called after a KTX file is loaded.
     *
     * This will parse the KTX file header and add a {@code BaseTexture} to the texture
     * cache.
     *
     * @see PIXI.Loader.loaderMiddleware
     * @param resource - loader resource that is checked to see if it is a KTX file
     * @param next - callback Function to call when done
     */
    KTXLoader.use = function (resource, next) {
        if (resource.extension === 'ktx' && resource.data) {
            try {
                var url_1 = resource.name || resource.url;
                var _a = KTXLoader.parse(url_1, resource.data), compressed = _a.compressed, uncompressed = _a.uncompressed;
                if (compressed) {
                    Object.assign(resource, registerCompressedTextures(url_1, compressed, resource.metadata));
                }
                else if (uncompressed) {
                    var textures_1 = {};
                    uncompressed.forEach(function (image, i) {
                        var texture = new Texture(new BaseTexture(image.resource, {
                            mipmap: constants_MIPMAP_MODES.OFF,
                            alphaMode: constants_ALPHA_MODES.NO_PREMULTIPLIED_ALPHA,
                            type: image.type,
                            format: image.format,
                        }));
                        var cacheID = url_1 + "-" + (i + 1);
                        BaseTexture.addToCache(texture.baseTexture, cacheID);
                        Texture.addToCache(texture, cacheID);
                        if (i === 0) {
                            textures_1[url_1] = texture;
                            BaseTexture.addToCache(texture.baseTexture, url_1);
                            Texture.addToCache(texture, url_1);
                        }
                        textures_1[cacheID] = texture;
                    });
                    Object.assign(resource, { textures: textures_1 });
                }
            }
            catch (err) {
                next(err);
                return;
            }
        }
        next();
    };
    /** Parses the KTX file header, generates base-textures, and puts them into the texture cache. */
    KTXLoader.parse = function (url, arrayBuffer) {
        var dataView = new DataView(arrayBuffer);
        if (!KTXLoader.validate(url, dataView)) {
            return null;
        }
        var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS;
        var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian);
        // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian);
        var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian);
        var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian);
        var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian);
        var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1"
        var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^
        var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^
        var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian);
        var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian);
        var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian);
        // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the
        // file contents must be endian-converted!
        // TODO: Endianness conversion
        // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01;
        if (pixelHeight === 0 || pixelDepth !== 1) {
            throw new Error('Only 2D textures are supported');
        }
        if (numberOfFaces !== 1) {
            throw new Error('CubeTextures are not supported by KTXLoader yet!');
        }
        if (numberOfArrayElements !== 1) {
            // TODO: Support splitting array-textures into multiple BaseTextures
            throw new Error('WebGL does not support array textures');
        }
        // TODO: 8x4 blocks for 2bpp pvrtc
        var blockWidth = 4;
        var blockHeight = 4;
        var alignedWidth = (pixelWidth + 3) & ~3;
        var alignedHeight = (pixelHeight + 3) & ~3;
        var imageBuffers = new Array(numberOfArrayElements);
        var imagePixels = pixelWidth * pixelHeight;
        if (glType === 0) {
            // Align to 16 pixels (4x4 blocks)
            imagePixels = alignedWidth * alignedHeight;
        }
        var imagePixelByteSize;
        if (glType !== 0) {
            // Uncompressed texture format
            if (TYPES_TO_BYTES_PER_COMPONENT[glType]) {
                imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat];
            }
            else {
                imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType];
            }
        }
        else {
            imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat];
        }
        if (imagePixelByteSize === undefined) {
            throw new Error('Unable to resolve the pixel format stored in the *.ktx file!');
        }
        var imageByteSize = imagePixels * imagePixelByteSize;
        var mipByteSize = imageByteSize;
        var mipWidth = pixelWidth;
        var mipHeight = pixelHeight;
        var alignedMipWidth = alignedWidth;
        var alignedMipHeight = alignedHeight;
        var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData;
        for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) {
            var imageSize = dataView.getUint32(imageOffset, littleEndian);
            var elementOffset = imageOffset + 4;
            for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) {
                // TODO: Maybe support 3D textures? :-)
                // for (let zSlice = 0; zSlice < pixelDepth; zSlice)
                var mips = imageBuffers[arrayElement];
                if (!mips) {
                    mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels);
                }
                mips[mipmapLevel] = {
                    levelID: mipmapLevel,
                    // don't align mipWidth when texture not compressed! (glType not zero)
                    levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth,
                    levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight,
                    levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize)
                };
                elementOffset += mipByteSize;
            }
            // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding)
            imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself)
            imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset;
            // Calculate mipWidth, mipHeight for _next_ iteration
            mipWidth = (mipWidth >> 1) || 1;
            mipHeight = (mipHeight >> 1) || 1;
            alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1);
            alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1);
            // Each mipmap level is 4-times smaller?
            mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize;
        }
        // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major.
        if (glType !== 0) {
            return {
                uncompressed: imageBuffers.map(function (levelBuffers) {
                    var buffer = levelBuffers[0].levelBuffer;
                    var convertToInt = false;
                    if (glType === constants_TYPES.FLOAT) {
                        buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
                    }
                    else if (glType === constants_TYPES.UNSIGNED_INT) {
                        convertToInt = true;
                        buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
                    }
                    else if (glType === constants_TYPES.INT) {
                        convertToInt = true;
                        buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
                    }
                    return {
                        resource: new BufferResource(buffer, {
                            width: levelBuffers[0].levelWidth,
                            height: levelBuffers[0].levelHeight,
                        }),
                        type: glType,
                        format: convertToInt ? KTXLoader.convertFormatToInteger(glFormat) : glFormat,
                    };
                })
            };
        }
        return {
            compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, {
                format: glInternalFormat,
                width: pixelWidth,
                height: pixelHeight,
                levels: numberOfMipmapLevels,
                levelBuffers: levelBuffers,
            }); })
        };
    };
    /** Checks whether the arrayBuffer contains a valid *.ktx file. */
    KTXLoader.validate = function (url, dataView) {
        // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness
        // of the data is not specified.
        for (var i = 0; i < FILE_IDENTIFIER.length; i++) {
            if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) {
                console.error(url + " is not a valid *.ktx file!");
                return false;
            }
        }
        return true;
    };
    KTXLoader.convertFormatToInteger = function (format) {
        switch (format) {
            case constants_FORMATS.RGBA: return constants_FORMATS.RGBA_INTEGER;
            case constants_FORMATS.RGB: return constants_FORMATS.RGB_INTEGER;
            case constants_FORMATS.RG: return constants_FORMATS.RG_INTEGER;
            case constants_FORMATS.RED: return constants_FORMATS.RED_INTEGER;
            default: return format;
        }
    };
    return KTXLoader;
}());


//# sourceMappingURL=compressed-textures.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/particle-container/dist/esm/particle-container.js
/*!
 * @pixi/particle-container - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/particle-container is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */






/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var particle_container_extendStatics = function(d, b) {
    particle_container_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return particle_container_extendStatics(d, b);
};

function particle_container_extends(d, b) {
    particle_container_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * The ParticleContainer class is a really fast version of the Container built solely for speed,
 * so use when you need a lot of sprites or particles.
 *
 * The tradeoff of the ParticleContainer is that most advanced functionality will not work.
 * ParticleContainer implements the basic object transform (position, scale, rotation)
 * and some advanced functionality like tint (as of v4.5.6).
 *
 * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch.
 *
 * It's extremely easy to use:
 * ```js
 * let container = new ParticleContainer();
 *
 * for (let i = 0; i < 100; ++i)
 * {
 *     let sprite = PIXI.Sprite.from("myImage.png");
 *     container.addChild(sprite);
 * }
 * ```
 *
 * And here you have a hundred sprites that will be rendered at the speed of light.
 *
 * @memberof PIXI
 */
var ParticleContainer = /** @class */ (function (_super) {
    particle_container_extends(ParticleContainer, _super);
    /**
     * @param maxSize - The maximum number of particles that can be rendered by the container.
     *  Affects size of allocated buffers.
     * @param properties - The properties of children that should be uploaded to the gpu and applied.
     * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied.
     *                  if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`.
     * @param {boolean} [properties.position=true] - When true, position be uploaded and applied.
     * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied.
     * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied.
     * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied.
     * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead.
     * @param {boolean} [autoResize=false] - If true, container allocates more batches in case
     *  there are more than `maxSize` particles.
     */
    function ParticleContainer(maxSize, properties, batchSize, autoResize) {
        if (maxSize === void 0) { maxSize = 1500; }
        if (batchSize === void 0) { batchSize = 16384; }
        if (autoResize === void 0) { autoResize = false; }
        var _this = _super.call(this) || this;
        // Making sure the batch size is valid
        // 65535 is max vertex index in the index buffer (see ParticleRenderer)
        // so max number of particles is 65536 / 4 = 16384
        var maxBatchSize = 16384;
        if (batchSize > maxBatchSize) {
            batchSize = maxBatchSize;
        }
        _this._properties = [false, true, false, false, false];
        _this._maxSize = maxSize;
        _this._batchSize = batchSize;
        _this._buffers = null;
        _this._bufferUpdateIDs = [];
        _this._updateID = 0;
        _this.interactiveChildren = false;
        _this.blendMode = constants_BLEND_MODES.NORMAL;
        _this.autoResize = autoResize;
        _this.roundPixels = true;
        _this.baseTexture = null;
        _this.setProperties(properties);
        _this._tint = 0;
        _this.tintRgb = new Float32Array(4);
        _this.tint = 0xFFFFFF;
        return _this;
    }
    /**
     * Sets the private properties array to dynamic / static based on the passed properties object
     *
     * @param properties - The properties to be uploaded
     */
    ParticleContainer.prototype.setProperties = function (properties) {
        if (properties) {
            this._properties[0] = 'vertices' in properties || 'scale' in properties
                ? !!properties.vertices || !!properties.scale : this._properties[0];
            this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1];
            this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2];
            this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3];
            this._properties[4] = 'tint' in properties || 'alpha' in properties
                ? !!properties.tint || !!properties.alpha : this._properties[4];
        }
    };
    ParticleContainer.prototype.updateTransform = function () {
        // TODO don't need to!
        this.displayObjectUpdateTransform();
    };
    Object.defineProperty(ParticleContainer.prototype, "tint", {
        /**
         * The tint applied to the container. This is a hex value.
         * A value of 0xFFFFFF will remove any tint effect.
         * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer.
         *
         * @default 0xFFFFFF
         */
        get: function () {
            return this._tint;
        },
        set: function (value) {
            this._tint = value;
            hex2rgb(value, this.tintRgb);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Renders the container using the WebGL renderer.
     *
     * @param renderer - The WebGL renderer.
     */
    ParticleContainer.prototype.render = function (renderer) {
        var _this = this;
        if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) {
            return;
        }
        if (!this.baseTexture) {
            this.baseTexture = this.children[0]._texture.baseTexture;
            if (!this.baseTexture.valid) {
                this.baseTexture.once('update', function () { return _this.onChildrenChange(0); });
            }
        }
        renderer.batch.setObjectRenderer(renderer.plugins.particle);
        renderer.plugins.particle.render(this);
    };
    /**
     * Set the flag that static data should be updated to true
     *
     * @param smallestChildIndex - The smallest child index.
     */
    ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) {
        var bufferIndex = Math.floor(smallestChildIndex / this._batchSize);
        while (this._bufferUpdateIDs.length < bufferIndex) {
            this._bufferUpdateIDs.push(0);
        }
        this._bufferUpdateIDs[bufferIndex] = ++this._updateID;
    };
    ParticleContainer.prototype.dispose = function () {
        if (this._buffers) {
            for (var i = 0; i < this._buffers.length; ++i) {
                this._buffers[i].destroy();
            }
            this._buffers = null;
        }
    };
    /**
     * Destroys the container
     *
     * @param options - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their
     *  destroy method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
     *  Should it destroy the texture of the child sprite
     * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
     *  Should it destroy the base texture of the child sprite
     */
    ParticleContainer.prototype.destroy = function (options) {
        _super.prototype.destroy.call(this, options);
        this.dispose();
        this._properties = null;
        this._buffers = null;
        this._bufferUpdateIDs = null;
    };
    return ParticleContainer;
}(Container));

/*
 * @author Mat Groves
 *
 * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
 * for creating the original PixiJS version!
 * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that
 * they now share 4 bytes on the vertex buffer
 *
 * Heavily inspired by LibGDX's ParticleBuffer:
 * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java
 */
/**
 * The particle buffer manages the static and dynamic buffers for a particle container.
 *
 * @private
 * @memberof PIXI
 */
var ParticleBuffer = /** @class */ (function () {
    /**
     * @param {object} properties - The properties to upload.
     * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic.
     * @param {number} size - The size of the batch.
     */
    function ParticleBuffer(properties, dynamicPropertyFlags, size) {
        this.geometry = new Geometry();
        this.indexBuffer = null;
        this.size = size;
        this.dynamicProperties = [];
        this.staticProperties = [];
        for (var i = 0; i < properties.length; ++i) {
            var property = properties[i];
            // Make copy of properties object so that when we edit the offset it doesn't
            // change all other instances of the object literal
            property = {
                attributeName: property.attributeName,
                size: property.size,
                uploadFunction: property.uploadFunction,
                type: property.type || constants_TYPES.FLOAT,
                offset: property.offset,
            };
            if (dynamicPropertyFlags[i]) {
                this.dynamicProperties.push(property);
            }
            else {
                this.staticProperties.push(property);
            }
        }
        this.staticStride = 0;
        this.staticBuffer = null;
        this.staticData = null;
        this.staticDataUint32 = null;
        this.dynamicStride = 0;
        this.dynamicBuffer = null;
        this.dynamicData = null;
        this.dynamicDataUint32 = null;
        this._updateID = 0;
        this.initBuffers();
    }
    /** Sets up the renderer context and necessary buffers. */
    ParticleBuffer.prototype.initBuffers = function () {
        var geometry = this.geometry;
        var dynamicOffset = 0;
        this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true);
        geometry.addIndex(this.indexBuffer);
        this.dynamicStride = 0;
        for (var i = 0; i < this.dynamicProperties.length; ++i) {
            var property = this.dynamicProperties[i];
            property.offset = dynamicOffset;
            dynamicOffset += property.size;
            this.dynamicStride += property.size;
        }
        var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4);
        this.dynamicData = new Float32Array(dynBuffer);
        this.dynamicDataUint32 = new Uint32Array(dynBuffer);
        this.dynamicBuffer = new Buffer(this.dynamicData, false, false);
        // static //
        var staticOffset = 0;
        this.staticStride = 0;
        for (var i = 0; i < this.staticProperties.length; ++i) {
            var property = this.staticProperties[i];
            property.offset = staticOffset;
            staticOffset += property.size;
            this.staticStride += property.size;
        }
        var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4);
        this.staticData = new Float32Array(statBuffer);
        this.staticDataUint32 = new Uint32Array(statBuffer);
        this.staticBuffer = new Buffer(this.staticData, true, false);
        for (var i = 0; i < this.dynamicProperties.length; ++i) {
            var property = this.dynamicProperties[i];
            geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === constants_TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4);
        }
        for (var i = 0; i < this.staticProperties.length; ++i) {
            var property = this.staticProperties[i];
            geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === constants_TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4);
        }
    };
    /**
     * Uploads the dynamic properties.
     *
     * @param children - The children to upload.
     * @param startIndex - The index to start at.
     * @param amount - The number to upload.
     */
    ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) {
        for (var i = 0; i < this.dynamicProperties.length; i++) {
            var property = this.dynamicProperties[i];
            property.uploadFunction(children, startIndex, amount, property.type === constants_TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset);
        }
        this.dynamicBuffer._updateID++;
    };
    /**
     * Uploads the static properties.
     *
     * @param children - The children to upload.
     * @param startIndex - The index to start at.
     * @param amount - The number to upload.
     */
    ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) {
        for (var i = 0; i < this.staticProperties.length; i++) {
            var property = this.staticProperties[i];
            property.uploadFunction(children, startIndex, amount, property.type === constants_TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset);
        }
        this.staticBuffer._updateID++;
    };
    /** Destroys the ParticleBuffer. */
    ParticleBuffer.prototype.destroy = function () {
        this.indexBuffer = null;
        this.dynamicProperties = null;
        this.dynamicBuffer = null;
        this.dynamicData = null;
        this.dynamicDataUint32 = null;
        this.staticProperties = null;
        this.staticBuffer = null;
        this.staticData = null;
        this.staticDataUint32 = null;
        // all buffers are destroyed inside geometry
        this.geometry.destroy();
    };
    return ParticleBuffer;
}());

var particle_container_fragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n    vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n    gl_FragColor = color;\n}";

var particle_container_vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n    float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n    float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n    vec2 v = vec2(x, y);\n    v = v + aPositionCoord;\n\n    gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = aTextureCoord;\n    vColor = aColor * uColor;\n}\n";

/*
 * @author Mat Groves
 *
 * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
 * for creating the original PixiJS version!
 * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now
 * share 4 bytes on the vertex buffer
 *
 * Heavily inspired by LibGDX's ParticleRenderer:
 * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java
 */
/**
 * Renderer for Particles that is designer for speed over feature set.
 *
 * @memberof PIXI
 */
var ParticleRenderer = /** @class */ (function (_super) {
    particle_container_extends(ParticleRenderer, _super);
    /**
     * @param renderer - The renderer this sprite batch works for.
     */
    function ParticleRenderer(renderer) {
        var _this = _super.call(this, renderer) || this;
        // 65535 is max vertex index in the index buffer (see ParticleRenderer)
        // so max number of particles is 65536 / 4 = 16384
        // and max number of element in the index buffer is 16384 * 6 = 98304
        // Creating a full index buffer, overhead is 98304 * 2 = 196Ko
        // let numIndices = 98304;
        _this.shader = null;
        _this.properties = null;
        _this.tempMatrix = new Matrix();
        _this.properties = [
            // verticesData
            {
                attributeName: 'aVertexPosition',
                size: 2,
                uploadFunction: _this.uploadVertices,
                offset: 0,
            },
            // positionData
            {
                attributeName: 'aPositionCoord',
                size: 2,
                uploadFunction: _this.uploadPosition,
                offset: 0,
            },
            // rotationData
            {
                attributeName: 'aRotation',
                size: 1,
                uploadFunction: _this.uploadRotation,
                offset: 0,
            },
            // uvsData
            {
                attributeName: 'aTextureCoord',
                size: 2,
                uploadFunction: _this.uploadUvs,
                offset: 0,
            },
            // tintData
            {
                attributeName: 'aColor',
                size: 1,
                type: constants_TYPES.UNSIGNED_BYTE,
                uploadFunction: _this.uploadTint,
                offset: 0,
            } ];
        _this.shader = Shader.from(particle_container_vertex, particle_container_fragment, {});
        _this.state = State.for2d();
        return _this;
    }
    /**
     * Renders the particle container object.
     *
     * @param container - The container to render using this ParticleRenderer.
     */
    ParticleRenderer.prototype.render = function (container) {
        var children = container.children;
        var maxSize = container._maxSize;
        var batchSize = container._batchSize;
        var renderer = this.renderer;
        var totalChildren = children.length;
        if (totalChildren === 0) {
            return;
        }
        else if (totalChildren > maxSize && !container.autoResize) {
            totalChildren = maxSize;
        }
        var buffers = container._buffers;
        if (!buffers) {
            buffers = container._buffers = this.generateBuffers(container);
        }
        var baseTexture = children[0]._texture.baseTexture;
        // if the uvs have not updated then no point rendering just yet!
        this.state.blendMode = correctBlendMode(container.blendMode, baseTexture.alphaMode);
        renderer.state.set(this.state);
        var gl = renderer.gl;
        var m = container.worldTransform.copyTo(this.tempMatrix);
        m.prepend(renderer.globalUniforms.uniforms.projectionMatrix);
        this.shader.uniforms.translationMatrix = m.toArray(true);
        this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.alphaMode);
        this.shader.uniforms.uSampler = baseTexture;
        this.renderer.shader.bind(this.shader);
        var updateStatic = false;
        // now lets upload and render the buffers..
        for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) {
            var amount = (totalChildren - i);
            if (amount > batchSize) {
                amount = batchSize;
            }
            if (j >= buffers.length) {
                buffers.push(this._generateOneMoreBuffer(container));
            }
            var buffer = buffers[j];
            // we always upload the dynamic
            buffer.uploadDynamic(children, i, amount);
            var bid = container._bufferUpdateIDs[j] || 0;
            updateStatic = updateStatic || (buffer._updateID < bid);
            // we only upload the static content when we have to!
            if (updateStatic) {
                buffer._updateID = container._updateID;
                buffer.uploadStatic(children, i, amount);
            }
            // bind the buffer
            renderer.geometry.bind(buffer.geometry);
            gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0);
        }
    };
    /**
     * Creates one particle buffer for each child in the container we want to render and updates internal properties.
     *
     * @param container - The container to render using this ParticleRenderer
     * @return - The buffers
     */
    ParticleRenderer.prototype.generateBuffers = function (container) {
        var buffers = [];
        var size = container._maxSize;
        var batchSize = container._batchSize;
        var dynamicPropertyFlags = container._properties;
        for (var i = 0; i < size; i += batchSize) {
            buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize));
        }
        return buffers;
    };
    /**
     * Creates one more particle buffer, because container has autoResize feature.
     *
     * @param container - The container to render using this ParticleRenderer
     * @return - The generated buffer
     */
    ParticleRenderer.prototype._generateOneMoreBuffer = function (container) {
        var batchSize = container._batchSize;
        var dynamicPropertyFlags = container._properties;
        return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize);
    };
    /**
     * Uploads the vertices.
     *
     * @param children - the array of display objects to render
     * @param startIndex - the index to start from in the children array
     * @param amount - the amount of children that will have their vertices uploaded
     * @param array - The vertices to upload.
     * @param stride - Stride to use for iteration.
     * @param offset - Offset to start at.
     */
    ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) {
        var w0 = 0;
        var w1 = 0;
        var h0 = 0;
        var h1 = 0;
        for (var i = 0; i < amount; ++i) {
            var sprite = children[startIndex + i];
            var texture = sprite._texture;
            var sx = sprite.scale.x;
            var sy = sprite.scale.y;
            var trim = texture.trim;
            var orig = texture.orig;
            if (trim) {
                // if the sprite is trimmed and is not a tilingsprite then we need to add the
                // extra space before transforming the sprite coords..
                w1 = trim.x - (sprite.anchor.x * orig.width);
                w0 = w1 + trim.width;
                h1 = trim.y - (sprite.anchor.y * orig.height);
                h0 = h1 + trim.height;
            }
            else {
                w0 = (orig.width) * (1 - sprite.anchor.x);
                w1 = (orig.width) * -sprite.anchor.x;
                h0 = orig.height * (1 - sprite.anchor.y);
                h1 = orig.height * -sprite.anchor.y;
            }
            array[offset] = w1 * sx;
            array[offset + 1] = h1 * sy;
            array[offset + stride] = w0 * sx;
            array[offset + stride + 1] = h1 * sy;
            array[offset + (stride * 2)] = w0 * sx;
            array[offset + (stride * 2) + 1] = h0 * sy;
            array[offset + (stride * 3)] = w1 * sx;
            array[offset + (stride * 3) + 1] = h0 * sy;
            offset += stride * 4;
        }
    };
    /**
     * Uploads the position.
     *
     * @param children - the array of display objects to render
     * @param startIndex - the index to start from in the children array
     * @param amount - the amount of children that will have their positions uploaded
     * @param array - The vertices to upload.
     * @param stride - Stride to use for iteration.
     * @param offset - Offset to start at.
     */
    ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) {
        for (var i = 0; i < amount; i++) {
            var spritePosition = children[startIndex + i].position;
            array[offset] = spritePosition.x;
            array[offset + 1] = spritePosition.y;
            array[offset + stride] = spritePosition.x;
            array[offset + stride + 1] = spritePosition.y;
            array[offset + (stride * 2)] = spritePosition.x;
            array[offset + (stride * 2) + 1] = spritePosition.y;
            array[offset + (stride * 3)] = spritePosition.x;
            array[offset + (stride * 3) + 1] = spritePosition.y;
            offset += stride * 4;
        }
    };
    /**
     * Uploads the rotation.
     *
     * @param children - the array of display objects to render
     * @param startIndex - the index to start from in the children array
     * @param amount - the amount of children that will have their rotation uploaded
     * @param array - The vertices to upload.
     * @param stride - Stride to use for iteration.
     * @param offset - Offset to start at.
     */
    ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) {
        for (var i = 0; i < amount; i++) {
            var spriteRotation = children[startIndex + i].rotation;
            array[offset] = spriteRotation;
            array[offset + stride] = spriteRotation;
            array[offset + (stride * 2)] = spriteRotation;
            array[offset + (stride * 3)] = spriteRotation;
            offset += stride * 4;
        }
    };
    /**
     * Uploads the UVs.
     *
     * @param children - the array of display objects to render
     * @param startIndex - the index to start from in the children array
     * @param amount - the amount of children that will have their rotation uploaded
     * @param array - The vertices to upload.
     * @param stride - Stride to use for iteration.
     * @param offset - Offset to start at.
     */
    ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) {
        for (var i = 0; i < amount; ++i) {
            var textureUvs = children[startIndex + i]._texture._uvs;
            if (textureUvs) {
                array[offset] = textureUvs.x0;
                array[offset + 1] = textureUvs.y0;
                array[offset + stride] = textureUvs.x1;
                array[offset + stride + 1] = textureUvs.y1;
                array[offset + (stride * 2)] = textureUvs.x2;
                array[offset + (stride * 2) + 1] = textureUvs.y2;
                array[offset + (stride * 3)] = textureUvs.x3;
                array[offset + (stride * 3) + 1] = textureUvs.y3;
                offset += stride * 4;
            }
            else {
                // TODO you know this can be easier!
                array[offset] = 0;
                array[offset + 1] = 0;
                array[offset + stride] = 0;
                array[offset + stride + 1] = 0;
                array[offset + (stride * 2)] = 0;
                array[offset + (stride * 2) + 1] = 0;
                array[offset + (stride * 3)] = 0;
                array[offset + (stride * 3) + 1] = 0;
                offset += stride * 4;
            }
        }
    };
    /**
     * Uploads the tint.
     *
     * @param children - the array of display objects to render
     * @param startIndex - the index to start from in the children array
     * @param amount - the amount of children that will have their rotation uploaded
     * @param array - The vertices to upload.
     * @param stride - Stride to use for iteration.
     * @param offset - Offset to start at.
     */
    ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) {
        for (var i = 0; i < amount; ++i) {
            var sprite = children[startIndex + i];
            var premultiplied = sprite._texture.baseTexture.alphaMode > 0;
            var alpha = sprite.alpha;
            // we dont call extra function if alpha is 1.0, that's faster
            var argb = alpha < 1.0 && premultiplied
                ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24);
            array[offset] = argb;
            array[offset + stride] = argb;
            array[offset + (stride * 2)] = argb;
            array[offset + (stride * 3)] = argb;
            offset += stride * 4;
        }
    };
    /** Destroys the ParticleRenderer. */
    ParticleRenderer.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        if (this.shader) {
            this.shader.destroy();
            this.shader = null;
        }
        this.tempMatrix = null;
    };
    return ParticleRenderer;
}(ObjectRenderer));


//# sourceMappingURL=particle-container.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/graphics/dist/esm/graphics.js
/*!
 * @pixi/graphics - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/graphics is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */






/**
 * Supported line joints in `PIXI.LineStyle` for graphics.
 *
 * @see PIXI.Graphics#lineStyle
 * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator
 *
 * @name LINE_JOIN
 * @memberof PIXI
 * @static
 * @enum {string}
 * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet
 * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn
 * @property {string} ROUND - 'round': add an arc at the joint
 */
var LINE_JOIN;
(function (LINE_JOIN) {
    LINE_JOIN["MITER"] = "miter";
    LINE_JOIN["BEVEL"] = "bevel";
    LINE_JOIN["ROUND"] = "round";
})(LINE_JOIN || (LINE_JOIN = {}));
/**
 * Support line caps in `PIXI.LineStyle` for graphics.
 *
 * @see PIXI.Graphics#lineStyle
 *
 * @name LINE_CAP
 * @memberof PIXI
 * @static
 * @enum {string}
 * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges)
 * @property {string} ROUND - 'round': add semicircle at ends
 * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end)
 */
var LINE_CAP;
(function (LINE_CAP) {
    LINE_CAP["BUTT"] = "butt";
    LINE_CAP["ROUND"] = "round";
    LINE_CAP["SQUARE"] = "square";
})(LINE_CAP || (LINE_CAP = {}));
/**
 * Graphics curves resolution settings. If `adaptive` flag is set to `true`,
 * the resolution is calculated based on the curve's length to ensure better visual quality.
 * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name GRAPHICS_CURVES
 * @type {object}
 * @property {boolean} adaptive=true - flag indicating if the resolution should be adaptive
 * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored)
 * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored)
 * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored)
 */
var GRAPHICS_CURVES = {
    adaptive: true,
    maxLength: 10,
    minSegments: 8,
    maxSegments: 2048,
    epsilon: 0.0001,
    _segmentsCount: function (length, defaultSegments) {
        if (defaultSegments === void 0) { defaultSegments = 20; }
        if (!this.adaptive || !length || isNaN(length)) {
            return defaultSegments;
        }
        var result = Math.ceil(length / this.maxLength);
        if (result < this.minSegments) {
            result = this.minSegments;
        }
        else if (result > this.maxSegments) {
            result = this.maxSegments;
        }
        return result;
    },
};

/**
 * Fill style object for Graphics.
 *
 * @memberof PIXI
 */
var FillStyle = /** @class */ (function () {
    function FillStyle() {
        /**
         * The hex color value used when coloring the Graphics object.
         *
         * @default 0xFFFFFF
         */
        this.color = 0xFFFFFF;
        /** The alpha value used when filling the Graphics object. */
        this.alpha = 1.0;
        /**
         * The texture to be used for the fill.
         *
         * @default 0
         */
        this.texture = Texture.WHITE;
        /**
         * The transform applied to the texture.
         *
         * @default null
         */
        this.matrix = null;
        /** If the current fill is visible. */
        this.visible = false;
        this.reset();
    }
    /** Clones the object */
    FillStyle.prototype.clone = function () {
        var obj = new FillStyle();
        obj.color = this.color;
        obj.alpha = this.alpha;
        obj.texture = this.texture;
        obj.matrix = this.matrix;
        obj.visible = this.visible;
        return obj;
    };
    /** Reset */
    FillStyle.prototype.reset = function () {
        this.color = 0xFFFFFF;
        this.alpha = 1;
        this.texture = Texture.WHITE;
        this.matrix = null;
        this.visible = false;
    };
    /** Destroy and don't use after this. */
    FillStyle.prototype.destroy = function () {
        this.texture = null;
        this.matrix = null;
    };
    return FillStyle;
}());

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var graphics_extendStatics = function(d, b) {
    graphics_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return graphics_extendStatics(d, b);
};

function graphics_extends(d, b) {
    graphics_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

function fixOrientation(points, hole) {
    var _a, _b;
    if (hole === void 0) { hole = false; }
    var m = points.length;
    if (m < 6) {
        return;
    }
    var area = 0;
    for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) {
        var x2 = points[i];
        var y2 = points[i + 1];
        area += (x2 - x1) * (y2 + y1);
        x1 = x2;
        y1 = y2;
    }
    if ((!hole && area > 0) || (hole && area <= 0)) {
        var n = m / 2;
        for (var i = n + (n % 2); i < m; i += 2) {
            var i1 = m - i - 2;
            var i2 = m - i - 1;
            var i3 = i;
            var i4 = i + 1;
            _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1];
            _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1];
        }
    }
}
/**
 * Builds a polygon to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
 * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
 */
var buildPoly = {
    build: function (graphicsData) {
        graphicsData.points = graphicsData.shape.points.slice();
    },
    triangulate: function (graphicsData, graphicsGeometry) {
        var points = graphicsData.points;
        var holes = graphicsData.holes;
        var verts = graphicsGeometry.points;
        var indices = graphicsGeometry.indices;
        if (points.length >= 6) {
            fixOrientation(points, false);
            var holeArray = [];
            // Process holes..
            for (var i = 0; i < holes.length; i++) {
                var hole = holes[i];
                fixOrientation(hole.points, true);
                holeArray.push(points.length / 2);
                points = points.concat(hole.points);
            }
            // sort color
            var triangles = earcut_default()(points, holeArray, 2);
            if (!triangles) {
                return;
            }
            var vertPos = verts.length / 2;
            for (var i = 0; i < triangles.length; i += 3) {
                indices.push(triangles[i] + vertPos);
                indices.push(triangles[i + 1] + vertPos);
                indices.push(triangles[i + 2] + vertPos);
            }
            for (var i = 0; i < points.length; i++) {
                verts.push(points[i]);
            }
        }
    },
};

// for type only
/**
 * Builds a circle to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw
 * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
 * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
 */
var buildCircle = {
    build: function (graphicsData) {
        // need to convert points to a nice regular data
        var points = graphicsData.points;
        var x;
        var y;
        var dx;
        var dy;
        var rx;
        var ry;
        if (graphicsData.type === SHAPES.CIRC) {
            var circle = graphicsData.shape;
            x = circle.x;
            y = circle.y;
            rx = ry = circle.radius;
            dx = dy = 0;
        }
        else if (graphicsData.type === SHAPES.ELIP) {
            var ellipse = graphicsData.shape;
            x = ellipse.x;
            y = ellipse.y;
            rx = ellipse.width;
            ry = ellipse.height;
            dx = dy = 0;
        }
        else {
            var roundedRect = graphicsData.shape;
            var halfWidth = roundedRect.width / 2;
            var halfHeight = roundedRect.height / 2;
            x = roundedRect.x + halfWidth;
            y = roundedRect.y + halfHeight;
            rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight)));
            dx = halfWidth - rx;
            dy = halfHeight - ry;
        }
        // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029
        var n = Math.ceil(2.3 * Math.sqrt(rx + ry));
        var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0);
        points.length = m;
        if (m === 0) {
            return;
        }
        if (n === 0) {
            points.length = 8;
            points[0] = points[6] = x + dx;
            points[1] = points[3] = y + dy;
            points[2] = points[4] = x - dx;
            points[5] = points[7] = y - dy;
            return;
        }
        var j1 = 0;
        var j2 = (n * 4) + (dx ? 2 : 0) + 2;
        var j3 = j2;
        var j4 = m;
        {
            var x0 = dx + rx;
            var y0 = dy;
            var x1 = x + x0;
            var x2 = x - x0;
            var y1 = y + y0;
            points[j1++] = x1;
            points[j1++] = y1;
            points[--j2] = y1;
            points[--j2] = x2;
            if (dy) {
                var y2 = y - y0;
                points[j3++] = x2;
                points[j3++] = y2;
                points[--j4] = y2;
                points[--j4] = x1;
            }
        }
        for (var i = 1; i < n; i++) {
            var a = Math.PI / 2 * (i / n);
            var x0 = dx + (Math.cos(a) * rx);
            var y0 = dy + (Math.sin(a) * ry);
            var x1 = x + x0;
            var x2 = x - x0;
            var y1 = y + y0;
            var y2 = y - y0;
            points[j1++] = x1;
            points[j1++] = y1;
            points[--j2] = y1;
            points[--j2] = x2;
            points[j3++] = x2;
            points[j3++] = y2;
            points[--j4] = y2;
            points[--j4] = x1;
        }
        {
            var x0 = dx;
            var y0 = dy + ry;
            var x1 = x + x0;
            var x2 = x - x0;
            var y1 = y + y0;
            var y2 = y - y0;
            points[j1++] = x1;
            points[j1++] = y1;
            points[--j4] = y2;
            points[--j4] = x1;
            if (dx) {
                points[j1++] = x2;
                points[j1++] = y1;
                points[--j4] = y2;
                points[--j4] = x2;
            }
        }
    },
    triangulate: function (graphicsData, graphicsGeometry) {
        var points = graphicsData.points;
        var verts = graphicsGeometry.points;
        var indices = graphicsGeometry.indices;
        var vertPos = verts.length / 2;
        var center = vertPos;
        var x;
        var y;
        if (graphicsData.type !== SHAPES.RREC) {
            var circle = graphicsData.shape;
            x = circle.x;
            y = circle.y;
        }
        else {
            var roundedRect = graphicsData.shape;
            x = roundedRect.x + (roundedRect.width / 2);
            y = roundedRect.y + (roundedRect.height / 2);
        }
        var matrix = graphicsData.matrix;
        // Push center (special point)
        verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y);
        vertPos++;
        verts.push(points[0], points[1]);
        for (var i = 2; i < points.length; i += 2) {
            verts.push(points[i], points[i + 1]);
            // add some uvs
            indices.push(vertPos++, center, vertPos);
        }
        indices.push(center + 1, center, vertPos);
    },
};

/**
 * Builds a rectangle to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
 * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
 */
var buildRectangle = {
    build: function (graphicsData) {
        // --- //
        // need to convert points to a nice regular data
        //
        var rectData = graphicsData.shape;
        var x = rectData.x;
        var y = rectData.y;
        var width = rectData.width;
        var height = rectData.height;
        var points = graphicsData.points;
        points.length = 0;
        points.push(x, y, x + width, y, x + width, y + height, x, y + height);
    },
    triangulate: function (graphicsData, graphicsGeometry) {
        var points = graphicsData.points;
        var verts = graphicsGeometry.points;
        var vertPos = verts.length / 2;
        verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]);
        graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3);
    },
};

/**
 * Calculate a single point for a quadratic bezier curve.
 * Utility function used by quadraticBezierCurve.
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {number} n1 - first number
 * @param {number} n2 - second number
 * @param {number} perc - percentage
 * @return {number} the result
 *
 */
function getPt(n1, n2, perc) {
    var diff = n2 - n1;
    return n1 + (diff * perc);
}
/**
 * Calculate the points for a quadratic bezier curve. (helper function..)
 * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {number} fromX - Origin point x
 * @param {number} fromY - Origin point x
 * @param {number} cpX - Control point x
 * @param {number} cpY - Control point y
 * @param {number} toX - Destination point x
 * @param {number} toY - Destination point y
 * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created.
 * @return {number[]} an array of points
 */
function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) {
    if (out === void 0) { out = []; }
    var n = 20;
    var points = out;
    var xa = 0;
    var ya = 0;
    var xb = 0;
    var yb = 0;
    var x = 0;
    var y = 0;
    for (var i = 0, j = 0; i <= n; ++i) {
        j = i / n;
        // The Green Line
        xa = getPt(fromX, cpX, j);
        ya = getPt(fromY, cpY, j);
        xb = getPt(cpX, toX, j);
        yb = getPt(cpY, toY, j);
        // The Black Dot
        x = getPt(xa, xb, j);
        y = getPt(ya, yb, j);
        // Handle case when first curve points overlaps and earcut fails to triangulate
        if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) {
            continue;
        }
        points.push(x, y);
    }
    return points;
}
/**
 * Builds a rounded rectangle to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
 * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
 */
var buildRoundedRectangle = {
    build: function (graphicsData) {
        if (Graphics.nextRoundedRectBehavior) {
            buildCircle.build(graphicsData);
            return;
        }
        var rrectData = graphicsData.shape;
        var points = graphicsData.points;
        var x = rrectData.x;
        var y = rrectData.y;
        var width = rrectData.width;
        var height = rrectData.height;
        // Don't allow negative radius or greater than half the smallest width
        var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2));
        points.length = 0;
        // No radius, do a simple rectangle
        if (!radius) {
            points.push(x, y, x + width, y, x + width, y + height, x, y + height);
        }
        else {
            quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points);
            quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points);
            quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points);
            quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points);
        }
    },
    triangulate: function (graphicsData, graphicsGeometry) {
        if (Graphics.nextRoundedRectBehavior) {
            buildCircle.triangulate(graphicsData, graphicsGeometry);
            return;
        }
        var points = graphicsData.points;
        var verts = graphicsGeometry.points;
        var indices = graphicsGeometry.indices;
        var vecPos = verts.length / 2;
        var triangles = earcut_default()(points, null, 2);
        for (var i = 0, j = triangles.length; i < j; i += 3) {
            indices.push(triangles[i] + vecPos);
            //     indices.push(triangles[i] + vecPos);
            indices.push(triangles[i + 1] + vecPos);
            //   indices.push(triangles[i + 2] + vecPos);
            indices.push(triangles[i + 2] + vecPos);
        }
        for (var i = 0, j = points.length; i < j; i++) {
            verts.push(points[i], points[++i]);
        }
    },
};

/**
 * Buffers vertices to draw a square cap.
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {number} x - X-coord of end point
 * @param {number} y - Y-coord of end point
 * @param {number} nx - X-coord of line normal pointing inside
 * @param {number} ny - Y-coord of line normal pointing inside
 * @param {Array<number>} verts - vertex buffer
 * @returns {}
 */
function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) {
    var ix = x - (nx * innerWeight);
    var iy = y - (ny * innerWeight);
    var ox = x + (nx * outerWeight);
    var oy = y + (ny * outerWeight);
    /* Rotate nx,ny for extension vector */
    var exx;
    var eyy;
    if (clockwise) {
        exx = ny;
        eyy = -nx;
    }
    else {
        exx = -ny;
        eyy = nx;
    }
    /* [i|0]x,y extended at cap */
    var eix = ix + exx;
    var eiy = iy + eyy;
    var eox = ox + exx;
    var eoy = oy + eyy;
    /* Square itself must be inserted clockwise*/
    verts.push(eix, eiy);
    verts.push(eox, eoy);
    return 2;
}
/**
 * Buffers vertices to draw an arc at the line joint or cap.
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {number} cx - X-coord of center
 * @param {number} cy - Y-coord of center
 * @param {number} sx - X-coord of arc start
 * @param {number} sy - Y-coord of arc start
 * @param {number} ex - X-coord of arc end
 * @param {number} ey - Y-coord of arc end
 * @param {Array<number>} verts - buffer of vertices
 * @param {boolean} clockwise - orientation of vertices
 * @returns {number} - no. of vertices pushed
 */
function round(cx, cy, sx, sy, ex, ey, verts, clockwise) {
    var cx2p0x = sx - cx;
    var cy2p0y = sy - cy;
    var angle0 = Math.atan2(cx2p0x, cy2p0y);
    var angle1 = Math.atan2(ex - cx, ey - cy);
    if (clockwise && angle0 < angle1) {
        angle0 += Math.PI * 2;
    }
    else if (!clockwise && angle0 > angle1) {
        angle1 += Math.PI * 2;
    }
    var startAngle = angle0;
    var angleDiff = angle1 - angle0;
    var absAngleDiff = Math.abs(angleDiff);
    /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND)
    {
        const r1x = cx - nxtPx;
        const r1y = cy - nxtPy;

        if (r1x === 0)
        {
            if (r1y > 0)
            {
                angleDiff = -angleDiff;
            }
        }
        else if (r1x >= -GRAPHICS_CURVES.epsilon)
        {
            angleDiff = -angleDiff;
        }
    }*/
    var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y));
    var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1;
    var angleInc = angleDiff / segCount;
    startAngle += angleInc;
    if (clockwise) {
        verts.push(cx, cy);
        verts.push(sx, sy);
        for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) {
            verts.push(cx, cy);
            verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius)));
        }
        verts.push(cx, cy);
        verts.push(ex, ey);
    }
    else {
        verts.push(sx, sy);
        verts.push(cx, cy);
        for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) {
            verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius)));
            verts.push(cx, cy);
        }
        verts.push(ex, ey);
        verts.push(cx, cy);
    }
    return segCount * 2;
}
/**
 * Builds a line to draw using the polygon method.
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
 */
function buildNonNativeLine(graphicsData, graphicsGeometry) {
    var shape = graphicsData.shape;
    var points = graphicsData.points || shape.points.slice();
    var eps = graphicsGeometry.closePointEps;
    if (points.length === 0) {
        return;
    }
    // if the line width is an odd number add 0.5 to align to a whole pixel
    // commenting this out fixes #711 and #1620
    // if (graphicsData.lineWidth%2)
    // {
    //     for (i = 0; i < points.length; i++)
    //     {
    //         points[i] += 0.5;
    //     }
    // }
    var style = graphicsData.lineStyle;
    // get first and last point.. figure out the middle!
    var firstPoint = new Point(points[0], points[1]);
    var lastPoint = new Point(points[points.length - 2], points[points.length - 1]);
    var closedShape = shape.type !== SHAPES.POLY || shape.closeStroke;
    var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps
        && Math.abs(firstPoint.y - lastPoint.y) < eps;
    // if the first point is the last point - gonna have issues :)
    if (closedShape) {
        // need to clone as we are going to slightly modify the shape..
        points = points.slice();
        if (closedPath) {
            points.pop();
            points.pop();
            lastPoint.set(points[points.length - 2], points[points.length - 1]);
        }
        var midPointX = (firstPoint.x + lastPoint.x) * 0.5;
        var midPointY = (lastPoint.y + firstPoint.y) * 0.5;
        points.unshift(midPointX, midPointY);
        points.push(midPointX, midPointY);
    }
    var verts = graphicsGeometry.points;
    var length = points.length / 2;
    var indexCount = points.length;
    var indexStart = verts.length / 2;
    // Max. inner and outer width
    var width = style.width / 2;
    var widthSquared = width * width;
    var miterLimitSquared = style.miterLimit * style.miterLimit;
    /* Line segments of interest where (x1,y1) forms the corner. */
    var x0 = points[0];
    var y0 = points[1];
    var x1 = points[2];
    var y1 = points[3];
    var x2 = 0;
    var y2 = 0;
    /* perp[?](x|y) = the line normal with magnitude lineWidth. */
    var perpx = -(y0 - y1);
    var perpy = x0 - x1;
    var perp1x = 0;
    var perp1y = 0;
    var dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
    perpx /= dist;
    perpy /= dist;
    perpx *= width;
    perpy *= width;
    var ratio = style.alignment; // 0.5;
    var innerWeight = (1 - ratio) * 2;
    var outerWeight = ratio * 2;
    if (!closedShape) {
        if (style.cap === LINE_CAP.ROUND) {
            indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2;
        }
        else if (style.cap === LINE_CAP.SQUARE) {
            indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts);
        }
    }
    // Push first point (below & above vertices)
    verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight));
    verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight));
    for (var i = 1; i < length - 1; ++i) {
        x0 = points[(i - 1) * 2];
        y0 = points[((i - 1) * 2) + 1];
        x1 = points[i * 2];
        y1 = points[(i * 2) + 1];
        x2 = points[(i + 1) * 2];
        y2 = points[((i + 1) * 2) + 1];
        perpx = -(y0 - y1);
        perpy = x0 - x1;
        dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
        perpx /= dist;
        perpy /= dist;
        perpx *= width;
        perpy *= width;
        perp1x = -(y1 - y2);
        perp1y = x1 - x2;
        dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y));
        perp1x /= dist;
        perp1y /= dist;
        perp1x *= width;
        perp1y *= width;
        /* d[x|y](0|1) = the component displacement between points p(0,1|1,2) */
        var dx0 = x1 - x0;
        var dy0 = y0 - y1;
        var dx1 = x1 - x2;
        var dy1 = y2 - y1;
        /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */
        var cross = (dy0 * dx1) - (dy1 * dx0);
        var clockwise = (cross < 0);
        /* Going nearly straight? */
        if (Math.abs(cross) < 0.1) {
            verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight));
            verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight));
            continue;
        }
        /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */
        var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0));
        var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2));
        var px = ((dx0 * c2) - (dx1 * c1)) / cross;
        var py = ((dy1 * c1) - (dy0 * c2)) / cross;
        var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1));
        /* Inner miter point */
        var imx = x1 + ((px - x1) * innerWeight);
        var imy = y1 + ((py - y1) * innerWeight);
        /* Outer miter point */
        var omx = x1 - ((px - x1) * outerWeight);
        var omy = y1 - ((py - y1) * outerWeight);
        /* Is the inside miter point too far away, creating a spike? */
        var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1));
        var insideWeight = clockwise ? innerWeight : outerWeight;
        var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared);
        var insideMiterOk = pdist <= smallerInsideDiagonalSq;
        if (insideMiterOk) {
            if (style.join === LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) {
                if (clockwise) /* rotating at inner angle */ {
                    verts.push(imx, imy); // inner miter point
                    verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex
                    verts.push(imx, imy); // inner miter point
                    verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex
                }
                else /* rotating at outer angle */ {
                    verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex
                    verts.push(omx, omy); // outer miter point
                    verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex
                    verts.push(omx, omy); // outer miter point
                }
                indexCount += 2;
            }
            else if (style.join === LINE_JOIN.ROUND) {
                if (clockwise) /* arc is outside */ {
                    verts.push(imx, imy);
                    verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight));
                    indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4;
                    verts.push(imx, imy);
                    verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight));
                }
                else /* arc is inside */ {
                    verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight));
                    verts.push(omx, omy);
                    indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4;
                    verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight));
                    verts.push(omx, omy);
                }
            }
            else {
                verts.push(imx, imy);
                verts.push(omx, omy);
            }
        }
        else // inside miter is NOT ok
         {
            verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex
            verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex
            if (style.join === LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) ;
            else if (style.join === LINE_JOIN.ROUND) {
                if (clockwise) /* arc is outside */ {
                    indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2;
                }
                else /* arc is inside */ {
                    indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2;
                }
            }
            else {
                if (clockwise) {
                    verts.push(omx, omy); // inner miter point
                    verts.push(omx, omy); // inner miter point
                }
                else {
                    verts.push(imx, imy); // outer miter point
                    verts.push(imx, imy); // outer miter point
                }
                indexCount += 2;
            }
            verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex
            verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex
            indexCount += 2;
        }
    }
    x0 = points[(length - 2) * 2];
    y0 = points[((length - 2) * 2) + 1];
    x1 = points[(length - 1) * 2];
    y1 = points[((length - 1) * 2) + 1];
    perpx = -(y0 - y1);
    perpy = x0 - x1;
    dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
    perpx /= dist;
    perpy /= dist;
    perpx *= width;
    perpy *= width;
    verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight));
    verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight));
    if (!closedShape) {
        if (style.cap === LINE_CAP.ROUND) {
            indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2;
        }
        else if (style.cap === LINE_CAP.SQUARE) {
            indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts);
        }
    }
    var indices = graphicsGeometry.indices;
    var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon;
    // indices.push(indexStart);
    for (var i = indexStart; i < indexCount + indexStart - 2; ++i) {
        x0 = verts[(i * 2)];
        y0 = verts[(i * 2) + 1];
        x1 = verts[(i + 1) * 2];
        y1 = verts[((i + 1) * 2) + 1];
        x2 = verts[(i + 2) * 2];
        y2 = verts[((i + 2) * 2) + 1];
        /* Skip zero area triangles */
        if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) {
            continue;
        }
        indices.push(i, i + 1, i + 2);
    }
}
/**
 * Builds a line to draw using the gl.drawArrays(gl.LINES) method
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
 */
function buildNativeLine(graphicsData, graphicsGeometry) {
    var i = 0;
    var shape = graphicsData.shape;
    var points = graphicsData.points || shape.points;
    var closedShape = shape.type !== SHAPES.POLY || shape.closeStroke;
    if (points.length === 0)
        { return; }
    var verts = graphicsGeometry.points;
    var indices = graphicsGeometry.indices;
    var length = points.length / 2;
    var startIndex = verts.length / 2;
    var currentIndex = startIndex;
    verts.push(points[0], points[1]);
    for (i = 1; i < length; i++) {
        verts.push(points[i * 2], points[(i * 2) + 1]);
        indices.push(currentIndex, currentIndex + 1);
        currentIndex++;
    }
    if (closedShape) {
        indices.push(currentIndex, startIndex);
    }
}
/**
 * Builds a line to draw
 *
 * Ignored from docs since it is not directly exposed.
 *
 * @ignore
 * @private
 * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
 * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
 */
function buildLine(graphicsData, graphicsGeometry) {
    if (graphicsData.lineStyle.native) {
        buildNativeLine(graphicsData, graphicsGeometry);
    }
    else {
        buildNonNativeLine(graphicsData, graphicsGeometry);
    }
}

/**
 * Utilities for arc curves.
 *
 * @private
 */
var ArcUtils = /** @class */ (function () {
    function ArcUtils() {
    }
    /**
     * The arcTo() method creates an arc/curve between two tangents on the canvas.
     *
     * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
     *
     * @private
     * @param x1 - The x-coordinate of the beginning of the arc
     * @param y1 - The y-coordinate of the beginning of the arc
     * @param x2 - The x-coordinate of the end of the arc
     * @param y2 - The y-coordinate of the end of the arc
     * @param radius - The radius of the arc
     * @return - If the arc length is valid, return center of circle, radius and other info otherwise `null`.
     */
    ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) {
        var fromX = points[points.length - 2];
        var fromY = points[points.length - 1];
        var a1 = fromY - y1;
        var b1 = fromX - x1;
        var a2 = y2 - y1;
        var b2 = x2 - x1;
        var mm = Math.abs((a1 * b2) - (b1 * a2));
        if (mm < 1.0e-8 || radius === 0) {
            if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) {
                points.push(x1, y1);
            }
            return null;
        }
        var dd = (a1 * a1) + (b1 * b1);
        var cc = (a2 * a2) + (b2 * b2);
        var tt = (a1 * a2) + (b1 * b2);
        var k1 = radius * Math.sqrt(dd) / mm;
        var k2 = radius * Math.sqrt(cc) / mm;
        var j1 = k1 * tt / dd;
        var j2 = k2 * tt / cc;
        var cx = (k1 * b2) + (k2 * b1);
        var cy = (k1 * a2) + (k2 * a1);
        var px = b1 * (k2 + j1);
        var py = a1 * (k2 + j1);
        var qx = b2 * (k1 + j2);
        var qy = a2 * (k1 + j2);
        var startAngle = Math.atan2(py - cy, px - cx);
        var endAngle = Math.atan2(qy - cy, qx - cx);
        return {
            cx: (cx + x1),
            cy: (cy + y1),
            radius: radius,
            startAngle: startAngle,
            endAngle: endAngle,
            anticlockwise: (b1 * a2 > b2 * a1),
        };
    };
    /* eslint-disable max-len */
    /**
     * The arc method creates an arc/curve (used to create circles, or parts of circles).
     *
     * @private
     * @param startX - Start x location of arc
     * @param startY - Start y location of arc
     * @param cx - The x-coordinate of the center of the circle
     * @param cy - The y-coordinate of the center of the circle
     * @param radius - The radius of the circle
     * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position
     *  of the arc's circle)
     * @param endAngle - The ending angle, in radians
     * @param anticlockwise - Specifies whether the drawing should be
     *  counter-clockwise or clockwise. False is default, and indicates clockwise, while true
     *  indicates counter-clockwise.
     * @param points - Collection of points to add to
     */
    ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) {
        var sweep = endAngle - startAngle;
        var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40);
        var theta = (sweep) / (n * 2);
        var theta2 = theta * 2;
        var cTheta = Math.cos(theta);
        var sTheta = Math.sin(theta);
        var segMinus = n - 1;
        var remainder = (segMinus % 1) / segMinus;
        for (var i = 0; i <= segMinus; ++i) {
            var real = i + (remainder * i);
            var angle = ((theta) + startAngle + (theta2 * real));
            var c = Math.cos(angle);
            var s = -Math.sin(angle);
            points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy);
        }
    };
    return ArcUtils;
}());

/**
 * Utilities for bezier curves
 *
 * @private
 */
var BezierUtils = /** @class */ (function () {
    function BezierUtils() {
    }
    /**
     * Calculate length of bezier curve.
     * Analytical solution is impossible, since it involves an integral that does not integrate in general.
     * Therefore numerical solution is used.
     *
     * @private
     * @param fromX - Starting point x
     * @param fromY - Starting point y
     * @param cpX - Control point x
     * @param cpY - Control point y
     * @param cpX2 - Second Control point x
     * @param cpY2 - Second Control point y
     * @param toX - Destination point x
     * @param toY - Destination point y
     * @return - Length of bezier curve
     */
    BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) {
        var n = 10;
        var result = 0.0;
        var t = 0.0;
        var t2 = 0.0;
        var t3 = 0.0;
        var nt = 0.0;
        var nt2 = 0.0;
        var nt3 = 0.0;
        var x = 0.0;
        var y = 0.0;
        var dx = 0.0;
        var dy = 0.0;
        var prevX = fromX;
        var prevY = fromY;
        for (var i = 1; i <= n; ++i) {
            t = i / n;
            t2 = t * t;
            t3 = t2 * t;
            nt = (1.0 - t);
            nt2 = nt * nt;
            nt3 = nt2 * nt;
            x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX);
            y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY);
            dx = prevX - x;
            dy = prevY - y;
            prevX = x;
            prevY = y;
            result += Math.sqrt((dx * dx) + (dy * dy));
        }
        return result;
    };
    /**
     * Calculate the points for a bezier curve and then draws it.
     *
     * Ignored from docs since it is not directly exposed.
     *
     * @ignore
     * @param cpX - Control point x
     * @param cpY - Control point y
     * @param cpX2 - Second Control point x
     * @param cpY2 - Second Control point y
     * @param toX - Destination point x
     * @param toY - Destination point y
     * @param points - Path array to push points into
     */
    BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) {
        var fromX = points[points.length - 2];
        var fromY = points[points.length - 1];
        points.length -= 2;
        var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY));
        var dt = 0;
        var dt2 = 0;
        var dt3 = 0;
        var t2 = 0;
        var t3 = 0;
        points.push(fromX, fromY);
        for (var i = 1, j = 0; i <= n; ++i) {
            j = i / n;
            dt = (1 - j);
            dt2 = dt * dt;
            dt3 = dt2 * dt;
            t2 = j * j;
            t3 = t2 * j;
            points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY));
        }
    };
    return BezierUtils;
}());

/**
 * Utilities for quadratic curves.
 *
 * @private
 */
var QuadraticUtils = /** @class */ (function () {
    function QuadraticUtils() {
    }
    /**
     * Calculate length of quadratic curve
     * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/}
     * for the detailed explanation of math behind this.
     *
     * @private
     * @param fromX - x-coordinate of curve start point
     * @param fromY - y-coordinate of curve start point
     * @param cpX - x-coordinate of curve control point
     * @param cpY - y-coordinate of curve control point
     * @param toX - x-coordinate of curve end point
     * @param toY - y-coordinate of curve end point
     * @return - Length of quadratic curve
     */
    QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) {
        var ax = fromX - (2.0 * cpX) + toX;
        var ay = fromY - (2.0 * cpY) + toY;
        var bx = (2.0 * cpX) - (2.0 * fromX);
        var by = (2.0 * cpY) - (2.0 * fromY);
        var a = 4.0 * ((ax * ax) + (ay * ay));
        var b = 4.0 * ((ax * bx) + (ay * by));
        var c = (bx * bx) + (by * by);
        var s = 2.0 * Math.sqrt(a + b + c);
        var a2 = Math.sqrt(a);
        var a32 = 2.0 * a * a2;
        var c2 = 2.0 * Math.sqrt(c);
        var ba = b / a2;
        return ((a32 * s)
            + (a2 * b * (s - c2))
            + (((4.0 * c * a) - (b * b))
                * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32);
    };
    /**
     * Calculate the points for a quadratic bezier curve and then draws it.
     * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
     *
     * @private
     * @param cpX - Control point x
     * @param cpY - Control point y
     * @param toX - Destination point x
     * @param toY - Destination point y
     * @param points - Points to add segments to.
     */
    QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) {
        var fromX = points[points.length - 2];
        var fromY = points[points.length - 1];
        var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY));
        var xa = 0;
        var ya = 0;
        for (var i = 1; i <= n; ++i) {
            var j = i / n;
            xa = fromX + ((cpX - fromX) * j);
            ya = fromY + ((cpY - fromY) * j);
            points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j));
        }
    };
    return QuadraticUtils;
}());

/**
 * A structure to hold interim batch objects for Graphics.
 *
 * @memberof PIXI.graphicsUtils
 */
var BatchPart = /** @class */ (function () {
    function BatchPart() {
        this.reset();
    }
    /** Begin batch part. */
    BatchPart.prototype.begin = function (style, startIndex, attribStart) {
        this.reset();
        this.style = style;
        this.start = startIndex;
        this.attribStart = attribStart;
    };
    /** End batch part. */
    BatchPart.prototype.end = function (endIndex, endAttrib) {
        this.attribSize = endAttrib - this.attribStart;
        this.size = endIndex - this.start;
    };
    BatchPart.prototype.reset = function () {
        this.style = null;
        this.size = 0;
        this.start = 0;
        this.attribStart = 0;
        this.attribSize = 0;
    };
    return BatchPart;
}());

/**
 * Generalized convenience utilities for Graphics.
 *
 * @namespace graphicsUtils
 * @memberof PIXI
 */
var graphics_a;
/**
 * Map of fill commands for each shape type.
 *
 * @memberof PIXI.graphicsUtils
 * @member {Object} FILL_COMMANDS
 */
var FILL_COMMANDS = (graphics_a = {},
    graphics_a[SHAPES.POLY] = buildPoly,
    graphics_a[SHAPES.CIRC] = buildCircle,
    graphics_a[SHAPES.ELIP] = buildCircle,
    graphics_a[SHAPES.RECT] = buildRectangle,
    graphics_a[SHAPES.RREC] = buildRoundedRectangle,
    graphics_a);
/**
 * Batch pool, stores unused batches for preventing allocations.
 *
 * @memberof PIXI.graphicsUtils
 * @member {Array<PIXI.graphicsUtils.BatchPart>} BATCH_POOL
 */
var BATCH_POOL = [];
/**
 * Draw call pool, stores unused draw calls for preventing allocations.
 *
 * @memberof PIXI.graphicsUtils
 * @member {Array<PIXI.BatchDrawCall>} DRAW_CALL_POOL
 */
var DRAW_CALL_POOL = [];

/**
 * A class to contain data useful for Graphics objects
 *
 * @memberof PIXI
 */
var GraphicsData = /** @class */ (function () {
    /**
     * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
     * @param fillStyle - the width of the line to draw
     * @param lineStyle - the color of the line to draw
     * @param matrix - Transform matrix
     */
    function GraphicsData(shape, fillStyle, lineStyle, matrix) {
        if (fillStyle === void 0) { fillStyle = null; }
        if (lineStyle === void 0) { lineStyle = null; }
        if (matrix === void 0) { matrix = null; }
        /** The collection of points. */
        this.points = [];
        /** The collection of holes. */
        this.holes = [];
        this.shape = shape;
        this.lineStyle = lineStyle;
        this.fillStyle = fillStyle;
        this.matrix = matrix;
        this.type = shape.type;
    }
    /**
     * Creates a new GraphicsData object with the same values as this one.
     *
     * @return - Cloned GraphicsData object
     */
    GraphicsData.prototype.clone = function () {
        return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix);
    };
    /** Destroys the Graphics data. */
    GraphicsData.prototype.destroy = function () {
        this.shape = null;
        this.holes.length = 0;
        this.holes = null;
        this.points.length = 0;
        this.points = null;
        this.lineStyle = null;
        this.fillStyle = null;
    };
    return GraphicsData;
}());

var tmpPoint = new Point();
var tmpBounds = new Bounds();
/**
 * The Graphics class contains methods used to draw primitive shapes such as lines, circles and
 * rectangles to the display, and to color and fill them.
 *
 * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive
 * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster.
 *
 * @memberof PIXI
 */
var GraphicsGeometry = /** @class */ (function (_super) {
    graphics_extends(GraphicsGeometry, _super);
    // eslint-disable-next-line @typescript-eslint/no-useless-constructor
    function GraphicsGeometry() {
        var _this = _super.call(this) || this;
        /**
         * Minimal distance between points that are considered different.
         * Affects line tesselation.
         */
        _this.closePointEps = 1e-4;
        /** Padding to add to the bounds. */
        _this.boundsPadding = 0;
        _this.uvsFloat32 = null;
        _this.indicesUint16 = null;
        _this.batchable = false;
        /** An array of points to draw, 2 numbers per point */
        _this.points = [];
        /** The collection of colors */
        _this.colors = [];
        /** The UVs collection */
        _this.uvs = [];
        /** The indices of the vertices */
        _this.indices = [];
        /** Reference to the texture IDs. */
        _this.textureIds = [];
        /**
         * The collection of drawn shapes.
         *
         * @member {PIXI.GraphicsData[]}
         */
        _this.graphicsData = [];
        /**
         * List of current draw calls drived from the batches.
         *
         * @member {PIXI.BatchDrawCall[]}
         */
        _this.drawCalls = [];
        /** Batches need to regenerated if the geometry is updated. */
        _this.batchDirty = -1;
        /**
         * Intermediate abstract format sent to batch system.
         * Can be converted to drawCalls or to batchable objects.
         *
         * @member {PIXI.graphicsUtils.BatchPart[]}
         */
        _this.batches = [];
        /** Used to detect if the graphics object has changed. */
        _this.dirty = 0;
        /** Used to check if the cache is dirty. */
        _this.cacheDirty = -1;
        /** Used to detect if we cleared the graphicsData. */
        _this.clearDirty = 0;
        /** Index of the last batched shape in the stack of calls. */
        _this.shapeIndex = 0;
        /** Cached bounds. */
        _this._bounds = new Bounds();
        /** The bounds dirty flag. */
        _this.boundsDirty = -1;
        return _this;
    }
    Object.defineProperty(GraphicsGeometry.prototype, "bounds", {
        /**
         * Get the current bounds of the graphic geometry.
         *
         * @readonly
         */
        get: function () {
            if (this.boundsDirty !== this.dirty) {
                this.boundsDirty = this.dirty;
                this.calculateBounds();
            }
            return this._bounds;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Call if you changed graphicsData manually.
     * Empties all batch buffers.
     */
    GraphicsGeometry.prototype.invalidate = function () {
        this.boundsDirty = -1;
        this.dirty++;
        this.batchDirty++;
        this.shapeIndex = 0;
        this.points.length = 0;
        this.colors.length = 0;
        this.uvs.length = 0;
        this.indices.length = 0;
        this.textureIds.length = 0;
        for (var i = 0; i < this.drawCalls.length; i++) {
            this.drawCalls[i].texArray.clear();
            DRAW_CALL_POOL.push(this.drawCalls[i]);
        }
        this.drawCalls.length = 0;
        for (var i = 0; i < this.batches.length; i++) {
            var batchPart = this.batches[i];
            batchPart.reset();
            BATCH_POOL.push(batchPart);
        }
        this.batches.length = 0;
    };
    /**
     * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
     *
     * @return - This GraphicsGeometry object. Good for chaining method calls
     */
    GraphicsGeometry.prototype.clear = function () {
        if (this.graphicsData.length > 0) {
            this.invalidate();
            this.clearDirty++;
            this.graphicsData.length = 0;
        }
        return this;
    };
    /**
     * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
     *
     * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
     * @param fillStyle - Defines style of the fill.
     * @param lineStyle - Defines style of the lines.
     * @param matrix - Transform applied to the points of the shape.
     * @return - Returns geometry for chaining.
     */
    GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) {
        if (fillStyle === void 0) { fillStyle = null; }
        if (lineStyle === void 0) { lineStyle = null; }
        if (matrix === void 0) { matrix = null; }
        var data = new GraphicsData(shape, fillStyle, lineStyle, matrix);
        this.graphicsData.push(data);
        this.dirty++;
        return this;
    };
    /**
     * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
     *
     * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
     * @param matrix - Transform applied to the points of the shape.
     * @return - Returns geometry for chaining.
     */
    GraphicsGeometry.prototype.drawHole = function (shape, matrix) {
        if (matrix === void 0) { matrix = null; }
        if (!this.graphicsData.length) {
            return null;
        }
        var data = new GraphicsData(shape, null, null, matrix);
        var lastShape = this.graphicsData[this.graphicsData.length - 1];
        data.lineStyle = lastShape.lineStyle;
        lastShape.holes.push(data);
        this.dirty++;
        return this;
    };
    /** Destroys the GraphicsGeometry object. */
    GraphicsGeometry.prototype.destroy = function () {
        _super.prototype.destroy.call(this);
        // destroy each of the GraphicsData objects
        for (var i = 0; i < this.graphicsData.length; ++i) {
            this.graphicsData[i].destroy();
        }
        this.points.length = 0;
        this.points = null;
        this.colors.length = 0;
        this.colors = null;
        this.uvs.length = 0;
        this.uvs = null;
        this.indices.length = 0;
        this.indices = null;
        this.indexBuffer.destroy();
        this.indexBuffer = null;
        this.graphicsData.length = 0;
        this.graphicsData = null;
        this.drawCalls.length = 0;
        this.drawCalls = null;
        this.batches.length = 0;
        this.batches = null;
        this._bounds = null;
    };
    /**
     * Check to see if a point is contained within this geometry.
     *
     * @param point - Point to check if it's contained.
     * @return {Boolean} `true` if the point is contained within geometry.
     */
    GraphicsGeometry.prototype.containsPoint = function (point) {
        var graphicsData = this.graphicsData;
        for (var i = 0; i < graphicsData.length; ++i) {
            var data = graphicsData[i];
            if (!data.fillStyle.visible) {
                continue;
            }
            // only deal with fills..
            if (data.shape) {
                if (data.matrix) {
                    data.matrix.applyInverse(point, tmpPoint);
                }
                else {
                    tmpPoint.copyFrom(point);
                }
                if (data.shape.contains(tmpPoint.x, tmpPoint.y)) {
                    var hitHole = false;
                    if (data.holes) {
                        for (var i_1 = 0; i_1 < data.holes.length; i_1++) {
                            var hole = data.holes[i_1];
                            if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) {
                                hitHole = true;
                                break;
                            }
                        }
                    }
                    if (!hitHole) {
                        return true;
                    }
                }
            }
        }
        return false;
    };
    /**
     * Generates intermediate batch data. Either gets converted to drawCalls
     * or used to convert to batch objects directly by the Graphics object.
     *
     * @param allow32Indices - Allow using 32-bit indices for preventing artifacts when more that 65535 vertices
     */
    GraphicsGeometry.prototype.updateBatches = function (allow32Indices) {
        if (!this.graphicsData.length) {
            this.batchable = true;
            return;
        }
        if (!this.validateBatching()) {
            return;
        }
        this.cacheDirty = this.dirty;
        var uvs = this.uvs;
        var graphicsData = this.graphicsData;
        var batchPart = null;
        var currentStyle = null;
        if (this.batches.length > 0) {
            batchPart = this.batches[this.batches.length - 1];
            currentStyle = batchPart.style;
        }
        for (var i = this.shapeIndex; i < graphicsData.length; i++) {
            this.shapeIndex++;
            var data = graphicsData[i];
            var fillStyle = data.fillStyle;
            var lineStyle = data.lineStyle;
            var command = FILL_COMMANDS[data.type];
            // build out the shapes points..
            command.build(data);
            if (data.matrix) {
                this.transformPoints(data.points, data.matrix);
            }
            if (fillStyle.visible || lineStyle.visible) {
                this.processHoles(data.holes);
            }
            for (var j = 0; j < 2; j++) {
                var style = (j === 0) ? fillStyle : lineStyle;
                if (!style.visible)
                    { continue; }
                var nextTexture = style.texture.baseTexture;
                var index_1 = this.indices.length;
                var attribIndex = this.points.length / 2;
                nextTexture.wrapMode = constants_WRAP_MODES.REPEAT;
                if (j === 0) {
                    this.processFill(data);
                }
                else {
                    this.processLine(data);
                }
                var size = (this.points.length / 2) - attribIndex;
                if (size === 0)
                    { continue; }
                // close batch if style is different
                if (batchPart && !this._compareStyles(currentStyle, style)) {
                    batchPart.end(index_1, attribIndex);
                    batchPart = null;
                }
                // spawn new batch if its first batch or previous was closed
                if (!batchPart) {
                    batchPart = BATCH_POOL.pop() || new BatchPart();
                    batchPart.begin(style, index_1, attribIndex);
                    this.batches.push(batchPart);
                    currentStyle = style;
                }
                this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix);
            }
        }
        var index = this.indices.length;
        var attrib = this.points.length / 2;
        if (batchPart) {
            batchPart.end(index, attrib);
        }
        if (this.batches.length === 0) {
            // there are no visible styles in GraphicsData
            // its possible that someone wants Graphics just for the bounds
            this.batchable = true;
            return;
        }
        // prevent allocation when length is same as buffer
        if (this.indicesUint16 && this.indices.length === this.indicesUint16.length) {
            this.indicesUint16.set(this.indices);
        }
        else {
            var need32 = attrib > 0xffff && allow32Indices;
            this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices);
        }
        // TODO make this a const..
        this.batchable = this.isBatchable();
        if (this.batchable) {
            this.packBatches();
        }
        else {
            this.buildDrawCalls();
        }
    };
    /**
     * Affinity check
     *
     * @param styleA
     * @param styleB
     */
    GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) {
        if (!styleA || !styleB) {
            return false;
        }
        if (styleA.texture.baseTexture !== styleB.texture.baseTexture) {
            return false;
        }
        if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) {
            return false;
        }
        if (!!styleA.native !== !!styleB.native) {
            return false;
        }
        return true;
    };
    /** Test geometry for batching process. */
    GraphicsGeometry.prototype.validateBatching = function () {
        if (this.dirty === this.cacheDirty || !this.graphicsData.length) {
            return false;
        }
        for (var i = 0, l = this.graphicsData.length; i < l; i++) {
            var data = this.graphicsData[i];
            var fill = data.fillStyle;
            var line = data.lineStyle;
            if (fill && !fill.texture.baseTexture.valid)
                { return false; }
            if (line && !line.texture.baseTexture.valid)
                { return false; }
        }
        return true;
    };
    /** Offset the indices so that it works with the batcher. */
    GraphicsGeometry.prototype.packBatches = function () {
        this.batchDirty++;
        this.uvsFloat32 = new Float32Array(this.uvs);
        var batches = this.batches;
        for (var i = 0, l = batches.length; i < l; i++) {
            var batch = batches[i];
            for (var j = 0; j < batch.size; j++) {
                var index = batch.start + j;
                this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart;
            }
        }
    };
    /**
     * Checks to see if this graphics geometry can be batched.
     * Currently it needs to be small enough and not contain any native lines.
     */
    GraphicsGeometry.prototype.isBatchable = function () {
        // prevent heavy mesh batching
        if (this.points.length > 0xffff * 2) {
            return false;
        }
        var batches = this.batches;
        for (var i = 0; i < batches.length; i++) {
            if (batches[i].style.native) {
                return false;
            }
        }
        return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2);
    };
    /** Converts intermediate batches data to drawCalls. */
    GraphicsGeometry.prototype.buildDrawCalls = function () {
        var TICK = ++BaseTexture._globalBatch;
        for (var i = 0; i < this.drawCalls.length; i++) {
            this.drawCalls[i].texArray.clear();
            DRAW_CALL_POOL.push(this.drawCalls[i]);
        }
        this.drawCalls.length = 0;
        var colors = this.colors;
        var textureIds = this.textureIds;
        var currentGroup = DRAW_CALL_POOL.pop();
        if (!currentGroup) {
            currentGroup = new BatchDrawCall();
            currentGroup.texArray = new BatchTextureArray();
        }
        currentGroup.texArray.count = 0;
        currentGroup.start = 0;
        currentGroup.size = 0;
        currentGroup.type = constants_DRAW_MODES.TRIANGLES;
        var textureCount = 0;
        var currentTexture = null;
        var textureId = 0;
        var native = false;
        var drawMode = constants_DRAW_MODES.TRIANGLES;
        var index = 0;
        this.drawCalls.push(currentGroup);
        // TODO - this can be simplified
        for (var i = 0; i < this.batches.length; i++) {
            var data = this.batches[i];
            // TODO add some full on MAX_TEXTURE CODE..
            var MAX_TEXTURES = 8;
            // Forced cast for checking `native` without errors
            var style = data.style;
            var nextTexture = style.texture.baseTexture;
            if (native !== !!style.native) {
                native = !!style.native;
                drawMode = native ? constants_DRAW_MODES.LINES : constants_DRAW_MODES.TRIANGLES;
                // force the batch to break!
                currentTexture = null;
                textureCount = MAX_TEXTURES;
                TICK++;
            }
            if (currentTexture !== nextTexture) {
                currentTexture = nextTexture;
                if (nextTexture._batchEnabled !== TICK) {
                    if (textureCount === MAX_TEXTURES) {
                        TICK++;
                        textureCount = 0;
                        if (currentGroup.size > 0) {
                            currentGroup = DRAW_CALL_POOL.pop();
                            if (!currentGroup) {
                                currentGroup = new BatchDrawCall();
                                currentGroup.texArray = new BatchTextureArray();
                            }
                            this.drawCalls.push(currentGroup);
                        }
                        currentGroup.start = index;
                        currentGroup.size = 0;
                        currentGroup.texArray.count = 0;
                        currentGroup.type = drawMode;
                    }
                    // TODO add this to the render part..
                    // Hack! Because texture has protected `touched`
                    nextTexture.touched = 1; // touch;
                    nextTexture._batchEnabled = TICK;
                    nextTexture._batchLocation = textureCount;
                    nextTexture.wrapMode = constants_WRAP_MODES.REPEAT;
                    currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture;
                    textureCount++;
                }
            }
            currentGroup.size += data.size;
            index += data.size;
            textureId = nextTexture._batchLocation;
            this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart);
            this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart);
        }
        BaseTexture._globalBatch = TICK;
        // upload..
        // merge for now!
        this.packAttributes();
    };
    /** Packs attributes to single buffer. */
    GraphicsGeometry.prototype.packAttributes = function () {
        var verts = this.points;
        var uvs = this.uvs;
        var colors = this.colors;
        var textureIds = this.textureIds;
        // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes
        var glPoints = new ArrayBuffer(verts.length * 3 * 4);
        var f32 = new Float32Array(glPoints);
        var u32 = new Uint32Array(glPoints);
        var p = 0;
        for (var i = 0; i < verts.length / 2; i++) {
            f32[p++] = verts[i * 2];
            f32[p++] = verts[(i * 2) + 1];
            f32[p++] = uvs[i * 2];
            f32[p++] = uvs[(i * 2) + 1];
            u32[p++] = colors[i];
            f32[p++] = textureIds[i];
        }
        this._buffer.update(glPoints);
        this._indexBuffer.update(this.indicesUint16);
    };
    /** Process fill part of Graphics. */
    GraphicsGeometry.prototype.processFill = function (data) {
        if (data.holes.length) {
            buildPoly.triangulate(data, this);
        }
        else {
            var command = FILL_COMMANDS[data.type];
            command.triangulate(data, this);
        }
    };
    /** Process line part of Graphics. */
    GraphicsGeometry.prototype.processLine = function (data) {
        buildLine(data, this);
        for (var i = 0; i < data.holes.length; i++) {
            buildLine(data.holes[i], this);
        }
    };
    /** Process the holes data. */
    GraphicsGeometry.prototype.processHoles = function (holes) {
        for (var i = 0; i < holes.length; i++) {
            var hole = holes[i];
            var command = FILL_COMMANDS[hole.type];
            command.build(hole);
            if (hole.matrix) {
                this.transformPoints(hole.points, hole.matrix);
            }
        }
    };
    /** Update the local bounds of the object. Expensive to use performance-wise. */
    GraphicsGeometry.prototype.calculateBounds = function () {
        var bounds = this._bounds;
        var sequenceBounds = tmpBounds;
        var curMatrix = Matrix.IDENTITY;
        this._bounds.clear();
        sequenceBounds.clear();
        for (var i = 0; i < this.graphicsData.length; i++) {
            var data = this.graphicsData[i];
            var shape = data.shape;
            var type = data.type;
            var lineStyle = data.lineStyle;
            var nextMatrix = data.matrix || Matrix.IDENTITY;
            var lineWidth = 0.0;
            if (lineStyle && lineStyle.visible) {
                lineWidth = lineStyle.width * Math.max(0, lineStyle.alignment);
            }
            if (curMatrix !== nextMatrix) {
                if (!sequenceBounds.isEmpty()) {
                    bounds.addBoundsMatrix(sequenceBounds, curMatrix);
                    sequenceBounds.clear();
                }
                curMatrix = nextMatrix;
            }
            if (type === SHAPES.RECT || type === SHAPES.RREC) {
                var rect = shape;
                sequenceBounds.addFramePad(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, lineWidth, lineWidth);
            }
            else if (type === SHAPES.CIRC) {
                var circle = shape;
                sequenceBounds.addFramePad(circle.x, circle.y, circle.x, circle.y, circle.radius + lineWidth, circle.radius + lineWidth);
            }
            else if (type === SHAPES.ELIP) {
                var ellipse = shape;
                sequenceBounds.addFramePad(ellipse.x, ellipse.y, ellipse.x, ellipse.y, ellipse.width + lineWidth, ellipse.height + lineWidth);
            }
            else {
                var poly = shape;
                // adding directly to the bounds
                bounds.addVerticesMatrix(curMatrix, poly.points, 0, poly.points.length, lineWidth, lineWidth);
            }
        }
        if (!sequenceBounds.isEmpty()) {
            bounds.addBoundsMatrix(sequenceBounds, curMatrix);
        }
        bounds.pad(this.boundsPadding, this.boundsPadding);
    };
    /**
     * Transform points using matrix.
     *
     * @param points - Points to transform
     * @param matrix - Transform matrix
     */
    GraphicsGeometry.prototype.transformPoints = function (points, matrix) {
        for (var i = 0; i < points.length / 2; i++) {
            var x = points[(i * 2)];
            var y = points[(i * 2) + 1];
            points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx;
            points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty;
        }
    };
    /**
     * Add colors.
     *
     * @param colors - List of colors to add to
     * @param color - Color to add
     * @param alpha - Alpha to use
     * @param size - Number of colors to add
     * @param offset
     */
    GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) {
        if (offset === void 0) { offset = 0; }
        // TODO use the premultiply bits Ivan added
        var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16);
        var rgba = premultiplyTint(rgb, alpha);
        colors.length = Math.max(colors.length, offset + size);
        for (var i = 0; i < size; i++) {
            colors[offset + i] = rgba;
        }
    };
    /** Add texture id that the shader/fragment wants to use. */
    GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) {
        if (offset === void 0) { offset = 0; }
        textureIds.length = Math.max(textureIds.length, offset + size);
        for (var i = 0; i < size; i++) {
            textureIds[offset + i] = id;
        }
    };
    /**
     * Generates the UVs for a shape.
     *
     * @param verts - Vertices
     * @param uvs - UVs
     * @param texture - Reference to Texture
     * @param start - Index buffer start index.
     * @param size - The size/length for index buffer.
     * @param matrix - Optional transform for all points.
     */
    GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) {
        if (matrix === void 0) { matrix = null; }
        var index = 0;
        var uvsStart = uvs.length;
        var frame = texture.frame;
        while (index < size) {
            var x = verts[(start + index) * 2];
            var y = verts[((start + index) * 2) + 1];
            if (matrix) {
                var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx;
                y = (matrix.b * x) + (matrix.d * y) + matrix.ty;
                x = nx;
            }
            index++;
            uvs.push(x / frame.width, y / frame.height);
        }
        var baseTexture = texture.baseTexture;
        if (frame.width < baseTexture.width
            || frame.height < baseTexture.height) {
            this.adjustUvs(uvs, texture, uvsStart, size);
        }
    };
    /**
     * Modify uvs array according to position of texture region
     * Does not work with rotated or trimmed textures
     *
     * @param uvs - array
     * @param texture - region
     * @param start - starting index for uvs
     * @param size - how many points to adjust
     */
    GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) {
        var baseTexture = texture.baseTexture;
        var eps = 1e-6;
        var finish = start + (size * 2);
        var frame = texture.frame;
        var scaleX = frame.width / baseTexture.width;
        var scaleY = frame.height / baseTexture.height;
        var offsetX = frame.x / frame.width;
        var offsetY = frame.y / frame.height;
        var minX = Math.floor(uvs[start] + eps);
        var minY = Math.floor(uvs[start + 1] + eps);
        for (var i = start + 2; i < finish; i += 2) {
            minX = Math.min(minX, Math.floor(uvs[i] + eps));
            minY = Math.min(minY, Math.floor(uvs[i + 1] + eps));
        }
        offsetX -= minX;
        offsetY -= minY;
        for (var i = start; i < finish; i += 2) {
            uvs[i] = (uvs[i] + offsetX) * scaleX;
            uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY;
        }
    };
    /**
     * The maximum number of points to consider an object "batchable",
     * able to be batched by the renderer's batch system.
\    */
    GraphicsGeometry.BATCHABLE_SIZE = 100;
    return GraphicsGeometry;
}(BatchGeometry));

/**
 * Represents the line style for Graphics.
 *
 * @memberof PIXI
 */
var LineStyle = /** @class */ (function (_super) {
    graphics_extends(LineStyle, _super);
    function LineStyle() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        /** The width (thickness) of any lines drawn. */
        _this.width = 0;
        /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */
        _this.alignment = 0.5;
        /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */
        _this.native = false;
        /**
         * Line cap style.
         *
         * @member {PIXI.LINE_CAP}
         * @default PIXI.LINE_CAP.BUTT
         */
        _this.cap = LINE_CAP.BUTT;
        /**
         * Line join style.
         *
         * @member {PIXI.LINE_JOIN}
         * @default PIXI.LINE_JOIN.MITER
         */
        _this.join = LINE_JOIN.MITER;
        /** Miter limit. */
        _this.miterLimit = 10;
        return _this;
    }
    /** Clones the object. */
    LineStyle.prototype.clone = function () {
        var obj = new LineStyle();
        obj.color = this.color;
        obj.alpha = this.alpha;
        obj.texture = this.texture;
        obj.matrix = this.matrix;
        obj.visible = this.visible;
        obj.width = this.width;
        obj.alignment = this.alignment;
        obj.native = this.native;
        obj.cap = this.cap;
        obj.join = this.join;
        obj.miterLimit = this.miterLimit;
        return obj;
    };
    /** Reset the line style to default. */
    LineStyle.prototype.reset = function () {
        _super.prototype.reset.call(this);
        // Override default line style color
        this.color = 0x0;
        this.alignment = 0.5;
        this.width = 0;
        this.native = false;
    };
    return LineStyle;
}(FillStyle));

var temp = new Float32Array(3);
// a default shaders map used by graphics..
var DEFAULT_SHADERS = {};
/**
 * The Graphics class is primarily used to render primitive shapes such as lines, circles and
 * rectangles to the display, and to color and fill them.  However, you can also use a Graphics
 * object to build a list of primitives to use as a mask, or as a complex hitArea.
 *
 * Please note that due to legacy naming conventions, the behavior of some functions in this class
 * can be confusing.  Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive
 * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the
 * functions do not directly draw anything to the screen.  Similarly, the `clear()` function doesn't
 * change the screen, it simply resets the list of primitives, which can be useful if you want to
 * rebuild the contents of an existing Graphics object.
 *
 * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as
 * an optimization, by passing it into a new Geometry object's constructor.  Because of this
 * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to
 * properly dereference each GraphicsGeometry and prevent memory leaks.
 *
 * @memberof PIXI
 */
var Graphics = /** @class */ (function (_super) {
    graphics_extends(Graphics, _super);
    /**
     * @param geometry - Geometry to use, if omitted will create a new GraphicsGeometry instance.
     */
    function Graphics(geometry) {
        if (geometry === void 0) { geometry = null; }
        var _this = _super.call(this) || this;
        /**
         * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
         * Can be shared between multiple Graphics objects.
         */
        _this.shader = null;
        /** Renderer plugin for batching */
        _this.pluginName = 'batch';
        /**
         * Current path
         *
         * @readonly
         */
        _this.currentPath = null;
        /** A collections of batches! These can be drawn by the renderer batch system. */
        _this.batches = [];
        /** Update dirty for limiting calculating tints for batches. */
        _this.batchTint = -1;
        /** Update dirty for limiting calculating batches.*/
        _this.batchDirty = -1;
        /** Copy of the object vertex data. */
        _this.vertexData = null;
        /** Current fill style. */
        _this._fillStyle = new FillStyle();
        /** Current line style. */
        _this._lineStyle = new LineStyle();
        /** Current shape transform matrix. */
        _this._matrix = null;
        /** Current hole mode is enabled. */
        _this._holeMode = false;
        /**
         * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g.,
         * blend mode, culling, depth testing, direction of rendering triangles, backface, etc.
         */
        _this.state = State.for2d();
        _this._geometry = geometry || new GraphicsGeometry();
        _this._geometry.refCount++;
        /**
         * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
         * This is useful if your graphics element does not change often, as it will speed up the rendering
         * of the object in exchange for taking up texture memory. It is also useful if you need the graphics
         * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if
         * you are constantly redrawing the graphics element.
         *
         * @name cacheAsBitmap
         * @member {boolean}
         * @memberof PIXI.Graphics#
         * @default false
         */
        _this._transformID = -1;
        // Set default
        _this.tint = 0xFFFFFF;
        _this.blendMode = constants_BLEND_MODES.NORMAL;
        return _this;
    }
    Object.defineProperty(Graphics.prototype, "geometry", {
        /**
         * Includes vertex positions, face indices, normals, colors, UVs, and
         * custom attributes within buffers, reducing the cost of passing all
         * this data to the GPU. Can be shared between multiple Mesh or Graphics objects.
         *
         * @readonly
         */
        get: function () {
            return this._geometry;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Creates a new Graphics object with the same values as this one.
     * Note that only the geometry of the object is cloned, not its transform (position,scale,etc)
     *
     * @return - A clone of the graphics object
     */
    Graphics.prototype.clone = function () {
        this.finishPoly();
        return new Graphics(this._geometry);
    };
    Object.defineProperty(Graphics.prototype, "blendMode", {
        get: function () {
            return this.state.blendMode;
        },
        /**
         * The blend mode to be applied to the graphic shape. Apply a value of
         * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.  Note that, since each
         * primitive in the GraphicsGeometry list is rendered sequentially, modes
         * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will
         * be applied per-primitive.
         *
         * @default PIXI.BLEND_MODES.NORMAL
         */
        set: function (value) {
            this.state.blendMode = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Graphics.prototype, "tint", {
        /**
         * The tint applied to each graphic shape. This is a hex value. A value of
         * 0xFFFFFF will remove any tint effect.
         *
         * @default 0xFFFFFF
         */
        get: function () {
            return this._tint;
        },
        set: function (value) {
            this._tint = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Graphics.prototype, "fill", {
        /**
         * The current fill style.
         *
         * @readonly
         */
        get: function () {
            return this._fillStyle;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Graphics.prototype, "line", {
        /**
         * The current line style.
         *
         * @readonly
         */
        get: function () {
            return this._lineStyle;
        },
        enumerable: false,
        configurable: true
    });
    Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) {
        if (options === void 0) { options = null; }
        if (color === void 0) { color = 0x0; }
        if (alpha === void 0) { alpha = 1; }
        if (alignment === void 0) { alignment = 0.5; }
        if (native === void 0) { native = false; }
        // Support non-object params: (width, color, alpha, alignment, native)
        if (typeof options === 'number') {
            options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native };
        }
        return this.lineTextureStyle(options);
    };
    /**
     * Like line style but support texture for line fill.
     *
     * @param options - Collection of options for setting line style.
     * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style
     * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use
     * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style.
     *  Default 0xFFFFFF if texture present.
     * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style
     * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture
     * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outer).
     *        WebGL only.
     * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP
     * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style
     * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style
     * @param {number}[options.miterLimit=10] - miter limit ratio
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.lineTextureStyle = function (options) {
        // Apply defaults
        options = Object.assign({
            width: 0,
            texture: Texture.WHITE,
            color: (options && options.texture) ? 0xFFFFFF : 0x0,
            alpha: 1,
            matrix: null,
            alignment: 0.5,
            native: false,
            cap: LINE_CAP.BUTT,
            join: LINE_JOIN.MITER,
            miterLimit: 10,
        }, options);
        if (this.currentPath) {
            this.startPoly();
        }
        var visible = options.width > 0 && options.alpha > 0;
        if (!visible) {
            this._lineStyle.reset();
        }
        else {
            if (options.matrix) {
                options.matrix = options.matrix.clone();
                options.matrix.invert();
            }
            Object.assign(this._lineStyle, { visible: visible }, options);
        }
        return this;
    };
    /**
     * Start a polygon object internally.
     *
     * @protected
     */
    Graphics.prototype.startPoly = function () {
        if (this.currentPath) {
            var points = this.currentPath.points;
            var len = this.currentPath.points.length;
            if (len > 2) {
                this.drawShape(this.currentPath);
                this.currentPath = new Polygon();
                this.currentPath.closeStroke = false;
                this.currentPath.points.push(points[len - 2], points[len - 1]);
            }
        }
        else {
            this.currentPath = new Polygon();
            this.currentPath.closeStroke = false;
        }
    };
    /**
     * Finish the polygon object.
     *
     * @protected
     */
    Graphics.prototype.finishPoly = function () {
        if (this.currentPath) {
            if (this.currentPath.points.length > 2) {
                this.drawShape(this.currentPath);
                this.currentPath = null;
            }
            else {
                this.currentPath.points.length = 0;
            }
        }
    };
    /**
     * Moves the current drawing position to x, y.
     *
     * @param x - the X coordinate to move to
     * @param y - the Y coordinate to move to
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.moveTo = function (x, y) {
        this.startPoly();
        this.currentPath.points[0] = x;
        this.currentPath.points[1] = y;
        return this;
    };
    /**
     * Draws a line using the current line style from the current drawing position to (x, y);
     * The current drawing position is then set to (x, y).
     *
     * @param x - the X coordinate to draw to
     * @param y - the Y coordinate to draw to
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.lineTo = function (x, y) {
        if (!this.currentPath) {
            this.moveTo(0, 0);
        }
        // remove duplicates..
        var points = this.currentPath.points;
        var fromX = points[points.length - 2];
        var fromY = points[points.length - 1];
        if (fromX !== x || fromY !== y) {
            points.push(x, y);
        }
        return this;
    };
    /** Initialize the curve */
    Graphics.prototype._initCurve = function (x, y) {
        if (x === void 0) { x = 0; }
        if (y === void 0) { y = 0; }
        if (this.currentPath) {
            if (this.currentPath.points.length === 0) {
                this.currentPath.points = [x, y];
            }
        }
        else {
            this.moveTo(x, y);
        }
    };
    /**
     * Calculate the points for a quadratic bezier curve and then draws it.
     * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
     *
     * @param cpX - Control point x
     * @param cpY - Control point y
     * @param toX - Destination point x
     * @param toY - Destination point y
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) {
        this._initCurve();
        var points = this.currentPath.points;
        if (points.length === 0) {
            this.moveTo(0, 0);
        }
        QuadraticUtils.curveTo(cpX, cpY, toX, toY, points);
        return this;
    };
    /**
     * Calculate the points for a bezier curve and then draws it.
     *
     * @param cpX - Control point x
     * @param cpY - Control point y
     * @param cpX2 - Second Control point x
     * @param cpY2 - Second Control point y
     * @param toX - Destination point x
     * @param toY - Destination point y
     * @return This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) {
        this._initCurve();
        BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points);
        return this;
    };
    /**
     * The arcTo() method creates an arc/curve between two tangents on the canvas.
     *
     * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
     *
     * @param x1 - The x-coordinate of the first tangent point of the arc
     * @param y1 - The y-coordinate of the first tangent point of the arc
     * @param x2 - The x-coordinate of the end of the arc
     * @param y2 - The y-coordinate of the end of the arc
     * @param radius - The radius of the arc
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) {
        this._initCurve(x1, y1);
        var points = this.currentPath.points;
        var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points);
        if (result) {
            var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise;
            this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise);
        }
        return this;
    };
    /**
     * The arc method creates an arc/curve (used to create circles, or parts of circles).
     *
     * @param cx - The x-coordinate of the center of the circle
     * @param cy - The y-coordinate of the center of the circle
     * @param radius - The radius of the circle
     * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position
     *  of the arc's circle)
     * @param endAngle - The ending angle, in radians
     * @param anticlockwise - Specifies whether the drawing should be
     *  counter-clockwise or clockwise. False is default, and indicates clockwise, while true
     *  indicates counter-clockwise.
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) {
        if (anticlockwise === void 0) { anticlockwise = false; }
        if (startAngle === endAngle) {
            return this;
        }
        if (!anticlockwise && endAngle <= startAngle) {
            endAngle += PI_2;
        }
        else if (anticlockwise && startAngle <= endAngle) {
            startAngle += PI_2;
        }
        var sweep = endAngle - startAngle;
        if (sweep === 0) {
            return this;
        }
        var startX = cx + (Math.cos(startAngle) * radius);
        var startY = cy + (Math.sin(startAngle) * radius);
        var eps = this._geometry.closePointEps;
        // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path.
        var points = this.currentPath ? this.currentPath.points : null;
        if (points) {
            // TODO: make a better fix.
            // We check how far our start is from the last existing point
            var xDiff = Math.abs(points[points.length - 2] - startX);
            var yDiff = Math.abs(points[points.length - 1] - startY);
            if (xDiff < eps && yDiff < eps) ;
            else {
                points.push(startX, startY);
            }
        }
        else {
            this.moveTo(startX, startY);
            points = this.currentPath.points;
        }
        ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points);
        return this;
    };
    /**
     * Specifies a simple one-color fill that subsequent calls to other Graphics methods
     * (such as lineTo() or drawCircle()) use when drawing.
     *
     * @param color - the color of the fill
     * @param alpha - the alpha of the fill
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.beginFill = function (color, alpha) {
        if (color === void 0) { color = 0; }
        if (alpha === void 0) { alpha = 1; }
        return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha });
    };
    /**
     * Begin the texture fill
     *
     * @param options - Object object.
     * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill
     * @param {number} [options.color=0xffffff] - Background to fill behind texture
     * @param {number} [options.alpha=1] - Alpha of fill
     * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix
     * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.beginTextureFill = function (options) {
        // Apply defaults
        options = Object.assign({
            texture: Texture.WHITE,
            color: 0xFFFFFF,
            alpha: 1,
            matrix: null,
        }, options);
        if (this.currentPath) {
            this.startPoly();
        }
        var visible = options.alpha > 0;
        if (!visible) {
            this._fillStyle.reset();
        }
        else {
            if (options.matrix) {
                options.matrix = options.matrix.clone();
                options.matrix.invert();
            }
            Object.assign(this._fillStyle, { visible: visible }, options);
        }
        return this;
    };
    /**
     * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
     *
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.endFill = function () {
        this.finishPoly();
        this._fillStyle.reset();
        return this;
    };
    /**
     * Draws a rectangle shape.
     *
     * @param x - The X coord of the top-left of the rectangle
     * @param y - The Y coord of the top-left of the rectangle
     * @param width - The width of the rectangle
     * @param height - The height of the rectangle
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.drawRect = function (x, y, width, height) {
        return this.drawShape(new Rectangle(x, y, width, height));
    };
    /**
     * Draw a rectangle shape with rounded/beveled corners.
     *
     * @param x - The X coord of the top-left of the rectangle
     * @param y - The Y coord of the top-left of the rectangle
     * @param width - The width of the rectangle
     * @param height - The height of the rectangle
     * @param radius - Radius of the rectangle corners
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) {
        return this.drawShape(new RoundedRectangle(x, y, width, height, radius));
    };
    /**
     * Draws a circle.
     *
     * @param x - The X coordinate of the center of the circle
     * @param y - The Y coordinate of the center of the circle
     * @param radius - The radius of the circle
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.drawCircle = function (x, y, radius) {
        return this.drawShape(new Circle(x, y, radius));
    };
    /**
     * Draws an ellipse.
     *
     * @param x - The X coordinate of the center of the ellipse
     * @param y - The Y coordinate of the center of the ellipse
     * @param width - The half width of the ellipse
     * @param height - The half height of the ellipse
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.drawEllipse = function (x, y, width, height) {
        return this.drawShape(new Ellipse(x, y, width, height));
    };
    /**
     * Draws a polygon using the given path.
     *
     * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon.
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.drawPolygon = function () {
        var arguments$1 = arguments;

        var path = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            path[_i] = arguments$1[_i];
        }
        var points;
        var closeStroke = true; // !!this._fillStyle;
        var poly = path[0];
        // check if data has points..
        if (poly.points) {
            closeStroke = poly.closeStroke;
            points = poly.points;
        }
        else if (Array.isArray(path[0])) {
            points = path[0];
        }
        else {
            points = path;
        }
        var shape = new Polygon(points);
        shape.closeStroke = closeStroke;
        this.drawShape(shape);
        return this;
    };
    /**
     * Draw any shape.
     *
     * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.drawShape = function (shape) {
        if (!this._holeMode) {
            this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix);
        }
        else {
            this._geometry.drawHole(shape, this._matrix);
        }
        return this;
    };
    /**
     * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
     *
     * @return - This Graphics object. Good for chaining method calls
     */
    Graphics.prototype.clear = function () {
        this._geometry.clear();
        this._lineStyle.reset();
        this._fillStyle.reset();
        this._boundsID++;
        this._matrix = null;
        this._holeMode = false;
        this.currentPath = null;
        return this;
    };
    /**
     * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and
     * masked with gl.scissor.
     *
     * @returns - True if only 1 rect.
     */
    Graphics.prototype.isFastRect = function () {
        var data = this._geometry.graphicsData;
        return data.length === 1
            && data[0].shape.type === SHAPES.RECT
            && !data[0].matrix
            && !data[0].holes.length
            && !(data[0].lineStyle.visible && data[0].lineStyle.width);
    };
    /**
     * Renders the object using the WebGL renderer
     *
     * @param renderer - The renderer
     */
    Graphics.prototype._render = function (renderer) {
        this.finishPoly();
        var geometry = this._geometry;
        var hasuint32 = renderer.context.supports.uint32Indices;
        // batch part..
        // batch it!
        geometry.updateBatches(hasuint32);
        if (geometry.batchable) {
            if (this.batchDirty !== geometry.batchDirty) {
                this._populateBatches();
            }
            this._renderBatched(renderer);
        }
        else {
            // no batching...
            renderer.batch.flush();
            this._renderDirect(renderer);
        }
    };
    /** Populating batches for rendering. */
    Graphics.prototype._populateBatches = function () {
        var geometry = this._geometry;
        var blendMode = this.blendMode;
        var len = geometry.batches.length;
        this.batchTint = -1;
        this._transformID = -1;
        this.batchDirty = geometry.batchDirty;
        this.batches.length = len;
        this.vertexData = new Float32Array(geometry.points);
        for (var i = 0; i < len; i++) {
            var gI = geometry.batches[i];
            var color = gI.style.color;
            var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2);
            var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2);
            var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size);
            var batch = {
                vertexData: vertexData,
                blendMode: blendMode,
                indices: indices,
                uvs: uvs,
                _batchRGB: hex2rgb(color),
                _tintRGB: color,
                _texture: gI.style.texture,
                alpha: gI.style.alpha,
                worldAlpha: 1
            };
            this.batches[i] = batch;
        }
    };
    /**
     * Renders the batches using the BathedRenderer plugin
     *
     * @param renderer - The renderer
     */
    Graphics.prototype._renderBatched = function (renderer) {
        if (!this.batches.length) {
            return;
        }
        renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
        this.calculateVertices();
        this.calculateTints();
        for (var i = 0, l = this.batches.length; i < l; i++) {
            var batch = this.batches[i];
            batch.worldAlpha = this.worldAlpha * batch.alpha;
            renderer.plugins[this.pluginName].render(batch);
        }
    };
    /**
     * Renders the graphics direct
     *
     * @param renderer - The renderer
     */
    Graphics.prototype._renderDirect = function (renderer) {
        var shader = this._resolveDirectShader(renderer);
        var geometry = this._geometry;
        var tint = this.tint;
        var worldAlpha = this.worldAlpha;
        var uniforms = shader.uniforms;
        var drawCalls = geometry.drawCalls;
        // lets set the transfomr
        uniforms.translationMatrix = this.transform.worldTransform;
        // and then lets set the tint..
        uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha;
        uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha;
        uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha;
        uniforms.tint[3] = worldAlpha;
        // the first draw call, we can set the uniforms of the shader directly here.
        // this means that we can tack advantage of the sync function of pixi!
        // bind and sync uniforms..
        // there is a way to optimise this..
        renderer.shader.bind(shader);
        renderer.geometry.bind(geometry, shader);
        // set state..
        renderer.state.set(this.state);
        // then render the rest of them...
        for (var i = 0, l = drawCalls.length; i < l; i++) {
            this._renderDrawCallDirect(renderer, geometry.drawCalls[i]);
        }
    };
    /** Renders specific DrawCall */
    Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) {
        var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start;
        var groupTextureCount = texArray.count;
        for (var j = 0; j < groupTextureCount; j++) {
            renderer.texture.bind(texArray.elements[j], j);
        }
        renderer.geometry.draw(type, size, start);
    };
    /**
     * Resolves shader for direct rendering
     *
     * @param renderer - The renderer
     */
    Graphics.prototype._resolveDirectShader = function (renderer) {
        var shader = this.shader;
        var pluginName = this.pluginName;
        if (!shader) {
            // if there is no shader here, we can use the default shader.
            // and that only gets created if we actually need it..
            // but may be more than one plugins for graphics
            if (!DEFAULT_SHADERS[pluginName]) {
                var MAX_TEXTURES = renderer.plugins.batch.MAX_TEXTURES;
                var sampleValues = new Int32Array(MAX_TEXTURES);
                for (var i = 0; i < MAX_TEXTURES; i++) {
                    sampleValues[i] = i;
                }
                var uniforms = {
                    tint: new Float32Array([1, 1, 1, 1]),
                    translationMatrix: new Matrix(),
                    default: UniformGroup.from({ uSamplers: sampleValues }, true),
                };
                var program = renderer.plugins[pluginName]._shader.program;
                DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms);
            }
            shader = DEFAULT_SHADERS[pluginName];
        }
        return shader;
    };
    /** Retrieves the bounds of the graphic shape as a rectangle object. */
    Graphics.prototype._calculateBounds = function () {
        this.finishPoly();
        var geometry = this._geometry;
        // skipping when graphics is empty, like a container
        if (!geometry.graphicsData.length) {
            return;
        }
        var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY;
        this._bounds.addFrame(this.transform, minX, minY, maxX, maxY);
    };
    /**
     * Tests if a point is inside this graphics object
     *
     * @param point - the point to test
     * @return - the result of the test
     */
    Graphics.prototype.containsPoint = function (point) {
        this.worldTransform.applyInverse(point, Graphics._TEMP_POINT);
        return this._geometry.containsPoint(Graphics._TEMP_POINT);
    };
    /** Recalculate the tint by applying tint to batches using Graphics tint. */
    Graphics.prototype.calculateTints = function () {
        if (this.batchTint !== this.tint) {
            this.batchTint = this.tint;
            var tintRGB = hex2rgb(this.tint, temp);
            for (var i = 0; i < this.batches.length; i++) {
                var batch = this.batches[i];
                var batchTint = batch._batchRGB;
                var r = (tintRGB[0] * batchTint[0]) * 255;
                var g = (tintRGB[1] * batchTint[1]) * 255;
                var b = (tintRGB[2] * batchTint[2]) * 255;
                // TODO Ivan, can this be done in one go?
                var color = (r << 16) + (g << 8) + (b | 0);
                batch._tintRGB = (color >> 16)
                    + (color & 0xff00)
                    + ((color & 0xff) << 16);
            }
        }
    };
    /**
     * If there's a transform update or a change to the shape of the
     * geometry, recalculate the vertices.
     */
    Graphics.prototype.calculateVertices = function () {
        var wtID = this.transform._worldID;
        if (this._transformID === wtID) {
            return;
        }
        this._transformID = wtID;
        var wt = this.transform.worldTransform;
        var a = wt.a;
        var b = wt.b;
        var c = wt.c;
        var d = wt.d;
        var tx = wt.tx;
        var ty = wt.ty;
        var data = this._geometry.points; // batch.vertexDataOriginal;
        var vertexData = this.vertexData;
        var count = 0;
        for (var i = 0; i < data.length; i += 2) {
            var x = data[i];
            var y = data[i + 1];
            vertexData[count++] = (a * x) + (c * y) + tx;
            vertexData[count++] = (d * y) + (b * x) + ty;
        }
    };
    /**
     * Closes the current path.
     *
     * @return - Returns itself.
     */
    Graphics.prototype.closePath = function () {
        var currentPath = this.currentPath;
        if (currentPath) {
            // we don't need to add extra point in the end because buildLine will take care of that
            currentPath.closeStroke = true;
            // ensure that the polygon is completed, and is available for hit detection
            // (even if the graphics is not rendered yet)
            this.finishPoly();
        }
        return this;
    };
    /**
     * Apply a matrix to the positional data.
     *
     * @param matrix - Matrix to use for transform current shape.
     * @return - Returns itself.
     */
    Graphics.prototype.setMatrix = function (matrix) {
        this._matrix = matrix;
        return this;
    };
    /**
     * Begin adding holes to the last draw shape
     * IMPORTANT: holes must be fully inside a shape to work
     * Also weirdness ensues if holes overlap!
     * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer,
     * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle.
     *
     * @return - Returns itself.
     */
    Graphics.prototype.beginHole = function () {
        this.finishPoly();
        this._holeMode = true;
        return this;
    };
    /**
     * End adding holes to the last draw shape.
     *
     * @return - Returns itself.
     */
    Graphics.prototype.endHole = function () {
        this.finishPoly();
        this._holeMode = false;
        return this;
    };
    /**
     * Destroys the Graphics object.
     *
     * @param options - Options parameter. A boolean will act as if all
     *  options have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have
     *  their destroy method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
     *  Should it destroy the texture of the child sprite
     * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
     *  Should it destroy the base texture of the child sprite
     */
    Graphics.prototype.destroy = function (options) {
        this._geometry.refCount--;
        if (this._geometry.refCount === 0) {
            this._geometry.dispose();
        }
        this._matrix = null;
        this.currentPath = null;
        this._lineStyle.destroy();
        this._lineStyle = null;
        this._fillStyle.destroy();
        this._fillStyle = null;
        this._geometry = null;
        this.shader = null;
        this.vertexData = null;
        this.batches.length = 0;
        this.batches = null;
        _super.prototype.destroy.call(this, options);
    };
    /**
     * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves.
     * In the next major release, we'll enable this by default.
     */
    Graphics.nextRoundedRectBehavior = false;
    /**
     * Temporary point to use for containsPoint.
     *
     * @private
     */
    Graphics._TEMP_POINT = new Point();
    return Graphics;
}(Container));

var graphicsUtils = {
    buildPoly: buildPoly,
    buildCircle: buildCircle,
    buildRectangle: buildRectangle,
    buildRoundedRectangle: buildRoundedRectangle,
    buildLine: buildLine,
    ArcUtils: ArcUtils,
    BezierUtils: BezierUtils,
    QuadraticUtils: QuadraticUtils,
    BatchPart: BatchPart,
    FILL_COMMANDS: FILL_COMMANDS,
    BATCH_POOL: BATCH_POOL,
    DRAW_CALL_POOL: DRAW_CALL_POOL
};


//# sourceMappingURL=graphics.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/sprite/dist/esm/sprite.js
/*!
 * @pixi/sprite - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/sprite is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */







/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var sprite_extendStatics = function(d, b) {
    sprite_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return sprite_extendStatics(d, b);
};

function sprite_extends(d, b) {
    sprite_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var tempPoint = new Point();
var indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
/**
 * The Sprite object is the base for all textured objects that are rendered to the screen
*
 * A sprite can be created directly from an image like this:
 *
 * ```js
 * let sprite = PIXI.Sprite.from('assets/image.png');
 * ```
 *
 * The more efficient way to create sprites is using a {@link PIXI.Spritesheet},
 * as swapping base textures when rendering to the screen is inefficient.
 *
 * ```js
 * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
 *
 * function setup() {
 *   let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
 *   let sprite = new PIXI.Sprite(sheet.textures["image.png"]);
 *   ...
 * }
 * ```
 *
 * @memberof PIXI
 */
var Sprite = /** @class */ (function (_super) {
    sprite_extends(Sprite, _super);
    /** @param texture - The texture for this sprite. */
    function Sprite(texture) {
        var _this = _super.call(this) || this;
        _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0));
        _this._texture = null;
        _this._width = 0;
        _this._height = 0;
        _this._tint = null;
        _this._tintRGB = null;
        _this.tint = 0xFFFFFF;
        _this.blendMode = constants_BLEND_MODES.NORMAL;
        _this._cachedTint = 0xFFFFFF;
        _this.uvs = null;
        // call texture setter
        _this.texture = texture || Texture.EMPTY;
        _this.vertexData = new Float32Array(8);
        _this.vertexTrimmedData = null;
        _this._transformID = -1;
        _this._textureID = -1;
        _this._transformTrimmedID = -1;
        _this._textureTrimmedID = -1;
        // Batchable stuff..
        // TODO could make this a mixin?
        _this.indices = indices;
        _this.pluginName = 'batch';
        /**
         * Used to fast check if a sprite is.. a sprite!
         * @member {boolean}
         */
        _this.isSprite = true;
        _this._roundPixels = settings.ROUND_PIXELS;
        return _this;
    }
    /** When the texture is updated, this event will fire to update the scale and frame. */
    Sprite.prototype._onTextureUpdate = function () {
        this._textureID = -1;
        this._textureTrimmedID = -1;
        this._cachedTint = 0xFFFFFF;
        // so if _width is 0 then width was not set..
        if (this._width) {
            this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
        }
        if (this._height) {
            this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
        }
    };
    /** Called when the anchor position updates. */
    Sprite.prototype._onAnchorUpdate = function () {
        this._transformID = -1;
        this._transformTrimmedID = -1;
    };
    /** Calculates worldTransform * vertices, store it in vertexData. */
    Sprite.prototype.calculateVertices = function () {
        var texture = this._texture;
        if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) {
            return;
        }
        // update texture UV here, because base texture can be changed without calling `_onTextureUpdate`
        if (this._textureID !== texture._updateID) {
            this.uvs = this._texture._uvs.uvsFloat32;
        }
        this._transformID = this.transform._worldID;
        this._textureID = texture._updateID;
        // set the vertex data
        var wt = this.transform.worldTransform;
        var a = wt.a;
        var b = wt.b;
        var c = wt.c;
        var d = wt.d;
        var tx = wt.tx;
        var ty = wt.ty;
        var vertexData = this.vertexData;
        var trim = texture.trim;
        var orig = texture.orig;
        var anchor = this._anchor;
        var w0 = 0;
        var w1 = 0;
        var h0 = 0;
        var h1 = 0;
        if (trim) {
            // if the sprite is trimmed and is not a tilingsprite then we need to add the extra
            // space before transforming the sprite coords.
            w1 = trim.x - (anchor._x * orig.width);
            w0 = w1 + trim.width;
            h1 = trim.y - (anchor._y * orig.height);
            h0 = h1 + trim.height;
        }
        else {
            w1 = -anchor._x * orig.width;
            w0 = w1 + orig.width;
            h1 = -anchor._y * orig.height;
            h0 = h1 + orig.height;
        }
        // xy
        vertexData[0] = (a * w1) + (c * h1) + tx;
        vertexData[1] = (d * h1) + (b * w1) + ty;
        // xy
        vertexData[2] = (a * w0) + (c * h1) + tx;
        vertexData[3] = (d * h1) + (b * w0) + ty;
        // xy
        vertexData[4] = (a * w0) + (c * h0) + tx;
        vertexData[5] = (d * h0) + (b * w0) + ty;
        // xy
        vertexData[6] = (a * w1) + (c * h0) + tx;
        vertexData[7] = (d * h0) + (b * w1) + ty;
        if (this._roundPixels) {
            var resolution = settings.RESOLUTION;
            for (var i = 0; i < vertexData.length; ++i) {
                vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution);
            }
        }
    };
    /**
     * Calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData.
     *
     * This is used to ensure that the true width and height of a trimmed texture is respected.
     */
    Sprite.prototype.calculateTrimmedVertices = function () {
        if (!this.vertexTrimmedData) {
            this.vertexTrimmedData = new Float32Array(8);
        }
        else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) {
            return;
        }
        this._transformTrimmedID = this.transform._worldID;
        this._textureTrimmedID = this._texture._updateID;
        // lets do some special trim code!
        var texture = this._texture;
        var vertexData = this.vertexTrimmedData;
        var orig = texture.orig;
        var anchor = this._anchor;
        // lets calculate the new untrimmed bounds..
        var wt = this.transform.worldTransform;
        var a = wt.a;
        var b = wt.b;
        var c = wt.c;
        var d = wt.d;
        var tx = wt.tx;
        var ty = wt.ty;
        var w1 = -anchor._x * orig.width;
        var w0 = w1 + orig.width;
        var h1 = -anchor._y * orig.height;
        var h0 = h1 + orig.height;
        // xy
        vertexData[0] = (a * w1) + (c * h1) + tx;
        vertexData[1] = (d * h1) + (b * w1) + ty;
        // xy
        vertexData[2] = (a * w0) + (c * h1) + tx;
        vertexData[3] = (d * h1) + (b * w0) + ty;
        // xy
        vertexData[4] = (a * w0) + (c * h0) + tx;
        vertexData[5] = (d * h0) + (b * w0) + ty;
        // xy
        vertexData[6] = (a * w1) + (c * h0) + tx;
        vertexData[7] = (d * h0) + (b * w1) + ty;
    };
    /**
     *
     * Renders the object using the WebGL renderer
     *
     * @param renderer - The webgl renderer to use.
     */
    Sprite.prototype._render = function (renderer) {
        this.calculateVertices();
        renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
        renderer.plugins[this.pluginName].render(this);
    };
    /** Updates the bounds of the sprite. */
    Sprite.prototype._calculateBounds = function () {
        var trim = this._texture.trim;
        var orig = this._texture.orig;
        // First lets check to see if the current texture has a trim..
        if (!trim || (trim.width === orig.width && trim.height === orig.height)) {
            // no trim! lets use the usual calculations..
            this.calculateVertices();
            this._bounds.addQuad(this.vertexData);
        }
        else {
            // lets calculate a special trimmed bounds...
            this.calculateTrimmedVertices();
            this._bounds.addQuad(this.vertexTrimmedData);
        }
    };
    /**
     * Gets the local bounds of the sprite object.
     *
     * @param rect - Optional output rectangle.
     * @return The bounds.
     */
    Sprite.prototype.getLocalBounds = function (rect) {
        // we can do a fast local bounds if the sprite has no children!
        if (this.children.length === 0) {
            if (!this._localBounds) {
                this._localBounds = new Bounds();
            }
            this._localBounds.minX = this._texture.orig.width * -this._anchor._x;
            this._localBounds.minY = this._texture.orig.height * -this._anchor._y;
            this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
            this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y);
            if (!rect) {
                if (!this._localBoundsRect) {
                    this._localBoundsRect = new Rectangle();
                }
                rect = this._localBoundsRect;
            }
            return this._localBounds.getRectangle(rect);
        }
        return _super.prototype.getLocalBounds.call(this, rect);
    };
    /**
     * Tests if a point is inside this sprite
     *
     * @param point - the point to test
     * @return The result of the test
     */
    Sprite.prototype.containsPoint = function (point) {
        this.worldTransform.applyInverse(point, tempPoint);
        var width = this._texture.orig.width;
        var height = this._texture.orig.height;
        var x1 = -width * this.anchor.x;
        var y1 = 0;
        if (tempPoint.x >= x1 && tempPoint.x < x1 + width) {
            y1 = -height * this.anchor.y;
            if (tempPoint.y >= y1 && tempPoint.y < y1 + height) {
                return true;
            }
        }
        return false;
    };
    /**
     * Destroys this sprite and optionally its texture and children.
     *
     * @param options - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param [options.children=false] - if set to true, all the children will have their destroy
     *      method called as well. 'options' will be passed on to those calls.
     * @param [options.texture=false] - Should it destroy the current texture of the sprite as well
     * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
     */
    Sprite.prototype.destroy = function (options) {
        _super.prototype.destroy.call(this, options);
        this._texture.off('update', this._onTextureUpdate, this);
        this._anchor = null;
        var destroyTexture = typeof options === 'boolean' ? options : options && options.texture;
        if (destroyTexture) {
            var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture;
            this._texture.destroy(!!destroyBaseTexture);
        }
        this._texture = null;
    };
    // some helper functions..
    /**
     * Helper function that creates a new sprite based on the source you provide.
     * The source can be - frame id, image url, video url, canvas element, video element, base texture
     *
     * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
     * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options.
     * @return The newly created sprite
     */
    Sprite.from = function (source, options) {
        var texture = (source instanceof Texture)
            ? source
            : Texture.from(source, options);
        return new Sprite(texture);
    };
    Object.defineProperty(Sprite.prototype, "roundPixels", {
        get: function () {
            return this._roundPixels;
        },
        /**
         * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
         *
         * Advantages can include sharper image quality (like text) and faster rendering on canvas.
         * The main disadvantage is movement of objects may appear less smooth.
         *
         * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}.
         *
         * @default false
         */
        set: function (value) {
            if (this._roundPixels !== value) {
                this._transformID = -1;
            }
            this._roundPixels = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sprite.prototype, "width", {
        /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            return Math.abs(this.scale.x) * this._texture.orig.width;
        },
        set: function (value) {
            var s = sign(this.scale.x) || 1;
            this.scale.x = s * value / this._texture.orig.width;
            this._width = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sprite.prototype, "height", {
        /** The height of the sprite, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            return Math.abs(this.scale.y) * this._texture.orig.height;
        },
        set: function (value) {
            var s = sign(this.scale.y) || 1;
            this.scale.y = s * value / this._texture.orig.height;
            this._height = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sprite.prototype, "anchor", {
        /**
         * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture}
         * and passed to the constructor.
         *
         * The default is `(0,0)`, this means the sprite's origin is the top left.
         *
         * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered.
         *
         * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner.
         *
         * If you pass only single parameter, it will set both x and y to the same value as shown in the example below.
         *
         * @example
         * const sprite = new PIXI.Sprite(texture);
         * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5).
         */
        get: function () {
            return this._anchor;
        },
        set: function (value) {
            this._anchor.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sprite.prototype, "tint", {
        /**
         * The tint applied to the sprite. This is a hex value.
         *
         * A value of 0xFFFFFF will remove any tint effect.
         *
         * @default 0xFFFFFF
         */
        get: function () {
            return this._tint;
        },
        set: function (value) {
            this._tint = value;
            this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sprite.prototype, "texture", {
        /** The texture that the sprite is using. */
        get: function () {
            return this._texture;
        },
        set: function (value) {
            if (this._texture === value) {
                return;
            }
            if (this._texture) {
                this._texture.off('update', this._onTextureUpdate, this);
            }
            this._texture = value || Texture.EMPTY;
            this._cachedTint = 0xFFFFFF;
            this._textureID = -1;
            this._textureTrimmedID = -1;
            if (value) {
                // wait for the texture to load
                if (value.baseTexture.valid) {
                    this._onTextureUpdate();
                }
                else {
                    value.once('update', this._onTextureUpdate, this);
                }
            }
        },
        enumerable: false,
        configurable: true
    });
    return Sprite;
}(Container));


//# sourceMappingURL=sprite.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/text/dist/esm/text.js
/*!
 * @pixi/text - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/text is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */






/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var text_extendStatics = function(d, b) {
    text_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return text_extendStatics(d, b);
};

function text_extends(d, b) {
    text_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * Constants that define the type of gradient on text.
 *
 * @static
 * @constant
 * @name TEXT_GRADIENT
 * @memberof PIXI
 * @type {object}
 * @property {number} LINEAR_VERTICAL Vertical gradient
 * @property {number} LINEAR_HORIZONTAL Linear gradient
 */
var TEXT_GRADIENT;
(function (TEXT_GRADIENT) {
    TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL";
    TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL";
})(TEXT_GRADIENT || (TEXT_GRADIENT = {}));

// disabling eslint for now, going to rewrite this in v5
var defaultStyle = {
    align: 'left',
    breakWords: false,
    dropShadow: false,
    dropShadowAlpha: 1,
    dropShadowAngle: Math.PI / 6,
    dropShadowBlur: 0,
    dropShadowColor: 'black',
    dropShadowDistance: 5,
    fill: 'black',
    fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL,
    fillGradientStops: [],
    fontFamily: 'Arial',
    fontSize: 26,
    fontStyle: 'normal',
    fontVariant: 'normal',
    fontWeight: 'normal',
    letterSpacing: 0,
    lineHeight: 0,
    lineJoin: 'miter',
    miterLimit: 10,
    padding: 0,
    stroke: 'black',
    strokeThickness: 0,
    textBaseline: 'alphabetic',
    trim: false,
    whiteSpace: 'pre',
    wordWrap: false,
    wordWrapWidth: 100,
    leading: 0,
};
var genericFontFamilies = [
    'serif',
    'sans-serif',
    'monospace',
    'cursive',
    'fantasy',
    'system-ui' ];
/**
 * A TextStyle Object contains information to decorate a Text objects.
 *
 * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it.
 *
 * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style).
 *
 * @memberof PIXI
 */
var TextStyle = /** @class */ (function () {
    /**
     * @param {object} [style] - The style parameters
     * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'),
     *  does not affect single line text
     * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it
     *  needs wordWrap to be set to true
     * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text
     * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow
     * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow
     * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius
     * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00'
     * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow
     * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas
     *  fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient
     *  eg ['#000000','#FFFFFF']
     * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
     * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours
     *  to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT}
     * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set
     * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
     * @param {string|string[]} [style.fontFamily='Arial'] - The font family
     * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string,
     *  equivalents are '26px','20pt','160%' or '1.6em')
     * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique')
     * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps')
     * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100',
     *  '200', '300', '400', '500', '600', '700', '800' or '900')
     * @param {number} [style.leading=0] - The space between lines
     * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0
     * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses
     * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve
     *      spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel"
     *      (creates a squared corner).
     * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce
     *      or increase the spikiness of rendered text.
     * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from
     *     happening by adding padding to all sides of the text.
     * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke
     *  e.g 'blue', '#FCFF00'
     * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke.
     *  Default is 0 (no stroke)
     * @param {boolean} [style.trim=false] - Trim transparent borders
     * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered.
     * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal"
     *      (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true
     * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used
     * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true
     */
    function TextStyle(style) {
        this.styleID = 0;
        this.reset();
        deepCopyProperties(this, style, style);
    }
    /**
     * Creates a new TextStyle object with the same values as this one.
     * Note that the only the properties of the object are cloned.
     *
     * @return New cloned TextStyle object
     */
    TextStyle.prototype.clone = function () {
        var clonedProperties = {};
        deepCopyProperties(clonedProperties, this, defaultStyle);
        return new TextStyle(clonedProperties);
    };
    /** Resets all properties to the defaults specified in TextStyle.prototype._default */
    TextStyle.prototype.reset = function () {
        deepCopyProperties(this, defaultStyle, defaultStyle);
    };
    Object.defineProperty(TextStyle.prototype, "align", {
        /**
         * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
         *
         * @member {string}
         */
        get: function () {
            return this._align;
        },
        set: function (align) {
            if (this._align !== align) {
                this._align = align;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "breakWords", {
        /** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */
        get: function () {
            return this._breakWords;
        },
        set: function (breakWords) {
            if (this._breakWords !== breakWords) {
                this._breakWords = breakWords;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "dropShadow", {
        /** Set a drop shadow for the text. */
        get: function () {
            return this._dropShadow;
        },
        set: function (dropShadow) {
            if (this._dropShadow !== dropShadow) {
                this._dropShadow = dropShadow;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", {
        /** Set alpha for the drop shadow. */
        get: function () {
            return this._dropShadowAlpha;
        },
        set: function (dropShadowAlpha) {
            if (this._dropShadowAlpha !== dropShadowAlpha) {
                this._dropShadowAlpha = dropShadowAlpha;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "dropShadowAngle", {
        /** Set a angle of the drop shadow. */
        get: function () {
            return this._dropShadowAngle;
        },
        set: function (dropShadowAngle) {
            if (this._dropShadowAngle !== dropShadowAngle) {
                this._dropShadowAngle = dropShadowAngle;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "dropShadowBlur", {
        /** Set a shadow blur radius. */
        get: function () {
            return this._dropShadowBlur;
        },
        set: function (dropShadowBlur) {
            if (this._dropShadowBlur !== dropShadowBlur) {
                this._dropShadowBlur = dropShadowBlur;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "dropShadowColor", {
        /** A fill style to be used on the dropshadow e.g 'red', '#00FF00'. */
        get: function () {
            return this._dropShadowColor;
        },
        set: function (dropShadowColor) {
            var outputColor = getColor(dropShadowColor);
            if (this._dropShadowColor !== outputColor) {
                this._dropShadowColor = outputColor;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "dropShadowDistance", {
        /** Set a distance of the drop shadow. */
        get: function () {
            return this._dropShadowDistance;
        },
        set: function (dropShadowDistance) {
            if (this._dropShadowDistance !== dropShadowDistance) {
                this._dropShadowDistance = dropShadowDistance;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fill", {
        /**
         * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'.
         *
         * Can be an array to create a gradient eg ['#000000','#FFFFFF']
         * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
         *
         * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern}
         */
        get: function () {
            return this._fill;
        },
        set: function (fill) {
            // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
            //       the setter converts to string. See this thread for more details:
            //       https://github.com/microsoft/TypeScript/issues/2521
            // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in
            //       without casting here.
            var outputColor = getColor(fill);
            if (this._fill !== outputColor) {
                this._fill = outputColor;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fillGradientType", {
        /**
         * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient.
         *
         * @see PIXI.TEXT_GRADIENT
         */
        get: function () {
            return this._fillGradientType;
        },
        set: function (fillGradientType) {
            if (this._fillGradientType !== fillGradientType) {
                this._fillGradientType = fillGradientType;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fillGradientStops", {
        /**
         * If fill is an array of colours to create a gradient, this array can set the stop points
         * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
         */
        get: function () {
            return this._fillGradientStops;
        },
        set: function (fillGradientStops) {
            if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) {
                this._fillGradientStops = fillGradientStops;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fontFamily", {
        /** The font family. */
        get: function () {
            return this._fontFamily;
        },
        set: function (fontFamily) {
            if (this.fontFamily !== fontFamily) {
                this._fontFamily = fontFamily;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fontSize", {
        /**
         * The font size
         * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em')
         */
        get: function () {
            return this._fontSize;
        },
        set: function (fontSize) {
            if (this._fontSize !== fontSize) {
                this._fontSize = fontSize;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fontStyle", {
        /**
         * The font style
         * ('normal', 'italic' or 'oblique')
         *
         * @member {string}
         */
        get: function () {
            return this._fontStyle;
        },
        set: function (fontStyle) {
            if (this._fontStyle !== fontStyle) {
                this._fontStyle = fontStyle;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fontVariant", {
        /**
         * The font variant
         * ('normal' or 'small-caps')
         *
         * @member {string}
         */
        get: function () {
            return this._fontVariant;
        },
        set: function (fontVariant) {
            if (this._fontVariant !== fontVariant) {
                this._fontVariant = fontVariant;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "fontWeight", {
        /**
         * The font weight
         * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900')
         *
         * @member {string}
         */
        get: function () {
            return this._fontWeight;
        },
        set: function (fontWeight) {
            if (this._fontWeight !== fontWeight) {
                this._fontWeight = fontWeight;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "letterSpacing", {
        /** The amount of spacing between letters, default is 0. */
        get: function () {
            return this._letterSpacing;
        },
        set: function (letterSpacing) {
            if (this._letterSpacing !== letterSpacing) {
                this._letterSpacing = letterSpacing;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "lineHeight", {
        /** The line height, a number that represents the vertical space that a letter uses. */
        get: function () {
            return this._lineHeight;
        },
        set: function (lineHeight) {
            if (this._lineHeight !== lineHeight) {
                this._lineHeight = lineHeight;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "leading", {
        /** The space between lines. */
        get: function () {
            return this._leading;
        },
        set: function (leading) {
            if (this._leading !== leading) {
                this._leading = leading;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "lineJoin", {
        /**
         * The lineJoin property sets the type of corner created, it can resolve spiked text issues.
         * Default is 'miter' (creates a sharp corner).
         *
         * @member {string}
         */
        get: function () {
            return this._lineJoin;
        },
        set: function (lineJoin) {
            if (this._lineJoin !== lineJoin) {
                this._lineJoin = lineJoin;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "miterLimit", {
        /**
         * The miter limit to use when using the 'miter' lineJoin mode.
         *
         * This can reduce or increase the spikiness of rendered text.
         */
        get: function () {
            return this._miterLimit;
        },
        set: function (miterLimit) {
            if (this._miterLimit !== miterLimit) {
                this._miterLimit = miterLimit;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "padding", {
        /**
         * Occasionally some fonts are cropped. Adding some padding will prevent this from happening
         * by adding padding to all sides of the text.
         */
        get: function () {
            return this._padding;
        },
        set: function (padding) {
            if (this._padding !== padding) {
                this._padding = padding;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "stroke", {
        /**
         * A canvas fillstyle that will be used on the text stroke
         * e.g 'blue', '#FCFF00'
         */
        get: function () {
            return this._stroke;
        },
        set: function (stroke) {
            // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
            //       the setter converts to string. See this thread for more details:
            //       https://github.com/microsoft/TypeScript/issues/2521
            var outputColor = getColor(stroke);
            if (this._stroke !== outputColor) {
                this._stroke = outputColor;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "strokeThickness", {
        /**
         * A number that represents the thickness of the stroke.
         *
         * @default 0
         */
        get: function () {
            return this._strokeThickness;
        },
        set: function (strokeThickness) {
            if (this._strokeThickness !== strokeThickness) {
                this._strokeThickness = strokeThickness;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "textBaseline", {
        /**
         * The baseline of the text that is rendered.
         *
         * @member {string}
         */
        get: function () {
            return this._textBaseline;
        },
        set: function (textBaseline) {
            if (this._textBaseline !== textBaseline) {
                this._textBaseline = textBaseline;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "trim", {
        /** Trim transparent borders. */
        get: function () {
            return this._trim;
        },
        set: function (trim) {
            if (this._trim !== trim) {
                this._trim = trim;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "whiteSpace", {
        /**
         * How newlines and spaces should be handled.
         * Default is 'pre' (preserve, preserve).
         *
         *  value       | New lines     |   Spaces
         *  ---         | ---           |   ---
         * 'normal'     | Collapse      |   Collapse
         * 'pre'        | Preserve      |   Preserve
         * 'pre-line'   | Preserve      |   Collapse
         *
         * @member {string}
         */
        get: function () {
            return this._whiteSpace;
        },
        set: function (whiteSpace) {
            if (this._whiteSpace !== whiteSpace) {
                this._whiteSpace = whiteSpace;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "wordWrap", {
        /** Indicates if word wrap should be used. */
        get: function () {
            return this._wordWrap;
        },
        set: function (wordWrap) {
            if (this._wordWrap !== wordWrap) {
                this._wordWrap = wordWrap;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextStyle.prototype, "wordWrapWidth", {
        /** The width at which text will wrap, it needs wordWrap to be set to true. */
        get: function () {
            return this._wordWrapWidth;
        },
        set: function (wordWrapWidth) {
            if (this._wordWrapWidth !== wordWrapWidth) {
                this._wordWrapWidth = wordWrapWidth;
                this.styleID++;
            }
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Generates a font style string to use for `TextMetrics.measureFont()`.
     *
     * @return Font style string, for passing to `TextMetrics.measureFont()`
     */
    TextStyle.prototype.toFontString = function () {
        // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
        var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize;
        // Clean-up fontFamily property by quoting each font name
        // this will support font names with spaces
        var fontFamilies = this.fontFamily;
        if (!Array.isArray(this.fontFamily)) {
            fontFamilies = this.fontFamily.split(',');
        }
        for (var i = fontFamilies.length - 1; i >= 0; i--) {
            // Trim any extra white-space
            var fontFamily = fontFamilies[i].trim();
            // Check if font already contains strings
            if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) {
                fontFamily = "\"" + fontFamily + "\"";
            }
            fontFamilies[i] = fontFamily;
        }
        return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(',');
    };
    return TextStyle;
}());
/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 * @private
 * @param color
 * @return The color as a string.
 */
function getSingleColor(color) {
    if (typeof color === 'number') {
        return hex2string(color);
    }
    else if (typeof color === 'string') {
        if (color.indexOf('0x') === 0) {
            color = color.replace('0x', '#');
        }
    }
    return color;
}
function getColor(color) {
    if (!Array.isArray(color)) {
        return getSingleColor(color);
    }
    else {
        for (var i = 0; i < color.length; ++i) {
            color[i] = getSingleColor(color[i]);
        }
        return color;
    }
}
/**
 * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
 * This version can also convert array of colors
 * @private
 * @param array1 - First array to compare
 * @param array2 - Second array to compare
 * @return Do the arrays contain the same values in the same order
 */
function areArraysEqual(array1, array2) {
    if (!Array.isArray(array1) || !Array.isArray(array2)) {
        return false;
    }
    if (array1.length !== array2.length) {
        return false;
    }
    for (var i = 0; i < array1.length; ++i) {
        if (array1[i] !== array2[i]) {
            return false;
        }
    }
    return true;
}
/**
 * Utility function to ensure that object properties are copied by value, and not by reference
 * @private
 * @param target - Target object to copy properties into
 * @param source - Source object for the properties to copy
 * @param propertyObj - Object containing properties names we want to loop over
 */
function deepCopyProperties(target, source, propertyObj) {
    for (var prop in propertyObj) {
        if (Array.isArray(source[prop])) {
            target[prop] = source[prop].slice();
        }
        else {
            target[prop] = source[prop];
        }
    }
}

/**
 * The TextMetrics object represents the measurement of a block of text with a specified style.
 *
 * ```js
 * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'})
 * let textMetrics = PIXI.TextMetrics.measureText('Your text', style)
 * ```
 *
 * @memberof PIXI
 */
var TextMetrics = /** @class */ (function () {
    /**
     * @param text - the text that was measured
     * @param style - the style that was measured
     * @param width - the measured width of the text
     * @param height - the measured height of the text
     * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style
     * @param lineWidths - an array of the line widths for each line matched to `lines`
     * @param lineHeight - the measured line height for this style
     * @param maxLineWidth - the maximum line width for all measured lines
     * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont
     */
    function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) {
        this.text = text;
        this.style = style;
        this.width = width;
        this.height = height;
        this.lines = lines;
        this.lineWidths = lineWidths;
        this.lineHeight = lineHeight;
        this.maxLineWidth = maxLineWidth;
        this.fontProperties = fontProperties;
    }
    /**
     * Measures the supplied string of text and returns a Rectangle.
     *
     * @param text - The text to measure.
     * @param style - The text style to use for measuring
     * @param wordWrap - Override for if word-wrap should be applied to the text.
     * @param canvas - optional specification of the canvas to use for measuring.
     * @return Measured width and height of the text.
     */
    TextMetrics.measureText = function (text, style, wordWrap, canvas) {
        if (canvas === void 0) { canvas = TextMetrics._canvas; }
        wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap;
        var font = style.toFontString();
        var fontProperties = TextMetrics.measureFont(font);
        // fallback in case UA disallow canvas data extraction
        // (toDataURI, getImageData functions)
        if (fontProperties.fontSize === 0) {
            fontProperties.fontSize = style.fontSize;
            fontProperties.ascent = style.fontSize;
        }
        var context = canvas.getContext('2d');
        context.font = font;
        var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text;
        var lines = outputText.split(/(?:\r\n|\r|\n)/);
        var lineWidths = new Array(lines.length);
        var maxLineWidth = 0;
        for (var i = 0; i < lines.length; i++) {
            var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing);
            lineWidths[i] = lineWidth;
            maxLineWidth = Math.max(maxLineWidth, lineWidth);
        }
        var width = maxLineWidth + style.strokeThickness;
        if (style.dropShadow) {
            width += style.dropShadowDistance;
        }
        var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness;
        var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness)
            + ((lines.length - 1) * (lineHeight + style.leading));
        if (style.dropShadow) {
            height += style.dropShadowDistance;
        }
        return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties);
    };
    /**
     * Applies newlines to a string to have it optimally fit into the horizontal
     * bounds set by the Text object's wordWrapWidth property.
     *
     * @param text - String to apply word wrapping to
     * @param style - the style to use when wrapping
     * @param canvas - optional specification of the canvas to use for measuring.
     * @return New string with new lines applied where required
     */
    TextMetrics.wordWrap = function (text, style, canvas) {
        if (canvas === void 0) { canvas = TextMetrics._canvas; }
        var context = canvas.getContext('2d');
        var width = 0;
        var line = '';
        var lines = '';
        var cache = Object.create(null);
        var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace;
        // How to handle whitespaces
        var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace);
        var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace);
        // whether or not spaces may be added to the beginning of lines
        var canPrependSpaces = !collapseSpaces;
        // There is letterSpacing after every char except the last one
        // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!
        // so for convenience the above needs to be compared to width + 1 extra letterSpace
        // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_
        // ________________________________________________
        // And then the final space is simply no appended to each line
        var wordWrapWidth = style.wordWrapWidth + letterSpacing;
        // break text into words, spaces and newline chars
        var tokens = TextMetrics.tokenize(text);
        for (var i = 0; i < tokens.length; i++) {
            // get the word, space or newlineChar
            var token = tokens[i];
            // if word is a new line
            if (TextMetrics.isNewline(token)) {
                // keep the new line
                if (!collapseNewlines) {
                    lines += TextMetrics.addLine(line);
                    canPrependSpaces = !collapseSpaces;
                    line = '';
                    width = 0;
                    continue;
                }
                // if we should collapse new lines
                // we simply convert it into a space
                token = ' ';
            }
            // if we should collapse repeated whitespaces
            if (collapseSpaces) {
                // check both this and the last tokens for spaces
                var currIsBreakingSpace = TextMetrics.isBreakingSpace(token);
                var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]);
                if (currIsBreakingSpace && lastIsBreakingSpace) {
                    continue;
                }
            }
            // get word width from cache if possible
            var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context);
            // word is longer than desired bounds
            if (tokenWidth > wordWrapWidth) {
                // if we are not already at the beginning of a line
                if (line !== '') {
                    // start newlines for overflow words
                    lines += TextMetrics.addLine(line);
                    line = '';
                    width = 0;
                }
                // break large word over multiple lines
                if (TextMetrics.canBreakWords(token, style.breakWords)) {
                    // break word into characters
                    var characters = TextMetrics.wordWrapSplit(token);
                    // loop the characters
                    for (var j = 0; j < characters.length; j++) {
                        var char = characters[j];
                        var k = 1;
                        // we are not at the end of the token
                        while (characters[j + k]) {
                            var nextChar = characters[j + k];
                            var lastChar = char[char.length - 1];
                            // should not split chars
                            if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) {
                                // combine chars & move forward one
                                char += nextChar;
                            }
                            else {
                                break;
                            }
                            k++;
                        }
                        j += char.length - 1;
                        var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context);
                        if (characterWidth + width > wordWrapWidth) {
                            lines += TextMetrics.addLine(line);
                            canPrependSpaces = false;
                            line = '';
                            width = 0;
                        }
                        line += char;
                        width += characterWidth;
                    }
                }
                // run word out of the bounds
                else {
                    // if there are words in this line already
                    // finish that line and start a new one
                    if (line.length > 0) {
                        lines += TextMetrics.addLine(line);
                        line = '';
                        width = 0;
                    }
                    var isLastToken = i === tokens.length - 1;
                    // give it its own line if it's not the end
                    lines += TextMetrics.addLine(token, !isLastToken);
                    canPrependSpaces = false;
                    line = '';
                    width = 0;
                }
            }
            // word could fit
            else {
                // word won't fit because of existing words
                // start a new line
                if (tokenWidth + width > wordWrapWidth) {
                    // if its a space we don't want it
                    canPrependSpaces = false;
                    // add a new line
                    lines += TextMetrics.addLine(line);
                    // start a new line
                    line = '';
                    width = 0;
                }
                // don't add spaces to the beginning of lines
                if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) {
                    // add the word to the current line
                    line += token;
                    // update width counter
                    width += tokenWidth;
                }
            }
        }
        lines += TextMetrics.addLine(line, false);
        return lines;
    };
    /**
     * Convienience function for logging each line added during the wordWrap method.
     *
     * @param line    - The line of text to add
     * @param newLine - Add new line character to end
     * @return A formatted line
     */
    TextMetrics.addLine = function (line, newLine) {
        if (newLine === void 0) { newLine = true; }
        line = TextMetrics.trimRight(line);
        line = (newLine) ? line + "\n" : line;
        return line;
    };
    /**
     * Gets & sets the widths of calculated characters in a cache object
     *
     * @param key            - The key
     * @param letterSpacing  - The letter spacing
     * @param cache          - The cache
     * @param context        - The canvas context
     * @return The from cache.
     */
    TextMetrics.getFromCache = function (key, letterSpacing, cache, context) {
        var width = cache[key];
        if (typeof width !== 'number') {
            var spacing = ((key.length) * letterSpacing);
            width = context.measureText(key).width + spacing;
            cache[key] = width;
        }
        return width;
    };
    /**
     * Determines whether we should collapse breaking spaces.
     *
     * @param whiteSpace - The TextStyle property whiteSpace
     * @return Should collapse
     */
    TextMetrics.collapseSpaces = function (whiteSpace) {
        return (whiteSpace === 'normal' || whiteSpace === 'pre-line');
    };
    /**
     * Determines whether we should collapse newLine chars.
     *
     * @param whiteSpace - The white space
     * @return  should collapse
     */
    TextMetrics.collapseNewlines = function (whiteSpace) {
        return (whiteSpace === 'normal');
    };
    /**
     * Trims breaking whitespaces from string.
     *
     * @param  text - The text
     * @return Trimmed string
     */
    TextMetrics.trimRight = function (text) {
        if (typeof text !== 'string') {
            return '';
        }
        for (var i = text.length - 1; i >= 0; i--) {
            var char = text[i];
            if (!TextMetrics.isBreakingSpace(char)) {
                break;
            }
            text = text.slice(0, -1);
        }
        return text;
    };
    /**
     * Determines if char is a newline.
     *
     * @param  char - The character
     * @return True if newline, False otherwise.
     */
    TextMetrics.isNewline = function (char) {
        if (typeof char !== 'string') {
            return false;
        }
        return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0);
    };
    /**
     * Determines if char is a breaking whitespace.
     *
     * It allows one to determine whether char should be a breaking whitespace
     * For example certain characters in CJK langs or numbers.
     * It must return a boolean.
     *
     * @param char     - The character
     * @param [nextChar] - The next character
     * @return True if whitespace, False otherwise.
     */
    TextMetrics.isBreakingSpace = function (char, _nextChar) {
        if (typeof char !== 'string') {
            return false;
        }
        return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0);
    };
    /**
     * Splits a string into words, breaking-spaces and newLine characters
     *
     * @param  text - The text
     * @return  A tokenized array
     */
    TextMetrics.tokenize = function (text) {
        var tokens = [];
        var token = '';
        if (typeof text !== 'string') {
            return tokens;
        }
        for (var i = 0; i < text.length; i++) {
            var char = text[i];
            var nextChar = text[i + 1];
            if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) {
                if (token !== '') {
                    tokens.push(token);
                    token = '';
                }
                tokens.push(char);
                continue;
            }
            token += char;
        }
        if (token !== '') {
            tokens.push(token);
        }
        return tokens;
    };
    /**
     * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
     *
     * It allows one to customise which words should break
     * Examples are if the token is CJK or numbers.
     * It must return a boolean.
     *
     * @param  token       - The token
     * @param  breakWords - The style attr break words
     * @return Whether to break word or not
     */
    TextMetrics.canBreakWords = function (_token, breakWords) {
        return breakWords;
    };
    /**
     * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
     *
     * It allows one to determine whether a pair of characters
     * should be broken by newlines
     * For example certain characters in CJK langs or numbers.
     * It must return a boolean.
     *
     * @param  char        - The character
     * @param  nextChar    - The next character
     * @param  token       - The token/word the characters are from
     * @param  index       - The index in the token of the char
     * @param  breakWords - The style attr break words
     * @return whether to break word or not
     */
    TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) {
        return true;
    };
    /**
     * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
     *
     * It is called when a token (usually a word) has to be split into separate pieces
     * in order to determine the point to break a word.
     * It must return an array of characters.
     *
     * @example
     * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji.
     * TextMetrics.wordWrapSplit = (token) => [...token];
     *
     * @param  token - The token to split
     * @return The characters of the token
     */
    TextMetrics.wordWrapSplit = function (token) {
        return token.split('');
    };
    /**
     * Calculates the ascent, descent and fontSize of a given font-style
     *
     * @param font - String representing the style of the font
     * @return Font properties object
     */
    TextMetrics.measureFont = function (font) {
        // as this method is used for preparing assets, don't recalculate things if we don't need to
        if (TextMetrics._fonts[font]) {
            return TextMetrics._fonts[font];
        }
        var properties = {
            ascent: 0,
            descent: 0,
            fontSize: 0,
        };
        var canvas = TextMetrics._canvas;
        var context = TextMetrics._context;
        context.font = font;
        var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL;
        var width = Math.ceil(context.measureText(metricsString).width);
        var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width);
        var height = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * baseline);
        baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0;
        canvas.width = width;
        canvas.height = height;
        context.fillStyle = '#f00';
        context.fillRect(0, 0, width, height);
        context.font = font;
        context.textBaseline = 'alphabetic';
        context.fillStyle = '#000';
        context.fillText(metricsString, 0, baseline);
        var imagedata = context.getImageData(0, 0, width, height).data;
        var pixels = imagedata.length;
        var line = width * 4;
        var i = 0;
        var idx = 0;
        var stop = false;
        // ascent. scan from top to bottom until we find a non red pixel
        for (i = 0; i < baseline; ++i) {
            for (var j = 0; j < line; j += 4) {
                if (imagedata[idx + j] !== 255) {
                    stop = true;
                    break;
                }
            }
            if (!stop) {
                idx += line;
            }
            else {
                break;
            }
        }
        properties.ascent = baseline - i;
        idx = pixels - line;
        stop = false;
        // descent. scan from bottom to top until we find a non red pixel
        for (i = height; i > baseline; --i) {
            for (var j = 0; j < line; j += 4) {
                if (imagedata[idx + j] !== 255) {
                    stop = true;
                    break;
                }
            }
            if (!stop) {
                idx -= line;
            }
            else {
                break;
            }
        }
        properties.descent = i - baseline;
        properties.fontSize = properties.ascent + properties.descent;
        TextMetrics._fonts[font] = properties;
        return properties;
    };
    /**
     * Clear font metrics in metrics cache.
     *
     * @param {string} [font] - font name. If font name not set then clear cache for all fonts.
     */
    TextMetrics.clearMetrics = function (font) {
        if (font === void 0) { font = ''; }
        if (font) {
            delete TextMetrics._fonts[font];
        }
        else {
            TextMetrics._fonts = {};
        }
    };
    return TextMetrics;
}());
/**
 * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}.
 *
 * @typedef {object} FontMetrics
 * @property {number} ascent - The ascent distance
 * @property {number} descent - The descent distance
 * @property {number} fontSize - Font size from ascent to descent
 * @memberof PIXI.TextMetrics
 * @private
 */
var canvas = (function () {
    try {
        // OffscreenCanvas2D measureText can be up to 40% faster.
        var c = new OffscreenCanvas(0, 0);
        var context = c.getContext('2d');
        if (context && context.measureText) {
            return c;
        }
        return document.createElement('canvas');
    }
    catch (ex) {
        return document.createElement('canvas');
    }
})();
canvas.width = canvas.height = 10;
/**
 * Cached canvas element for measuring text
 *
 * @memberof PIXI.TextMetrics
 * @type {HTMLCanvasElement}
 * @private
 */
TextMetrics._canvas = canvas;
/**
 * Cache for context to use.
 *
 * @memberof PIXI.TextMetrics
 * @type {CanvasRenderingContext2D}
 * @private
 */
TextMetrics._context = canvas.getContext('2d');
/**
 * Cache of {@see PIXI.TextMetrics.FontMetrics} objects.
 *
 * @memberof PIXI.TextMetrics
 * @type {Object}
 * @private
 */
TextMetrics._fonts = {};
/**
 * String used for calculate font metrics.
 * These characters are all tall to help calculate the height required for text.
 *
 * @static
 * @memberof PIXI.TextMetrics
 * @name METRICS_STRING
 * @type {string}
 * @default |ÉqÅ
 */
TextMetrics.METRICS_STRING = '|ÉqÅ';
/**
 * Baseline symbol for calculate font metrics.
 *
 * @static
 * @memberof PIXI.TextMetrics
 * @name BASELINE_SYMBOL
 * @type {string}
 * @default M
 */
TextMetrics.BASELINE_SYMBOL = 'M';
/**
 * Baseline multiplier for calculate font metrics.
 *
 * @static
 * @memberof PIXI.TextMetrics
 * @name BASELINE_MULTIPLIER
 * @type {number}
 * @default 1.4
 */
TextMetrics.BASELINE_MULTIPLIER = 1.4;
/**
 * Height multiplier for setting height of canvas to calculate font metrics.
 *
 * @static
 * @memberof PIXI.TextMetrics
 * @name HEIGHT_MULTIPLIER
 * @type {number}
 * @default 2.00
 */
TextMetrics.HEIGHT_MULTIPLIER = 2.0;
/**
 * Cache of new line chars.
 *
 * @memberof PIXI.TextMetrics
 * @type {number[]}
 * @private
 */
TextMetrics._newlines = [
    0x000A,
    0x000D ];
/**
 * Cache of breaking spaces.
 *
 * @memberof PIXI.TextMetrics
 * @type {number[]}
 * @private
 */
TextMetrics._breakingSpaces = [
    0x0009,
    0x0020,
    0x2000,
    0x2001,
    0x2002,
    0x2003,
    0x2004,
    0x2005,
    0x2006,
    0x2008,
    0x2009,
    0x200A,
    0x205F,
    0x3000 ];
/**
 * A number, or a string containing a number.
 *
 * @memberof PIXI
 * @typedef {object} IFontMetrics
 * @property {number} ascent - Font ascent
 * @property {number} descent - Font descent
 * @property {number} fontSize - Font size
 */

var defaultDestroyOptions = {
    texture: true,
    children: false,
    baseTexture: true,
};
/**
 * A Text Object will create a line or multiple lines of text.
 *
 * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
 *
 * The primary advantage of this class over BitmapText is that you have great control over the style of the text,
 * which you can change at runtime.
 *
 * The primary disadvantages is that each piece of text has it's own texture, which can use more memory.
 * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time.
 *
 * To split a line you can use '\n' in your text string, or, on the `style` object,
 * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value.
 *
 * A Text can be created directly from a string and a style object,
 * which can be generated [here](https://pixijs.io/pixi-text-style).
 *
 * ```js
 * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'});
 * ```
 *
 * @memberof PIXI
 */
var Text = /** @class */ (function (_super) {
    text_extends(Text, _super);
    /**
     * @param text - The string that you would like the text to display
     * @param {object|PIXI.TextStyle} [style] - The style parameters
     * @param canvas - The canvas element for drawing text
     */
    function Text(text, style, canvas) {
        var _this = this;
        var ownCanvas = false;
        if (!canvas) {
            canvas = document.createElement('canvas');
            ownCanvas = true;
        }
        canvas.width = 3;
        canvas.height = 3;
        var texture = Texture.from(canvas);
        texture.orig = new Rectangle();
        texture.trim = new Rectangle();
        _this = _super.call(this, texture) || this;
        _this._ownCanvas = ownCanvas;
        _this.canvas = canvas;
        _this.context = _this.canvas.getContext('2d');
        _this._resolution = settings.RESOLUTION;
        _this._autoResolution = true;
        _this._text = null;
        _this._style = null;
        _this._styleListener = null;
        _this._font = '';
        _this.text = text;
        _this.style = style;
        _this.localStyleID = -1;
        return _this;
    }
    /**
     * Renders text to its canvas, and updates its texture.
     *
     * By default this is used internally to ensure the texture is correct before rendering,
     * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text,
     * and then shared across multiple Sprites.
     *
     * @param respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called.
     */
    Text.prototype.updateText = function (respectDirty) {
        var style = this._style;
        // check if style has changed..
        if (this.localStyleID !== style.styleID) {
            this.dirty = true;
            this.localStyleID = style.styleID;
        }
        if (!this.dirty && respectDirty) {
            return;
        }
        this._font = this._style.toFontString();
        var context = this.context;
        var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas);
        var width = measured.width;
        var height = measured.height;
        var lines = measured.lines;
        var lineHeight = measured.lineHeight;
        var lineWidths = measured.lineWidths;
        var maxLineWidth = measured.maxLineWidth;
        var fontProperties = measured.fontProperties;
        this.canvas.width = Math.ceil(Math.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution);
        this.canvas.height = Math.ceil(Math.ceil((Math.max(1, height) + (style.padding * 2))) * this._resolution);
        context.scale(this._resolution, this._resolution);
        context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        context.font = this._font;
        context.lineWidth = style.strokeThickness;
        context.textBaseline = style.textBaseline;
        context.lineJoin = style.lineJoin;
        context.miterLimit = style.miterLimit;
        var linePositionX;
        var linePositionY;
        // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text
        var passesCount = style.dropShadow ? 2 : 1;
        // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex,
        // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow.
        //
        // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more
        // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill
        // and the stroke; and fill drop shadows would appear over the top of the stroke.
        //
        // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal
        // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the
        // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow
        // beneath the text, whilst also having the proper text shadow styling.
        for (var i = 0; i < passesCount; ++i) {
            var isShadowPass = style.dropShadow && i === 0;
            // we only want the drop shadow, so put text way off-screen
            var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0;
            var dsOffsetShadow = dsOffsetText * this._resolution;
            if (isShadowPass) {
                // On Safari, text with gradient and drop shadows together do not position correctly
                // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689
                // Therefore we'll set the styles to be a plain black whilst generating this drop shadow
                context.fillStyle = 'black';
                context.strokeStyle = 'black';
                var dropShadowColor = style.dropShadowColor;
                var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
                var dropShadowBlur = style.dropShadowBlur * this._resolution;
                var dropShadowDistance = style.dropShadowDistance * this._resolution;
                context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")";
                context.shadowBlur = dropShadowBlur;
                context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance;
                context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * dropShadowDistance) + dsOffsetShadow;
            }
            else {
                // set canvas text styles
                context.fillStyle = this._generateFillStyle(style, lines, measured);
                // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
                //       the setter converts to string. See this thread for more details:
                //       https://github.com/microsoft/TypeScript/issues/2521
                context.strokeStyle = style.stroke;
                context.shadowColor = 'black';
                context.shadowBlur = 0;
                context.shadowOffsetX = 0;
                context.shadowOffsetY = 0;
            }
            var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2;
            if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) {
                linePositionYShift = 0;
            }
            // draw lines line by line
            for (var i_1 = 0; i_1 < lines.length; i_1++) {
                linePositionX = style.strokeThickness / 2;
                linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent
                    + linePositionYShift;
                if (style.align === 'right') {
                    linePositionX += maxLineWidth - lineWidths[i_1];
                }
                else if (style.align === 'center') {
                    linePositionX += (maxLineWidth - lineWidths[i_1]) / 2;
                }
                if (style.stroke && style.strokeThickness) {
                    this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true);
                }
                if (style.fill) {
                    this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText);
                }
            }
        }
        this.updateTexture();
    };
    /**
     * Render the text with letter-spacing.
     *
     * @param text - The text to draw
     * @param x - Horizontal position to draw the text
     * @param y - Vertical position to draw the text
     * @param isStroke - Is this drawing for the outside stroke of the
     *  text? If not, it's for the inside fill
     */
    Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) {
        if (isStroke === void 0) { isStroke = false; }
        var style = this._style;
        // letterSpacing of 0 means normal
        var letterSpacing = style.letterSpacing;
        // Checking that we can use moddern canvas2D api
        // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441
        // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing
        // eslint-disable-next-line max-len
        var supportLetterSpacing = Text.experimentalLetterSpacing
            && ('letterSpacing' in CanvasRenderingContext2D.prototype
                || 'textLetterSpacing' in CanvasRenderingContext2D.prototype);
        if (letterSpacing === 0 || supportLetterSpacing) {
            if (supportLetterSpacing) {
                this.context.letterSpacing = letterSpacing;
                this.context.textLetterSpacing = letterSpacing;
            }
            if (isStroke) {
                this.context.strokeText(text, x, y);
            }
            else {
                this.context.fillText(text, x, y);
            }
            return;
        }
        var currentPosition = x;
        // Using Array.from correctly splits characters whilst keeping emoji together.
        // This is not supported on IE as it requires ES6, so regular text splitting occurs.
        // This also doesn't account for emoji that are multiple emoji put together to make something else.
        // Handling all of this would require a big library itself.
        // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516
        // https://github.com/orling/grapheme-splitter
        var stringArray = Array.from ? Array.from(text) : text.split('');
        var previousWidth = this.context.measureText(text).width;
        var currentWidth = 0;
        for (var i = 0; i < stringArray.length; ++i) {
            var currentChar = stringArray[i];
            if (isStroke) {
                this.context.strokeText(currentChar, currentPosition, y);
            }
            else {
                this.context.fillText(currentChar, currentPosition, y);
            }
            var textStr = '';
            for (var j = i + 1; j < stringArray.length; ++j) {
                textStr += stringArray[j];
            }
            currentWidth = this.context.measureText(textStr).width;
            currentPosition += previousWidth - currentWidth + letterSpacing;
            previousWidth = currentWidth;
        }
    };
    /** Updates texture size based on canvas size. */
    Text.prototype.updateTexture = function () {
        var canvas = this.canvas;
        if (this._style.trim) {
            var trimmed = trimCanvas(canvas);
            if (trimmed.data) {
                canvas.width = trimmed.width;
                canvas.height = trimmed.height;
                this.context.putImageData(trimmed.data, 0, 0);
            }
        }
        var texture = this._texture;
        var style = this._style;
        var padding = style.trim ? 0 : style.padding;
        var baseTexture = texture.baseTexture;
        texture.trim.width = texture._frame.width = canvas.width / this._resolution;
        texture.trim.height = texture._frame.height = canvas.height / this._resolution;
        texture.trim.x = -padding;
        texture.trim.y = -padding;
        texture.orig.width = texture._frame.width - (padding * 2);
        texture.orig.height = texture._frame.height - (padding * 2);
        // call sprite onTextureUpdate to update scale if _width or _height were set
        this._onTextureUpdate();
        baseTexture.setRealSize(canvas.width, canvas.height, this._resolution);
        texture.updateUvs();
        // Recursively updates transform of all objects from the root to this one
        this._recursivePostUpdateTransform();
        this.dirty = false;
    };
    /**
     * Renders the object using the WebGL renderer
     *
     * @param renderer - The renderer
     */
    Text.prototype._render = function (renderer) {
        if (this._autoResolution && this._resolution !== renderer.resolution) {
            this._resolution = renderer.resolution;
            this.dirty = true;
        }
        this.updateText(true);
        _super.prototype._render.call(this, renderer);
    };
    /**
     * Gets the local bounds of the text object.
     *
     * @param rect - The output rectangle.
     * @return The bounds.
     */
    Text.prototype.getLocalBounds = function (rect) {
        this.updateText(true);
        return _super.prototype.getLocalBounds.call(this, rect);
    };
    /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */
    Text.prototype._calculateBounds = function () {
        this.updateText(true);
        this.calculateVertices();
        // if we have already done this on THIS frame.
        this._bounds.addQuad(this.vertexData);
    };
    /**
     * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
     *
     * @param style - The style.
     * @param lines - The lines of text.
     * @return The fill style
     */
    Text.prototype._generateFillStyle = function (style, lines, metrics) {
        // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
        //       the setter converts to string. See this thread for more details:
        //       https://github.com/microsoft/TypeScript/issues/2521
        var fillStyle = style.fill;
        if (!Array.isArray(fillStyle)) {
            return fillStyle;
        }
        else if (fillStyle.length === 1) {
            return fillStyle[0];
        }
        // the gradient will be evenly spaced out according to how large the array is.
        // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75
        var gradient;
        // a dropshadow will enlarge the canvas and result in the gradient being
        // generated with the incorrect dimensions
        var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0;
        // should also take padding into account, padding can offset the gradient
        var padding = style.padding || 0;
        var width = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2);
        var height = (this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2);
        // make a copy of the style settings, so we can manipulate them later
        var fill = fillStyle.slice();
        var fillGradientStops = style.fillGradientStops.slice();
        // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75
        if (!fillGradientStops.length) {
            var lengthPlus1 = fill.length + 1;
            for (var i = 1; i < lengthPlus1; ++i) {
                fillGradientStops.push(i / lengthPlus1);
            }
        }
        // stop the bleeding of the last gradient on the line above to the top gradient of the this line
        // by hard defining the first gradient colour at point 0, and last gradient colour at point 1
        fill.unshift(fillStyle[0]);
        fillGradientStops.unshift(0);
        fill.push(fillStyle[fillStyle.length - 1]);
        fillGradientStops.push(1);
        if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) {
            // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas
            gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding);
            // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect
            // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875
            // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc
            var textHeight = metrics.fontProperties.fontSize + style.strokeThickness;
            for (var i = 0; i < lines.length; i++) {
                var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight;
                var thisLineTop = metrics.lineHeight * i;
                var thisLineGradientStart = thisLineTop;
                // Handle case where last & this line overlap
                if (i > 0 && lastLineBottom > thisLineTop) {
                    thisLineGradientStart = (thisLineTop + lastLineBottom) / 2;
                }
                var thisLineBottom = thisLineTop + textHeight;
                var nextLineTop = metrics.lineHeight * (i + 1);
                var thisLineGradientEnd = thisLineBottom;
                // Handle case where this & next line overlap
                if (i + 1 < lines.length && nextLineTop < thisLineBottom) {
                    thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2;
                }
                // textHeight, but as a 0-1 size in global gradient stop space
                var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height;
                for (var j = 0; j < fill.length; j++) {
                    // 0-1 stop point for the current line, multiplied to global space afterwards
                    var lineStop = 0;
                    if (typeof fillGradientStops[j] === 'number') {
                        lineStop = fillGradientStops[j];
                    }
                    else {
                        lineStop = j / fill.length;
                    }
                    var globalStop = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight)));
                    // There's potential for floating point precision issues at the seams between gradient repeats.
                    globalStop = Number(globalStop.toFixed(5));
                    gradient.addColorStop(globalStop, fill[j]);
                }
            }
        }
        else {
            // start the gradient at the center left of the canvas, and end at the center right of the canvas
            gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2);
            // can just evenly space out the gradients in this case, as multiple lines makes no difference
            // to an even left to right gradient
            var totalIterations = fill.length + 1;
            var currentIteration = 1;
            for (var i = 0; i < fill.length; i++) {
                var stop = void 0;
                if (typeof fillGradientStops[i] === 'number') {
                    stop = fillGradientStops[i];
                }
                else {
                    stop = currentIteration / totalIterations;
                }
                gradient.addColorStop(stop, fill[i]);
                currentIteration++;
            }
        }
        return gradient;
    };
    /**
     * Destroys this text object.
     *
     * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as
     * the majority of the time the texture will not be shared with any other Sprites.
     *
     * @param options - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their
     *  destroy method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well
     * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well
     */
    Text.prototype.destroy = function (options) {
        if (typeof options === 'boolean') {
            options = { children: options };
        }
        options = Object.assign({}, defaultDestroyOptions, options);
        _super.prototype.destroy.call(this, options);
        // set canvas width and height to 0 to workaround memory leak in Safari < 13
        // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12
        if (this._ownCanvas) {
            this.canvas.height = this.canvas.width = 0;
        }
        // make sure to reset the context and canvas.. dont want this hanging around in memory!
        this.context = null;
        this.canvas = null;
        this._style = null;
    };
    Object.defineProperty(Text.prototype, "width", {
        /** The width of the Text, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            this.updateText(true);
            return Math.abs(this.scale.x) * this._texture.orig.width;
        },
        set: function (value) {
            this.updateText(true);
            var s = sign(this.scale.x) || 1;
            this.scale.x = s * value / this._texture.orig.width;
            this._width = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Text.prototype, "height", {
        /** The height of the Text, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            this.updateText(true);
            return Math.abs(this.scale.y) * this._texture.orig.height;
        },
        set: function (value) {
            this.updateText(true);
            var s = sign(this.scale.y) || 1;
            this.scale.y = s * value / this._texture.orig.height;
            this._height = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Text.prototype, "style", {
        /**
         * Set the style of the text.
         *
         * Set up an event listener to listen for changes on the style object and mark the text as dirty.
         */
        get: function () {
            // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle
            //       since the setter creates the TextStyle. See this thread for more details:
            //       https://github.com/microsoft/TypeScript/issues/2521
            return this._style;
        },
        set: function (style) {
            style = style || {};
            if (style instanceof TextStyle) {
                this._style = style;
            }
            else {
                this._style = new TextStyle(style);
            }
            this.localStyleID = -1;
            this.dirty = true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Text.prototype, "text", {
        /** Set the copy for the text object. To split a line you can use '\n'. */
        get: function () {
            return this._text;
        },
        set: function (text) {
            text = String(text === null || text === undefined ? '' : text);
            if (this._text === text) {
                return;
            }
            this._text = text;
            this.dirty = true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Text.prototype, "resolution", {
        /**
         * The resolution / device pixel ratio of the canvas.
         *
         * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually.
         *
         * @default 1
         */
        get: function () {
            return this._resolution;
        },
        set: function (value) {
            this._autoResolution = false;
            if (this._resolution === value) {
                return;
            }
            this._resolution = value;
            this.dirty = true;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will
     * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`.
     * A value of `false` will use the legacy behavior and not change the baseline of the first line.
     * In the next major release, we'll enable this by default.
     */
    Text.nextLineHeightBehavior = false;
    /**
     * New rendering behavior for letter-spacing which uses Chrome's new native API. This will
     * lead to more accurate letter-spacing results because it does not try to manually draw
     * each character. However, this Chrome API is experimental and may not serve all cases yet.
     */
    Text.experimentalLetterSpacing = false;
    return Text;
}(Sprite));


//# sourceMappingURL=text.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/prepare/dist/esm/prepare.js
/*!
 * @pixi/prepare - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/prepare is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */







/**
 * Default number of uploads per frame using prepare plugin.
 *
 * @static
 * @memberof PIXI.settings
 * @name UPLOADS_PER_FRAME
 * @type {number}
 * @default 4
 */
settings.UPLOADS_PER_FRAME = 4;

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var prepare_extendStatics = function(d, b) {
    prepare_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return prepare_extendStatics(d, b);
};

function prepare_extends(d, b) {
    prepare_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
 * number of items per frame.
 *
 * @memberof PIXI
 */
var CountLimiter = /** @class */ (function () {
    /**
     * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame.
     */
    function CountLimiter(maxItemsPerFrame) {
        this.maxItemsPerFrame = maxItemsPerFrame;
        this.itemsLeft = 0;
    }
    /** Resets any counting properties to start fresh on a new frame. */
    CountLimiter.prototype.beginFrame = function () {
        this.itemsLeft = this.maxItemsPerFrame;
    };
    /**
     * Checks to see if another item can be uploaded. This should only be called once per item.
     *
     * @return If the item is allowed to be uploaded.
     */
    CountLimiter.prototype.allowedToUpload = function () {
        return this.itemsLeft-- > 0;
    };
    return CountLimiter;
}());

/**
 * Built-in hook to find multiple textures from objects like AnimatedSprites.
 *
 * @private
 * @param item - Display object to check
 * @param queue - Collection of items to upload
 * @return If a PIXI.Texture object was found.
 */
function findMultipleBaseTextures(item, queue) {
    var result = false;
    // Objects with multiple textures
    if (item && item._textures && item._textures.length) {
        for (var i = 0; i < item._textures.length; i++) {
            if (item._textures[i] instanceof Texture) {
                var baseTexture = item._textures[i].baseTexture;
                if (queue.indexOf(baseTexture) === -1) {
                    queue.push(baseTexture);
                    result = true;
                }
            }
        }
    }
    return result;
}
/**
 * Built-in hook to find BaseTextures from Texture.
 *
 * @private
 * @param item - Display object to check
 * @param queue - Collection of items to upload
 * @return If a PIXI.Texture object was found.
 */
function findBaseTexture(item, queue) {
    if (item.baseTexture instanceof BaseTexture) {
        var texture = item.baseTexture;
        if (queue.indexOf(texture) === -1) {
            queue.push(texture);
        }
        return true;
    }
    return false;
}
/**
 * Built-in hook to find textures from objects.
 *
 * @private
 * @param item - Display object to check
 * @param queue - Collection of items to upload
 * @return If a PIXI.Texture object was found.
 */
function findTexture(item, queue) {
    if (item._texture && item._texture instanceof Texture) {
        var texture = item._texture.baseTexture;
        if (queue.indexOf(texture) === -1) {
            queue.push(texture);
        }
        return true;
    }
    return false;
}
/**
 * Built-in hook to draw PIXI.Text to its texture.
 *
 * @private
 * @param helper - Not used by this upload handler
 * @param item - Item to check
 * @return If item was uploaded.
 */
function drawText(_helper, item) {
    if (item instanceof Text) {
        // updating text will return early if it is not dirty
        item.updateText(true);
        return true;
    }
    return false;
}
/**
 * Built-in hook to calculate a text style for a PIXI.Text object.
 *
 * @private
 * @param helper - Not used by this upload handler
 * @param item - Item to check
 * @return If item was uploaded.
 */
function calculateTextStyle(_helper, item) {
    if (item instanceof TextStyle) {
        var font = item.toFontString();
        TextMetrics.measureFont(font);
        return true;
    }
    return false;
}
/**
 * Built-in hook to find Text objects.
 *
 * @private
 * @param item - Display object to check
 * @param queue - Collection of items to upload
 * @return if a PIXI.Text object was found.
 */
function findText(item, queue) {
    if (item instanceof Text) {
        // push the text style to prepare it - this can be really expensive
        if (queue.indexOf(item.style) === -1) {
            queue.push(item.style);
        }
        // also push the text object so that we can render it (to canvas/texture) if needed
        if (queue.indexOf(item) === -1) {
            queue.push(item);
        }
        // also push the Text's texture for upload to GPU
        var texture = item._texture.baseTexture;
        if (queue.indexOf(texture) === -1) {
            queue.push(texture);
        }
        return true;
    }
    return false;
}
/**
 * Built-in hook to find TextStyle objects.
 *
 * @private
 * @param item - Display object to check
 * @param queue - Collection of items to upload
 * @return If a PIXI.TextStyle object was found.
 */
function findTextStyle(item, queue) {
    if (item instanceof TextStyle) {
        if (queue.indexOf(item) === -1) {
            queue.push(item);
        }
        return true;
    }
    return false;
}
/**
 * The prepare manager provides functionality to upload content to the GPU.
 *
 * BasePrepare handles basic queuing functionality and is extended by
 * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare}
 * to provide preparation capabilities specific to their respective renderers.
 *
 * @example
 * // Create a sprite
 * const sprite = PIXI.Sprite.from('something.png');
 *
 * // Load object into GPU
 * app.renderer.plugins.prepare.upload(sprite, () => {
 *
 *     //Texture(s) has been uploaded to GPU
 *     app.stage.addChild(sprite);
 *
 * })
 *
 * @abstract
 * @memberof PIXI
 */
var BasePrepare = /** @class */ (function () {
    /**
     * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer
     */
    function BasePrepare(renderer) {
        var _this = this;
        this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME);
        this.renderer = renderer;
        this.uploadHookHelper = null;
        this.queue = [];
        this.addHooks = [];
        this.uploadHooks = [];
        this.completes = [];
        this.ticking = false;
        this.delayedTick = function () {
            // unlikely, but in case we were destroyed between tick() and delayedTick()
            if (!_this.queue) {
                return;
            }
            _this.prepareItems();
        };
        // hooks to find the correct texture
        this.registerFindHook(findText);
        this.registerFindHook(findTextStyle);
        this.registerFindHook(findMultipleBaseTextures);
        this.registerFindHook(findBaseTexture);
        this.registerFindHook(findTexture);
        // upload hooks
        this.registerUploadHook(drawText);
        this.registerUploadHook(calculateTextStyle);
    }
    /**
     * Upload all the textures and graphics to the GPU.
     *
     * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item -
     *        Either the container or display object to search for items to upload, the items to upload themselves,
     *        or the callback function, if items have been added using `prepare.add`.
     * @param {Function} [done] - Optional callback when all queued uploads have completed
     */
    BasePrepare.prototype.upload = function (item, done) {
        if (typeof item === 'function') {
            done = item;
            item = null;
        }
        // If a display object, search for items
        // that we could upload
        if (item) {
            this.add(item);
        }
        // Get the items for upload from the display
        if (this.queue.length) {
            if (done) {
                this.completes.push(done);
            }
            if (!this.ticking) {
                this.ticking = true;
                Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY);
            }
        }
        else if (done) {
            done();
        }
    };
    /**
     * Handle tick update
     *
     * @private
     */
    BasePrepare.prototype.tick = function () {
        setTimeout(this.delayedTick, 0);
    };
    /**
     * Actually prepare items. This is handled outside of the tick because it will take a while
     * and we do NOT want to block the current animation frame from rendering.
     *
     * @private
     */
    BasePrepare.prototype.prepareItems = function () {
        this.limiter.beginFrame();
        // Upload the graphics
        while (this.queue.length && this.limiter.allowedToUpload()) {
            var item = this.queue[0];
            var uploaded = false;
            if (item && !item._destroyed) {
                for (var i = 0, len = this.uploadHooks.length; i < len; i++) {
                    if (this.uploadHooks[i](this.uploadHookHelper, item)) {
                        this.queue.shift();
                        uploaded = true;
                        break;
                    }
                }
            }
            if (!uploaded) {
                this.queue.shift();
            }
        }
        // We're finished
        if (!this.queue.length) {
            this.ticking = false;
            var completes = this.completes.slice(0);
            this.completes.length = 0;
            for (var i = 0, len = completes.length; i < len; i++) {
                completes[i]();
            }
        }
        else {
            // if we are not finished, on the next rAF do this again
            Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY);
        }
    };
    /**
     * Adds hooks for finding items.
     *
     * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array`
     *          function must return `true` if it was able to add item to the queue.
     * @return Instance of plugin for chaining.
     */
    BasePrepare.prototype.registerFindHook = function (addHook) {
        if (addHook) {
            this.addHooks.push(addHook);
        }
        return this;
    };
    /**
     * Adds hooks for uploading items.
     *
     * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and
     *          function must return `true` if it was able to handle upload of item.
     * @return Instance of plugin for chaining.
     */
    BasePrepare.prototype.registerUploadHook = function (uploadHook) {
        if (uploadHook) {
            this.uploadHooks.push(uploadHook);
        }
        return this;
    };
    /**
     * Manually add an item to the uploading queue.
     *
     * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to
     *        add to the queue
     * @return Instance of plugin for chaining.
     */
    BasePrepare.prototype.add = function (item) {
        // Add additional hooks for finding elements on special
        // types of objects that
        for (var i = 0, len = this.addHooks.length; i < len; i++) {
            if (this.addHooks[i](item, this.queue)) {
                break;
            }
        }
        // Get children recursively
        if (item instanceof Container) {
            for (var i = item.children.length - 1; i >= 0; i--) {
                this.add(item.children[i]);
            }
        }
        return this;
    };
    /** Destroys the plugin, don't use after this. */
    BasePrepare.prototype.destroy = function () {
        if (this.ticking) {
            Ticker.system.remove(this.tick, this);
        }
        this.ticking = false;
        this.addHooks = null;
        this.uploadHooks = null;
        this.renderer = null;
        this.completes = null;
        this.queue = null;
        this.limiter = null;
        this.uploadHookHelper = null;
    };
    return BasePrepare;
}());

/**
 * Built-in hook to upload PIXI.Texture objects to the GPU.
 *
 * @private
 * @param renderer - instance of the webgl renderer
 * @param item - Item to check
 * @return If item was uploaded.
 */
function uploadBaseTextures(renderer, item) {
    if (item instanceof BaseTexture) {
        // if the texture already has a GL texture, then the texture has been prepared or rendered
        // before now. If the texture changed, then the changer should be calling texture.update() which
        // reuploads the texture without need for preparing it again
        if (!item._glTextures[renderer.CONTEXT_UID]) {
            renderer.texture.bind(item);
        }
        return true;
    }
    return false;
}
/**
 * Built-in hook to upload PIXI.Graphics to the GPU.
 *
 * @private
 * @param renderer - instance of the webgl renderer
 * @param item - Item to check
 * @return If item was uploaded.
 */
function uploadGraphics(renderer, item) {
    if (!(item instanceof Graphics)) {
        return false;
    }
    var geometry = item.geometry;
    // update dirty graphics to get batches
    item.finishPoly();
    geometry.updateBatches();
    var batches = geometry.batches;
    // upload all textures found in styles
    for (var i = 0; i < batches.length; i++) {
        var texture = batches[i].style.texture;
        if (texture) {
            uploadBaseTextures(renderer, texture.baseTexture);
        }
    }
    // if its not batchable - update vao for particular shader
    if (!geometry.batchable) {
        renderer.geometry.bind(geometry, item._resolveDirectShader(renderer));
    }
    return true;
}
/**
 * Built-in hook to find graphics.
 *
 * @private
 * @param item - Display object to check
 * @param queue - Collection of items to upload
 * @return if a PIXI.Graphics object was found.
 */
function findGraphics(item, queue) {
    if (item instanceof Graphics) {
        queue.push(item);
        return true;
    }
    return false;
}
/**
 * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for
 * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed.
 *
 * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property.
 * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}.
 * @example
 * // Create a new application
 * const app = new PIXI.Application();
 * document.body.appendChild(app.view);
 *
 * // Don't start rendering right away
 * app.stop();
 *
 * // create a display object
 * const rect = new PIXI.Graphics()
 *     .beginFill(0x00ff00)
 *     .drawRect(40, 40, 200, 200);
 *
 * // Add to the stage
 * app.stage.addChild(rect);
 *
 * // Don't start rendering until the graphic is uploaded to the GPU
 * app.renderer.plugins.prepare.upload(app.stage, () => {
 *     app.start();
 * });
 *
 *
 * @memberof PIXI
 */
var Prepare = /** @class */ (function (_super) {
    prepare_extends(Prepare, _super);
    /**
     * @param {PIXI.Renderer} renderer - A reference to the current renderer
     */
    function Prepare(renderer) {
        var _this = _super.call(this, renderer) || this;
        _this.uploadHookHelper = _this.renderer;
        // Add textures and graphics to upload
        _this.registerFindHook(findGraphics);
        _this.registerUploadHook(uploadBaseTextures);
        _this.registerUploadHook(uploadGraphics);
        return _this;
    }
    return Prepare;
}(BasePrepare));

/**
 * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
 * number of milliseconds per frame.
 *
 * @memberof PIXI
 */
var TimeLimiter = /** @class */ (function () {
    /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */
    function TimeLimiter(maxMilliseconds) {
        this.maxMilliseconds = maxMilliseconds;
        this.frameStart = 0;
    }
    /** Resets any counting properties to start fresh on a new frame. */
    TimeLimiter.prototype.beginFrame = function () {
        this.frameStart = Date.now();
    };
    /**
     * Checks to see if another item can be uploaded. This should only be called once per item.
     *
     * @return - If the item is allowed to be uploaded.
     */
    TimeLimiter.prototype.allowedToUpload = function () {
        return Date.now() - this.frameStart < this.maxMilliseconds;
    };
    return TimeLimiter;
}());


//# sourceMappingURL=prepare.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/spritesheet/dist/esm/spritesheet.js
/*!
 * @pixi/spritesheet - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/spritesheet is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */





/**
 * Utility class for maintaining reference to a collection
 * of Textures on a single Spritesheet.
 *
 * To access a sprite sheet from your code pass its JSON data file to Pixi's loader:
 *
 * ```js
 * PIXI.Loader.shared.add("images/spritesheet.json").load(setup);
 *
 * function setup() {
 *   let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet;
 *   ...
 * }
 * ```
 * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite.
 *
 * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker},
 * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}.
 * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only
 * supported by TexturePacker.
 *
 * @memberof PIXI
 */
var Spritesheet = /** @class */ (function () {
    /**
     * @param baseTexture - Reference to the source BaseTexture object.
     * @param {Object} data - Spritesheet image data.
     * @param resolutionFilename - The filename to consider when determining
     *        the resolution of the spritesheet. If not provided, the imageUrl will
     *        be used on the BaseTexture.
     */
    function Spritesheet(texture, data, resolutionFilename) {
        if (resolutionFilename === void 0) { resolutionFilename = null; }
        this._texture = texture instanceof Texture ? texture : null;
        this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture;
        this.textures = {};
        this.animations = {};
        this.data = data;
        var resource = this.baseTexture.resource;
        this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null));
        this._frames = this.data.frames;
        this._frameKeys = Object.keys(this._frames);
        this._batchIndex = 0;
        this._callback = null;
    }
    /**
     * Generate the resolution from the filename or fallback
     * to the meta.scale field of the JSON data.
     *
     * @param resolutionFilename - The filename to use for resolving
     *        the default resolution.
     * @return Resolution to use for spritesheet.
     */
    Spritesheet.prototype._updateResolution = function (resolutionFilename) {
        if (resolutionFilename === void 0) { resolutionFilename = null; }
        var scale = this.data.meta.scale;
        // Use a defaultValue of `null` to check if a url-based resolution is set
        var resolution = getResolutionOfUrl(resolutionFilename, null);
        // No resolution found via URL
        if (resolution === null) {
            // Use the scale value or default to 1
            resolution = scale !== undefined ? parseFloat(scale) : 1;
        }
        // For non-1 resolutions, update baseTexture
        if (resolution !== 1) {
            this.baseTexture.setResolution(resolution);
        }
        return resolution;
    };
    /**
     * Parser spritesheet from loaded data. This is done asynchronously
     * to prevent creating too many Texture within a single process.
     *
     * @param {Function} callback - Callback when complete returns
     *        a map of the Textures for this spritesheet.
     */
    Spritesheet.prototype.parse = function (callback) {
        this._batchIndex = 0;
        this._callback = callback;
        if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) {
            this._processFrames(0);
            this._processAnimations();
            this._parseComplete();
        }
        else {
            this._nextBatch();
        }
    };
    /**
     * Process a batch of frames
     *
     * @param initialFrameIndex - The index of frame to start.
     */
    Spritesheet.prototype._processFrames = function (initialFrameIndex) {
        var frameIndex = initialFrameIndex;
        var maxFrames = Spritesheet.BATCH_SIZE;
        while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) {
            var i = this._frameKeys[frameIndex];
            var data = this._frames[i];
            var rect = data.frame;
            if (rect) {
                var frame = null;
                var trim = null;
                var sourceSize = data.trimmed !== false && data.sourceSize
                    ? data.sourceSize : data.frame;
                var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution);
                if (data.rotated) {
                    frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution);
                }
                else {
                    frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
                }
                //  Check to see if the sprite is trimmed
                if (data.trimmed !== false && data.spriteSourceSize) {
                    trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
                }
                this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor);
                // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions
                Texture.addToCache(this.textures[i], i);
            }
            frameIndex++;
        }
    };
    /** Parse animations config. */
    Spritesheet.prototype._processAnimations = function () {
        var animations = this.data.animations || {};
        for (var animName in animations) {
            this.animations[animName] = [];
            for (var i = 0; i < animations[animName].length; i++) {
                var frameName = animations[animName][i];
                this.animations[animName].push(this.textures[frameName]);
            }
        }
    };
    /** The parse has completed. */
    Spritesheet.prototype._parseComplete = function () {
        var callback = this._callback;
        this._callback = null;
        this._batchIndex = 0;
        callback.call(this, this.textures);
    };
    /** Begin the next batch of textures. */
    Spritesheet.prototype._nextBatch = function () {
        var _this = this;
        this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE);
        this._batchIndex++;
        setTimeout(function () {
            if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) {
                _this._nextBatch();
            }
            else {
                _this._processAnimations();
                _this._parseComplete();
            }
        }, 0);
    };
    /**
     * Destroy Spritesheet and don't use after this.
     *
     * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well
     */
    Spritesheet.prototype.destroy = function (destroyBase) {
        var _a;
        if (destroyBase === void 0) { destroyBase = false; }
        for (var i in this.textures) {
            this.textures[i].destroy();
        }
        this._frames = null;
        this._frameKeys = null;
        this.data = null;
        this.textures = null;
        if (destroyBase) {
            (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy();
            this.baseTexture.destroy();
        }
        this._texture = null;
        this.baseTexture = null;
    };
    /** The maximum number of Textures to build per process. */
    Spritesheet.BATCH_SIZE = 1000;
    return Spritesheet;
}());
/**
 * Reference to Spritesheet object created.
 * @member {PIXI.Spritesheet} spritesheet
 * @memberof PIXI.LoaderResource
 * @instance
 */
/**
 * Dictionary of textures from Spritesheet.
 * @member {object<string, PIXI.Texture>} textures
 * @memberof PIXI.LoaderResource
 * @instance
 */

/**
 * {@link PIXI.Loader} middleware for loading texture atlases that have been created with
 * TexturePacker or similar JSON-based spritesheet.
 *
 * This middleware automatically generates Texture resources.
 *
 * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON,
 * use the {@link PIXI.Spritesheet} class to directly parse the JSON.
 *
 * The Loader's image Resource name is automatically appended with `"_image"`.
 * If a Resource with this name is already loaded, the Loader will skip parsing the
 * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`.
 *
 * @example
 * loader.add('myatlas', 'path/to/myatlas.json');
 * loader.load(() => {
 *   loader.resources.myatlas; // atlas JSON resource
 *   loader.resources.myatlas_image; // atlas Image resource
 * });
 *
 * @memberof PIXI
 */
var SpritesheetLoader = /** @class */ (function () {
    function SpritesheetLoader() {
    }
    /**
     * Called after a resource is loaded.
     *
     * @see PIXI.Loader.loaderMiddleware
     * @param resource
     * @param next
     */
    SpritesheetLoader.use = function (resource, next) {
        var _a, _b;
        // because this is middleware, it execute in loader context. `this` = loader
        var loader = this;
        var imageResourceName = resource.name + "_image";
        // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists
        if (!resource.data
            || resource.type !== LoaderResource.TYPE.JSON
            || !resource.data.frames
            || loader.resources[imageResourceName]) {
            next();
            return;
        }
        // Check and add the multi atlas
        // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js
        // eslint-disable-next-line camelcase
        var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs;
        if (Array.isArray(multiPacks)) {
            var _loop_1 = function (item) {
                if (typeof item !== 'string') {
                    return "continue";
                }
                var itemName = item.replace('.json', '');
                var itemUrl = utils_url.resolve(resource.url.replace(loader.baseUrl, ''), item);
                // Check if the file wasn't already added as multipacks are redundant
                if (loader.resources[itemName]
                    || Object.values(loader.resources).some(function (r) { return utils_url.format(utils_url.parse(r.url)) === itemUrl; })) {
                    return "continue";
                }
                var options = {
                    crossOrigin: resource.crossOrigin,
                    loadType: LoaderResource.LOAD_TYPE.XHR,
                    xhrType: LoaderResource.XHR_RESPONSE_TYPE.JSON,
                    parentResource: resource,
                    metadata: resource.metadata
                };
                loader.add(itemName, itemUrl, options);
            };
            for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) {
                var item = multiPacks_1[_i];
                _loop_1(item);
            }
        }
        var loadOptions = {
            crossOrigin: resource.crossOrigin,
            metadata: resource.metadata.imageMetadata,
            parentResource: resource,
        };
        var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl);
        // load the image for this sheet
        loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) {
            if (res.error) {
                next(res.error);
                return;
            }
            var spritesheet = new Spritesheet(res.texture, resource.data, resource.url);
            spritesheet.parse(function () {
                resource.spritesheet = spritesheet;
                resource.textures = spritesheet.textures;
                next();
            });
        });
    };
    /**
     * Get the spritesheets root path
     *
     * @param resource - Resource to check path
     * @param baseUrl - Base root url
     */
    SpritesheetLoader.getResourcePath = function (resource, baseUrl) {
        // Prepend url path unless the resource image is a data url
        if (resource.isDataUrl) {
            return resource.data.meta.image;
        }
        return utils_url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image);
    };
    return SpritesheetLoader;
}());


//# sourceMappingURL=spritesheet.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/sprite-tiling/dist/esm/sprite-tiling.js
/*!
 * @pixi/sprite-tiling - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/sprite-tiling is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */






/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var sprite_tiling_extendStatics = function(d, b) {
    sprite_tiling_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return sprite_tiling_extendStatics(d, b);
};

function sprite_tiling_extends(d, b) {
    sprite_tiling_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var sprite_tiling_tempPoint = new Point();
/**
 * A tiling sprite is a fast way of rendering a tiling image.
 *
 * @memberof PIXI
 */
var TilingSprite = /** @class */ (function (_super) {
    sprite_tiling_extends(TilingSprite, _super);
    /**
     * @param texture - The texture of the tiling sprite.
     * @param width - The width of the tiling sprite.
     * @param height - The height of the tiling sprite.
     */
    function TilingSprite(texture, width, height) {
        if (width === void 0) { width = 100; }
        if (height === void 0) { height = 100; }
        var _this = _super.call(this, texture) || this;
        _this.tileTransform = new Transform();
        // The width of the tiling sprite
        _this._width = width;
        // The height of the tiling sprite
        _this._height = height;
        _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture);
        /**
         * Plugin that is responsible for rendering this element.
         * Allows to customize the rendering process without overriding '_render' method.
         *
         * @default 'tilingSprite'
         */
        _this.pluginName = 'tilingSprite';
        _this.uvRespectAnchor = false;
        return _this;
    }
    Object.defineProperty(TilingSprite.prototype, "clampMargin", {
        /**
         * Changes frame clamping in corresponding textureTransform, shortcut
         * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
         *
         * @default 0.5
         * @member {number}
         */
        get: function () {
            return this.uvMatrix.clampMargin;
        },
        set: function (value) {
            this.uvMatrix.clampMargin = value;
            this.uvMatrix.update(true);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TilingSprite.prototype, "tileScale", {
        /** The scaling of the image that is being tiled. */
        get: function () {
            return this.tileTransform.scale;
        },
        set: function (value) {
            this.tileTransform.scale.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TilingSprite.prototype, "tilePosition", {
        /** The offset of the image that is being tiled. */
        get: function () {
            return this.tileTransform.position;
        },
        set: function (value) {
            this.tileTransform.position.copyFrom(value);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * @protected
     */
    TilingSprite.prototype._onTextureUpdate = function () {
        if (this.uvMatrix) {
            this.uvMatrix.texture = this._texture;
        }
        this._cachedTint = 0xFFFFFF;
    };
    /**
     * Renders the object using the WebGL renderer
     *
     * @param renderer - The renderer
     */
    TilingSprite.prototype._render = function (renderer) {
        // tweak our texture temporarily..
        var texture = this._texture;
        if (!texture || !texture.valid) {
            return;
        }
        this.tileTransform.updateLocalTransform();
        this.uvMatrix.update();
        renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
        renderer.plugins[this.pluginName].render(this);
    };
    /** Updates the bounds of the tiling sprite. */
    TilingSprite.prototype._calculateBounds = function () {
        var minX = this._width * -this._anchor._x;
        var minY = this._height * -this._anchor._y;
        var maxX = this._width * (1 - this._anchor._x);
        var maxY = this._height * (1 - this._anchor._y);
        this._bounds.addFrame(this.transform, minX, minY, maxX, maxY);
    };
    /**
     * Gets the local bounds of the sprite object.
     *
     * @param rect - Optional output rectangle.
     * @return The bounds.
     */
    TilingSprite.prototype.getLocalBounds = function (rect) {
        // we can do a fast local bounds if the sprite has no children!
        if (this.children.length === 0) {
            this._bounds.minX = this._width * -this._anchor._x;
            this._bounds.minY = this._height * -this._anchor._y;
            this._bounds.maxX = this._width * (1 - this._anchor._x);
            this._bounds.maxY = this._height * (1 - this._anchor._y);
            if (!rect) {
                if (!this._localBoundsRect) {
                    this._localBoundsRect = new Rectangle();
                }
                rect = this._localBoundsRect;
            }
            return this._bounds.getRectangle(rect);
        }
        return _super.prototype.getLocalBounds.call(this, rect);
    };
    /**
     * Checks if a point is inside this tiling sprite.
     *
     * @param point - The point to check.
     * @return Whether or not the sprite contains the point.
     */
    TilingSprite.prototype.containsPoint = function (point) {
        this.worldTransform.applyInverse(point, sprite_tiling_tempPoint);
        var width = this._width;
        var height = this._height;
        var x1 = -width * this.anchor._x;
        if (sprite_tiling_tempPoint.x >= x1 && sprite_tiling_tempPoint.x < x1 + width) {
            var y1 = -height * this.anchor._y;
            if (sprite_tiling_tempPoint.y >= y1 && sprite_tiling_tempPoint.y < y1 + height) {
                return true;
            }
        }
        return false;
    };
    /**
     * Destroys this sprite and optionally its texture and children
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
     *      method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
     * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
     */
    TilingSprite.prototype.destroy = function (options) {
        _super.prototype.destroy.call(this, options);
        this.tileTransform = null;
        this.uvMatrix = null;
    };
    /**
     * Helper function that creates a new tiling sprite based on the source you provide.
     * The source can be - frame id, image url, video url, canvas element, video element, base texture
     *
     * @static
     * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
     * @param {Object} options - See {@link PIXI.BaseTexture}'s constructor for options.
     * @param {number} options.width - required width of the tiling sprite
     * @param {number} options.height - required height of the tiling sprite
     * @return {PIXI.TilingSprite} The newly created texture
     */
    TilingSprite.from = function (source, options) {
        var texture = (source instanceof Texture)
            ? source
            : Texture.from(source, options);
        return new TilingSprite(texture, options.width, options.height);
    };
    Object.defineProperty(TilingSprite.prototype, "width", {
        /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            return this._width;
        },
        set: function (value) {
            this._width = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TilingSprite.prototype, "height", {
        /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */
        get: function () {
            return this._height;
        },
        set: function (value) {
            this._height = value;
        },
        enumerable: false,
        configurable: true
    });
    return TilingSprite;
}(Sprite));

var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n    vec4 texSample = texture2D(uSampler, vTextureCoord);\n    gl_FragColor = texSample * uColor;\n}\n";

var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n";

var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n    #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n    vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n    coord = (uMapCoord * vec3(coord, 1.0)).xy;\n    vec2 unclamped = coord;\n    coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n    #ifdef GL_EXT_shader_texture_lod\n        vec4 texSample = unclamped == coord\n            ? texture2D(uSampler, coord) \n            : texture2DLodEXT(uSampler, coord, 0);\n    #else\n        vec4 texSample = texture2D(uSampler, coord);\n    #endif\n\n    gl_FragColor = texSample * uColor;\n}\n";

var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n";

var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n    vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n    coord = (uMapCoord * vec3(coord, 1.0)).xy;\n    vec2 unclamped = coord;\n    coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n    vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n    fragmentColor = texSample * uColor;\n}\n";

var sprite_tiling_tempMat = new Matrix();
/**
 * WebGL renderer plugin for tiling sprites
 *
 * @class
 * @memberof PIXI
 * @extends PIXI.ObjectRenderer
 */
var TilingSpriteRenderer = /** @class */ (function (_super) {
    sprite_tiling_extends(TilingSpriteRenderer, _super);
    /**
     * constructor for renderer
     *
     * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for.
     */
    function TilingSpriteRenderer(renderer) {
        var _this = _super.call(this, renderer) || this;
        // WebGL version is not available during initialization!
        renderer.runners.contextChange.add(_this);
        _this.quad = new QuadUv();
        /**
         * The WebGL state in which this renderer will work.
         *
         * @member {PIXI.State}
         * @readonly
         */
        _this.state = State.for2d();
        return _this;
    }
    /**
     * Creates shaders when context is initialized.
     */
    TilingSpriteRenderer.prototype.contextChange = function () {
        var renderer = this.renderer;
        var uniforms = { globals: renderer.globalUniforms };
        this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms);
        this.shader = renderer.context.webGLVersion > 1
            ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms)
            : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms);
    };
    /**
     * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered
     */
    TilingSpriteRenderer.prototype.render = function (ts) {
        var renderer = this.renderer;
        var quad = this.quad;
        var vertices = quad.vertices;
        vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x;
        vertices[1] = vertices[3] = ts._height * -ts.anchor.y;
        vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x);
        vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y);
        var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0;
        var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0;
        vertices = quad.uvs;
        vertices[0] = vertices[6] = -anchorX;
        vertices[1] = vertices[3] = -anchorY;
        vertices[2] = vertices[4] = 1.0 - anchorX;
        vertices[5] = vertices[7] = 1.0 - anchorY;
        quad.invalidate();
        var tex = ts._texture;
        var baseTex = tex.baseTexture;
        var lt = ts.tileTransform.localTransform;
        var uv = ts.uvMatrix;
        var isSimple = baseTex.isPowerOfTwo
            && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height;
        // auto, force repeat wrapMode for big tiling textures
        if (isSimple) {
            if (!baseTex._glTextures[renderer.CONTEXT_UID]) {
                if (baseTex.wrapMode === constants_WRAP_MODES.CLAMP) {
                    baseTex.wrapMode = constants_WRAP_MODES.REPEAT;
                }
            }
            else {
                isSimple = baseTex.wrapMode !== constants_WRAP_MODES.CLAMP;
            }
        }
        var shader = isSimple ? this.simpleShader : this.shader;
        var w = tex.width;
        var h = tex.height;
        var W = ts._width;
        var H = ts._height;
        sprite_tiling_tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H);
        // that part is the same as above:
        // tempMat.identity();
        // tempMat.scale(tex.width, tex.height);
        // tempMat.prepend(lt);
        // tempMat.scale(1.0 / ts._width, 1.0 / ts._height);
        sprite_tiling_tempMat.invert();
        if (isSimple) {
            sprite_tiling_tempMat.prepend(uv.mapCoord);
        }
        else {
            shader.uniforms.uMapCoord = uv.mapCoord.toArray(true);
            shader.uniforms.uClampFrame = uv.uClampFrame;
            shader.uniforms.uClampOffset = uv.uClampOffset;
        }
        shader.uniforms.uTransform = sprite_tiling_tempMat.toArray(true);
        shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.alphaMode);
        shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true);
        shader.uniforms.uSampler = tex;
        renderer.shader.bind(shader);
        renderer.geometry.bind(quad);
        this.state.blendMode = correctBlendMode(ts.blendMode, baseTex.alphaMode);
        renderer.state.set(this.state);
        renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0);
    };
    return TilingSpriteRenderer;
}(ObjectRenderer));


//# sourceMappingURL=sprite-tiling.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/mesh/dist/esm/mesh.js
/*!
 * @pixi/mesh - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/mesh is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */







/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var mesh_extendStatics = function(d, b) {
    mesh_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return mesh_extendStatics(d, b);
};

function mesh_extends(d, b) {
    mesh_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space.
 *
 * @memberof PIXI
 */
var MeshBatchUvs = /** @class */ (function () {
    /**
     * @param uvBuffer - Buffer with normalized uv's
     * @param uvMatrix - Material UV matrix
     */
    function MeshBatchUvs(uvBuffer, uvMatrix) {
        this.uvBuffer = uvBuffer;
        this.uvMatrix = uvMatrix;
        this.data = null;
        this._bufferUpdateId = -1;
        this._textureUpdateId = -1;
        this._updateID = 0;
    }
    /**
     * Updates
     *
     * @param forceUpdate - force the update
     */
    MeshBatchUvs.prototype.update = function (forceUpdate) {
        if (!forceUpdate
            && this._bufferUpdateId === this.uvBuffer._updateID
            && this._textureUpdateId === this.uvMatrix._updateID) {
            return;
        }
        this._bufferUpdateId = this.uvBuffer._updateID;
        this._textureUpdateId = this.uvMatrix._updateID;
        var data = this.uvBuffer.data;
        if (!this.data || this.data.length !== data.length) {
            this.data = new Float32Array(data.length);
        }
        this.uvMatrix.multiplyUvs(data, this.data);
        this._updateID++;
    };
    return MeshBatchUvs;
}());

var mesh_tempPoint = new Point();
var tempPolygon = new Polygon();
/**
 * Base mesh class.
 *
 * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of.
 * This class assumes a certain level of WebGL knowledge.
 * If you know a bit this should abstract enough away to make your life easier!
 *
 * Pretty much ALL WebGL can be broken down into the following:
 * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc..
 * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry)
 * - State - This is the state of WebGL required to render the mesh.
 *
 * Through a combination of the above elements you can render anything you want, 2D or 3D!
 *
 * @memberof PIXI
 */
var Mesh = /** @class */ (function (_super) {
    mesh_extends(Mesh, _super);
    /**
     * @param geometry - The geometry the mesh will use.
     * @param {PIXI.MeshMaterial} shader - The shader the mesh will use.
     * @param state - The state that the WebGL context is required to be in to render the mesh
     *        if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS.
     * @param drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants.
     */
    function Mesh(geometry, shader, state, drawMode) {
        if (drawMode === void 0) { drawMode = constants_DRAW_MODES.TRIANGLES; }
        var _this = _super.call(this) || this;
        _this.geometry = geometry;
        _this.shader = shader;
        _this.state = state || State.for2d();
        _this.drawMode = drawMode;
        _this.start = 0;
        _this.size = 0;
        _this.uvs = null;
        _this.indices = null;
        _this.vertexData = new Float32Array(1);
        _this.vertexDirty = -1;
        _this._transformID = -1;
        _this._roundPixels = settings.ROUND_PIXELS;
        _this.batchUvs = null;
        return _this;
    }
    Object.defineProperty(Mesh.prototype, "geometry", {
        /**
         * Includes vertex positions, face indices, normals, colors, UVs, and
         * custom attributes within buffers, reducing the cost of passing all
         * this data to the GPU. Can be shared between multiple Mesh objects.
         */
        get: function () {
            return this._geometry;
        },
        set: function (value) {
            if (this._geometry === value) {
                return;
            }
            if (this._geometry) {
                this._geometry.refCount--;
                if (this._geometry.refCount === 0) {
                    this._geometry.dispose();
                }
            }
            this._geometry = value;
            if (this._geometry) {
                this._geometry.refCount++;
            }
            this.vertexDirty = -1;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "uvBuffer", {
        /**
         * To change mesh uv's, change its uvBuffer data and increment its _updateID.
         *
         * @readonly
         */
        get: function () {
            return this.geometry.buffers[1];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "verticesBuffer", {
        /**
         * To change mesh vertices, change its uvBuffer data and increment its _updateID.
         * Incrementing _updateID is optional because most of Mesh objects do it anyway.
         *
         * @readonly
         */
        get: function () {
            return this.geometry.buffers[0];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "material", {
        get: function () {
            return this.shader;
        },
        /** Alias for {@link PIXI.Mesh#shader}. */
        set: function (value) {
            this.shader = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "blendMode", {
        get: function () {
            return this.state.blendMode;
        },
        /**
         * The blend mode to be applied to the Mesh. Apply a value of
         * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
         *
         * @default PIXI.BLEND_MODES.NORMAL;
         */
        set: function (value) {
            this.state.blendMode = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "roundPixels", {
        get: function () {
            return this._roundPixels;
        },
        /**
         * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
         * Advantages can include sharper image quality (like text) and faster rendering on canvas.
         * The main disadvantage is movement of objects may appear less smooth.
         * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
         *
         * @default false
         */
        set: function (value) {
            if (this._roundPixels !== value) {
                this._transformID = -1;
            }
            this._roundPixels = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "tint", {
        /**
         * The multiply tint applied to the Mesh. This is a hex value. A value of
         * `0xFFFFFF` will remove any tint effect.
         *
         * Null for non-MeshMaterial shaders
         *
         * @default 0xFFFFFF
         */
        get: function () {
            return 'tint' in this.shader ? this.shader.tint : null;
        },
        set: function (value) {
            this.shader.tint = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Mesh.prototype, "texture", {
        /**
         * The texture that the Mesh uses.
         *
         * Null for non-MeshMaterial shaders
         */
        get: function () {
            return 'texture' in this.shader ? this.shader.texture : null;
        },
        set: function (value) {
            this.shader.texture = value;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Standard renderer draw.
     *
     * @param renderer - Instance to renderer.
     */
    Mesh.prototype._render = function (renderer) {
        // set properties for batching..
        // TODO could use a different way to grab verts?
        var vertices = this.geometry.buffers[0].data;
        var shader = this.shader;
        // TODO benchmark check for attribute size..
        if (shader.batchable
            && this.drawMode === constants_DRAW_MODES.TRIANGLES
            && vertices.length < Mesh.BATCHABLE_SIZE * 2) {
            this._renderToBatch(renderer);
        }
        else {
            this._renderDefault(renderer);
        }
    };
    /**
     * Standard non-batching way of rendering.
     *
     * @param renderer - Instance to renderer.
     */
    Mesh.prototype._renderDefault = function (renderer) {
        var shader = this.shader;
        shader.alpha = this.worldAlpha;
        if (shader.update) {
            shader.update();
        }
        renderer.batch.flush();
        // bind and sync uniforms..
        shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true);
        renderer.shader.bind(shader);
        // set state..
        renderer.state.set(this.state);
        // bind the geometry...
        renderer.geometry.bind(this.geometry, shader);
        // then render it
        renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount);
    };
    /**
     * Rendering by using the Batch system.
     *
     * @param renderer - Instance to renderer.
     */
    Mesh.prototype._renderToBatch = function (renderer) {
        var geometry = this.geometry;
        var shader = this.shader;
        if (shader.uvMatrix) {
            shader.uvMatrix.update();
            this.calculateUvs();
        }
        // set properties for batching..
        this.calculateVertices();
        this.indices = geometry.indexBuffer.data;
        this._tintRGB = shader._tintRGB;
        this._texture = shader.texture;
        var pluginName = this.material.pluginName;
        renderer.batch.setObjectRenderer(renderer.plugins[pluginName]);
        renderer.plugins[pluginName].render(this);
    };
    /** Updates vertexData field based on transform and vertices. */
    Mesh.prototype.calculateVertices = function () {
        var geometry = this.geometry;
        var verticesBuffer = geometry.buffers[0];
        var vertices = verticesBuffer.data;
        var vertexDirtyId = verticesBuffer._updateID;
        if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) {
            return;
        }
        this._transformID = this.transform._worldID;
        if (this.vertexData.length !== vertices.length) {
            this.vertexData = new Float32Array(vertices.length);
        }
        var wt = this.transform.worldTransform;
        var a = wt.a;
        var b = wt.b;
        var c = wt.c;
        var d = wt.d;
        var tx = wt.tx;
        var ty = wt.ty;
        var vertexData = this.vertexData;
        for (var i = 0; i < vertexData.length / 2; i++) {
            var x = vertices[(i * 2)];
            var y = vertices[(i * 2) + 1];
            vertexData[(i * 2)] = (a * x) + (c * y) + tx;
            vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty;
        }
        if (this._roundPixels) {
            var resolution = settings.RESOLUTION;
            for (var i = 0; i < vertexData.length; ++i) {
                vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution);
            }
        }
        this.vertexDirty = vertexDirtyId;
    };
    /** Updates uv field based on from geometry uv's or batchUvs. */
    Mesh.prototype.calculateUvs = function () {
        var geomUvs = this.geometry.buffers[1];
        var shader = this.shader;
        if (!shader.uvMatrix.isSimple) {
            if (!this.batchUvs) {
                this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix);
            }
            this.batchUvs.update();
            this.uvs = this.batchUvs.data;
        }
        else {
            this.uvs = geomUvs.data;
        }
    };
    /**
     * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
     * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly.
     */
    Mesh.prototype._calculateBounds = function () {
        this.calculateVertices();
        this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length);
    };
    /**
     * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES.
     *
     * @param point - The point to test.
     * @return - The result of the test.
     */
    Mesh.prototype.containsPoint = function (point) {
        if (!this.getBounds().contains(point.x, point.y)) {
            return false;
        }
        this.worldTransform.applyInverse(point, mesh_tempPoint);
        var vertices = this.geometry.getBuffer('aVertexPosition').data;
        var points = tempPolygon.points;
        var indices = this.geometry.getIndex().data;
        var len = indices.length;
        var step = this.drawMode === 4 ? 3 : 1;
        for (var i = 0; i + 2 < len; i += step) {
            var ind0 = indices[i] * 2;
            var ind1 = indices[i + 1] * 2;
            var ind2 = indices[i + 2] * 2;
            points[0] = vertices[ind0];
            points[1] = vertices[ind0 + 1];
            points[2] = vertices[ind1];
            points[3] = vertices[ind1 + 1];
            points[4] = vertices[ind2];
            points[5] = vertices[ind2 + 1];
            if (tempPolygon.contains(mesh_tempPoint.x, mesh_tempPoint.y)) {
                return true;
            }
        }
        return false;
    };
    Mesh.prototype.destroy = function (options) {
        _super.prototype.destroy.call(this, options);
        if (this._cachedTexture) {
            this._cachedTexture.destroy();
            this._cachedTexture = null;
        }
        this.geometry = null;
        this.shader = null;
        this.state = null;
        this.uvs = null;
        this.indices = null;
        this.vertexData = null;
    };
    /**
     * The maximum number of vertices to consider batchable. Generally, the complexity
     * of the geometry.
     */
    Mesh.BATCHABLE_SIZE = 100;
    return Mesh;
}(Container));

var mesh_fragment = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n    gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n";

var mesh_vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n    vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n";

/**
 * Slightly opinionated default shader for PixiJS 2D objects.
 *
 * @memberof PIXI
 */
var MeshMaterial = /** @class */ (function (_super) {
    mesh_extends(MeshMaterial, _super);
    /**
     * @param uSampler - Texture that material uses to render.
     * @param options - Additional options
     * @param {number} [options.alpha=1] - Default alpha.
     * @param {number} [options.tint=0xFFFFFF] - Default tint.
     * @param {string} [options.pluginName='batch'] - Renderer plugin for batching.
     * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program.
     * @param {object} [options.uniforms] - Custom uniforms.
     */
    function MeshMaterial(uSampler, options) {
        var _this = this;
        var uniforms = {
            uSampler: uSampler,
            alpha: 1,
            uTextureMatrix: Matrix.IDENTITY,
            uColor: new Float32Array([1, 1, 1, 1]),
        };
        // Set defaults
        options = Object.assign({
            tint: 0xFFFFFF,
            alpha: 1,
            pluginName: 'batch',
        }, options);
        if (options.uniforms) {
            Object.assign(uniforms, options.uniforms);
        }
        _this = _super.call(this, options.program || Program.from(mesh_vertex, mesh_fragment), uniforms) || this;
        _this._colorDirty = false;
        _this.uvMatrix = new TextureMatrix(uSampler);
        _this.batchable = options.program === undefined;
        _this.pluginName = options.pluginName;
        _this.tint = options.tint;
        _this.alpha = options.alpha;
        return _this;
    }
    Object.defineProperty(MeshMaterial.prototype, "texture", {
        /** Reference to the texture being rendered. */
        get: function () {
            return this.uniforms.uSampler;
        },
        set: function (value) {
            if (this.uniforms.uSampler !== value) {
                this.uniforms.uSampler = value;
                this.uvMatrix.texture = value;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MeshMaterial.prototype, "alpha", {
        get: function () {
            return this._alpha;
        },
        /**
         * This gets automatically set by the object using this.
         *
         * @default 1
         */
        set: function (value) {
            if (value === this._alpha)
                { return; }
            this._alpha = value;
            this._colorDirty = true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MeshMaterial.prototype, "tint", {
        get: function () {
            return this._tint;
        },
        /**
         * Multiply tint for the material.
         *
         * @default 0xFFFFFF
         */
        set: function (value) {
            if (value === this._tint)
                { return; }
            this._tint = value;
            this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
            this._colorDirty = true;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Gets called automatically by the Mesh. Intended to be overridden for custom
     * {@link MeshMaterial} objects.
     */
    MeshMaterial.prototype.update = function () {
        if (this._colorDirty) {
            this._colorDirty = false;
            var baseTexture = this.texture.baseTexture;
            premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode);
        }
        if (this.uvMatrix.update()) {
            this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord;
        }
    };
    return MeshMaterial;
}(Shader));

/**
 * Standard 2D geometry used in PixiJS.
 *
 * Geometry can be defined without passing in a style or data if required.
 *
 * ```js
 * const geometry = new PIXI.Geometry();
 *
 * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);
 * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2);
 * geometry.addIndex([0,1,2,1,3,2]);
 *
 * ```
 *
 * @memberof PIXI
 */
var MeshGeometry = /** @class */ (function (_super) {
    mesh_extends(MeshGeometry, _super);
    /**
     * @param {Float32Array|number[]} [vertices] - Positional data on geometry.
     * @param {Float32Array|number[]} [uvs] - Texture UVs.
     * @param {Uint16Array|number[]} [index] - IndexBuffer
     */
    function MeshGeometry(vertices, uvs, index) {
        var _this = _super.call(this) || this;
        var verticesBuffer = new Buffer(vertices);
        var uvsBuffer = new Buffer(uvs, true);
        var indexBuffer = new Buffer(index, true, true);
        _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, constants_TYPES.FLOAT)
            .addAttribute('aTextureCoord', uvsBuffer, 2, false, constants_TYPES.FLOAT)
            .addIndex(indexBuffer);
        _this._updateId = -1;
        return _this;
    }
    Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", {
        /**
         * If the vertex position is updated.
         *
         * @readonly
         * @private
         */
        get: function () {
            return this.buffers[0]._updateID;
        },
        enumerable: false,
        configurable: true
    });
    return MeshGeometry;
}(Geometry));


//# sourceMappingURL=mesh.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/text-bitmap/dist/esm/text-bitmap.js
/*!
 * @pixi/text-bitmap - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/text-bitmap is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */










/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var text_bitmap_extendStatics = function(d, b) {
    text_bitmap_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return text_bitmap_extendStatics(d, b);
};

function text_bitmap_extends(d, b) {
    text_bitmap_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/* eslint-disable max-len */
/**
 * Normalized parsed data from .fnt files.
 *
 * @memberof PIXI
 */
var BitmapFontData = /** @class */ (function () {
    function BitmapFontData() {
        this.info = [];
        this.common = [];
        this.page = [];
        this.char = [];
        this.kerning = [];
        this.distanceField = [];
    }
    return BitmapFontData;
}());

/**
 * BitmapFont format that's Text-based.
 *
 * @private
 */
var TextFormat = /** @class */ (function () {
    function TextFormat() {
    }
    /**
     * Check if resource refers to txt font data.
     *
     * @param data
     * @return - True if resource could be treated as font data, false otherwise.
     */
    TextFormat.test = function (data) {
        return typeof data === 'string' && data.indexOf('info face=') === 0;
    };
    /**
     * Convert text font data to a javascript object.
     *
     * @param txt - Raw string data to be converted
     * @return - Parsed font data
     */
    TextFormat.parse = function (txt) {
        // Retrieve data item
        var items = txt.match(/^[a-z]+\s+.+$/gm);
        var rawData = {
            info: [],
            common: [],
            page: [],
            char: [],
            chars: [],
            kerning: [],
            kernings: [],
            distanceField: [],
        };
        for (var i in items) {
            // Extract item name
            var name = items[i].match(/^[a-z]+/gm)[0];
            // Extract item attribute list as string ex.: "width=10"
            var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm);
            // Convert attribute list into an object
            var itemData = {};
            for (var i_1 in attributeList) {
                // Split key-value pairs
                var split = attributeList[i_1].split('=');
                var key = split[0];
                // Remove eventual quotes from value
                var strValue = split[1].replace(/"/gm, '');
                // Try to convert value into float
                var floatValue = parseFloat(strValue);
                // Use string value case float value is NaN
                var value = isNaN(floatValue) ? strValue : floatValue;
                itemData[key] = value;
            }
            // Push current item to the resulting data
            rawData[name].push(itemData);
        }
        var font = new BitmapFontData();
        rawData.info.forEach(function (info) { return font.info.push({
            face: info.face,
            size: parseInt(info.size, 10),
        }); });
        rawData.common.forEach(function (common) { return font.common.push({
            lineHeight: parseInt(common.lineHeight, 10),
        }); });
        rawData.page.forEach(function (page) { return font.page.push({
            id: parseInt(page.id, 10),
            file: page.file,
        }); });
        rawData.char.forEach(function (char) { return font.char.push({
            id: parseInt(char.id, 10),
            page: parseInt(char.page, 10),
            x: parseInt(char.x, 10),
            y: parseInt(char.y, 10),
            width: parseInt(char.width, 10),
            height: parseInt(char.height, 10),
            xoffset: parseInt(char.xoffset, 10),
            yoffset: parseInt(char.yoffset, 10),
            xadvance: parseInt(char.xadvance, 10),
        }); });
        rawData.kerning.forEach(function (kerning) { return font.kerning.push({
            first: parseInt(kerning.first, 10),
            second: parseInt(kerning.second, 10),
            amount: parseInt(kerning.amount, 10),
        }); });
        rawData.distanceField.forEach(function (df) { return font.distanceField.push({
            distanceRange: parseInt(df.distanceRange, 10),
            fieldType: df.fieldType,
        }); });
        return font;
    };
    return TextFormat;
}());

/**
 * BitmapFont format that's XML-based.
 *
 * @private
 */
var XMLFormat = /** @class */ (function () {
    function XMLFormat() {
    }
    /**
     * Check if resource refers to xml font data.
     *
     * @param data
     * @return - True if resource could be treated as font data, false otherwise.
     */
    XMLFormat.test = function (data) {
        return data instanceof XMLDocument
            && data.getElementsByTagName('page').length
            && data.getElementsByTagName('info')[0].getAttribute('face') !== null;
    };
    /**
     * Convert the XML into BitmapFontData that we can use.
     *
     * @param xml
     * @return - Data to use for BitmapFont
     */
    XMLFormat.parse = function (xml) {
        var data = new BitmapFontData();
        var info = xml.getElementsByTagName('info');
        var common = xml.getElementsByTagName('common');
        var page = xml.getElementsByTagName('page');
        var char = xml.getElementsByTagName('char');
        var kerning = xml.getElementsByTagName('kerning');
        var distanceField = xml.getElementsByTagName('distanceField');
        for (var i = 0; i < info.length; i++) {
            data.info.push({
                face: info[i].getAttribute('face'),
                size: parseInt(info[i].getAttribute('size'), 10),
            });
        }
        for (var i = 0; i < common.length; i++) {
            data.common.push({
                lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10),
            });
        }
        for (var i = 0; i < page.length; i++) {
            data.page.push({
                id: parseInt(page[i].getAttribute('id'), 10) || 0,
                file: page[i].getAttribute('file'),
            });
        }
        for (var i = 0; i < char.length; i++) {
            var letter = char[i];
            data.char.push({
                id: parseInt(letter.getAttribute('id'), 10),
                page: parseInt(letter.getAttribute('page'), 10) || 0,
                x: parseInt(letter.getAttribute('x'), 10),
                y: parseInt(letter.getAttribute('y'), 10),
                width: parseInt(letter.getAttribute('width'), 10),
                height: parseInt(letter.getAttribute('height'), 10),
                xoffset: parseInt(letter.getAttribute('xoffset'), 10),
                yoffset: parseInt(letter.getAttribute('yoffset'), 10),
                xadvance: parseInt(letter.getAttribute('xadvance'), 10),
            });
        }
        for (var i = 0; i < kerning.length; i++) {
            data.kerning.push({
                first: parseInt(kerning[i].getAttribute('first'), 10),
                second: parseInt(kerning[i].getAttribute('second'), 10),
                amount: parseInt(kerning[i].getAttribute('amount'), 10),
            });
        }
        for (var i = 0; i < distanceField.length; i++) {
            data.distanceField.push({
                fieldType: distanceField[i].getAttribute('fieldType'),
                distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10),
            });
        }
        return data;
    };
    return XMLFormat;
}());

/**
 * BitmapFont format that's XML-based.
 *
 * @private
 */
var XMLStringFormat = /** @class */ (function () {
    function XMLStringFormat() {
    }
    /**
     * Check if resource refers to text xml font data.
     *
     * @param data
     * @return - True if resource could be treated as font data, false otherwise.
     */
    XMLStringFormat.test = function (data) {
        if (typeof data === 'string' && data.indexOf('<font>') > -1) {
            var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml');
            return XMLFormat.test(xml);
        }
        return false;
    };
    /**
     * Convert the text XML into BitmapFontData that we can use.
     *
     * @param xmlTxt
     * @return - Data to use for BitmapFont
     */
    XMLStringFormat.parse = function (xmlTxt) {
        var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml');
        return XMLFormat.parse(xml);
    };
    return XMLStringFormat;
}());

// Registered formats, maybe make this extensible in the future?
var formats = [
    TextFormat,
    XMLFormat,
    XMLStringFormat ];
/**
 * Auto-detect BitmapFont parsing format based on data.
 * @private
 * @param {any} data - Data to detect format
 * @return {any} Format or null
 */
function autoDetectFormat(data) {
    for (var i = 0; i < formats.length; i++) {
        if (formats[i].test(data)) {
            return formats[i];
        }
    }
    return null;
}

// TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle
/**
 * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
 *
 * @private
 * @param {object} style - The style.
 * @param {string[]} lines - The lines of text.
 * @return {string|number|CanvasGradient} The fill style
 */
function generateFillStyle(canvas, context, style, resolution, lines, metrics) {
    // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
    //       the setter converts to string. See this thread for more details:
    //       https://github.com/microsoft/TypeScript/issues/2521
    var fillStyle = style.fill;
    if (!Array.isArray(fillStyle)) {
        return fillStyle;
    }
    else if (fillStyle.length === 1) {
        return fillStyle[0];
    }
    // the gradient will be evenly spaced out according to how large the array is.
    // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75
    var gradient;
    // a dropshadow will enlarge the canvas and result in the gradient being
    // generated with the incorrect dimensions
    var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0;
    // should also take padding into account, padding can offset the gradient
    var padding = style.padding || 0;
    var width = (canvas.width / resolution) - dropShadowCorrection - (padding * 2);
    var height = (canvas.height / resolution) - dropShadowCorrection - (padding * 2);
    // make a copy of the style settings, so we can manipulate them later
    var fill = fillStyle.slice();
    var fillGradientStops = style.fillGradientStops.slice();
    // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75
    if (!fillGradientStops.length) {
        var lengthPlus1 = fill.length + 1;
        for (var i = 1; i < lengthPlus1; ++i) {
            fillGradientStops.push(i / lengthPlus1);
        }
    }
    // stop the bleeding of the last gradient on the line above to the top gradient of the this line
    // by hard defining the first gradient colour at point 0, and last gradient colour at point 1
    fill.unshift(fillStyle[0]);
    fillGradientStops.unshift(0);
    fill.push(fillStyle[fillStyle.length - 1]);
    fillGradientStops.push(1);
    if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) {
        // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas
        gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding);
        // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect
        // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875
        // There's potential for floating point precision issues at the seams between gradient repeats.
        // The loop below generates the stops in order, so track the last generated one to prevent
        // floating point precision from making us go the teeniest bit backwards, resulting in
        // the first and last colors getting swapped.
        var lastIterationStop = 0;
        // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc
        var textHeight = metrics.fontProperties.fontSize + style.strokeThickness;
        // textHeight, but as a 0-1 size in global gradient stop space
        var gradStopLineHeight = textHeight / height;
        for (var i = 0; i < lines.length; i++) {
            var thisLineTop = metrics.lineHeight * i;
            for (var j = 0; j < fill.length; j++) {
                // 0-1 stop point for the current line, multiplied to global space afterwards
                var lineStop = 0;
                if (typeof fillGradientStops[j] === 'number') {
                    lineStop = fillGradientStops[j];
                }
                else {
                    lineStop = j / fill.length;
                }
                var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight);
                // Prevent color stop generation going backwards from floating point imprecision
                var clampedStop = Math.max(lastIterationStop, globalStop);
                clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw.
                gradient.addColorStop(clampedStop, fill[j]);
                lastIterationStop = clampedStop;
            }
        }
    }
    else {
        // start the gradient at the center left of the canvas, and end at the center right of the canvas
        gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2);
        // can just evenly space out the gradients in this case, as multiple lines makes no difference
        // to an even left to right gradient
        var totalIterations = fill.length + 1;
        var currentIteration = 1;
        for (var i = 0; i < fill.length; i++) {
            var stop = void 0;
            if (typeof fillGradientStops[i] === 'number') {
                stop = fillGradientStops[i];
            }
            else {
                stop = currentIteration / totalIterations;
            }
            gradient.addColorStop(stop, fill[i]);
            currentIteration++;
        }
    }
    return gradient;
}

// TODO: Prevent code duplication b/w drawGlyph & Text#updateText
/**
 * Draws the glyph `metrics.text` on the given canvas.
 *
 * Ignored because not directly exposed.
 *
 * @ignore
 * @param {HTMLCanvasElement} canvas
 * @param {CanvasRenderingContext2D} context
 * @param {TextMetrics} metrics
 * @param {number} x
 * @param {number} y
 * @param {number} resolution
 * @param {TextStyle} style
 */
function drawGlyph(canvas, context, metrics, x, y, resolution, style) {
    var char = metrics.text;
    var fontProperties = metrics.fontProperties;
    context.translate(x, y);
    context.scale(resolution, resolution);
    var tx = style.strokeThickness / 2;
    var ty = -(style.strokeThickness / 2);
    context.font = style.toFontString();
    context.lineWidth = style.strokeThickness;
    context.textBaseline = style.textBaseline;
    context.lineJoin = style.lineJoin;
    context.miterLimit = style.miterLimit;
    // set canvas text styles
    context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics);
    context.strokeStyle = style.stroke;
    if (style.dropShadow) {
        var dropShadowColor = style.dropShadowColor;
        var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
        var dropShadowBlur = style.dropShadowBlur * resolution;
        var dropShadowDistance = style.dropShadowDistance * resolution;
        context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")";
        context.shadowBlur = dropShadowBlur;
        context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance;
        context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance;
    }
    else {
        context.shadowColor = 'black';
        context.shadowBlur = 0;
        context.shadowOffsetX = 0;
        context.shadowOffsetY = 0;
    }
    if (style.stroke && style.strokeThickness) {
        context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent);
    }
    if (style.fill) {
        context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent);
    }
    context.setTransform(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29)
    context.fillStyle = 'rgba(0, 0, 0, 0)';
}

/**
 * Ponyfill for IE because it doesn't support `Array.from`
 * @private
 */
function splitTextToCharacters(text) {
    return Array.from ? Array.from(text) : text.split('');
}

/**
 * Processes the passed character set data and returns a flattened array of all the characters.
 *
 * Ignored because not directly exposed.
 *
 * @ignore
 * @param {string | string[] | string[][] } chars
 * @returns {string[]}
 */
function resolveCharacters(chars) {
    // Split the chars string into individual characters
    if (typeof chars === 'string') {
        chars = [chars];
    }
    // Handle an array of characters+ranges
    var result = [];
    for (var i = 0, j = chars.length; i < j; i++) {
        var item = chars[i];
        // Handle range delimited by start/end chars
        if (Array.isArray(item)) {
            if (item.length !== 2) {
                throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + ".");
            }
            var startCode = item[0].charCodeAt(0);
            var endCode = item[1].charCodeAt(0);
            if (endCode < startCode) {
                throw new Error('[BitmapFont]: Invalid character range.');
            }
            for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) {
                result.push(String.fromCharCode(i_1));
            }
        }
        // Handle a character set string
        else {
            result.push.apply(result, splitTextToCharacters(item));
        }
    }
    if (result.length === 0) {
        throw new Error('[BitmapFont]: Empty set when resolving characters.');
    }
    return result;
}

/**
 * Ponyfill for IE because it doesn't support `codePointAt`
 * @private
 */
function extractCharCode(str) {
    return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0);
}

/**
 * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install`
 * method for adding a font to be used.
 *
 * @memberof PIXI
 */
var BitmapFont = /** @class */ (function () {
    /**
     * @param data
     * @param textures
     * @param ownsTextures - Setting to `true` will destroy page textures
     *        when the font is uninstalled.
     */
    function BitmapFont(data, textures, ownsTextures) {
        var _a, _b;
        var info = data.info[0];
        var common = data.common[0];
        var page = data.page[0];
        var distanceField = data.distanceField[0];
        var res = getResolutionOfUrl(page.file);
        var pageTextures = {};
        this._ownsTextures = ownsTextures;
        this.font = info.face;
        this.size = info.size;
        this.lineHeight = common.lineHeight / res;
        this.chars = {};
        this.pageTextures = pageTextures;
        // Convert the input Texture, Textures or object
        // into a page Texture lookup by "id"
        for (var i = 0; i < data.page.length; i++) {
            var _c = data.page[i], id = _c.id, file = _c.file;
            pageTextures[id] = textures instanceof Array
                ? textures[i] : textures[file];
            // only MSDF and SDF fonts need no-premultiplied-alpha
            if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') {
                pageTextures[id].baseTexture.alphaMode = constants_ALPHA_MODES.NO_PREMULTIPLIED_ALPHA;
            }
        }
        // parse letters
        for (var i = 0; i < data.char.length; i++) {
            var _d = data.char[i], id = _d.id, page_1 = _d.page;
            var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance;
            x /= res;
            y /= res;
            width /= res;
            height /= res;
            xoffset /= res;
            yoffset /= res;
            xadvance /= res;
            var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height);
            this.chars[id] = {
                xOffset: xoffset,
                yOffset: yoffset,
                xAdvance: xadvance,
                kerning: {},
                texture: new Texture(pageTextures[page_1].baseTexture, rect),
                page: page_1,
            };
        }
        // parse kernings
        for (var i = 0; i < data.kerning.length; i++) {
            var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount;
            first /= res;
            second /= res;
            amount /= res;
            if (this.chars[second]) {
                this.chars[second].kerning[first] = amount;
            }
        }
        // Store distance field information
        this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange;
        this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none';
    }
    /** Remove references to created glyph textures. */
    BitmapFont.prototype.destroy = function () {
        for (var id in this.chars) {
            this.chars[id].texture.destroy();
            this.chars[id].texture = null;
        }
        for (var id in this.pageTextures) {
            if (this._ownsTextures) {
                this.pageTextures[id].destroy(true);
            }
            this.pageTextures[id] = null;
        }
        // Set readonly null.
        this.chars = null;
        this.pageTextures = null;
    };
    /**
     * Register a new bitmap font.
     *
     * @param data - The
     *        characters map that could be provided as xml or raw string.
     * @param textures - List of textures for each page.
     * @param ownsTextures - Set to `true` to destroy page textures
     *        when the font is uninstalled. By default fonts created with
     *        `BitmapFont.from` or from the `BitmapFontLoader` are `true`.
     * @return {PIXI.BitmapFont} Result font object with font, size, lineHeight
     *         and char fields.
     */
    BitmapFont.install = function (data, textures, ownsTextures) {
        var fontData;
        if (data instanceof BitmapFontData) {
            fontData = data;
        }
        else {
            var format = autoDetectFormat(data);
            if (!format) {
                throw new Error('Unrecognized data format for font.');
            }
            fontData = format.parse(data);
        }
        // Single texture, convert to list
        if (textures instanceof Texture) {
            textures = [textures];
        }
        var font = new BitmapFont(fontData, textures, ownsTextures);
        BitmapFont.available[font.font] = font;
        return font;
    };
    /**
     * Remove bitmap font by name.
     *
     * @param name - Name of the font to uninstall.
     */
    BitmapFont.uninstall = function (name) {
        var font = BitmapFont.available[name];
        if (!font) {
            throw new Error("No font found named '" + name + "'");
        }
        font.destroy();
        delete BitmapFont.available[name];
    };
    /**
     * Generates a bitmap-font for the given style and character set. This does not support
     * kernings yet. With `style` properties, only the following non-layout properties are used:
     *
     * - {@link PIXI.TextStyle#dropShadow|dropShadow}
     * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance}
     * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor}
     * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur}
     * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle}
     * - {@link PIXI.TextStyle#fill|fill}
     * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops}
     * - {@link PIXI.TextStyle#fillGradientType|fillGradientType}
     * - {@link PIXI.TextStyle#fontFamily|fontFamily}
     * - {@link PIXI.TextStyle#fontSize|fontSize}
     * - {@link PIXI.TextStyle#fontVariant|fontVariant}
     * - {@link PIXI.TextStyle#fontWeight|fontWeight}
     * - {@link PIXI.TextStyle#lineJoin|lineJoin}
     * - {@link PIXI.TextStyle#miterLimit|miterLimit}
     * - {@link PIXI.TextStyle#stroke|stroke}
     * - {@link PIXI.TextStyle#strokeThickness|strokeThickness}
     * - {@link PIXI.TextStyle#textBaseline|textBaseline}
     *
     * @param name - The name of the custom font to use with BitmapText.
     * @param style - Style options to render with BitmapFont.
     * @param options - Setup options for font or name of the font.
     * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included
     *      in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`.
     *      Don't forget to include spaces ' ' in your character set!
     * @param {number} [options.resolution=1] - Render resolution for glyphs.
     * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory.
     * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory.
     * @param {number} [options.padding=4] - Padding between glyphs on texture atlas.
     * @return Font generated by style options.
     * @example
     * PIXI.BitmapFont.from("TitleFont", {
     *     fontFamily: "Arial",
     *     fontSize: 12,
     *     strokeThickness: 2,
     *     fill: "purple"
     * });
     *
     * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" });
     */
    BitmapFont.from = function (name, textStyle, options) {
        if (!name) {
            throw new Error('[BitmapFont] Property `name` is required.');
        }
        var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight;
        var charsList = resolveCharacters(chars);
        var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle);
        var lineWidth = textureWidth;
        var fontData = new BitmapFontData();
        fontData.info[0] = {
            face: style.fontFamily,
            size: style.fontSize,
        };
        fontData.common[0] = {
            lineHeight: style.fontSize,
        };
        var positionX = 0;
        var positionY = 0;
        var canvas;
        var context;
        var baseTexture;
        var maxCharHeight = 0;
        var textures = [];
        for (var i = 0; i < charsList.length; i++) {
            if (!canvas) {
                canvas = document.createElement('canvas');
                canvas.width = textureWidth;
                canvas.height = textureHeight;
                context = canvas.getContext('2d');
                baseTexture = new BaseTexture(canvas, { resolution: resolution });
                textures.push(new Texture(baseTexture));
                fontData.page.push({
                    id: textures.length - 1,
                    file: '',
                });
            }
            // Measure glyph dimensions
            var metrics = TextMetrics.measureText(charsList[i], style, false, canvas);
            var width = metrics.width;
            var height = Math.ceil(metrics.height);
            // This is ugly - but italics are given more space so they don't overlap
            var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width);
            // Can't fit char anymore: next canvas please!
            if (positionY >= textureHeight - (height * resolution)) {
                if (positionY === 0) {
                    // We don't want user debugging an infinite loop (or do we? :)
                    throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is "
                        + ("too small for " + style.fontSize + "px fonts"));
                }
                --i;
                // Create new atlas once current has filled up
                canvas = null;
                context = null;
                baseTexture = null;
                positionY = 0;
                positionX = 0;
                maxCharHeight = 0;
                continue;
            }
            maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight);
            // Wrap line once full row has been rendered
            if ((textureGlyphWidth * resolution) + positionX >= lineWidth) {
                --i;
                positionY += maxCharHeight * resolution;
                positionY = Math.ceil(positionY);
                positionX = 0;
                maxCharHeight = 0;
                continue;
            }
            drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style);
            // Unique (numeric) ID mapping to this glyph
            var id = extractCharCode(metrics.text);
            // Create a texture holding just the glyph
            fontData.char.push({
                id: id,
                page: textures.length - 1,
                x: positionX / resolution,
                y: positionY / resolution,
                width: textureGlyphWidth,
                height: height,
                xoffset: 0,
                yoffset: 0,
                xadvance: Math.ceil(width
                    - (style.dropShadow ? style.dropShadowDistance : 0)
                    - (style.stroke ? style.strokeThickness : 0)),
            });
            positionX += (textureGlyphWidth + (2 * padding)) * resolution;
            positionX = Math.ceil(positionX);
        }
        // Brute-force kerning info, this can be expensive b/c it's an O(n²),
        // but we're using measureText which is native and fast.
        for (var i = 0, len = charsList.length; i < len; i++) {
            var first = charsList[i];
            for (var j = 0; j < len; j++) {
                var second = charsList[j];
                var c1 = context.measureText(first).width;
                var c2 = context.measureText(second).width;
                var total = context.measureText(first + second).width;
                var amount = total - (c1 + c2);
                if (amount) {
                    fontData.kerning.push({
                        first: extractCharCode(first),
                        second: extractCharCode(second),
                        amount: amount,
                    });
                }
            }
        }
        var font = new BitmapFont(fontData, textures, true);
        // Make it easier to replace a font
        if (BitmapFont.available[name] !== undefined) {
            BitmapFont.uninstall(name);
        }
        BitmapFont.available[name] = font;
        return font;
    };
    /**
     * This character set includes all the letters in the alphabet (both lower- and upper- case).
     *
     * @type {string[][]}
     * @example
     * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA })
     */
    BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' '];
    /**
     * This character set includes all decimal digits (from 0 to 9).
     *
     * @type {string[][]}
     * @example
     * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC })
     */
    BitmapFont.NUMERIC = [['0', '9']];
    /**
     * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`.
     *
     * @type {string[][]}
     */
    BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' '];
    /**
     * This character set consists of all the ASCII table.
     *
     * @member {string[][]}
     * @see http://www.asciitable.com/
     */
    BitmapFont.ASCII = [[' ', '~']];
    /**
     * Collection of default options when using `BitmapFont.from`.
     *
     * @property {number} resolution=1
     * @property {number} textureWidth=512
     * @property {number} textureHeight=512
     * @property {number} padding=4
     * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC
     */
    BitmapFont.defaultOptions = {
        resolution: 1,
        textureWidth: 512,
        textureHeight: 512,
        padding: 4,
        chars: BitmapFont.ALPHANUMERIC,
    };
    /** Collection of available/installed fonts. */
    BitmapFont.available = {};
    return BitmapFont;
}());

var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n  // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n  vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n  // MSDF\r\n  float median = texColor.r + texColor.g + texColor.b -\r\n                  min(texColor.r, min(texColor.g, texColor.b)) -\r\n                  max(texColor.r, max(texColor.g, texColor.b));\r\n  // SDF\r\n  median = min(median, texColor.a);\r\n\r\n  float screenPxDistance = uFWidth * (median - 0.5);\r\n  float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n\r\n  // NPM Textures, NPM outputs\r\n  gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n";

var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n    gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n    vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n";

// If we ever need more than two pools, please make a Dict or something better.
var pageMeshDataDefaultPageMeshData = [];
var pageMeshDataMSDFPageMeshData = [];
var charRenderDataPool = [];
/**
 * A BitmapText object will create a line or multiple lines of text using bitmap font.
 *
 * The primary advantage of this class over Text is that all of your textures are pre-generated and loading,
 * meaning that rendering is fast, and changing text has no performance implications.
 *
 * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters.
 *
 * To split a line you can use '\n', '\r' or '\r\n' in your string.
 *
 * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by:
 * http://www.angelcode.com/products/bmfont/ for Windows or
 * http://www.bmglyph.com/ for Mac.
 *
 * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by:
 * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or
 * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files
 *
 * A BitmapText can only be created when the font is loaded.
 *
 * ```js
 * // in this case the font is in a file called 'desyrel.fnt'
 * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {
 *   fontName: "Desyrel",
 *   fontSize: 35,
 *   align: "right"
 * });
 * ```
 *
 * @memberof PIXI
 */
var BitmapText = /** @class */ (function (_super) {
    text_bitmap_extends(BitmapText, _super);
    /**
     * @param text - A string that you would like the text to display.
     * @param style - The style parameters.
     * @param {string} style.fontName - The installed BitmapFont name.
     * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined,
     *.     this will default to the BitmapFont size.
     * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center', 'right' or 'justify'),
     *      does not affect single line text.
     * @param {number} [style.tint=0xFFFFFF] - The tint color.
     * @param {number} [style.letterSpacing=0] - The amount of spacing between letters.
     * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping.
     */
    function BitmapText(text, style) {
        if (style === void 0) { style = {}; }
        var _this = _super.call(this) || this;
        /**
         * Private tracker for the current tint.
         *
         * @private
         */
        _this._tint = 0xFFFFFF;
        // Apply the defaults
        var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize;
        if (!BitmapFont.available[fontName]) {
            throw new Error("Missing BitmapFont \"" + fontName + "\"");
        }
        _this._activePagesMeshData = [];
        _this._textWidth = 0;
        _this._textHeight = 0;
        _this._align = align;
        _this._tint = tint;
        _this._fontName = fontName;
        _this._fontSize = fontSize || BitmapFont.available[fontName].size;
        _this._text = text;
        _this._maxWidth = maxWidth;
        _this._maxLineHeight = 0;
        _this._letterSpacing = letterSpacing;
        _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0);
        _this._roundPixels = settings.ROUND_PIXELS;
        _this.dirty = true;
        _this._textureCache = {};
        return _this;
    }
    /**
     * Renders text and updates it when needed. This should only be called
     * if the BitmapFont is regenerated.
     */
    BitmapText.prototype.updateText = function () {
        var _a;
        var data = BitmapFont.available[this._fontName];
        var scale = this._fontSize / data.size;
        var pos = new Point();
        var chars = [];
        var lineWidths = [];
        var lineSpaces = [];
        var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' ';
        var charsInput = splitTextToCharacters(text);
        var maxWidth = this._maxWidth * data.size / this._fontSize;
        var pageMeshDataPool = data.distanceFieldType === 'none'
            ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData;
        var prevCharCode = null;
        var lastLineWidth = 0;
        var maxLineWidth = 0;
        var line = 0;
        var lastBreakPos = -1;
        var lastBreakWidth = 0;
        var spacesRemoved = 0;
        var maxLineHeight = 0;
        var spaceCount = 0;
        for (var i = 0; i < charsInput.length; i++) {
            var char = charsInput[i];
            var charCode = extractCharCode(char);
            if ((/(?:\s)/).test(char)) {
                lastBreakPos = i;
                lastBreakWidth = lastLineWidth;
                spaceCount++;
            }
            if (char === '\r' || char === '\n') {
                lineWidths.push(lastLineWidth);
                lineSpaces.push(-1);
                maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
                ++line;
                ++spacesRemoved;
                pos.x = 0;
                pos.y += data.lineHeight;
                prevCharCode = null;
                spaceCount = 0;
                continue;
            }
            var charData = data.chars[charCode];
            if (!charData) {
                continue;
            }
            if (prevCharCode && charData.kerning[prevCharCode]) {
                pos.x += charData.kerning[prevCharCode];
            }
            var charRenderData = charRenderDataPool.pop() || {
                texture: Texture.EMPTY,
                line: 0,
                charCode: 0,
                prevSpaces: 0,
                position: new Point(),
            };
            charRenderData.texture = charData.texture;
            charRenderData.line = line;
            charRenderData.charCode = charCode;
            charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2);
            charRenderData.position.y = pos.y + charData.yOffset;
            charRenderData.prevSpaces = spaceCount;
            chars.push(charRenderData);
            lastLineWidth = charRenderData.position.x + Math.max(charData.xAdvance, charData.texture.orig.width);
            pos.x += charData.xAdvance + this._letterSpacing;
            maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height));
            prevCharCode = charCode;
            if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) {
                ++spacesRemoved;
                removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos);
                i = lastBreakPos;
                lastBreakPos = -1;
                lineWidths.push(lastBreakWidth);
                lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0);
                maxLineWidth = Math.max(maxLineWidth, lastBreakWidth);
                line++;
                pos.x = 0;
                pos.y += data.lineHeight;
                prevCharCode = null;
                spaceCount = 0;
            }
        }
        var lastChar = charsInput[charsInput.length - 1];
        if (lastChar !== '\r' && lastChar !== '\n') {
            if ((/(?:\s)/).test(lastChar)) {
                lastLineWidth = lastBreakWidth;
            }
            lineWidths.push(lastLineWidth);
            maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
            lineSpaces.push(-1);
        }
        var lineAlignOffsets = [];
        for (var i = 0; i <= line; i++) {
            var alignOffset = 0;
            if (this._align === 'right') {
                alignOffset = maxLineWidth - lineWidths[i];
            }
            else if (this._align === 'center') {
                alignOffset = (maxLineWidth - lineWidths[i]) / 2;
            }
            else if (this._align === 'justify') {
                alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i];
            }
            lineAlignOffsets.push(alignOffset);
        }
        var lenChars = chars.length;
        var pagesMeshData = {};
        var newPagesMeshData = [];
        var activePagesMeshData = this._activePagesMeshData;
        for (var i = 0; i < activePagesMeshData.length; i++) {
            pageMeshDataPool.push(activePagesMeshData[i]);
        }
        for (var i = 0; i < lenChars; i++) {
            var texture = chars[i].texture;
            var baseTextureUid = texture.baseTexture.uid;
            if (!pagesMeshData[baseTextureUid]) {
                var pageMeshData = pageMeshDataPool.pop();
                if (!pageMeshData) {
                    var geometry = new MeshGeometry();
                    var material = void 0;
                    var meshBlendMode = void 0;
                    if (data.distanceFieldType === 'none') {
                        material = new MeshMaterial(Texture.EMPTY);
                        meshBlendMode = constants_BLEND_MODES.NORMAL;
                    }
                    else {
                        material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } });
                        meshBlendMode = constants_BLEND_MODES.NORMAL_NPM;
                    }
                    var mesh = new Mesh(geometry, material);
                    mesh.blendMode = meshBlendMode;
                    pageMeshData = {
                        index: 0,
                        indexCount: 0,
                        vertexCount: 0,
                        uvsCount: 0,
                        total: 0,
                        mesh: mesh,
                        vertices: null,
                        uvs: null,
                        indices: null,
                    };
                }
                // reset data..
                pageMeshData.index = 0;
                pageMeshData.indexCount = 0;
                pageMeshData.vertexCount = 0;
                pageMeshData.uvsCount = 0;
                pageMeshData.total = 0;
                // TODO need to get page texture here somehow..
                var _textureCache = this._textureCache;
                _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture);
                pageMeshData.mesh.texture = _textureCache[baseTextureUid];
                pageMeshData.mesh.tint = this._tint;
                newPagesMeshData.push(pageMeshData);
                pagesMeshData[baseTextureUid] = pageMeshData;
            }
            pagesMeshData[baseTextureUid].total++;
        }
        // lets find any previously active pageMeshDatas that are no longer required for
        // the updated text (if any), removed and return them to the pool.
        for (var i = 0; i < activePagesMeshData.length; i++) {
            if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) {
                this.removeChild(activePagesMeshData[i].mesh);
            }
        }
        // next lets add any new meshes, that have not yet been added to this BitmapText
        // we only add if its not already a child of this BitmapObject
        for (var i = 0; i < newPagesMeshData.length; i++) {
            if (newPagesMeshData[i].mesh.parent !== this) {
                this.addChild(newPagesMeshData[i].mesh);
            }
        }
        // active page mesh datas are set to be the new pages added.
        this._activePagesMeshData = newPagesMeshData;
        for (var i in pagesMeshData) {
            var pageMeshData = pagesMeshData[i];
            var total = pageMeshData.total;
            // lets only allocate new buffers if we can fit the new text in the current ones..
            // unless that is, we will be batching. Currently batching dose not respect the size property of mesh
            if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) {
                pageMeshData.vertices = new Float32Array(4 * 2 * total);
                pageMeshData.uvs = new Float32Array(4 * 2 * total);
                pageMeshData.indices = new Uint16Array(6 * total);
            }
            else {
                var total_1 = pageMeshData.total;
                var vertices = pageMeshData.vertices;
                // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation.
                for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) {
                    vertices[i_1] = 0;
                }
            }
            // as a buffer maybe bigger than the current word, we set the size of the meshMaterial
            // to match the number of letters needed
            pageMeshData.mesh.size = 6 * total;
        }
        for (var i = 0; i < lenChars; i++) {
            var char = chars[i];
            var offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1));
            if (this._roundPixels) {
                offset = Math.round(offset);
            }
            var xPos = offset * scale;
            var yPos = char.position.y * scale;
            var texture = char.texture;
            var pageMesh = pagesMeshData[texture.baseTexture.uid];
            var textureFrame = texture.frame;
            var textureUvs = texture._uvs;
            var index = pageMesh.index++;
            pageMesh.indices[(index * 6) + 0] = 0 + (index * 4);
            pageMesh.indices[(index * 6) + 1] = 1 + (index * 4);
            pageMesh.indices[(index * 6) + 2] = 2 + (index * 4);
            pageMesh.indices[(index * 6) + 3] = 0 + (index * 4);
            pageMesh.indices[(index * 6) + 4] = 2 + (index * 4);
            pageMesh.indices[(index * 6) + 5] = 3 + (index * 4);
            pageMesh.vertices[(index * 8) + 0] = xPos;
            pageMesh.vertices[(index * 8) + 1] = yPos;
            pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale);
            pageMesh.vertices[(index * 8) + 3] = yPos;
            pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale);
            pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale);
            pageMesh.vertices[(index * 8) + 6] = xPos;
            pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale);
            pageMesh.uvs[(index * 8) + 0] = textureUvs.x0;
            pageMesh.uvs[(index * 8) + 1] = textureUvs.y0;
            pageMesh.uvs[(index * 8) + 2] = textureUvs.x1;
            pageMesh.uvs[(index * 8) + 3] = textureUvs.y1;
            pageMesh.uvs[(index * 8) + 4] = textureUvs.x2;
            pageMesh.uvs[(index * 8) + 5] = textureUvs.y2;
            pageMesh.uvs[(index * 8) + 6] = textureUvs.x3;
            pageMesh.uvs[(index * 8) + 7] = textureUvs.y3;
        }
        this._textWidth = maxLineWidth * scale;
        this._textHeight = (pos.y + data.lineHeight) * scale;
        for (var i in pagesMeshData) {
            var pageMeshData = pagesMeshData[i];
            // apply anchor
            if (this.anchor.x !== 0 || this.anchor.y !== 0) {
                var vertexCount = 0;
                var anchorOffsetX = this._textWidth * this.anchor.x;
                var anchorOffsetY = this._textHeight * this.anchor.y;
                for (var i_2 = 0; i_2 < pageMeshData.total; i_2++) {
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
                    pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
                }
            }
            this._maxLineHeight = maxLineHeight * scale;
            var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition');
            var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord');
            var indexBuffer = pageMeshData.mesh.geometry.getIndex();
            vertexBuffer.data = pageMeshData.vertices;
            textureBuffer.data = pageMeshData.uvs;
            indexBuffer.data = pageMeshData.indices;
            vertexBuffer.update();
            textureBuffer.update();
            indexBuffer.update();
        }
        for (var i = 0; i < chars.length; i++) {
            charRenderDataPool.push(chars[i]);
        }
    };
    BitmapText.prototype.updateTransform = function () {
        this.validate();
        this.containerUpdateTransform();
    };
    BitmapText.prototype._render = function (renderer) {
        // Update the uniform
        var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size;
        if (distanceFieldType !== 'none') {
            // Inject the shader code with the correct value
            var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d;
            var dx = Math.sqrt((a * a) + (b * b));
            var dy = Math.sqrt((c * c) + (d * d));
            var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2;
            var fontScale = this._fontSize / size;
            for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) {
                var mesh = _c[_i];
                mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * renderer.resolution;
            }
        }
        _super.prototype._render.call(this, renderer);
    };
    /**
     * Validates text before calling parent's getLocalBounds
     *
     * @return - The rectangular bounding area
     */
    BitmapText.prototype.getLocalBounds = function () {
        this.validate();
        return _super.prototype.getLocalBounds.call(this);
    };
    /**
     * Updates text when needed
     *
     * @private
     */
    BitmapText.prototype.validate = function () {
        if (this.dirty) {
            this.updateText();
            this.dirty = false;
        }
    };
    Object.defineProperty(BitmapText.prototype, "tint", {
        /**
         * The tint of the BitmapText object.
         *
         * @default 0xffffff
         */
        get: function () {
            return this._tint;
        },
        set: function (value) {
            if (this._tint === value)
                { return; }
            this._tint = value;
            for (var i = 0; i < this._activePagesMeshData.length; i++) {
                this._activePagesMeshData[i].mesh.tint = value;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "align", {
        /**
         * The alignment of the BitmapText object.
         *
         * @member {string}
         * @default 'left'
         */
        get: function () {
            return this._align;
        },
        set: function (value) {
            if (this._align !== value) {
                this._align = value;
                this.dirty = true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "fontName", {
        /** The name of the BitmapFont. */
        get: function () {
            return this._fontName;
        },
        set: function (value) {
            if (!BitmapFont.available[value]) {
                throw new Error("Missing BitmapFont \"" + value + "\"");
            }
            if (this._fontName !== value) {
                this._fontName = value;
                this.dirty = true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "fontSize", {
        /** The size of the font to display. */
        get: function () {
            return this._fontSize;
        },
        set: function (value) {
            if (this._fontSize !== value) {
                this._fontSize = value;
                this.dirty = true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "anchor", {
        /**
         * The anchor sets the origin point of the text.
         *
         * The default is `(0,0)`, this means the text's origin is the top left.
         *
         * Setting the anchor to `(0.5,0.5)` means the text's origin is centered.
         *
         * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner.
         */
        get: function () {
            return this._anchor;
        },
        set: function (value) {
            if (typeof value === 'number') {
                this._anchor.set(value);
            }
            else {
                this._anchor.copyFrom(value);
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "text", {
        /** The text of the BitmapText object. */
        get: function () {
            return this._text;
        },
        set: function (text) {
            text = String(text === null || text === undefined ? '' : text);
            if (this._text === text) {
                return;
            }
            this._text = text;
            this.dirty = true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "maxWidth", {
        /**
         * The max width of this bitmap text in pixels. If the text provided is longer than the
         * value provided, line breaks will be automatically inserted in the last whitespace.
         * Disable by setting the value to 0.
         */
        get: function () {
            return this._maxWidth;
        },
        set: function (value) {
            if (this._maxWidth === value) {
                return;
            }
            this._maxWidth = value;
            this.dirty = true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "maxLineHeight", {
        /**
         * The max line height. This is useful when trying to use the total height of the Text,
         * i.e. when trying to vertically align.
         *
         * @readonly
         */
        get: function () {
            this.validate();
            return this._maxLineHeight;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "textWidth", {
        /**
         * The width of the overall text, different from fontSize,
         * which is defined in the style object.
         *
         * @readonly
         */
        get: function () {
            this.validate();
            return this._textWidth;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "letterSpacing", {
        /** Additional space between characters. */
        get: function () {
            return this._letterSpacing;
        },
        set: function (value) {
            if (this._letterSpacing !== value) {
                this._letterSpacing = value;
                this.dirty = true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "roundPixels", {
        /**
         * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
         * Advantages can include sharper image quality (like text) and faster rendering on canvas.
         * The main disadvantage is movement of objects may appear less smooth.
         * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
         *
         * @default PIXI.settings.ROUND_PIXELS
         */
        get: function () {
            return this._roundPixels;
        },
        set: function (value) {
            if (value !== this._roundPixels) {
                this._roundPixels = value;
                this.dirty = true;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BitmapText.prototype, "textHeight", {
        /**
         * The height of the overall text, different from fontSize,
         * which is defined in the style object.
         *
         * @readonly
         */
        get: function () {
            this.validate();
            return this._textHeight;
        },
        enumerable: false,
        configurable: true
    });
    BitmapText.prototype.destroy = function (options) {
        var _textureCache = this._textureCache;
        for (var id in _textureCache) {
            var texture = _textureCache[id];
            texture.destroy();
            delete _textureCache[id];
        }
        this._textureCache = null;
        _super.prototype.destroy.call(this, options);
    };
    BitmapText.styleDefaults = {
        align: 'left',
        tint: 0xFFFFFF,
        maxWidth: 0,
        letterSpacing: 0,
    };
    return BitmapText;
}(Container));

/**
 * {@link PIXI.Loader Loader} middleware for loading
 * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}.
 *
 * @memberof PIXI
 */
var BitmapFontLoader = /** @class */ (function () {
    function BitmapFontLoader() {
    }
    /**
     * Called when the plugin is installed.
     *
     * @see PIXI.Loader.registerPlugin
     */
    BitmapFontLoader.add = function () {
        LoaderResource.setExtensionXhrType('fnt', LoaderResource.XHR_RESPONSE_TYPE.TEXT);
    };
    /**
     * Called after a resource is loaded.
     *
     * @see PIXI.Loader.loaderMiddleware
     * @param {PIXI.LoaderResource} resource
     * @param {function} next
     */
    BitmapFontLoader.use = function (resource, next) {
        var format = autoDetectFormat(resource.data);
        // Resource was not recognised as any of the expected font data format
        if (!format) {
            next();
            return;
        }
        var baseUrl = BitmapFontLoader.getBaseUrl(this, resource);
        var data = format.parse(resource.data);
        var textures = {};
        // Handle completed, when the number of textures
        // load is the same number as references in the fnt file
        var completed = function (page) {
            textures[page.metadata.pageFile] = page.texture;
            if (Object.keys(textures).length === data.page.length) {
                resource.bitmapFont = BitmapFont.install(data, textures, true);
                next();
            }
        };
        for (var i = 0; i < data.page.length; ++i) {
            var pageFile = data.page[i].file;
            var url = baseUrl + pageFile;
            var exists = false;
            // incase the image is loaded outside
            // using the same loader, resource will be available
            for (var name in this.resources) {
                var bitmapResource = this.resources[name];
                if (bitmapResource.url === url) {
                    bitmapResource.metadata.pageFile = pageFile;
                    if (bitmapResource.texture) {
                        completed(bitmapResource);
                    }
                    else {
                        bitmapResource.onAfterMiddleware.add(completed);
                    }
                    exists = true;
                    break;
                }
            }
            // texture is not loaded, we'll attempt to add
            // it to the load and add the texture to the list
            if (!exists) {
                // Standard loading options for images
                var options = {
                    crossOrigin: resource.crossOrigin,
                    loadType: LoaderResource.LOAD_TYPE.IMAGE,
                    metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata),
                    parentResource: resource,
                };
                this.add(url, options, completed);
            }
        }
    };
    /** Get folder path from a resource. */
    BitmapFontLoader.getBaseUrl = function (loader, resource) {
        var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : '';
        if (resource.isDataUrl) {
            if (resUrl === '.') {
                resUrl = '';
            }
            if (loader.baseUrl && resUrl) {
                // if baseurl has a trailing slash then add one to resUrl so the replace works below
                if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') {
                    resUrl += '/';
                }
            }
        }
        // remove baseUrl from resUrl
        resUrl = resUrl.replace(loader.baseUrl, '');
        // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty.
        if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') {
            resUrl += '/';
        }
        return resUrl;
    };
    /**
     * Replacement for NodeJS's path.dirname
     *
     * @param {string} url - Path to get directory for
     */
    BitmapFontLoader.dirname = function (url) {
        var dir = url
            .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character
            .replace(/\/$/, '') // replace trailing slash
            .replace(/\/[^\/]*$/, ''); // remove everything after the last
        // File request is relative, use current directory
        if (dir === url) {
            return '.';
        }
        // Started with a slash
        else if (dir === '') {
            return '/';
        }
        return dir;
    };
    return BitmapFontLoader;
}());


//# sourceMappingURL=text-bitmap.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/filter-alpha/dist/esm/filter-alpha.js
/*!
 * @pixi/filter-alpha - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/filter-alpha is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var filter_alpha_extendStatics = function(d, b) {
    filter_alpha_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return filter_alpha_extendStatics(d, b);
};

function filter_alpha_extends(d, b) {
    filter_alpha_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var filter_alpha_fragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n   gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n";

/**
 * Simplest filter - applies alpha.
 *
 * Use this instead of Container's alpha property to avoid visual layering of individual elements.
 * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains.
 * If elements are not opaque, they will blend with each other anyway.
 *
 * Very handy if you want to use common features of all filters:
 *
 * 1. Assign a blendMode to this filter, blend all elements inside display object with background.
 *
 * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter.
 *
 * @memberof PIXI.filters
 */
var AlphaFilter = /** @class */ (function (_super) {
    filter_alpha_extends(AlphaFilter, _super);
    /**
     * @param alpha - Amount of alpha from 0 to 1, where 0 is transparent
     */
    function AlphaFilter(alpha) {
        if (alpha === void 0) { alpha = 1.0; }
        var _this = _super.call(this, defaultVertex$2, filter_alpha_fragment, { uAlpha: 1 }) || this;
        _this.alpha = alpha;
        return _this;
    }
    Object.defineProperty(AlphaFilter.prototype, "alpha", {
        /**
         * Coefficient for alpha multiplication
         *
         * @default 1
         */
        get: function () {
            return this.uniforms.uAlpha;
        },
        set: function (value) {
            this.uniforms.uAlpha = value;
        },
        enumerable: false,
        configurable: true
    });
    return AlphaFilter;
}(Filter));


//# sourceMappingURL=filter-alpha.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/filter-blur/dist/esm/filter-blur.js
/*!
 * @pixi/filter-blur - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/filter-blur is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */



/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var filter_blur_extendStatics = function(d, b) {
    filter_blur_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return filter_blur_extendStatics(d, b);
};

function filter_blur_extends(d, b) {
    filter_blur_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var vertTemplate = "\n    attribute vec2 aVertexPosition;\n\n    uniform mat3 projectionMatrix;\n\n    uniform float strength;\n\n    varying vec2 vBlurTexCoords[%size%];\n\n    uniform vec4 inputSize;\n    uniform vec4 outputFrame;\n\n    vec4 filterVertexPosition( void )\n    {\n        vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n        return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n    }\n\n    vec2 filterTextureCoord( void )\n    {\n        return aVertexPosition * (outputFrame.zw * inputSize.zw);\n    }\n\n    void main(void)\n    {\n        gl_Position = filterVertexPosition();\n\n        vec2 textureCoord = filterTextureCoord();\n        %blur%\n    }";
function generateBlurVertSource(kernelSize, x) {
    var halfLength = Math.ceil(kernelSize / 2);
    var vertSource = vertTemplate;
    var blurLoop = '';
    var template;
    if (x) {
        template = 'vBlurTexCoords[%index%] =  textureCoord + vec2(%sampleIndex% * strength, 0.0);';
    }
    else {
        template = 'vBlurTexCoords[%index%] =  textureCoord + vec2(0.0, %sampleIndex% * strength);';
    }
    for (var i = 0; i < kernelSize; i++) {
        var blur = template.replace('%index%', i.toString());
        blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0");
        blurLoop += blur;
        blurLoop += '\n';
    }
    vertSource = vertSource.replace('%blur%', blurLoop);
    vertSource = vertSource.replace('%size%', kernelSize.toString());
    return vertSource;
}

var GAUSSIAN_VALUES = {
    5: [0.153388, 0.221461, 0.250301],
    7: [0.071303, 0.131514, 0.189879, 0.214607],
    9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236],
    11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596],
    13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641],
    15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448],
};
var filter_blur_fragTemplate = [
    'varying vec2 vBlurTexCoords[%size%];',
    'uniform sampler2D uSampler;',
    'void main(void)',
    '{',
    '    gl_FragColor = vec4(0.0);',
    '    %blur%',
    '}' ].join('\n');
function generateBlurFragSource(kernelSize) {
    var kernel = GAUSSIAN_VALUES[kernelSize];
    var halfLength = kernel.length;
    var fragSource = filter_blur_fragTemplate;
    var blurLoop = '';
    var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;';
    var value;
    for (var i = 0; i < kernelSize; i++) {
        var blur = template.replace('%index%', i.toString());
        value = i;
        if (i >= halfLength) {
            value = kernelSize - i - 1;
        }
        blur = blur.replace('%value%', kernel[value].toString());
        blurLoop += blur;
        blurLoop += '\n';
    }
    fragSource = fragSource.replace('%blur%', blurLoop);
    fragSource = fragSource.replace('%size%', kernelSize.toString());
    return fragSource;
}

/*!
 * @pixi/constants - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/constants is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * Different types of environments for WebGL.
 *
 * @static
 * @memberof PIXI
 * @name ENV
 * @enum {number}
 * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
 *  with older / less advanced devices. If you experience unexplained flickering prefer this environment.
 * @property {number} WEBGL - Version 1 of WebGL
 * @property {number} WEBGL2 - Version 2 of WebGL
 */
var filter_blur_ENV;
(function (ENV) {
    ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
    ENV[ENV["WEBGL"] = 1] = "WEBGL";
    ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
})(filter_blur_ENV || (filter_blur_ENV = {}));
/**
 * Constant to identify the Renderer Type.
 *
 * @static
 * @memberof PIXI
 * @name RENDERER_TYPE
 * @enum {number}
 * @property {number} UNKNOWN - Unknown render type.
 * @property {number} WEBGL - WebGL render type.
 * @property {number} CANVAS - Canvas render type.
 */
var filter_blur_RENDERER_TYPE;
(function (RENDERER_TYPE) {
    RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
    RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
    RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
})(filter_blur_RENDERER_TYPE || (filter_blur_RENDERER_TYPE = {}));
/**
 * Bitwise OR of masks that indicate the buffers to be cleared.
 *
 * @static
 * @memberof PIXI
 * @name BUFFER_BITS
 * @enum {number}
 * @property {number} COLOR - Indicates the buffers currently enabled for color writing.
 * @property {number} DEPTH - Indicates the depth buffer.
 * @property {number} STENCIL - Indicates the stencil buffer.
 */
var filter_blur_BUFFER_BITS;
(function (BUFFER_BITS) {
    BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR";
    BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH";
    BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL";
})(filter_blur_BUFFER_BITS || (filter_blur_BUFFER_BITS = {}));
/**
 * Various blend modes supported by PIXI.
 *
 * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
 * Anything else will silently act like NORMAL.
 *
 * @memberof PIXI
 * @name BLEND_MODES
 * @enum {number}
 * @property {number} NORMAL
 * @property {number} ADD
 * @property {number} MULTIPLY
 * @property {number} SCREEN
 * @property {number} OVERLAY
 * @property {number} DARKEN
 * @property {number} LIGHTEN
 * @property {number} COLOR_DODGE
 * @property {number} COLOR_BURN
 * @property {number} HARD_LIGHT
 * @property {number} SOFT_LIGHT
 * @property {number} DIFFERENCE
 * @property {number} EXCLUSION
 * @property {number} HUE
 * @property {number} SATURATION
 * @property {number} COLOR
 * @property {number} LUMINOSITY
 * @property {number} NORMAL_NPM
 * @property {number} ADD_NPM
 * @property {number} SCREEN_NPM
 * @property {number} NONE
 * @property {number} SRC_IN
 * @property {number} SRC_OUT
 * @property {number} SRC_ATOP
 * @property {number} DST_OVER
 * @property {number} DST_IN
 * @property {number} DST_OUT
 * @property {number} DST_ATOP
 * @property {number} SUBTRACT
 * @property {number} SRC_OVER
 * @property {number} ERASE
 * @property {number} XOR
 */
var filter_blur_BLEND_MODES;
(function (BLEND_MODES) {
    BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
    BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
    BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
    BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
    BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
    BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
    BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
    BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
    BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
    BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
    BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
    BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
    BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
    BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
    BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
    BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
    BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
    BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
    BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
    BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
    BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
    BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER";
    BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN";
    BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT";
    BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP";
    BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER";
    BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN";
    BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT";
    BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP";
    BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE";
    BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT";
    BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR";
})(filter_blur_BLEND_MODES || (filter_blur_BLEND_MODES = {}));
/**
 * Various webgl draw modes. These can be used to specify which GL drawMode to use
 * under certain situations and renderers.
 *
 * @memberof PIXI
 * @static
 * @name DRAW_MODES
 * @enum {number}
 * @property {number} POINTS
 * @property {number} LINES
 * @property {number} LINE_LOOP
 * @property {number} LINE_STRIP
 * @property {number} TRIANGLES
 * @property {number} TRIANGLE_STRIP
 * @property {number} TRIANGLE_FAN
 */
var filter_blur_DRAW_MODES;
(function (DRAW_MODES) {
    DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
    DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
    DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
    DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
    DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
})(filter_blur_DRAW_MODES || (filter_blur_DRAW_MODES = {}));
/**
 * Various GL texture/resources formats.
 *
 * @memberof PIXI
 * @static
 * @name FORMATS
 * @enum {number}
 * @property {number} RGBA=6408
 * @property {number} RGB=6407
 * @property {number} RG=33319
 * @property {number} RED=6403
 * @property {number} RGBA_INTEGER=36249
 * @property {number} RGB_INTEGER=36248
 * @property {number} RG_INTEGER=33320
 * @property {number} RED_INTEGER=36244
 * @property {number} ALPHA=6406
 * @property {number} LUMINANCE=6409
 * @property {number} LUMINANCE_ALPHA=6410
 * @property {number} DEPTH_COMPONENT=6402
 * @property {number} DEPTH_STENCIL=34041
 */
var filter_blur_FORMATS;
(function (FORMATS) {
    FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
    FORMATS[FORMATS["RGB"] = 6407] = "RGB";
    FORMATS[FORMATS["RG"] = 33319] = "RG";
    FORMATS[FORMATS["RED"] = 6403] = "RED";
    FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
    FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
    FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
    FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
    FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA";
    FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE";
    FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
    FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
    FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
})(filter_blur_FORMATS || (filter_blur_FORMATS = {}));
/**
 * Various GL target types.
 *
 * @memberof PIXI
 * @static
 * @name TARGETS
 * @enum {number}
 * @property {number} TEXTURE_2D=3553
 * @property {number} TEXTURE_CUBE_MAP=34067
 * @property {number} TEXTURE_2D_ARRAY=35866
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074
 */
var filter_blur_TARGETS;
(function (TARGETS) {
    TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
    TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
})(filter_blur_TARGETS || (filter_blur_TARGETS = {}));
/**
 * Various GL data format types.
 *
 * @memberof PIXI
 * @static
 * @name TYPES
 * @enum {number}
 * @property {number} UNSIGNED_BYTE=5121
 * @property {number} UNSIGNED_SHORT=5123
 * @property {number} UNSIGNED_SHORT_5_6_5=33635
 * @property {number} UNSIGNED_SHORT_4_4_4_4=32819
 * @property {number} UNSIGNED_SHORT_5_5_5_1=32820
 * @property {number} UNSIGNED_INT=5125
 * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
 * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
 * @property {number} UNSIGNED_INT_24_8=34042
 * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
 * @property {number} BYTE=5120
 * @property {number} SHORT=5122
 * @property {number} INT=5124
 * @property {number} FLOAT=5126
 * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
 * @property {number} HALF_FLOAT=36193
 */
var filter_blur_TYPES;
(function (TYPES) {
    TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
    TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
    TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
    TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
    TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
    TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
    TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
    TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
    TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
    TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
    TYPES[TYPES["BYTE"] = 5120] = "BYTE";
    TYPES[TYPES["SHORT"] = 5122] = "SHORT";
    TYPES[TYPES["INT"] = 5124] = "INT";
    TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
    TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
    TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
})(filter_blur_TYPES || (filter_blur_TYPES = {}));
/**
 * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
 * WebGL1 works only with FLOAT.
 *
 * @memberof PIXI
 * @static
 * @name SAMPLER_TYPES
 * @enum {number}
 * @property {number} FLOAT=0
 * @property {number} INT=1
 * @property {number} UINT=2
 */
var filter_blur_SAMPLER_TYPES;
(function (SAMPLER_TYPES) {
    SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
    SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
    SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
})(filter_blur_SAMPLER_TYPES || (filter_blur_SAMPLER_TYPES = {}));
/**
 * The scale modes that are supported by pixi.
 *
 * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
 * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
 *
 * @memberof PIXI
 * @static
 * @name SCALE_MODES
 * @enum {number}
 * @property {number} LINEAR Smooth scaling
 * @property {number} NEAREST Pixelating scaling
 */
var filter_blur_SCALE_MODES;
(function (SCALE_MODES) {
    SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
    SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
})(filter_blur_SCALE_MODES || (filter_blur_SCALE_MODES = {}));
/**
 * The wrap modes that are supported by pixi.
 *
 * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
 * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
 * If the texture is non power of two then clamp will be used regardless as WebGL can
 * only use REPEAT if the texture is po2.
 *
 * This property only affects WebGL.
 *
 * @name WRAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} CLAMP - The textures uvs are clamped
 * @property {number} REPEAT - The texture uvs tile and repeat
 * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
 */
var filter_blur_WRAP_MODES;
(function (WRAP_MODES) {
    WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
    WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
    WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
})(filter_blur_WRAP_MODES || (filter_blur_WRAP_MODES = {}));
/**
 * Mipmap filtering modes that are supported by pixi.
 *
 * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
 * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
 * or its `POW2` and texture dimensions are powers of 2.
 * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
 *
 * This property only affects WebGL.
 *
 * @name MIPMAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} OFF - No mipmaps
 * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
 * @property {number} ON - Always generate mipmaps
 * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
 *   that supports buffering each level-of-detail.
 */
var filter_blur_MIPMAP_MODES;
(function (MIPMAP_MODES) {
    MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF";
    MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2";
    MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON";
    MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL";
})(filter_blur_MIPMAP_MODES || (filter_blur_MIPMAP_MODES = {}));
/**
 * How to treat textures with premultiplied alpha
 *
 * @name ALPHA_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that.
 *  Option for compressed and data textures that are created from typed arrays.
 * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload.
 *  Default option, used for all loaded images.
 * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied
 *  Example: spine atlases with `_pma` suffix.
 * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA.
 * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD.
 * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA.
 */
var filter_blur_ALPHA_MODES;
(function (ALPHA_MODES) {
    ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM";
    ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK";
    ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA";
    ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
})(filter_blur_ALPHA_MODES || (filter_blur_ALPHA_MODES = {}));
/**
 * Configure whether filter textures are cleared after binding.
 *
 * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
 * this and skip clearing as an optimization.
 *
 * @name CLEAR_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
 * @property {number} CLEAR - Always clear the filter texture.
 * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
 * @property {number} NO - Alias for BLEND, same as `false` in earlier versions
 * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions
 * @property {number} AUTO - Alias for BLIT
 */
var filter_blur_CLEAR_MODES;
(function (CLEAR_MODES) {
    CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO";
    CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES";
    CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO";
    CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND";
    CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR";
    CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT";
})(filter_blur_CLEAR_MODES || (filter_blur_CLEAR_MODES = {}));
/**
 * The gc modes that are supported by pixi.
 *
 * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
 * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
 * used for a specified period of time they will be removed from the GPU. They will of course
 * be uploaded again when they are required. This is a silent behind the scenes process that
 * should ensure that the GPU does not  get filled up.
 *
 * Handy for mobile devices!
 * This property only affects WebGL.
 *
 * @name GC_MODES
 * @enum {number}
 * @static
 * @memberof PIXI
 * @property {number} AUTO - Garbage collection will happen periodically automatically
 * @property {number} MANUAL - Garbage collection will need to be called manually
 */
var filter_blur_GC_MODES;
(function (GC_MODES) {
    GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
    GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
})(filter_blur_GC_MODES || (filter_blur_GC_MODES = {}));
/**
 * Constants that specify float precision in shaders.
 *
 * @name PRECISION
 * @memberof PIXI
 * @constant
 * @static
 * @enum {string}
 * @property {string} LOW='lowp'
 * @property {string} MEDIUM='mediump'
 * @property {string} HIGH='highp'
 */
var filter_blur_PRECISION;
(function (PRECISION) {
    PRECISION["LOW"] = "lowp";
    PRECISION["MEDIUM"] = "mediump";
    PRECISION["HIGH"] = "highp";
})(filter_blur_PRECISION || (filter_blur_PRECISION = {}));
/**
 * Constants for mask implementations.
 * We use `type` suffix because it leads to very different behaviours
 *
 * @name MASK_TYPES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - Mask is ignored
 * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap
 * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil
 * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture
 */
var filter_blur_MASK_TYPES;
(function (MASK_TYPES) {
    MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE";
    MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR";
    MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL";
    MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE";
})(filter_blur_MASK_TYPES || (filter_blur_MASK_TYPES = {}));
/**
 * Constants for multi-sampling antialiasing.
 *
 * @see PIXI.Framebuffer#multisample
 *
 * @name MSAA_QUALITY
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - No multisampling for this renderTexture
 * @property {number} LOW - Try 2 samples
 * @property {number} MEDIUM - Try 4 samples
 * @property {number} HIGH - Try 8 samples
 */
var filter_blur_MSAA_QUALITY;
(function (MSAA_QUALITY) {
    MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE";
    MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW";
    MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM";
    MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH";
})(filter_blur_MSAA_QUALITY || (filter_blur_MSAA_QUALITY = {}));
/**
 * Constants for various buffer types in Pixi
 *
 * @see PIXI.BUFFER_TYPE
 *
 * @name BUFFER_TYPE
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
 * @property {number} ARRAY_BUFFER - buffer type for using attribute data
 * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
 */
var filter_blur_BUFFER_TYPE;
(function (BUFFER_TYPE) {
    BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
    BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
    // NOT YET SUPPORTED
    BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
})(filter_blur_BUFFER_TYPE || (filter_blur_BUFFER_TYPE = {}));

/**
 * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object.
 *
 * @memberof PIXI.filters
 */
var BlurFilterPass = /** @class */ (function (_super) {
    filter_blur_extends(BlurFilterPass, _super);
    /**
     * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`).
     * @param strength - The strength of the blur filter.
     * @param quality - The quality of the blur filter.
     * @param resolution - The resolution of the blur filter.
     * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
     */
    function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) {
        if (strength === void 0) { strength = 8; }
        if (quality === void 0) { quality = 4; }
        if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; }
        if (kernelSize === void 0) { kernelSize = 5; }
        var _this = this;
        var vertSrc = generateBlurVertSource(kernelSize, horizontal);
        var fragSrc = generateBlurFragSource(kernelSize);
        _this = _super.call(this, 
        // vertex shader
        vertSrc, 
        // fragment shader
        fragSrc) || this;
        _this.horizontal = horizontal;
        _this.resolution = resolution;
        _this._quality = 0;
        _this.quality = quality;
        _this.blur = strength;
        return _this;
    }
    /**
     * Applies the filter.
     *
     * @param filterManager - The manager.
     * @param input - The input target.
     * @param output - The output target.
     * @param clearMode - How to clear
     */
    BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) {
        if (output) {
            if (this.horizontal) {
                this.uniforms.strength = (1 / output.width) * (output.width / input.width);
            }
            else {
                this.uniforms.strength = (1 / output.height) * (output.height / input.height);
            }
        }
        else {
            if (this.horizontal) // eslint-disable-line
             {
                this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width);
            }
            else {
                this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line
            }
        }
        // screen space!
        this.uniforms.strength *= this.strength;
        this.uniforms.strength /= this.passes;
        if (this.passes === 1) {
            filterManager.applyFilter(this, input, output, clearMode);
        }
        else {
            var renderTarget = filterManager.getFilterTexture();
            var renderer = filterManager.renderer;
            var flip = input;
            var flop = renderTarget;
            this.state.blend = false;
            filterManager.applyFilter(this, flip, flop, filter_blur_CLEAR_MODES.CLEAR);
            for (var i = 1; i < this.passes - 1; i++) {
                filterManager.bindAndClear(flip, filter_blur_CLEAR_MODES.BLIT);
                this.uniforms.uSampler = flop;
                var temp = flop;
                flop = flip;
                flip = temp;
                renderer.shader.bind(this);
                renderer.geometry.draw(5);
            }
            this.state.blend = true;
            filterManager.applyFilter(this, flop, output, clearMode);
            filterManager.returnFilterTexture(renderTarget);
        }
    };
    Object.defineProperty(BlurFilterPass.prototype, "blur", {
        /**
         * Sets the strength of both the blur.
         *
         * @default 16
         */
        get: function () {
            return this.strength;
        },
        set: function (value) {
            this.padding = 1 + (Math.abs(value) * 2);
            this.strength = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BlurFilterPass.prototype, "quality", {
        /**
         * Sets the quality of the blur by modifying the number of passes. More passes means higher
         * quality bluring but the lower the performance.
         *
         * @default 4
         */
        get: function () {
            return this._quality;
        },
        set: function (value) {
            this._quality = value;
            this.passes = value;
        },
        enumerable: false,
        configurable: true
    });
    return BlurFilterPass;
}(Filter));

/**
 * The BlurFilter applies a Gaussian blur to an object.
 *
 * The strength of the blur can be set for the x-axis and y-axis separately.
 *
 * @memberof PIXI.filters
 */
var BlurFilter = /** @class */ (function (_super) {
    filter_blur_extends(BlurFilter, _super);
    /**
     * @param strength - The strength of the blur filter.
     * @param quality - The quality of the blur filter.
     * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter.
     * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
     */
    function BlurFilter(strength, quality, resolution, kernelSize) {
        if (strength === void 0) { strength = 8; }
        if (quality === void 0) { quality = 4; }
        if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; }
        if (kernelSize === void 0) { kernelSize = 5; }
        var _this = _super.call(this) || this;
        _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize);
        _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize);
        _this.resolution = resolution;
        _this.quality = quality;
        _this.blur = strength;
        _this.repeatEdgePixels = false;
        return _this;
    }
    /**
     * Applies the filter.
     *
     * @param filterManager - The manager.
     * @param input - The input target.
     * @param output - The output target.
     * @param clearMode - How to clear
     */
    BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) {
        var xStrength = Math.abs(this.blurXFilter.strength);
        var yStrength = Math.abs(this.blurYFilter.strength);
        if (xStrength && yStrength) {
            var renderTarget = filterManager.getFilterTexture();
            this.blurXFilter.apply(filterManager, input, renderTarget, filter_blur_CLEAR_MODES.CLEAR);
            this.blurYFilter.apply(filterManager, renderTarget, output, clearMode);
            filterManager.returnFilterTexture(renderTarget);
        }
        else if (yStrength) {
            this.blurYFilter.apply(filterManager, input, output, clearMode);
        }
        else {
            this.blurXFilter.apply(filterManager, input, output, clearMode);
        }
    };
    BlurFilter.prototype.updatePadding = function () {
        if (this._repeatEdgePixels) {
            this.padding = 0;
        }
        else {
            this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
        }
    };
    Object.defineProperty(BlurFilter.prototype, "blur", {
        /**
         * Sets the strength of both the blurX and blurY properties simultaneously
         *
         * @default 2
         */
        get: function () {
            return this.blurXFilter.blur;
        },
        set: function (value) {
            this.blurXFilter.blur = this.blurYFilter.blur = value;
            this.updatePadding();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BlurFilter.prototype, "quality", {
        /**
         * Sets the number of passes for blur. More passes means higher quality bluring.
         *
         * @default 1
         */
        get: function () {
            return this.blurXFilter.quality;
        },
        set: function (value) {
            this.blurXFilter.quality = this.blurYFilter.quality = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BlurFilter.prototype, "blurX", {
        /**
         * Sets the strength of the blurX property
         *
         * @default 2
         */
        get: function () {
            return this.blurXFilter.blur;
        },
        set: function (value) {
            this.blurXFilter.blur = value;
            this.updatePadding();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BlurFilter.prototype, "blurY", {
        /**
         * Sets the strength of the blurY property
         *
         * @default 2
         */
        get: function () {
            return this.blurYFilter.blur;
        },
        set: function (value) {
            this.blurYFilter.blur = value;
            this.updatePadding();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BlurFilter.prototype, "blendMode", {
        /**
         * Sets the blendmode of the filter
         *
         * @default PIXI.BLEND_MODES.NORMAL
         */
        get: function () {
            return this.blurYFilter.blendMode;
        },
        set: function (value) {
            this.blurYFilter.blendMode = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", {
        /**
         * If set to true the edge of the target will be clamped
         *
         * @default false
         */
        get: function () {
            return this._repeatEdgePixels;
        },
        set: function (value) {
            this._repeatEdgePixels = value;
            this.updatePadding();
        },
        enumerable: false,
        configurable: true
    });
    return BlurFilter;
}(Filter));


//# sourceMappingURL=filter-blur.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/filter-color-matrix/dist/esm/filter-color-matrix.js
/*!
 * @pixi/filter-color-matrix - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/filter-color-matrix is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var filter_color_matrix_extendStatics = function(d, b) {
    filter_color_matrix_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return filter_color_matrix_extendStatics(d, b);
};

function filter_color_matrix_extends(d, b) {
    filter_color_matrix_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var filter_color_matrix_fragment = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n    vec4 c = texture2D(uSampler, vTextureCoord);\n\n    if (uAlpha == 0.0) {\n        gl_FragColor = c;\n        return;\n    }\n\n    // Un-premultiply alpha before applying the color matrix. See issue #3539.\n    if (c.a > 0.0) {\n      c.rgb /= c.a;\n    }\n\n    vec4 result;\n\n    result.r = (m[0] * c.r);\n        result.r += (m[1] * c.g);\n        result.r += (m[2] * c.b);\n        result.r += (m[3] * c.a);\n        result.r += m[4];\n\n    result.g = (m[5] * c.r);\n        result.g += (m[6] * c.g);\n        result.g += (m[7] * c.b);\n        result.g += (m[8] * c.a);\n        result.g += m[9];\n\n    result.b = (m[10] * c.r);\n       result.b += (m[11] * c.g);\n       result.b += (m[12] * c.b);\n       result.b += (m[13] * c.a);\n       result.b += m[14];\n\n    result.a = (m[15] * c.r);\n       result.a += (m[16] * c.g);\n       result.a += (m[17] * c.b);\n       result.a += (m[18] * c.a);\n       result.a += m[19];\n\n    vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n    // Premultiply alpha again.\n    rgb *= result.a;\n\n    gl_FragColor = vec4(rgb, result.a);\n}\n";

/**
 * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA
 * color and alpha values of every pixel on your displayObject to produce a result
 * with a new set of RGBA color and alpha values. It's pretty powerful!
 *
 * ```js
 *  let colorMatrix = new PIXI.filters.ColorMatrixFilter();
 *  container.filters = [colorMatrix];
 *  colorMatrix.contrast(2);
 * ```
 * @author Clément Chenebault <clement@goodboydigital.com>
 * @memberof PIXI.filters
 */
var ColorMatrixFilter = /** @class */ (function (_super) {
    filter_color_matrix_extends(ColorMatrixFilter, _super);
    function ColorMatrixFilter() {
        var _this = this;
        var uniforms = {
            m: new Float32Array([1, 0, 0, 0, 0,
                0, 1, 0, 0, 0,
                0, 0, 1, 0, 0,
                0, 0, 0, 1, 0]),
            uAlpha: 1,
        };
        _this = _super.call(this, defaultFilterVertex, filter_color_matrix_fragment, uniforms) || this;
        _this.alpha = 1;
        return _this;
    }
    /**
     * Transforms current matrix and set the new one
     *
     * @param {number[]} matrix - 5x4 matrix
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) {
        if (multiply === void 0) { multiply = false; }
        var newMatrix = matrix;
        if (multiply) {
            this._multiply(newMatrix, this.uniforms.m, matrix);
            newMatrix = this._colorMatrix(newMatrix);
        }
        // set the new matrix
        this.uniforms.m = newMatrix;
    };
    /**
     * Multiplies two mat5's
     *
     * @private
     * @param out - 5x4 matrix the receiving matrix
     * @param a - 5x4 matrix the first operand
     * @param b - 5x4 matrix the second operand
     * @returns {number[]} 5x4 matrix
     */
    ColorMatrixFilter.prototype._multiply = function (out, a, b) {
        // Red Channel
        out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]);
        out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]);
        out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]);
        out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]);
        out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4];
        // Green Channel
        out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]);
        out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]);
        out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]);
        out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]);
        out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9];
        // Blue Channel
        out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]);
        out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]);
        out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]);
        out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]);
        out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14];
        // Alpha Channel
        out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]);
        out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]);
        out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]);
        out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]);
        out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19];
        return out;
    };
    /**
     * Create a Float32 Array and normalize the offset component to 0-1
     *
     * @param {number[]} matrix - 5x4 matrix
     * @return {number[]} 5x4 matrix with all values between 0-1
     */
    ColorMatrixFilter.prototype._colorMatrix = function (matrix) {
        // Create a Float32 Array and normalize the offset component to 0-1
        var m = new Float32Array(matrix);
        m[4] /= 255;
        m[9] /= 255;
        m[14] /= 255;
        m[19] /= 255;
        return m;
    };
    /**
     * Adjusts brightness
     *
     * @param b - value of the brigthness (0-1, where 0 is black)
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.brightness = function (b, multiply) {
        var matrix = [
            b, 0, 0, 0, 0,
            0, b, 0, 0, 0,
            0, 0, b, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Sets each channel on the diagonal of the color matrix.
     * This can be used to achieve a tinting effect on Containers similar to the tint field of some
     * display objects like Sprite, Text, Graphics, and Mesh.
     *
     * @param color - Color of the tint. This is a hex value.
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.tint = function (color, multiply) {
        var r = (color >> 16) & 0xff;
        var g = (color >> 8) & 0xff;
        var b = color & 0xff;
        var matrix = [
            r / 255, 0, 0, 0, 0,
            0, g / 255, 0, 0, 0,
            0, 0, b / 255, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Set the matrices in grey scales
     *
     * @param scale - value of the grey (0-1, where 0 is black)
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.greyscale = function (scale, multiply) {
        var matrix = [
            scale, scale, scale, 0, 0,
            scale, scale, scale, 0, 0,
            scale, scale, scale, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Set the black and white matrice.
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.blackAndWhite = function (multiply) {
        var matrix = [
            0.3, 0.6, 0.1, 0, 0,
            0.3, 0.6, 0.1, 0, 0,
            0.3, 0.6, 0.1, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Set the hue property of the color
     *
     * @param rotation - in degrees
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.hue = function (rotation, multiply) {
        rotation = (rotation || 0) / 180 * Math.PI;
        var cosR = Math.cos(rotation);
        var sinR = Math.sin(rotation);
        var sqrt = Math.sqrt;
        /* a good approximation for hue rotation
         This matrix is far better than the versions with magic luminance constants
         formerly used here, but also used in the starling framework (flash) and known from this
         old part of the internet: quasimondo.com/archives/000565.php

         This new matrix is based on rgb cube rotation in space. Look here for a more descriptive
         implementation as a shader not a general matrix:
         https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js

         This is the source for the code:
         see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751
         */
        var w = 1 / 3;
        var sqrW = sqrt(w); // weight is
        var a00 = cosR + ((1.0 - cosR) * w);
        var a01 = (w * (1.0 - cosR)) - (sqrW * sinR);
        var a02 = (w * (1.0 - cosR)) + (sqrW * sinR);
        var a10 = (w * (1.0 - cosR)) + (sqrW * sinR);
        var a11 = cosR + (w * (1.0 - cosR));
        var a12 = (w * (1.0 - cosR)) - (sqrW * sinR);
        var a20 = (w * (1.0 - cosR)) - (sqrW * sinR);
        var a21 = (w * (1.0 - cosR)) + (sqrW * sinR);
        var a22 = cosR + (w * (1.0 - cosR));
        var matrix = [
            a00, a01, a02, 0, 0,
            a10, a11, a12, 0, 0,
            a20, a21, a22, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Set the contrast matrix, increase the separation between dark and bright
     * Increase contrast : shadows darker and highlights brighter
     * Decrease contrast : bring the shadows up and the highlights down
     *
     * @param amount - value of the contrast (0-1)
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.contrast = function (amount, multiply) {
        var v = (amount || 0) + 1;
        var o = -0.5 * (v - 1);
        var matrix = [
            v, 0, 0, 0, o,
            0, v, 0, 0, o,
            0, 0, v, 0, o,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Set the saturation matrix, increase the separation between colors
     * Increase saturation : increase contrast, brightness, and sharpness
     *
     * @param amount - The saturation amount (0-1)
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.saturate = function (amount, multiply) {
        if (amount === void 0) { amount = 0; }
        var x = (amount * 2 / 3) + 1;
        var y = ((x - 1) * -0.5);
        var matrix = [
            x, y, y, 0, 0,
            y, x, y, 0, 0,
            y, y, x, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Desaturate image (remove color)
     *
     * Call the saturate function
     */
    ColorMatrixFilter.prototype.desaturate = function () {
        this.saturate(-1);
    };
    /**
     * Negative image (inverse of classic rgb matrix)
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.negative = function (multiply) {
        var matrix = [
            -1, 0, 0, 1, 0,
            0, -1, 0, 1, 0,
            0, 0, -1, 1, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Sepia image
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.sepia = function (multiply) {
        var matrix = [
            0.393, 0.7689999, 0.18899999, 0, 0,
            0.349, 0.6859999, 0.16799999, 0, 0,
            0.272, 0.5339999, 0.13099999, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Color motion picture process invented in 1916 (thanks Dominic Szablewski)
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.technicolor = function (multiply) {
        var matrix = [
            1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,
            -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,
            -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Polaroid filter
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.polaroid = function (multiply) {
        var matrix = [
            1.438, -0.062, -0.062, 0, 0,
            -0.122, 1.378, -0.122, 0, 0,
            -0.016, -0.016, 1.483, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Filter who transforms : Red -> Blue and Blue -> Red
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.toBGR = function (multiply) {
        var matrix = [
            0, 0, 1, 0, 0,
            0, 1, 0, 0, 0,
            1, 0, 0, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski)
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.kodachrome = function (multiply) {
        var matrix = [
            1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,
            -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,
            -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Brown delicious browni filter (thanks Dominic Szablewski)
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.browni = function (multiply) {
        var matrix = [
            0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,
            -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,
            0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Vintage filter (thanks Dominic Szablewski)
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.vintage = function (multiply) {
        var matrix = [
            0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,
            0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,
            0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * We don't know exactly what it does, kind of gradient map, but funny to play with!
     *
     * @param desaturation - Tone values.
     * @param toned - Tone values.
     * @param lightColor - Tone values, example: `0xFFE580`
     * @param darkColor - Tone values, example: `0xFFE580`
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) {
        desaturation = desaturation || 0.2;
        toned = toned || 0.15;
        lightColor = lightColor || 0xFFE580;
        darkColor = darkColor || 0x338000;
        var lR = ((lightColor >> 16) & 0xFF) / 255;
        var lG = ((lightColor >> 8) & 0xFF) / 255;
        var lB = (lightColor & 0xFF) / 255;
        var dR = ((darkColor >> 16) & 0xFF) / 255;
        var dG = ((darkColor >> 8) & 0xFF) / 255;
        var dB = (darkColor & 0xFF) / 255;
        var matrix = [
            0.3, 0.59, 0.11, 0, 0,
            lR, lG, lB, desaturation, 0,
            dR, dG, dB, toned, 0,
            lR - dR, lG - dG, lB - dB, 0, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Night effect
     *
     * @param intensity - The intensity of the night effect.
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.night = function (intensity, multiply) {
        intensity = intensity || 0.1;
        var matrix = [
            intensity * (-2.0), -intensity, 0, 0, 0,
            -intensity, 0, intensity, 0, 0,
            0, intensity, intensity * 2.0, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * Predator effect
     *
     * Erase the current matrix by setting a new indepent one
     *
     * @param amount - how much the predator feels his future victim
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.predator = function (amount, multiply) {
        var matrix = [
            // row 1
            11.224130630493164 * amount,
            -4.794486999511719 * amount,
            -2.8746118545532227 * amount,
            0 * amount,
            0.40342438220977783 * amount,
            // row 2
            -3.6330697536468506 * amount,
            9.193157196044922 * amount,
            -2.951810836791992 * amount,
            0 * amount,
            -1.316135048866272 * amount,
            // row 3
            -3.2184197902679443 * amount,
            -4.2375030517578125 * amount,
            7.476448059082031 * amount,
            0 * amount,
            0.8044459223747253 * amount,
            // row 4
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /**
     * LSD effect
     *
     * Multiply the current matrix
     *
     * @param multiply - if true, current matrix and matrix are multiplied. If false,
     *  just set the current matrix with @param matrix
     */
    ColorMatrixFilter.prototype.lsd = function (multiply) {
        var matrix = [
            2, -0.4, 0.5, 0, 0,
            -0.5, 2, -0.4, 0, 0,
            -0.4, -0.5, 3, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, multiply);
    };
    /** Erase the current matrix by setting the default one. */
    ColorMatrixFilter.prototype.reset = function () {
        var matrix = [
            1, 0, 0, 0, 0,
            0, 1, 0, 0, 0,
            0, 0, 1, 0, 0,
            0, 0, 0, 1, 0 ];
        this._loadMatrix(matrix, false);
    };
    Object.defineProperty(ColorMatrixFilter.prototype, "matrix", {
        /**
         * The matrix of the color matrix filter
         *
         * @member {number[]}
         * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]
         */
        get: function () {
            return this.uniforms.m;
        },
        set: function (value) {
            this.uniforms.m = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ColorMatrixFilter.prototype, "alpha", {
        /**
         * The opacity value to use when mixing the original and resultant colors.
         *
         * When the value is 0, the original color is used without modification.
         * When the value is 1, the result color is used.
         * When in the range (0, 1) the color is interpolated between the original and result by this amount.
         *
         * @default 1
         */
        get: function () {
            return this.uniforms.uAlpha;
        },
        set: function (value) {
            this.uniforms.uAlpha = value;
        },
        enumerable: false,
        configurable: true
    });
    return ColorMatrixFilter;
}(Filter));
// Americanized alias
ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale;


//# sourceMappingURL=filter-color-matrix.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/filter-displacement/dist/esm/filter-displacement.js
/*!
 * @pixi/filter-displacement - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/filter-displacement is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */



/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var filter_displacement_extendStatics = function(d, b) {
    filter_displacement_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return filter_displacement_extendStatics(d, b);
};

function filter_displacement_extends(d, b) {
    filter_displacement_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var filter_displacement_fragment = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n  vec4 map =  texture2D(mapSampler, vFilterCoord);\n\n  map -= 0.5;\n  map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n  gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n";

var filter_displacement_vertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n    vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n    return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n    return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0)  ).xy;\n}\n";

/**
 * The DisplacementFilter class uses the pixel values from the specified texture
 * (called the displacement map) to perform a displacement of an object.
 *
 * You can use this filter to apply all manor of crazy warping effects.
 * Currently the `r` property of the texture is used to offset the `x`
 * and the `g` property of the texture is used to offset the `y`.
 *
 * The way it works is it uses the values of the displacement map to look up the
 * correct pixels to output. This means it's not technically moving the original.
 * Instead, it's starting at the output and asking "which pixel from the original goes here".
 * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`,
 * this filter will output the pixel approximately 20 pixels to the right of the original.
 *
 * @memberof PIXI.filters
 */
var DisplacementFilter = /** @class */ (function (_super) {
    filter_displacement_extends(DisplacementFilter, _super);
    /**
     * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!)
     * @param scale - The scale of the displacement
     */
    function DisplacementFilter(sprite, scale) {
        var _this = this;
        var maskMatrix = new Matrix();
        sprite.renderable = false;
        _this = _super.call(this, filter_displacement_vertex, filter_displacement_fragment, {
            mapSampler: sprite._texture,
            filterMatrix: maskMatrix,
            scale: { x: 1, y: 1 },
            rotation: new Float32Array([1, 0, 0, 1]),
        }) || this;
        _this.maskSprite = sprite;
        _this.maskMatrix = maskMatrix;
        if (scale === null || scale === undefined) {
            scale = 20;
        }
        /**
         * scaleX, scaleY for displacements
         * @member {PIXI.Point}
         */
        _this.scale = new Point(scale, scale);
        return _this;
    }
    /**
     * Applies the filter.
     *
     * @param filterManager - The manager.
     * @param input - The input target.
     * @param output - The output target.
     * @param clearMode - clearMode.
     */
    DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) {
        // fill maskMatrix with _normalized sprite texture coords_
        this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite);
        this.uniforms.scale.x = this.scale.x;
        this.uniforms.scale.y = this.scale.y;
        // Extract rotation from world transform
        var wt = this.maskSprite.worldTransform;
        var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b));
        var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d));
        if (lenX !== 0 && lenY !== 0) {
            this.uniforms.rotation[0] = wt.a / lenX;
            this.uniforms.rotation[1] = wt.b / lenX;
            this.uniforms.rotation[2] = wt.c / lenY;
            this.uniforms.rotation[3] = wt.d / lenY;
        }
        // draw the filter...
        filterManager.applyFilter(this, input, output, clearMode);
    };
    Object.defineProperty(DisplacementFilter.prototype, "map", {
        /** The texture used for the displacement map. Must be power of 2 sized texture. */
        get: function () {
            return this.uniforms.mapSampler;
        },
        set: function (value) {
            this.uniforms.mapSampler = value;
        },
        enumerable: false,
        configurable: true
    });
    return DisplacementFilter;
}(Filter));


//# sourceMappingURL=filter-displacement.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/filter-fxaa/dist/esm/filter-fxaa.js
/*!
 * @pixi/filter-fxaa - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/filter-fxaa is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var filter_fxaa_extendStatics = function(d, b) {
    filter_fxaa_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return filter_fxaa_extendStatics(d, b);
};

function filter_fxaa_extends(d, b) {
    filter_fxaa_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var filter_fxaa_vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n    vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n    return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n               out vec2 v_rgbNW, out vec2 v_rgbNE,\n               out vec2 v_rgbSW, out vec2 v_rgbSE,\n               out vec2 v_rgbM) {\n    v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n    v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n    v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n    v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n    v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n   gl_Position = filterVertexPosition();\n\n   vFragCoord = aVertexPosition * outputFrame.zw;\n\n   texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n";

var filter_fxaa_fragment = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN   (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL   (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX     8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n          vec2 v_rgbNW, vec2 v_rgbNE,\n          vec2 v_rgbSW, vec2 v_rgbSE,\n          vec2 v_rgbM) {\n    vec4 color;\n    vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n    vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n    vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n    vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n    vec4 texColor = texture2D(tex, v_rgbM);\n    vec3 rgbM  = texColor.xyz;\n    vec3 luma = vec3(0.299, 0.587, 0.114);\n    float lumaNW = dot(rgbNW, luma);\n    float lumaNE = dot(rgbNE, luma);\n    float lumaSW = dot(rgbSW, luma);\n    float lumaSE = dot(rgbSE, luma);\n    float lumaM  = dot(rgbM,  luma);\n    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n    mediump vec2 dir;\n    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n    float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n                          (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n    dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n              max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n                  dir * rcpDirMin)) * inverseVP;\n\n    vec3 rgbA = 0.5 * (\n                       texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n                       texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n    vec3 rgbB = rgbA * 0.5 + 0.25 * (\n                                     texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n                                     texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n    float lumaB = dot(rgbB, luma);\n    if ((lumaB < lumaMin) || (lumaB > lumaMax))\n        color = vec4(rgbA, texColor.a);\n    else\n        color = vec4(rgbB, texColor.a);\n    return color;\n}\n\nvoid main() {\n\n      vec4 color;\n\n      color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n      gl_FragColor = color;\n}\n";

/**
 * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com
 * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL.
 *
 * @see https://github.com/mitsuhiko/webgl-meincraft
 *
 * @memberof PIXI.filters
 */
var FXAAFilter = /** @class */ (function (_super) {
    filter_fxaa_extends(FXAAFilter, _super);
    function FXAAFilter() {
        // TODO - needs work
        return _super.call(this, filter_fxaa_vertex, filter_fxaa_fragment) || this;
    }
    return FXAAFilter;
}(Filter));


//# sourceMappingURL=filter-fxaa.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/filter-noise/dist/esm/filter-noise.js
/*!
 * @pixi/filter-noise - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/filter-noise is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var filter_noise_extendStatics = function(d, b) {
    filter_noise_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return filter_noise_extendStatics(d, b);
};

function filter_noise_extends(d, b) {
    filter_noise_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var filter_noise_fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n    return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n    vec4 color = texture2D(uSampler, vTextureCoord);\n    float randomValue = rand(gl_FragCoord.xy * uSeed);\n    float diff = (randomValue - 0.5) * uNoise;\n\n    // Un-premultiply alpha before applying the color matrix. See issue #3539.\n    if (color.a > 0.0) {\n        color.rgb /= color.a;\n    }\n\n    color.r += diff;\n    color.g += diff;\n    color.b += diff;\n\n    // Premultiply alpha again.\n    color.rgb *= color.a;\n\n    gl_FragColor = color;\n}\n";

/**
 * A Noise effect filter.
 *
 * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js
 *
 * @memberof PIXI.filters
 * @author Vico @vicocotea
 */
var NoiseFilter = /** @class */ (function (_super) {
    filter_noise_extends(NoiseFilter, _super);
    /**
     * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1].
     * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`.
     */
    function NoiseFilter(noise, seed) {
        if (noise === void 0) { noise = 0.5; }
        if (seed === void 0) { seed = Math.random(); }
        var _this = _super.call(this, defaultFilterVertex, filter_noise_fragment, {
            uNoise: 0,
            uSeed: 0,
        }) || this;
        _this.noise = noise;
        _this.seed = seed;
        return _this;
    }
    Object.defineProperty(NoiseFilter.prototype, "noise", {
        /**
         * The amount of noise to apply, this value should be in the range (0, 1].
         *
         * @default 0.5
         */
        get: function () {
            return this.uniforms.uNoise;
        },
        set: function (value) {
            this.uniforms.uNoise = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(NoiseFilter.prototype, "seed", {
        /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */
        get: function () {
            return this.uniforms.uSeed;
        },
        set: function (value) {
            this.uniforms.uSeed = value;
        },
        enumerable: false,
        configurable: true
    });
    return NoiseFilter;
}(Filter));


//# sourceMappingURL=filter-noise.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/mixin-cache-as-bitmap/dist/esm/mixin-cache-as-bitmap.js
/*!
 * @pixi/mixin-cache-as-bitmap - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/mixin-cache-as-bitmap is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */







/*!
 * @pixi/constants - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/constants is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
/**
 * Different types of environments for WebGL.
 *
 * @static
 * @memberof PIXI
 * @name ENV
 * @enum {number}
 * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
 *  with older / less advanced devices. If you experience unexplained flickering prefer this environment.
 * @property {number} WEBGL - Version 1 of WebGL
 * @property {number} WEBGL2 - Version 2 of WebGL
 */
var mixin_cache_as_bitmap_ENV;
(function (ENV) {
    ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
    ENV[ENV["WEBGL"] = 1] = "WEBGL";
    ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
})(mixin_cache_as_bitmap_ENV || (mixin_cache_as_bitmap_ENV = {}));
/**
 * Constant to identify the Renderer Type.
 *
 * @static
 * @memberof PIXI
 * @name RENDERER_TYPE
 * @enum {number}
 * @property {number} UNKNOWN - Unknown render type.
 * @property {number} WEBGL - WebGL render type.
 * @property {number} CANVAS - Canvas render type.
 */
var mixin_cache_as_bitmap_RENDERER_TYPE;
(function (RENDERER_TYPE) {
    RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
    RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
    RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
})(mixin_cache_as_bitmap_RENDERER_TYPE || (mixin_cache_as_bitmap_RENDERER_TYPE = {}));
/**
 * Bitwise OR of masks that indicate the buffers to be cleared.
 *
 * @static
 * @memberof PIXI
 * @name BUFFER_BITS
 * @enum {number}
 * @property {number} COLOR - Indicates the buffers currently enabled for color writing.
 * @property {number} DEPTH - Indicates the depth buffer.
 * @property {number} STENCIL - Indicates the stencil buffer.
 */
var mixin_cache_as_bitmap_BUFFER_BITS;
(function (BUFFER_BITS) {
    BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR";
    BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH";
    BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL";
})(mixin_cache_as_bitmap_BUFFER_BITS || (mixin_cache_as_bitmap_BUFFER_BITS = {}));
/**
 * Various blend modes supported by PIXI.
 *
 * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
 * Anything else will silently act like NORMAL.
 *
 * @memberof PIXI
 * @name BLEND_MODES
 * @enum {number}
 * @property {number} NORMAL
 * @property {number} ADD
 * @property {number} MULTIPLY
 * @property {number} SCREEN
 * @property {number} OVERLAY
 * @property {number} DARKEN
 * @property {number} LIGHTEN
 * @property {number} COLOR_DODGE
 * @property {number} COLOR_BURN
 * @property {number} HARD_LIGHT
 * @property {number} SOFT_LIGHT
 * @property {number} DIFFERENCE
 * @property {number} EXCLUSION
 * @property {number} HUE
 * @property {number} SATURATION
 * @property {number} COLOR
 * @property {number} LUMINOSITY
 * @property {number} NORMAL_NPM
 * @property {number} ADD_NPM
 * @property {number} SCREEN_NPM
 * @property {number} NONE
 * @property {number} SRC_IN
 * @property {number} SRC_OUT
 * @property {number} SRC_ATOP
 * @property {number} DST_OVER
 * @property {number} DST_IN
 * @property {number} DST_OUT
 * @property {number} DST_ATOP
 * @property {number} SUBTRACT
 * @property {number} SRC_OVER
 * @property {number} ERASE
 * @property {number} XOR
 */
var mixin_cache_as_bitmap_BLEND_MODES;
(function (BLEND_MODES) {
    BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
    BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
    BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
    BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
    BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
    BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
    BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
    BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
    BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
    BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
    BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
    BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
    BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
    BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
    BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
    BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
    BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
    BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
    BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
    BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
    BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
    BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER";
    BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN";
    BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT";
    BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP";
    BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER";
    BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN";
    BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT";
    BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP";
    BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE";
    BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT";
    BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR";
})(mixin_cache_as_bitmap_BLEND_MODES || (mixin_cache_as_bitmap_BLEND_MODES = {}));
/**
 * Various webgl draw modes. These can be used to specify which GL drawMode to use
 * under certain situations and renderers.
 *
 * @memberof PIXI
 * @static
 * @name DRAW_MODES
 * @enum {number}
 * @property {number} POINTS
 * @property {number} LINES
 * @property {number} LINE_LOOP
 * @property {number} LINE_STRIP
 * @property {number} TRIANGLES
 * @property {number} TRIANGLE_STRIP
 * @property {number} TRIANGLE_FAN
 */
var mixin_cache_as_bitmap_DRAW_MODES;
(function (DRAW_MODES) {
    DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
    DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
    DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
    DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
    DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
    DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
})(mixin_cache_as_bitmap_DRAW_MODES || (mixin_cache_as_bitmap_DRAW_MODES = {}));
/**
 * Various GL texture/resources formats.
 *
 * @memberof PIXI
 * @static
 * @name FORMATS
 * @enum {number}
 * @property {number} RGBA=6408
 * @property {number} RGB=6407
 * @property {number} RG=33319
 * @property {number} RED=6403
 * @property {number} RGBA_INTEGER=36249
 * @property {number} RGB_INTEGER=36248
 * @property {number} RG_INTEGER=33320
 * @property {number} RED_INTEGER=36244
 * @property {number} ALPHA=6406
 * @property {number} LUMINANCE=6409
 * @property {number} LUMINANCE_ALPHA=6410
 * @property {number} DEPTH_COMPONENT=6402
 * @property {number} DEPTH_STENCIL=34041
 */
var mixin_cache_as_bitmap_FORMATS;
(function (FORMATS) {
    FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
    FORMATS[FORMATS["RGB"] = 6407] = "RGB";
    FORMATS[FORMATS["RG"] = 33319] = "RG";
    FORMATS[FORMATS["RED"] = 6403] = "RED";
    FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
    FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
    FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
    FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
    FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA";
    FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE";
    FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
    FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
    FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
})(mixin_cache_as_bitmap_FORMATS || (mixin_cache_as_bitmap_FORMATS = {}));
/**
 * Various GL target types.
 *
 * @memberof PIXI
 * @static
 * @name TARGETS
 * @enum {number}
 * @property {number} TEXTURE_2D=3553
 * @property {number} TEXTURE_CUBE_MAP=34067
 * @property {number} TEXTURE_2D_ARRAY=35866
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072
 * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073
 * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074
 */
var mixin_cache_as_bitmap_TARGETS;
(function (TARGETS) {
    TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
    TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
    TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
})(mixin_cache_as_bitmap_TARGETS || (mixin_cache_as_bitmap_TARGETS = {}));
/**
 * Various GL data format types.
 *
 * @memberof PIXI
 * @static
 * @name TYPES
 * @enum {number}
 * @property {number} UNSIGNED_BYTE=5121
 * @property {number} UNSIGNED_SHORT=5123
 * @property {number} UNSIGNED_SHORT_5_6_5=33635
 * @property {number} UNSIGNED_SHORT_4_4_4_4=32819
 * @property {number} UNSIGNED_SHORT_5_5_5_1=32820
 * @property {number} UNSIGNED_INT=5125
 * @property {number} UNSIGNED_INT_10F_11F_11F_REV=35899
 * @property {number} UNSIGNED_INT_2_10_10_10_REV=33640
 * @property {number} UNSIGNED_INT_24_8=34042
 * @property {number} UNSIGNED_INT_5_9_9_9_REV=35902
 * @property {number} BYTE=5120
 * @property {number} SHORT=5122
 * @property {number} INT=5124
 * @property {number} FLOAT=5126
 * @property {number} FLOAT_32_UNSIGNED_INT_24_8_REV=36269
 * @property {number} HALF_FLOAT=36193
 */
var mixin_cache_as_bitmap_TYPES;
(function (TYPES) {
    TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
    TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
    TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
    TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
    TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
    TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
    TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
    TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
    TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
    TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
    TYPES[TYPES["BYTE"] = 5120] = "BYTE";
    TYPES[TYPES["SHORT"] = 5122] = "SHORT";
    TYPES[TYPES["INT"] = 5124] = "INT";
    TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
    TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
    TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
})(mixin_cache_as_bitmap_TYPES || (mixin_cache_as_bitmap_TYPES = {}));
/**
 * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
 * WebGL1 works only with FLOAT.
 *
 * @memberof PIXI
 * @static
 * @name SAMPLER_TYPES
 * @enum {number}
 * @property {number} FLOAT=0
 * @property {number} INT=1
 * @property {number} UINT=2
 */
var mixin_cache_as_bitmap_SAMPLER_TYPES;
(function (SAMPLER_TYPES) {
    SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
    SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
    SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
})(mixin_cache_as_bitmap_SAMPLER_TYPES || (mixin_cache_as_bitmap_SAMPLER_TYPES = {}));
/**
 * The scale modes that are supported by pixi.
 *
 * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
 * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
 *
 * @memberof PIXI
 * @static
 * @name SCALE_MODES
 * @enum {number}
 * @property {number} LINEAR Smooth scaling
 * @property {number} NEAREST Pixelating scaling
 */
var mixin_cache_as_bitmap_SCALE_MODES;
(function (SCALE_MODES) {
    SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
    SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
})(mixin_cache_as_bitmap_SCALE_MODES || (mixin_cache_as_bitmap_SCALE_MODES = {}));
/**
 * The wrap modes that are supported by pixi.
 *
 * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
 * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
 * If the texture is non power of two then clamp will be used regardless as WebGL can
 * only use REPEAT if the texture is po2.
 *
 * This property only affects WebGL.
 *
 * @name WRAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} CLAMP - The textures uvs are clamped
 * @property {number} REPEAT - The texture uvs tile and repeat
 * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
 */
var mixin_cache_as_bitmap_WRAP_MODES;
(function (WRAP_MODES) {
    WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
    WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
    WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
})(mixin_cache_as_bitmap_WRAP_MODES || (mixin_cache_as_bitmap_WRAP_MODES = {}));
/**
 * Mipmap filtering modes that are supported by pixi.
 *
 * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
 * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
 * or its `POW2` and texture dimensions are powers of 2.
 * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
 *
 * This property only affects WebGL.
 *
 * @name MIPMAP_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} OFF - No mipmaps
 * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
 * @property {number} ON - Always generate mipmaps
 * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
 *   that supports buffering each level-of-detail.
 */
var mixin_cache_as_bitmap_MIPMAP_MODES;
(function (MIPMAP_MODES) {
    MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF";
    MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2";
    MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON";
    MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL";
})(mixin_cache_as_bitmap_MIPMAP_MODES || (mixin_cache_as_bitmap_MIPMAP_MODES = {}));
/**
 * How to treat textures with premultiplied alpha
 *
 * @name ALPHA_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that.
 *  Option for compressed and data textures that are created from typed arrays.
 * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload.
 *  Default option, used for all loaded images.
 * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied
 *  Example: spine atlases with `_pma` suffix.
 * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA.
 * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD.
 * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA.
 */
var mixin_cache_as_bitmap_ALPHA_MODES;
(function (ALPHA_MODES) {
    ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM";
    ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK";
    ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA";
    ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA";
    ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
})(mixin_cache_as_bitmap_ALPHA_MODES || (mixin_cache_as_bitmap_ALPHA_MODES = {}));
/**
 * Configure whether filter textures are cleared after binding.
 *
 * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
 * this and skip clearing as an optimization.
 *
 * @name CLEAR_MODES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
 * @property {number} CLEAR - Always clear the filter texture.
 * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
 * @property {number} NO - Alias for BLEND, same as `false` in earlier versions
 * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions
 * @property {number} AUTO - Alias for BLIT
 */
var mixin_cache_as_bitmap_CLEAR_MODES;
(function (CLEAR_MODES) {
    CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO";
    CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES";
    CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO";
    CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND";
    CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR";
    CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT";
})(mixin_cache_as_bitmap_CLEAR_MODES || (mixin_cache_as_bitmap_CLEAR_MODES = {}));
/**
 * The gc modes that are supported by pixi.
 *
 * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
 * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
 * used for a specified period of time they will be removed from the GPU. They will of course
 * be uploaded again when they are required. This is a silent behind the scenes process that
 * should ensure that the GPU does not  get filled up.
 *
 * Handy for mobile devices!
 * This property only affects WebGL.
 *
 * @name GC_MODES
 * @enum {number}
 * @static
 * @memberof PIXI
 * @property {number} AUTO - Garbage collection will happen periodically automatically
 * @property {number} MANUAL - Garbage collection will need to be called manually
 */
var mixin_cache_as_bitmap_GC_MODES;
(function (GC_MODES) {
    GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
    GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
})(mixin_cache_as_bitmap_GC_MODES || (mixin_cache_as_bitmap_GC_MODES = {}));
/**
 * Constants that specify float precision in shaders.
 *
 * @name PRECISION
 * @memberof PIXI
 * @constant
 * @static
 * @enum {string}
 * @property {string} LOW='lowp'
 * @property {string} MEDIUM='mediump'
 * @property {string} HIGH='highp'
 */
var mixin_cache_as_bitmap_PRECISION;
(function (PRECISION) {
    PRECISION["LOW"] = "lowp";
    PRECISION["MEDIUM"] = "mediump";
    PRECISION["HIGH"] = "highp";
})(mixin_cache_as_bitmap_PRECISION || (mixin_cache_as_bitmap_PRECISION = {}));
/**
 * Constants for mask implementations.
 * We use `type` suffix because it leads to very different behaviours
 *
 * @name MASK_TYPES
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - Mask is ignored
 * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap
 * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil
 * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture
 */
var mixin_cache_as_bitmap_MASK_TYPES;
(function (MASK_TYPES) {
    MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE";
    MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR";
    MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL";
    MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE";
})(mixin_cache_as_bitmap_MASK_TYPES || (mixin_cache_as_bitmap_MASK_TYPES = {}));
/**
 * Constants for multi-sampling antialiasing.
 *
 * @see PIXI.Framebuffer#multisample
 *
 * @name MSAA_QUALITY
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} NONE - No multisampling for this renderTexture
 * @property {number} LOW - Try 2 samples
 * @property {number} MEDIUM - Try 4 samples
 * @property {number} HIGH - Try 8 samples
 */
var mixin_cache_as_bitmap_MSAA_QUALITY;
(function (MSAA_QUALITY) {
    MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE";
    MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW";
    MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM";
    MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH";
})(mixin_cache_as_bitmap_MSAA_QUALITY || (mixin_cache_as_bitmap_MSAA_QUALITY = {}));
/**
 * Constants for various buffer types in Pixi
 *
 * @see PIXI.BUFFER_TYPE
 *
 * @name BUFFER_TYPE
 * @memberof PIXI
 * @static
 * @enum {number}
 * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
 * @property {number} ARRAY_BUFFER - buffer type for using attribute data
 * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
 */
var mixin_cache_as_bitmap_BUFFER_TYPE;
(function (BUFFER_TYPE) {
    BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
    BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
    // NOT YET SUPPORTED
    BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
})(mixin_cache_as_bitmap_BUFFER_TYPE || (mixin_cache_as_bitmap_BUFFER_TYPE = {}));

var _tempMatrix = new Matrix();
DisplayObject.prototype._cacheAsBitmap = false;
DisplayObject.prototype._cacheData = null;
DisplayObject.prototype._cacheAsBitmapResolution = null;
DisplayObject.prototype._cacheAsBitmapMultisample = mixin_cache_as_bitmap_MSAA_QUALITY.NONE;
// figured there's no point adding ALL the extra variables to prototype.
// this model can hold the information needed. This can also be generated on demand as
// most objects are not cached as bitmaps.
/**
 * @class
 * @ignore
 * @private
 */
var CacheData = /** @class */ (function () {
    function CacheData() {
        this.textureCacheId = null;
        this.originalRender = null;
        this.originalRenderCanvas = null;
        this.originalCalculateBounds = null;
        this.originalGetLocalBounds = null;
        this.originalUpdateTransform = null;
        this.originalDestroy = null;
        this.originalMask = null;
        this.originalFilterArea = null;
        this.originalContainsPoint = null;
        this.sprite = null;
    }
    return CacheData;
}());
Object.defineProperties(DisplayObject.prototype, {
    /**
     * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution
     * but can be overriden for performance. Lower values will reduce memory usage at the expense
     * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution.
     * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution.
     *
     * @member {number} cacheAsBitmapResolution
     * @memberof PIXI.DisplayObject#
     * @default null
     */
    cacheAsBitmapResolution: {
        get: function () {
            return this._cacheAsBitmapResolution;
        },
        set: function (resolution) {
            if (resolution === this._cacheAsBitmapResolution) {
                return;
            }
            this._cacheAsBitmapResolution = resolution;
            if (this.cacheAsBitmap) {
                // Toggle to re-render at the new resolution
                this.cacheAsBitmap = false;
                this.cacheAsBitmap = true;
            }
        },
    },
    /**
     * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's
     * sample count is used.
     * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples.
     *
     * @member {number} cacheAsBitmapMultisample
     * @memberof PIXI.DisplayObject#
     * @default PIXI.MSAA_QUALITY.NONE
     */
    cacheAsBitmapMultisample: {
        get: function () {
            return this._cacheAsBitmapMultisample;
        },
        set: function (multisample) {
            if (multisample === this._cacheAsBitmapMultisample) {
                return;
            }
            this._cacheAsBitmapMultisample = multisample;
            if (this.cacheAsBitmap) {
                // Toggle to re-render with new multisample
                this.cacheAsBitmap = false;
                this.cacheAsBitmap = true;
            }
        },
    },
    /**
     * Set this to true if you want this display object to be cached as a bitmap.
     * This basically takes a snap shot of the display object as it is at that moment. It can
     * provide a performance benefit for complex static displayObjects.
     * To remove simply set this property to `false`
     *
     * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true
     * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear.
     *
     * @member {boolean}
     * @memberof PIXI.DisplayObject#
     */
    cacheAsBitmap: {
        get: function () {
            return this._cacheAsBitmap;
        },
        set: function (value) {
            if (this._cacheAsBitmap === value) {
                return;
            }
            this._cacheAsBitmap = value;
            var data;
            if (value) {
                if (!this._cacheData) {
                    this._cacheData = new CacheData();
                }
                data = this._cacheData;
                data.originalRender = this.render;
                data.originalRenderCanvas = this.renderCanvas;
                data.originalUpdateTransform = this.updateTransform;
                data.originalCalculateBounds = this.calculateBounds;
                data.originalGetLocalBounds = this.getLocalBounds;
                data.originalDestroy = this.destroy;
                data.originalContainsPoint = this.containsPoint;
                data.originalMask = this._mask;
                data.originalFilterArea = this.filterArea;
                this.render = this._renderCached;
                this.renderCanvas = this._renderCachedCanvas;
                this.destroy = this._cacheAsBitmapDestroy;
            }
            else {
                data = this._cacheData;
                if (data.sprite) {
                    this._destroyCachedDisplayObject();
                }
                this.render = data.originalRender;
                this.renderCanvas = data.originalRenderCanvas;
                this.calculateBounds = data.originalCalculateBounds;
                this.getLocalBounds = data.originalGetLocalBounds;
                this.destroy = data.originalDestroy;
                this.updateTransform = data.originalUpdateTransform;
                this.containsPoint = data.originalContainsPoint;
                this._mask = data.originalMask;
                this.filterArea = data.originalFilterArea;
            }
        },
    },
});
/**
 * Renders a cached version of the sprite with WebGL
 *
 * @private
 * @method _renderCached
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.Renderer} renderer - the WebGL renderer
 */
DisplayObject.prototype._renderCached = function _renderCached(renderer) {
    if (!this.visible || this.worldAlpha <= 0 || !this.renderable) {
        return;
    }
    this._initCachedDisplayObject(renderer);
    this._cacheData.sprite.transform._worldID = this.transform._worldID;
    this._cacheData.sprite.worldAlpha = this.worldAlpha;
    this._cacheData.sprite._render(renderer);
};
/**
 * Prepares the WebGL renderer to cache the sprite
 *
 * @private
 * @method _initCachedDisplayObject
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.Renderer} renderer - the WebGL renderer
 */
DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) {
    var _a;
    if (this._cacheData && this._cacheData.sprite) {
        return;
    }
    // make sure alpha is set to 1 otherwise it will get rendered as invisible!
    var cacheAlpha = this.alpha;
    this.alpha = 1;
    // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture)
    renderer.batch.flush();
    // this.filters= [];
    // next we find the dimensions of the untransformed object
    // this function also calls updatetransform on all its children as part of the measuring.
    // This means we don't need to update the transform again in this function
    // TODO pass an object to clone too? saves having to create a new one each time!
    var bounds = this.getLocalBounds(null, true).clone();
    // add some padding!
    if (this.filters && this.filters.length) {
        var padding = this.filters[0].padding;
        bounds.pad(padding);
    }
    bounds.ceil(settings.RESOLUTION);
    // for now we cache the current renderTarget that the WebGL renderer is currently using.
    // this could be more elegant..
    var cachedRenderTexture = renderer.renderTexture.current;
    var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone();
    var cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone();
    var cachedProjectionTransform = renderer.projection.transform;
    // We also store the filter stack - I will definitely look to change how this works a little later down the line.
    // const stack = renderer.filterManager.filterStack;
    // this renderTexture will be used to store the cached DisplayObject
    var renderTexture = RenderTexture.create({
        width: bounds.width,
        height: bounds.height,
        resolution: this.cacheAsBitmapResolution || renderer.resolution,
        multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample,
    });
    var textureCacheId = "cacheAsBitmap_" + uid();
    this._cacheData.textureCacheId = textureCacheId;
    BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
    Texture.addToCache(renderTexture, textureCacheId);
    // need to set //
    var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y);
    // set all properties to there original so we can render to a texture
    this.render = this._cacheData.originalRender;
    renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false });
    renderer.framebuffer.blit();
    // now restore the state be setting the new properties
    renderer.projection.transform = cachedProjectionTransform;
    renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame);
    // renderer.filterManager.filterStack = stack;
    this.render = this._renderCached;
    // the rest is the same as for Canvas
    this.updateTransform = this.displayObjectUpdateTransform;
    this.calculateBounds = this._calculateCachedBounds;
    this.getLocalBounds = this._getCachedLocalBounds;
    this._mask = null;
    this.filterArea = null;
    this.alpha = cacheAlpha;
    // create our cached sprite
    var cachedSprite = new Sprite(renderTexture);
    cachedSprite.transform.worldTransform = this.transform.worldTransform;
    cachedSprite.anchor.x = -(bounds.x / bounds.width);
    cachedSprite.anchor.y = -(bounds.y / bounds.height);
    cachedSprite.alpha = cacheAlpha;
    cachedSprite._bounds = this._bounds;
    this._cacheData.sprite = cachedSprite;
    this.transform._parentID = -1;
    // restore the transform of the cached sprite to avoid the nasty flicker..
    if (!this.parent) {
        this.enableTempParent();
        this.updateTransform();
        this.disableTempParent(null);
    }
    else {
        this.updateTransform();
    }
    // map the hit test..
    this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite);
};
/**
 * Renders a cached version of the sprite with canvas
 *
 * @private
 * @method _renderCachedCanvas
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
 */
DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) {
    if (!this.visible || this.worldAlpha <= 0 || !this.renderable) {
        return;
    }
    this._initCachedDisplayObjectCanvas(renderer);
    this._cacheData.sprite.worldAlpha = this.worldAlpha;
    this._cacheData.sprite._renderCanvas(renderer);
};
// TODO this can be the same as the WebGL version.. will need to do a little tweaking first though..
/**
 * Prepares the Canvas renderer to cache the sprite
 *
 * @private
 * @method _initCachedDisplayObjectCanvas
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
 */
DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) {
    if (this._cacheData && this._cacheData.sprite) {
        return;
    }
    // get bounds actually transforms the object for us already!
    var bounds = this.getLocalBounds(null, true);
    var cacheAlpha = this.alpha;
    this.alpha = 1;
    var cachedRenderTarget = renderer.context;
    var cachedProjectionTransform = renderer._projTransform;
    bounds.ceil(settings.RESOLUTION);
    var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height });
    var textureCacheId = "cacheAsBitmap_" + uid();
    this._cacheData.textureCacheId = textureCacheId;
    BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
    Texture.addToCache(renderTexture, textureCacheId);
    // need to set //
    var m = _tempMatrix;
    this.transform.localTransform.copyTo(m);
    m.invert();
    m.tx -= bounds.x;
    m.ty -= bounds.y;
    // m.append(this.transform.worldTransform.)
    // set all properties to there original so we can render to a texture
    this.renderCanvas = this._cacheData.originalRenderCanvas;
    renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false });
    // now restore the state be setting the new properties
    renderer.context = cachedRenderTarget;
    renderer._projTransform = cachedProjectionTransform;
    this.renderCanvas = this._renderCachedCanvas;
    // the rest is the same as for WebGL
    this.updateTransform = this.displayObjectUpdateTransform;
    this.calculateBounds = this._calculateCachedBounds;
    this.getLocalBounds = this._getCachedLocalBounds;
    this._mask = null;
    this.filterArea = null;
    this.alpha = cacheAlpha;
    // create our cached sprite
    var cachedSprite = new Sprite(renderTexture);
    cachedSprite.transform.worldTransform = this.transform.worldTransform;
    cachedSprite.anchor.x = -(bounds.x / bounds.width);
    cachedSprite.anchor.y = -(bounds.y / bounds.height);
    cachedSprite.alpha = cacheAlpha;
    cachedSprite._bounds = this._bounds;
    this._cacheData.sprite = cachedSprite;
    this.transform._parentID = -1;
    // restore the transform of the cached sprite to avoid the nasty flicker..
    if (!this.parent) {
        this.parent = renderer._tempDisplayObjectParent;
        this.updateTransform();
        this.parent = null;
    }
    else {
        this.updateTransform();
    }
    // map the hit test..
    this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite);
};
/**
 * Calculates the bounds of the cached sprite
 *
 * @private
 * @method
 */
DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() {
    this._bounds.clear();
    this._cacheData.sprite.transform._worldID = this.transform._worldID;
    this._cacheData.sprite._calculateBounds();
    this._bounds.updateID = this._boundsID;
};
/**
 * Gets the bounds of the cached sprite.
 *
 * @private
 * @method
 * @return {Rectangle} The local bounds.
 */
DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() {
    return this._cacheData.sprite.getLocalBounds(null);
};
/**
 * Destroys the cached sprite.
 *
 * @private
 * @method
 */
DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() {
    this._cacheData.sprite._texture.destroy(true);
    this._cacheData.sprite = null;
    BaseTexture.removeFromCache(this._cacheData.textureCacheId);
    Texture.removeFromCache(this._cacheData.textureCacheId);
    this._cacheData.textureCacheId = null;
};
/**
 * Destroys the cached object.
 *
 * @private
 * @method
 * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
 *  have been set to that value.
 *  Used when destroying containers, see the Container.destroy method.
 */
DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) {
    this.cacheAsBitmap = false;
    this.destroy(options);
};


//# sourceMappingURL=mixin-cache-as-bitmap.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/mixin-get-child-by-name/dist/esm/mixin-get-child-by-name.js
/*!
 * @pixi/mixin-get-child-by-name - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/mixin-get-child-by-name is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


/**
 * The instance name of the object.
 *
 * @memberof PIXI.DisplayObject#
 * @member {string} name
 */
DisplayObject.prototype.name = null;
/**
 * Returns the display object in the container.
 *
 * Recursive searches are done in a preorder traversal.
 *
 * @method getChildByName
 * @memberof PIXI.Container#
 * @param {string} name - Instance name.
 * @param {boolean}[deep=false] - Whether to search recursively
 * @return {PIXI.DisplayObject} The child with the specified name.
 */
Container.prototype.getChildByName = function getChildByName(name, deep) {
    for (var i = 0, j = this.children.length; i < j; i++) {
        if (this.children[i].name === name) {
            return this.children[i];
        }
    }
    if (deep) {
        for (var i = 0, j = this.children.length; i < j; i++) {
            var child = this.children[i];
            if (!child.getChildByName) {
                continue;
            }
            var target = this.children[i].getChildByName(name, true);
            if (target) {
                return target;
            }
        }
    }
    return null;
};
//# sourceMappingURL=mixin-get-child-by-name.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/mixin-get-global-position/dist/esm/mixin-get-global-position.js
/*!
 * @pixi/mixin-get-global-position - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/mixin-get-global-position is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */



/**
 * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot.
 *
 * @method getGlobalPosition
 * @memberof PIXI.DisplayObject#
 * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to.
 * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from
 *  being updated. This means the calculation returned MAY be out of date BUT will give you a
 *  nice performance boost.
 * @return {PIXI.Point} The updated point.
 */
DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) {
    if (point === void 0) { point = new Point(); }
    if (skipUpdate === void 0) { skipUpdate = false; }
    if (this.parent) {
        this.parent.toGlobal(this.position, point, skipUpdate);
    }
    else {
        point.x = this.position.x;
        point.y = this.position.y;
    }
    return point;
};
//# sourceMappingURL=mixin-get-global-position.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/mesh-extras/dist/esm/mesh-extras.js
/*!
 * @pixi/mesh-extras - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/mesh-extras is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */




/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var mesh_extras_extendStatics = function(d, b) {
    mesh_extras_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return mesh_extras_extendStatics(d, b);
};

function mesh_extras_extends(d, b) {
    mesh_extras_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * @memberof PIXI
 */
var PlaneGeometry = /** @class */ (function (_super) {
    mesh_extras_extends(PlaneGeometry, _super);
    /**
     * @param width - The width of the plane.
     * @param height - The height of the plane.
     * @param segWidth - Number of horizontal segments.
     * @param segHeight - Number of vertical segments.
     */
    function PlaneGeometry(width, height, segWidth, segHeight) {
        if (width === void 0) { width = 100; }
        if (height === void 0) { height = 100; }
        if (segWidth === void 0) { segWidth = 10; }
        if (segHeight === void 0) { segHeight = 10; }
        var _this = _super.call(this) || this;
        _this.segWidth = segWidth;
        _this.segHeight = segHeight;
        _this.width = width;
        _this.height = height;
        _this.build();
        return _this;
    }
    /**
     * Refreshes plane coordinates
     * @private
     */
    PlaneGeometry.prototype.build = function () {
        var total = this.segWidth * this.segHeight;
        var verts = [];
        var uvs = [];
        var indices = [];
        var segmentsX = this.segWidth - 1;
        var segmentsY = this.segHeight - 1;
        var sizeX = (this.width) / segmentsX;
        var sizeY = (this.height) / segmentsY;
        for (var i = 0; i < total; i++) {
            var x = (i % this.segWidth);
            var y = ((i / this.segWidth) | 0);
            verts.push(x * sizeX, y * sizeY);
            uvs.push(x / segmentsX, y / segmentsY);
        }
        var totalSub = segmentsX * segmentsY;
        for (var i = 0; i < totalSub; i++) {
            var xpos = i % segmentsX;
            var ypos = (i / segmentsX) | 0;
            var value = (ypos * this.segWidth) + xpos;
            var value2 = (ypos * this.segWidth) + xpos + 1;
            var value3 = ((ypos + 1) * this.segWidth) + xpos;
            var value4 = ((ypos + 1) * this.segWidth) + xpos + 1;
            indices.push(value, value2, value3, value2, value4, value3);
        }
        this.buffers[0].data = new Float32Array(verts);
        this.buffers[1].data = new Float32Array(uvs);
        this.indexBuffer.data = new Uint16Array(indices);
        // ensure that the changes are uploaded
        this.buffers[0].update();
        this.buffers[1].update();
        this.indexBuffer.update();
    };
    return PlaneGeometry;
}(MeshGeometry));

/**
 * RopeGeometry allows you to draw a geometry across several points and then manipulate these points.
 *
 * ```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * const rope = new PIXI.RopeGeometry(100, points);
 * ```
 *
 * @memberof PIXI
 */
var RopeGeometry = /** @class */ (function (_super) {
    mesh_extras_extends(RopeGeometry, _super);
    /**
     * @param width - The width (i.e., thickness) of the rope.
     * @param points - An array of {@link PIXI.Point} objects to construct this rope.
     * @param textureScale - By default the rope texture will be stretched to match
     *     rope length. If textureScale is positive this value will be treated as a scaling
     *     factor and the texture will preserve its aspect ratio instead. To create a tiling rope
     *     set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture,
     *     then set textureScale=1 to keep the original texture pixel size.
     *     In order to reduce alpha channel artifacts provide a larger texture and downsample -
     *     i.e. set textureScale=0.5 to scale it down twice.
     */
    function RopeGeometry(width, points, textureScale) {
        if (width === void 0) { width = 200; }
        if (textureScale === void 0) { textureScale = 0; }
        var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this;
        _this.points = points;
        _this._width = width;
        _this.textureScale = textureScale;
        _this.build();
        return _this;
    }
    Object.defineProperty(RopeGeometry.prototype, "width", {
        /**
         * The width (i.e., thickness) of the rope.
         *
         * @readOnly
         */
        get: function () {
            return this._width;
        },
        enumerable: false,
        configurable: true
    });
    /** Refreshes Rope indices and uvs */
    RopeGeometry.prototype.build = function () {
        var points = this.points;
        if (!points)
            { return; }
        var vertexBuffer = this.getBuffer('aVertexPosition');
        var uvBuffer = this.getBuffer('aTextureCoord');
        var indexBuffer = this.getIndex();
        // if too little points, or texture hasn't got UVs set yet just move on.
        if (points.length < 1) {
            return;
        }
        // if the number of points has changed we will need to recreate the arraybuffers
        if (vertexBuffer.data.length / 4 !== points.length) {
            vertexBuffer.data = new Float32Array(points.length * 4);
            uvBuffer.data = new Float32Array(points.length * 4);
            indexBuffer.data = new Uint16Array((points.length - 1) * 6);
        }
        var uvs = uvBuffer.data;
        var indices = indexBuffer.data;
        uvs[0] = 0;
        uvs[1] = 0;
        uvs[2] = 0;
        uvs[3] = 1;
        var amount = 0;
        var prev = points[0];
        var textureWidth = this._width * this.textureScale;
        var total = points.length; // - 1;
        for (var i = 0; i < total; i++) {
            // time to do some smart drawing!
            var index = i * 4;
            if (this.textureScale > 0) {
                // calculate pixel distance from previous point
                var dx = prev.x - points[i].x;
                var dy = prev.y - points[i].y;
                var distance = Math.sqrt((dx * dx) + (dy * dy));
                prev = points[i];
                amount += distance / textureWidth;
            }
            else {
                // stretch texture
                amount = i / (total - 1);
            }
            uvs[index] = amount;
            uvs[index + 1] = 0;
            uvs[index + 2] = amount;
            uvs[index + 3] = 1;
        }
        var indexCount = 0;
        for (var i = 0; i < total - 1; i++) {
            var index = i * 2;
            indices[indexCount++] = index;
            indices[indexCount++] = index + 1;
            indices[indexCount++] = index + 2;
            indices[indexCount++] = index + 2;
            indices[indexCount++] = index + 1;
            indices[indexCount++] = index + 3;
        }
        // ensure that the changes are uploaded
        uvBuffer.update();
        indexBuffer.update();
        this.updateVertices();
    };
    /**
     * refreshes vertices of Rope mesh
     */
    RopeGeometry.prototype.updateVertices = function () {
        var points = this.points;
        if (points.length < 1) {
            return;
        }
        var lastPoint = points[0];
        var nextPoint;
        var perpX = 0;
        var perpY = 0;
        var vertices = this.buffers[0].data;
        var total = points.length;
        for (var i = 0; i < total; i++) {
            var point = points[i];
            var index = i * 4;
            if (i < points.length - 1) {
                nextPoint = points[i + 1];
            }
            else {
                nextPoint = point;
            }
            perpY = -(nextPoint.x - lastPoint.x);
            perpX = nextPoint.y - lastPoint.y;
            var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY));
            var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2;
            perpX /= perpLength;
            perpY /= perpLength;
            perpX *= num;
            perpY *= num;
            vertices[index] = point.x + perpX;
            vertices[index + 1] = point.y + perpY;
            vertices[index + 2] = point.x - perpX;
            vertices[index + 3] = point.y - perpY;
            lastPoint = point;
        }
        this.buffers[0].update();
    };
    RopeGeometry.prototype.update = function () {
        if (this.textureScale > 0) {
            this.build(); // we need to update UVs
        }
        else {
            this.updateVertices();
        }
    };
    return RopeGeometry;
}(MeshGeometry));

/**
 * The rope allows you to draw a texture across several points and then manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points);
 *  ```
 *
 * @memberof PIXI
 */
var SimpleRope = /** @class */ (function (_super) {
    mesh_extras_extends(SimpleRope, _super);
    /**
     * @param texture - The texture to use on the rope.
     * @param points - An array of {@link PIXI.Point} objects to construct this rope.
     * @param {number} textureScale - Optional. Positive values scale rope texture
     * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture
     * and downsampling here. If set to zero, texture will be stretched instead.
     */
    function SimpleRope(texture, points, textureScale) {
        if (textureScale === void 0) { textureScale = 0; }
        var _this = this;
        var ropeGeometry = new RopeGeometry(texture.height, points, textureScale);
        var meshMaterial = new MeshMaterial(texture);
        if (textureScale > 0) {
            // attempt to set UV wrapping, will fail on non-power of two textures
            texture.baseTexture.wrapMode = constants_WRAP_MODES.REPEAT;
        }
        _this = _super.call(this, ropeGeometry, meshMaterial) || this;
        /**
         * re-calculate vertices by rope points each frame
         *
         * @member {boolean}
         */
        _this.autoUpdate = true;
        return _this;
    }
    SimpleRope.prototype._render = function (renderer) {
        var geometry = this.geometry;
        if (this.autoUpdate || geometry._width !== this.shader.texture.height) {
            geometry._width = this.shader.texture.height;
            geometry.update();
        }
        _super.prototype._render.call(this, renderer);
    };
    return SimpleRope;
}(Mesh));

/**
 * The SimplePlane allows you to draw a texture across several points and then manipulate these points
 *
 *```js
 * for (let i = 0; i < 20; i++) {
 *     points.push(new PIXI.Point(i * 50, 0));
 * };
 * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points);
 *  ```
 *
 * @memberof PIXI
 */
var SimplePlane = /** @class */ (function (_super) {
    mesh_extras_extends(SimplePlane, _super);
    /**
     * @param texture - The texture to use on the SimplePlane.
     * @param verticesX - The number of vertices in the x-axis
     * @param verticesY - The number of vertices in the y-axis
     */
    function SimplePlane(texture, verticesX, verticesY) {
        var _this = this;
        var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY);
        var meshMaterial = new MeshMaterial(Texture.WHITE);
        _this = _super.call(this, planeGeometry, meshMaterial) || this;
        // lets call the setter to ensure all necessary updates are performed
        _this.texture = texture;
        _this.autoResize = true;
        return _this;
    }
    /**
     * Method used for overrides, to do something in case texture frame was changed.
     * Meshes based on plane can override it and change more details based on texture.
     */
    SimplePlane.prototype.textureUpdated = function () {
        this._textureID = this.shader.texture._updateID;
        var geometry = this.geometry;
        var _a = this.shader.texture, width = _a.width, height = _a.height;
        if (this.autoResize && (geometry.width !== width || geometry.height !== height)) {
            geometry.width = this.shader.texture.width;
            geometry.height = this.shader.texture.height;
            geometry.build();
        }
    };
    Object.defineProperty(SimplePlane.prototype, "texture", {
        get: function () {
            return this.shader.texture;
        },
        set: function (value) {
            // Track texture same way sprite does.
            // For generated meshes like NineSlicePlane it can change the geometry.
            // Unfortunately, this method might not work if you directly change texture in material.
            if (this.shader.texture === value) {
                return;
            }
            this.shader.texture = value;
            this._textureID = -1;
            if (value.baseTexture.valid) {
                this.textureUpdated();
            }
            else {
                value.once('update', this.textureUpdated, this);
            }
        },
        enumerable: false,
        configurable: true
    });
    SimplePlane.prototype._render = function (renderer) {
        if (this._textureID !== this.shader.texture._updateID) {
            this.textureUpdated();
        }
        _super.prototype._render.call(this, renderer);
    };
    SimplePlane.prototype.destroy = function (options) {
        this.shader.texture.off('update', this.textureUpdated, this);
        _super.prototype.destroy.call(this, options);
    };
    return SimplePlane;
}(Mesh));

/**
 * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments.
 * For more robust customization, use {@link PIXI.Mesh}.
 *
 * @memberof PIXI
 */
var SimpleMesh = /** @class */ (function (_super) {
    mesh_extras_extends(SimpleMesh, _super);
    /**
     * @param texture - The texture to use
     * @param {Float32Array} [vertices] - if you want to specify the vertices
     * @param {Float32Array} [uvs] - if you want to specify the uvs
     * @param {Uint16Array} [indices] - if you want to specify the indices
     * @param drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts
     */
    function SimpleMesh(texture, vertices, uvs, indices, drawMode) {
        if (texture === void 0) { texture = Texture.EMPTY; }
        var _this = this;
        var geometry = new MeshGeometry(vertices, uvs, indices);
        geometry.getBuffer('aVertexPosition').static = false;
        var meshMaterial = new MeshMaterial(texture);
        _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this;
        _this.autoUpdate = true;
        return _this;
    }
    Object.defineProperty(SimpleMesh.prototype, "vertices", {
        /**
         * Collection of vertices data.
         * @type {Float32Array}
         */
        get: function () {
            return this.geometry.getBuffer('aVertexPosition').data;
        },
        set: function (value) {
            this.geometry.getBuffer('aVertexPosition').data = value;
        },
        enumerable: false,
        configurable: true
    });
    SimpleMesh.prototype._render = function (renderer) {
        if (this.autoUpdate) {
            this.geometry.getBuffer('aVertexPosition').update();
        }
        _super.prototype._render.call(this, renderer);
    };
    return SimpleMesh;
}(Mesh));

var DEFAULT_BORDER_SIZE = 10;
/**
 * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful
 * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically
 *
 *```js
 * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15);
 *  ```
 * <pre>
 *      A                          B
 *    +---+----------------------+---+
 *  C | 1 |          2           | 3 |
 *    +---+----------------------+---+
 *    |   |                      |   |
 *    | 4 |          5           | 6 |
 *    |   |                      |   |
 *    +---+----------------------+---+
 *  D | 7 |          8           | 9 |
 *    +---+----------------------+---+

 *  When changing this objects width and/or height:
 *     areas 1 3 7 and 9 will remain unscaled.
 *     areas 2 and 8 will be stretched horizontally
 *     areas 4 and 6 will be stretched vertically
 *     area 5 will be stretched both horizontally and vertically
 * </pre>
 *
 * @memberof PIXI
 */
var NineSlicePlane = /** @class */ (function (_super) {
    mesh_extras_extends(NineSlicePlane, _super);
    /**
     * @param texture - The texture to use on the NineSlicePlane.
     * @param {number} [leftWidth=10] - size of the left vertical bar (A)
     * @param {number} [topHeight=10] - size of the top horizontal bar (C)
     * @param {number} [rightWidth=10] - size of the right vertical bar (B)
     * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D)
     */
    function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) {
        if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; }
        if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; }
        if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; }
        if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; }
        var _this = _super.call(this, Texture.WHITE, 4, 4) || this;
        _this._origWidth = texture.orig.width;
        _this._origHeight = texture.orig.height;
        /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
        _this._width = _this._origWidth;
        /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
        _this._height = _this._origHeight;
        _this._leftWidth = leftWidth;
        _this._rightWidth = rightWidth;
        _this._topHeight = topHeight;
        _this._bottomHeight = bottomHeight;
        // lets call the setter to ensure all necessary updates are performed
        _this.texture = texture;
        return _this;
    }
    NineSlicePlane.prototype.textureUpdated = function () {
        this._textureID = this.shader.texture._updateID;
        this._refresh();
    };
    Object.defineProperty(NineSlicePlane.prototype, "vertices", {
        get: function () {
            return this.geometry.getBuffer('aVertexPosition').data;
        },
        set: function (value) {
            this.geometry.getBuffer('aVertexPosition').data = value;
        },
        enumerable: false,
        configurable: true
    });
    /** Updates the horizontal vertices. */
    NineSlicePlane.prototype.updateHorizontalVertices = function () {
        var vertices = this.vertices;
        var scale = this._getMinScale();
        vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale;
        vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale);
        vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height;
    };
    /** Updates the vertical vertices. */
    NineSlicePlane.prototype.updateVerticalVertices = function () {
        var vertices = this.vertices;
        var scale = this._getMinScale();
        vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale;
        vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale);
        vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width;
    };
    /**
     * Returns the smaller of a set of vertical and horizontal scale of nine slice corners.
     *
     * @return Smaller number of vertical and horizontal scale.
     */
    NineSlicePlane.prototype._getMinScale = function () {
        var w = this._leftWidth + this._rightWidth;
        var scaleW = this._width > w ? 1.0 : this._width / w;
        var h = this._topHeight + this._bottomHeight;
        var scaleH = this._height > h ? 1.0 : this._height / h;
        var scale = Math.min(scaleW, scaleH);
        return scale;
    };
    Object.defineProperty(NineSlicePlane.prototype, "width", {
        /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
        get: function () {
            return this._width;
        },
        set: function (value) {
            this._width = value;
            this._refresh();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(NineSlicePlane.prototype, "height", {
        /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
        get: function () {
            return this._height;
        },
        set: function (value) {
            this._height = value;
            this._refresh();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(NineSlicePlane.prototype, "leftWidth", {
        /** The width of the left column. */
        get: function () {
            return this._leftWidth;
        },
        set: function (value) {
            this._leftWidth = value;
            this._refresh();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(NineSlicePlane.prototype, "rightWidth", {
        /** The width of the right column. */
        get: function () {
            return this._rightWidth;
        },
        set: function (value) {
            this._rightWidth = value;
            this._refresh();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(NineSlicePlane.prototype, "topHeight", {
        /** The height of the top row. */
        get: function () {
            return this._topHeight;
        },
        set: function (value) {
            this._topHeight = value;
            this._refresh();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", {
        /** The height of the bottom row. */
        get: function () {
            return this._bottomHeight;
        },
        set: function (value) {
            this._bottomHeight = value;
            this._refresh();
        },
        enumerable: false,
        configurable: true
    });
    /** Refreshes NineSlicePlane coords. All of them. */
    NineSlicePlane.prototype._refresh = function () {
        var texture = this.texture;
        var uvs = this.geometry.buffers[1].data;
        this._origWidth = texture.orig.width;
        this._origHeight = texture.orig.height;
        var _uvw = 1.0 / this._origWidth;
        var _uvh = 1.0 / this._origHeight;
        uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0;
        uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0;
        uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1;
        uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1;
        uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth;
        uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth);
        uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight;
        uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight);
        this.updateHorizontalVertices();
        this.updateVerticalVertices();
        this.geometry.buffers[0].update();
        this.geometry.buffers[1].update();
    };
    return NineSlicePlane;
}(SimplePlane));


//# sourceMappingURL=mesh-extras.js.map

;// CONCATENATED MODULE: ./node_modules/@pixi/sprite-animated/dist/esm/sprite-animated.js
/*!
 * @pixi/sprite-animated - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * @pixi/sprite-animated is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */




/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var sprite_animated_extendStatics = function(d, b) {
    sprite_animated_extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
    return sprite_animated_extendStatics(d, b);
};

function sprite_animated_extends(d, b) {
    sprite_animated_extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/**
 * An AnimatedSprite is a simple way to display an animation depicted by a list of textures.
 *
 * ```js
 * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"];
 * let textureArray = [];
 *
 * for (let i=0; i < 4; i++)
 * {
 *      let texture = PIXI.Texture.from(alienImages[i]);
 *      textureArray.push(texture);
 * };
 *
 * let animatedSprite = new PIXI.AnimatedSprite(textureArray);
 * ```
 *
 * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet}
 * containing the animation definitions:
 *
 * ```js
 * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
 *
 * function setup() {
 *   let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
 *   animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]);
 *   ...
 * }
 * ```
 *
 * @memberof PIXI
 */
var AnimatedSprite = /** @class */ (function (_super) {
    sprite_animated_extends(AnimatedSprite, _super);
    /**
     * @param textures - An array of {@link PIXI.Texture} or frame
     *  objects that make up the animation.
     * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time.
     */
    function AnimatedSprite(textures, autoUpdate) {
        if (autoUpdate === void 0) { autoUpdate = true; }
        var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this;
        _this._textures = null;
        _this._durations = null;
        _this._autoUpdate = autoUpdate;
        _this._isConnectedToTicker = false;
        _this.animationSpeed = 1;
        _this.loop = true;
        _this.updateAnchor = false;
        _this.onComplete = null;
        _this.onFrameChange = null;
        _this.onLoop = null;
        _this._currentTime = 0;
        _this._playing = false;
        _this._previousFrame = null;
        _this.textures = textures;
        return _this;
    }
    /** Stops the AnimatedSprite. */
    AnimatedSprite.prototype.stop = function () {
        if (!this._playing) {
            return;
        }
        this._playing = false;
        if (this._autoUpdate && this._isConnectedToTicker) {
            Ticker.shared.remove(this.update, this);
            this._isConnectedToTicker = false;
        }
    };
    /** Plays the AnimatedSprite. */
    AnimatedSprite.prototype.play = function () {
        if (this._playing) {
            return;
        }
        this._playing = true;
        if (this._autoUpdate && !this._isConnectedToTicker) {
            Ticker.shared.add(this.update, this, UPDATE_PRIORITY.HIGH);
            this._isConnectedToTicker = true;
        }
    };
    /**
     * Stops the AnimatedSprite and goes to a specific frame.
     *
     * @param frameNumber - Frame index to stop at.
     */
    AnimatedSprite.prototype.gotoAndStop = function (frameNumber) {
        this.stop();
        var previousFrame = this.currentFrame;
        this._currentTime = frameNumber;
        if (previousFrame !== this.currentFrame) {
            this.updateTexture();
        }
    };
    /**
     * Goes to a specific frame and begins playing the AnimatedSprite.
     *
     * @param frameNumber - Frame index to start at.
     */
    AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) {
        var previousFrame = this.currentFrame;
        this._currentTime = frameNumber;
        if (previousFrame !== this.currentFrame) {
            this.updateTexture();
        }
        this.play();
    };
    /**
     * Updates the object transform for rendering.
     *
     * @param deltaTime - Time since last tick.
     */
    AnimatedSprite.prototype.update = function (deltaTime) {
        if (!this._playing) {
            return;
        }
        var elapsed = this.animationSpeed * deltaTime;
        var previousFrame = this.currentFrame;
        if (this._durations !== null) {
            var lag = this._currentTime % 1 * this._durations[this.currentFrame];
            lag += elapsed / 60 * 1000;
            while (lag < 0) {
                this._currentTime--;
                lag += this._durations[this.currentFrame];
            }
            var sign = Math.sign(this.animationSpeed * deltaTime);
            this._currentTime = Math.floor(this._currentTime);
            while (lag >= this._durations[this.currentFrame]) {
                lag -= this._durations[this.currentFrame] * sign;
                this._currentTime += sign;
            }
            this._currentTime += lag / this._durations[this.currentFrame];
        }
        else {
            this._currentTime += elapsed;
        }
        if (this._currentTime < 0 && !this.loop) {
            this.gotoAndStop(0);
            if (this.onComplete) {
                this.onComplete();
            }
        }
        else if (this._currentTime >= this._textures.length && !this.loop) {
            this.gotoAndStop(this._textures.length - 1);
            if (this.onComplete) {
                this.onComplete();
            }
        }
        else if (previousFrame !== this.currentFrame) {
            if (this.loop && this.onLoop) {
                if (this.animationSpeed > 0 && this.currentFrame < previousFrame) {
                    this.onLoop();
                }
                else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) {
                    this.onLoop();
                }
            }
            this.updateTexture();
        }
    };
    /** Updates the displayed texture to match the current frame index. */
    AnimatedSprite.prototype.updateTexture = function () {
        var currentFrame = this.currentFrame;
        if (this._previousFrame === currentFrame) {
            return;
        }
        this._previousFrame = currentFrame;
        this._texture = this._textures[currentFrame];
        this._textureID = -1;
        this._textureTrimmedID = -1;
        this._cachedTint = 0xFFFFFF;
        this.uvs = this._texture._uvs.uvsFloat32;
        if (this.updateAnchor) {
            this._anchor.copyFrom(this._texture.defaultAnchor);
        }
        if (this.onFrameChange) {
            this.onFrameChange(this.currentFrame);
        }
    };
    /**
     * Stops the AnimatedSprite and destroys it.
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value.
     * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy
     *      method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well.
     * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well.
     */
    AnimatedSprite.prototype.destroy = function (options) {
        this.stop();
        _super.prototype.destroy.call(this, options);
        this.onComplete = null;
        this.onFrameChange = null;
        this.onLoop = null;
    };
    /**
     * A short hand way of creating an AnimatedSprite from an array of frame ids.
     *
     * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames.
     * @return - The new animated sprite with the specified frames.
     */
    AnimatedSprite.fromFrames = function (frames) {
        var textures = [];
        for (var i = 0; i < frames.length; ++i) {
            textures.push(Texture.from(frames[i]));
        }
        return new AnimatedSprite(textures);
    };
    /**
     * A short hand way of creating an AnimatedSprite from an array of image ids.
     *
     * @param images - The array of image urls the AnimatedSprite will use as its texture frames.
     * @return The new animate sprite with the specified images as frames.
     */
    AnimatedSprite.fromImages = function (images) {
        var textures = [];
        for (var i = 0; i < images.length; ++i) {
            textures.push(Texture.from(images[i]));
        }
        return new AnimatedSprite(textures);
    };
    Object.defineProperty(AnimatedSprite.prototype, "totalFrames", {
        /**
         * The total number of frames in the AnimatedSprite. This is the same as number of textures
         * assigned to the AnimatedSprite.
         *
         * @readonly
         * @default 0
         */
        get: function () {
            return this._textures.length;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AnimatedSprite.prototype, "textures", {
        /** The array of textures used for this AnimatedSprite. */
        get: function () {
            return this._textures;
        },
        set: function (value) {
            if (value[0] instanceof Texture) {
                this._textures = value;
                this._durations = null;
            }
            else {
                this._textures = [];
                this._durations = [];
                for (var i = 0; i < value.length; i++) {
                    this._textures.push(value[i].texture);
                    this._durations.push(value[i].time);
                }
            }
            this._previousFrame = null;
            this.gotoAndStop(0);
            this.updateTexture();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AnimatedSprite.prototype, "currentFrame", {
        /**
         * The AnimatedSprites current frame index.
         *
         * @readonly
         */
        get: function () {
            var currentFrame = Math.floor(this._currentTime) % this._textures.length;
            if (currentFrame < 0) {
                currentFrame += this._textures.length;
            }
            return currentFrame;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AnimatedSprite.prototype, "playing", {
        /**
         * Indicates if the AnimatedSprite is currently playing.
         *
         * @readonly
         */
        get: function () {
            return this._playing;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", {
        /** Whether to use PIXI.Ticker.shared to auto update animation time. */
        get: function () {
            return this._autoUpdate;
        },
        set: function (value) {
            if (value !== this._autoUpdate) {
                this._autoUpdate = value;
                if (!this._autoUpdate && this._isConnectedToTicker) {
                    Ticker.shared.remove(this.update, this);
                    this._isConnectedToTicker = false;
                }
                else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) {
                    Ticker.shared.add(this.update, this);
                    this._isConnectedToTicker = true;
                }
            }
        },
        enumerable: false,
        configurable: true
    });
    return AnimatedSprite;
}(Sprite));


//# sourceMappingURL=sprite-animated.js.map

;// CONCATENATED MODULE: ./node_modules/pixi.js/dist/esm/pixi.js
/*!
 * pixi.js - v6.3.0
 * Compiled Wed, 23 Mar 2022 18:58:56 UTC
 *
 * pixi.js is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */


















































// Install renderer plugins
Renderer.registerPlugin('accessibility', AccessibilityManager);
Renderer.registerPlugin('extract', Extract);
Renderer.registerPlugin('interaction', InteractionManager);
Renderer.registerPlugin('particle', ParticleRenderer);
Renderer.registerPlugin('prepare', Prepare);
Renderer.registerPlugin('batch', BatchRenderer);
Renderer.registerPlugin('tilingSprite', TilingSpriteRenderer);
// Install loader plugins
Loader.registerPlugin(BitmapFontLoader);
Loader.registerPlugin(CompressedTextureLoader);
Loader.registerPlugin(DDSLoader);
Loader.registerPlugin(KTXLoader);
Loader.registerPlugin(SpritesheetLoader);
// Install application plugins
Application.registerPlugin(TickerPlugin);
Application.registerPlugin(AppLoaderPlugin);
/**
 * String of the current PIXI version.
 *
 * @static
 * @constant
 * @memberof PIXI
 * @name VERSION
 * @type {string}
 */
var pixi_VERSION = '6.3.0';
/**
 * @namespace PIXI
 */
/**
 * This namespace contains WebGL-only display filters that can be applied
 * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property.
 *
 * Since PixiJS only had a handful of built-in filters, additional filters
 * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the
 * PixiJS Filters repository.
 *
 * All filters must extend {@link PIXI.Filter}.
 *
 * @example
 * // Create a new application
 * const app = new PIXI.Application();
 *
 * // Draw a green rectangle
 * const rect = new PIXI.Graphics()
 *     .beginFill(0x00ff00)
 *     .drawRect(40, 40, 200, 200);
 *
 * // Add a blur filter
 * rect.filters = [new PIXI.filters.BlurFilter()];
 *
 * // Display rectangle
 * app.stage.addChild(rect);
 * document.body.appendChild(app.view);
 * @namespace PIXI.filters
 */
var filters = {
    AlphaFilter: AlphaFilter,
    BlurFilter: BlurFilter,
    BlurFilterPass: BlurFilterPass,
    ColorMatrixFilter: ColorMatrixFilter,
    DisplacementFilter: DisplacementFilter,
    FXAAFilter: FXAAFilter,
    NoiseFilter: NoiseFilter,
};


//# sourceMappingURL=pixi.js.map


/***/ }),

/***/ 4155:
/***/ ((module) => {

// 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; };


/***/ }),

/***/ 1798:
/***/ (function(module, exports, __webpack_require__) {

/* module decorator */ module = __webpack_require__.nmd(module);
/**
 * Copyright (c) 2010,2011,2012,2013,2014 Morgan Roderick http://roderick.dk
 * License: MIT - http://mrgnrdrck.mit-license.org
 *
 * https://github.com/mroderick/PubSubJS
 */

(function (root, factory){
    'use strict';

    var PubSub = {};

    if (root.PubSub) {
        PubSub = root.PubSub;
        console.warn("PubSub already loaded, using existing version");
    } else {
        root.PubSub = PubSub;
        factory(PubSub);
    }
    // CommonJS and Node.js module support
    if (true){
        if (module !== undefined && module.exports) {
            exports = module.exports = PubSub; // Node.js specific `module.exports`
        }
        exports.PubSub = PubSub; // CommonJS module 1.1.1 spec
        module.exports = exports = PubSub; // CommonJS
    }
    // AMD support
    /* eslint-disable no-undef */
    else {}

}(( typeof window === 'object' && window ) || this, function (PubSub){
    'use strict';

    var messages = {},
        lastUid = -1,
        ALL_SUBSCRIBING_MSG = '*';

    function hasKeys(obj){
        var key;

        for (key in obj){
            if ( Object.prototype.hasOwnProperty.call(obj, key) ){
                return true;
            }
        }
        return false;
    }

    /**
     * Returns a function that throws the passed exception, for use as argument for setTimeout
     * @alias throwException
     * @function
     * @param { Object } ex An Error object
     */
    function throwException( ex ){
        return function reThrowException(){
            throw ex;
        };
    }

    function callSubscriberWithDelayedExceptions( subscriber, message, data ){
        try {
            subscriber( message, data );
        } catch( ex ){
            setTimeout( throwException( ex ), 0);
        }
    }

    function callSubscriberWithImmediateExceptions( subscriber, message, data ){
        subscriber( message, data );
    }

    function deliverMessage( originalMessage, matchedMessage, data, immediateExceptions ){
        var subscribers = messages[matchedMessage],
            callSubscriber = immediateExceptions ? callSubscriberWithImmediateExceptions : callSubscriberWithDelayedExceptions,
            s;

        if ( !Object.prototype.hasOwnProperty.call( messages, matchedMessage ) ) {
            return;
        }

        for (s in subscribers){
            if ( Object.prototype.hasOwnProperty.call(subscribers, s)){
                callSubscriber( subscribers[s], originalMessage, data );
            }
        }
    }

    function createDeliveryFunction( message, data, immediateExceptions ){
        return function deliverNamespaced(){
            var topic = String( message ),
                position = topic.lastIndexOf( '.' );

            // deliver the message as it is now
            deliverMessage(message, message, data, immediateExceptions);

            // trim the hierarchy and deliver message to each level
            while( position !== -1 ){
                topic = topic.substr( 0, position );
                position = topic.lastIndexOf('.');
                deliverMessage( message, topic, data, immediateExceptions );
            }

            deliverMessage(message, ALL_SUBSCRIBING_MSG, data, immediateExceptions);
        };
    }

    function hasDirectSubscribersFor( message ) {
        var topic = String( message ),
            found = Boolean(Object.prototype.hasOwnProperty.call( messages, topic ) && hasKeys(messages[topic]));

        return found;
    }

    function messageHasSubscribers( message ){
        var topic = String( message ),
            found = hasDirectSubscribersFor(topic) || hasDirectSubscribersFor(ALL_SUBSCRIBING_MSG),
            position = topic.lastIndexOf( '.' );

        while ( !found && position !== -1 ){
            topic = topic.substr( 0, position );
            position = topic.lastIndexOf( '.' );
            found = hasDirectSubscribersFor(topic);
        }

        return found;
    }

    function publish( message, data, sync, immediateExceptions ){
        message = (typeof message === 'symbol') ? message.toString() : message;

        var deliver = createDeliveryFunction( message, data, immediateExceptions ),
            hasSubscribers = messageHasSubscribers( message );

        if ( !hasSubscribers ){
            return false;
        }

        if ( sync === true ){
            deliver();
        } else {
            setTimeout( deliver, 0 );
        }
        return true;
    }

    /**
     * Publishes the message, passing the data to it's subscribers
     * @function
     * @alias publish
     * @param { String } message The message to publish
     * @param {} data The data to pass to subscribers
     * @return { Boolean }
     */
    PubSub.publish = function( message, data ){
        return publish( message, data, false, PubSub.immediateExceptions );
    };

    /**
     * Publishes the message synchronously, passing the data to it's subscribers
     * @function
     * @alias publishSync
     * @param { String } message The message to publish
     * @param {} data The data to pass to subscribers
     * @return { Boolean }
     */
    PubSub.publishSync = function( message, data ){
        return publish( message, data, true, PubSub.immediateExceptions );
    };

    /**
     * Subscribes the passed function to the passed message. Every returned token is unique and should be stored if you need to unsubscribe
     * @function
     * @alias subscribe
     * @param { String } message The message to subscribe to
     * @param { Function } func The function to call when a new message is published
     * @return { String }
     */
    PubSub.subscribe = function( message, func ){
        if ( typeof func !== 'function'){
            return false;
        }

        message = (typeof message === 'symbol') ? message.toString() : message;

        // message is not registered yet
        if ( !Object.prototype.hasOwnProperty.call( messages, message ) ){
            messages[message] = {};
        }

        // forcing token as String, to allow for future expansions without breaking usage
        // and allow for easy use as key names for the 'messages' object
        var token = 'uid_' + String(++lastUid);
        messages[message][token] = func;

        // return token for unsubscribing
        return token;
    };

    PubSub.subscribeAll = function( func ){
        return PubSub.subscribe(ALL_SUBSCRIBING_MSG, func);
    };

    /**
     * Subscribes the passed function to the passed message once
     * @function
     * @alias subscribeOnce
     * @param { String } message The message to subscribe to
     * @param { Function } func The function to call when a new message is published
     * @return { PubSub }
     */
    PubSub.subscribeOnce = function( message, func ){
        var token = PubSub.subscribe( message, function(){
            // before func apply, unsubscribe message
            PubSub.unsubscribe( token );
            func.apply( this, arguments );
        });
        return PubSub;
    };

    /**
     * Clears all subscriptions
     * @function
     * @public
     * @alias clearAllSubscriptions
     */
    PubSub.clearAllSubscriptions = function clearAllSubscriptions(){
        messages = {};
    };

    /**
     * Clear subscriptions by the topic
     * @function
     * @public
     * @alias clearAllSubscriptions
     * @return { int }
     */
    PubSub.clearSubscriptions = function clearSubscriptions(topic){
        var m;
        for (m in messages){
            if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
                delete messages[m];
            }
        }
    };

    /**
       Count subscriptions by the topic
     * @function
     * @public
     * @alias countSubscriptions
     * @return { Array }
    */
    PubSub.countSubscriptions = function countSubscriptions(topic){
        var m;
        // eslint-disable-next-line no-unused-vars
        var token;
        var count = 0;
        for (m in messages) {
            if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0) {
                for (token in messages[m]) {
                    count++;
                }
                break;
            }
        }
        return count;
    };


    /**
       Gets subscriptions by the topic
     * @function
     * @public
     * @alias getSubscriptions
    */
    PubSub.getSubscriptions = function getSubscriptions(topic){
        var m;
        var list = [];
        for (m in messages){
            if (Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0){
                list.push(m);
            }
        }
        return list;
    };

    /**
     * Removes subscriptions
     *
     * - When passed a token, removes a specific subscription.
     *
	 * - When passed a function, removes all subscriptions for that function
     *
	 * - When passed a topic, removes all subscriptions for that topic (hierarchy)
     * @function
     * @public
     * @alias subscribeOnce
     * @param { String | Function } value A token, function or topic to unsubscribe from
     * @example // Unsubscribing with a token
     * var token = PubSub.subscribe('mytopic', myFunc);
     * PubSub.unsubscribe(token);
     * @example // Unsubscribing with a function
     * PubSub.unsubscribe(myFunc);
     * @example // Unsubscribing from a topic
     * PubSub.unsubscribe('mytopic');
     */
    PubSub.unsubscribe = function(value){
        var descendantTopicExists = function(topic) {
                var m;
                for ( m in messages ){
                    if ( Object.prototype.hasOwnProperty.call(messages, m) && m.indexOf(topic) === 0 ){
                        // a descendant of the topic exists:
                        return true;
                    }
                }

                return false;
            },
            isTopic    = typeof value === 'string' && ( Object.prototype.hasOwnProperty.call(messages, value) || descendantTopicExists(value) ),
            isToken    = !isTopic && typeof value === 'string',
            isFunction = typeof value === 'function',
            result = false,
            m, message, t;

        if (isTopic){
            PubSub.clearSubscriptions(value);
            return;
        }

        for ( m in messages ){
            if ( Object.prototype.hasOwnProperty.call( messages, m ) ){
                message = messages[m];

                if ( isToken && message[value] ){
                    delete message[value];
                    result = value;
                    // tokens are unique, so we can just stop here
                    break;
                }

                if (isFunction) {
                    for ( t in message ){
                        if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value){
                            delete message[t];
                            result = true;
                        }
                    }
                }
            }
        }

        return result;
    };
}));


/***/ }),

/***/ 2587:
/***/ ((module) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}

module.exports = function(qs, sep, eq, options) {
  sep = sep || '&';
  eq = eq || '=';
  var obj = {};

  if (typeof qs !== 'string' || qs.length === 0) {
    return obj;
  }

  var regexp = /\+/g;
  qs = qs.split(sep);

  var maxKeys = 1000;
  if (options && typeof options.maxKeys === 'number') {
    maxKeys = options.maxKeys;
  }

  var len = qs.length;
  // maxKeys <= 0 means that we should not limit keys count
  if (maxKeys > 0 && len > maxKeys) {
    len = maxKeys;
  }

  for (var i = 0; i < len; ++i) {
    var x = qs[i].replace(regexp, '%20'),
        idx = x.indexOf(eq),
        kstr, vstr, k, v;

    if (idx >= 0) {
      kstr = x.substr(0, idx);
      vstr = x.substr(idx + 1);
    } else {
      kstr = x;
      vstr = '';
    }

    k = decodeURIComponent(kstr);
    v = decodeURIComponent(vstr);

    if (!hasOwnProperty(obj, k)) {
      obj[k] = v;
    } else if (Array.isArray(obj[k])) {
      obj[k].push(v);
    } else {
      obj[k] = [obj[k], v];
    }
  }

  return obj;
};


/***/ }),

/***/ 2361:
/***/ ((module) => {

"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



var stringifyPrimitive = function(v) {
  switch (typeof v) {
    case 'string':
      return v;

    case 'boolean':
      return v ? 'true' : 'false';

    case 'number':
      return isFinite(v) ? v : '';

    default:
      return '';
  }
};

module.exports = function(obj, sep, eq, name) {
  sep = sep || '&';
  eq = eq || '=';
  if (obj === null) {
    obj = undefined;
  }

  if (typeof obj === 'object') {
    return Object.keys(obj).map(function(k) {
      var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
      if (Array.isArray(obj[k])) {
        return obj[k].map(function(v) {
          return ks + encodeURIComponent(stringifyPrimitive(v));
        }).join(sep);
      } else {
        return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
      }
    }).join(sep);

  }

  if (!name) return '';
  return encodeURIComponent(stringifyPrimitive(name)) + eq +
         encodeURIComponent(stringifyPrimitive(obj));
};


/***/ }),

/***/ 7673:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";


exports.decode = exports.parse = __webpack_require__(2587);
exports.encode = exports.stringify = __webpack_require__(2361);


/***/ }),

/***/ 2582:
/***/ (function(module) {

!function(t,i){ true?module.exports=i():0}(this,function(){"use strict";function t(t,r,e,a,h){!function t(n,r,e,a,h){for(;a>e;){if(a-e>600){var o=a-e+1,s=r-e+1,l=Math.log(o),f=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*f*(o-f)/o)*(s-o/2<0?-1:1),m=Math.max(e,Math.floor(r-s*f/o+u)),c=Math.min(a,Math.floor(r+(o-s)*f/o+u));t(n,r,m,c,h)}var p=n[r],d=e,x=a;for(i(n,e,r),h(n[a],p)>0&&i(n,e,a);d<x;){for(i(n,d,x),d++,x--;h(n[d],p)<0;)d++;for(;h(n[x],p)>0;)x--}0===h(n[e],p)?i(n,e,x):i(n,++x,a),x<=r&&(e=x+1),r<=x&&(a=x-1)}}(t,r,e||0,a||t.length-1,h||n)}function i(t,i,n){var r=t[i];t[i]=t[n],t[n]=r}function n(t,i){return t<i?-1:t>i?1:0}var r=function(t){void 0===t&&(t=9),this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function e(t,i,n){if(!n)return i.indexOf(t);for(var r=0;r<i.length;r++)if(n(t,i[r]))return r;return-1}function a(t,i){h(t,0,t.children.length,i,t)}function h(t,i,n,r,e){e||(e=p(null)),e.minX=1/0,e.minY=1/0,e.maxX=-1/0,e.maxY=-1/0;for(var a=i;a<n;a++){var h=t.children[a];o(e,t.leaf?r(h):h)}return e}function o(t,i){return t.minX=Math.min(t.minX,i.minX),t.minY=Math.min(t.minY,i.minY),t.maxX=Math.max(t.maxX,i.maxX),t.maxY=Math.max(t.maxY,i.maxY),t}function s(t,i){return t.minX-i.minX}function l(t,i){return t.minY-i.minY}function f(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function u(t){return t.maxX-t.minX+(t.maxY-t.minY)}function m(t,i){return t.minX<=i.minX&&t.minY<=i.minY&&i.maxX<=t.maxX&&i.maxY<=t.maxY}function c(t,i){return i.minX<=t.maxX&&i.minY<=t.maxY&&i.maxX>=t.minX&&i.maxY>=t.minY}function p(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function d(i,n,r,e,a){for(var h=[n,r];h.length;)if(!((r=h.pop())-(n=h.pop())<=e)){var o=n+Math.ceil((r-n)/e/2)*e;t(i,o,n,r,a),h.push(n,o,o,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(t){var i=this.data,n=[];if(!c(t,i))return n;for(var r=this.toBBox,e=[];i;){for(var a=0;a<i.children.length;a++){var h=i.children[a],o=i.leaf?r(h):h;c(t,o)&&(i.leaf?n.push(h):m(t,o)?this._all(h,n):e.push(h))}i=e.pop()}return n},r.prototype.collides=function(t){var i=this.data;if(!c(t,i))return!1;for(var n=[];i;){for(var r=0;r<i.children.length;r++){var e=i.children[r],a=i.leaf?this.toBBox(e):e;if(c(t,a)){if(i.leaf||m(t,a))return!0;n.push(e)}}i=n.pop()}return!1},r.prototype.load=function(t){if(!t||!t.length)return this;if(t.length<this._minEntries){for(var i=0;i<t.length;i++)this.insert(t[i]);return this}var n=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){var r=this.data;this.data=n,n=r}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this},r.prototype.insert=function(t){return t&&this._insert(t,this.data.height-1),this},r.prototype.clear=function(){return this.data=p([]),this},r.prototype.remove=function(t,i){if(!t)return this;for(var n,r,a,h=this.data,o=this.toBBox(t),s=[],l=[];h||s.length;){if(h||(h=s.pop(),r=s[s.length-1],n=l.pop(),a=!0),h.leaf){var f=e(t,h.children,i);if(-1!==f)return h.children.splice(f,1),s.push(h),this._condense(s),this}a||h.leaf||!m(h,o)?r?(n++,h=r.children[n],a=!1):h=null:(s.push(h),l.push(n),n=0,r=h,h=h.children[0])}return this},r.prototype.toBBox=function(t){return t},r.prototype.compareMinX=function(t,i){return t.minX-i.minX},r.prototype.compareMinY=function(t,i){return t.minY-i.minY},r.prototype.toJSON=function(){return this.data},r.prototype.fromJSON=function(t){return this.data=t,this},r.prototype._all=function(t,i){for(var n=[];t;)t.leaf?i.push.apply(i,t.children):n.push.apply(n,t.children),t=n.pop();return i},r.prototype._build=function(t,i,n,r){var e,h=n-i+1,o=this._maxEntries;if(h<=o)return a(e=p(t.slice(i,n+1)),this.toBBox),e;r||(r=Math.ceil(Math.log(h)/Math.log(o)),o=Math.ceil(h/Math.pow(o,r-1))),(e=p([])).leaf=!1,e.height=r;var s=Math.ceil(h/o),l=s*Math.ceil(Math.sqrt(o));d(t,i,n,l,this.compareMinX);for(var f=i;f<=n;f+=l){var u=Math.min(f+l-1,n);d(t,f,u,s,this.compareMinY);for(var m=f;m<=u;m+=s){var c=Math.min(m+s-1,u);e.children.push(this._build(t,m,c,r-1))}}return a(e,this.toBBox),e},r.prototype._chooseSubtree=function(t,i,n,r){for(;r.push(i),!i.leaf&&r.length-1!==n;){for(var e=1/0,a=1/0,h=void 0,o=0;o<i.children.length;o++){var s=i.children[o],l=f(s),u=(m=t,c=s,(Math.max(c.maxX,m.maxX)-Math.min(c.minX,m.minX))*(Math.max(c.maxY,m.maxY)-Math.min(c.minY,m.minY))-l);u<a?(a=u,e=l<e?l:e,h=s):u===a&&l<e&&(e=l,h=s)}i=h||i.children[0]}var m,c;return i},r.prototype._insert=function(t,i,n){var r=n?t:this.toBBox(t),e=[],a=this._chooseSubtree(r,this.data,i,e);for(a.children.push(t),o(a,r);i>=0&&e[i].children.length>this._maxEntries;)this._split(e,i),i--;this._adjustParentBBoxes(r,e,i)},r.prototype._split=function(t,i){var n=t[i],r=n.children.length,e=this._minEntries;this._chooseSplitAxis(n,e,r);var h=this._chooseSplitIndex(n,e,r),o=p(n.children.splice(h,n.children.length-h));o.height=n.height,o.leaf=n.leaf,a(n,this.toBBox),a(o,this.toBBox),i?t[i-1].children.push(o):this._splitRoot(n,o)},r.prototype._splitRoot=function(t,i){this.data=p([t,i]),this.data.height=t.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(t,i,n){for(var r,e,a,o,s,l,u,m=1/0,c=1/0,p=i;p<=n-i;p++){var d=h(t,0,p,this.toBBox),x=h(t,p,n,this.toBBox),v=(e=d,a=x,o=void 0,s=void 0,l=void 0,u=void 0,o=Math.max(e.minX,a.minX),s=Math.max(e.minY,a.minY),l=Math.min(e.maxX,a.maxX),u=Math.min(e.maxY,a.maxY),Math.max(0,l-o)*Math.max(0,u-s)),M=f(d)+f(x);v<m?(m=v,r=p,c=M<c?M:c):v===m&&M<c&&(c=M,r=p)}return r||n-i},r.prototype._chooseSplitAxis=function(t,i,n){var r=t.leaf?this.compareMinX:s,e=t.leaf?this.compareMinY:l;this._allDistMargin(t,i,n,r)<this._allDistMargin(t,i,n,e)&&t.children.sort(r)},r.prototype._allDistMargin=function(t,i,n,r){t.children.sort(r);for(var e=this.toBBox,a=h(t,0,i,e),s=h(t,n-i,n,e),l=u(a)+u(s),f=i;f<n-i;f++){var m=t.children[f];o(a,t.leaf?e(m):m),l+=u(a)}for(var c=n-i-1;c>=i;c--){var p=t.children[c];o(s,t.leaf?e(p):p),l+=u(s)}return l},r.prototype._adjustParentBBoxes=function(t,i,n){for(var r=n;r>=0;r--)o(i[r],t)},r.prototype._condense=function(t){for(var i=t.length-1,n=void 0;i>=0;i--)0===t[i].children.length?i>0?(n=t[i-1].children).splice(n.indexOf(t[i]),1):this.clear():a(t[i],this.toBBox)},r});


/***/ }),

/***/ 2467:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.serialize = exports.deserialize = exports.registerSerializer = void 0;
const serializers_1 = __webpack_require__(7381);
let registeredSerializer = serializers_1.DefaultSerializer;
function registerSerializer(serializer) {
    registeredSerializer = serializers_1.extendSerializer(registeredSerializer, serializer);
}
exports.registerSerializer = registerSerializer;
function deserialize(message) {
    return registeredSerializer.deserialize(message);
}
exports.deserialize = deserialize;
function serialize(input) {
    return registeredSerializer.serialize(input);
}
exports.serialize = serialize;


/***/ }),

/***/ 3734:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Transfer = exports.DefaultSerializer = exports.expose = exports.registerSerializer = void 0;
var common_1 = __webpack_require__(2467);
Object.defineProperty(exports, "registerSerializer", ({ enumerable: true, get: function () { return common_1.registerSerializer; } }));
__exportStar(__webpack_require__(5063), exports);
var index_1 = __webpack_require__(1934);
Object.defineProperty(exports, "expose", ({ enumerable: true, get: function () { return index_1.expose; } }));
var serializers_1 = __webpack_require__(7381);
Object.defineProperty(exports, "DefaultSerializer", ({ enumerable: true, get: function () { return serializers_1.DefaultSerializer; } }));
var transferable_1 = __webpack_require__(8180);
Object.defineProperty(exports, "Transfer", ({ enumerable: true, get: function () { return transferable_1.Transfer; } }));


/***/ }),

/***/ 4211:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

// Source: <https://github.com/parcel-bundler/parcel/blob/master/packages/core/parcel-bundler/src/builtins/bundle-url.js>
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getBundleURL = exports.getBaseURL = void 0;
let bundleURL;
function getBundleURLCached() {
    if (!bundleURL) {
        bundleURL = getBundleURL();
    }
    return bundleURL;
}
exports.getBundleURL = getBundleURLCached;
function getBundleURL() {
    // Attempt to find the URL of the current script and use that as the base URL
    try {
        throw new Error;
    }
    catch (err) {
        const matches = ("" + err.stack).match(/(https?|file|ftp|chrome-extension|moz-extension):\/\/[^)\n]+/g);
        if (matches) {
            return getBaseURL(matches[0]);
        }
    }
    return "/";
}
function getBaseURL(url) {
    return ("" + url).replace(/^((?:https?|file|ftp|chrome-extension|moz-extension):\/\/.+)?\/[^/]+(?:\?.*)?$/, '$1') + '/';
}
exports.getBaseURL = getBaseURL;


/***/ }),

/***/ 8390:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

// tslint:disable max-classes-per-file
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isWorkerRuntime = exports.getWorkerImplementation = exports.defaultPoolSize = void 0;
const get_bundle_url_browser_1 = __webpack_require__(4211);
exports.defaultPoolSize = typeof navigator !== "undefined" && navigator.hardwareConcurrency
    ? navigator.hardwareConcurrency
    : 4;
const isAbsoluteURL = (value) => /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(value);
function createSourceBlobURL(code) {
    const blob = new Blob([code], { type: "application/javascript" });
    return URL.createObjectURL(blob);
}
function selectWorkerImplementation() {
    if (typeof Worker === "undefined") {
        // Might happen on Safari, for instance
        // The idea is to only fail if the constructor is actually used
        return class NoWebWorker {
            constructor() {
                throw Error("No web worker implementation available. You might have tried to spawn a worker within a worker in a browser that doesn't support workers in workers.");
            }
        };
    }
    class WebWorker extends Worker {
        constructor(url, options) {
            var _a, _b;
            if (typeof url === "string" && options && options._baseURL) {
                url = new URL(url, options._baseURL);
            }
            else if (typeof url === "string" && !isAbsoluteURL(url) && get_bundle_url_browser_1.getBundleURL().match(/^file:\/\//i)) {
                url = new URL(url, get_bundle_url_browser_1.getBundleURL().replace(/\/[^\/]+$/, "/"));
                if ((_a = options === null || options === void 0 ? void 0 : options.CORSWorkaround) !== null && _a !== void 0 ? _a : true) {
                    url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`);
                }
            }
            if (typeof url === "string" && isAbsoluteURL(url)) {
                // Create source code blob loading JS file via `importScripts()`
                // to circumvent worker CORS restrictions
                if ((_b = options === null || options === void 0 ? void 0 : options.CORSWorkaround) !== null && _b !== void 0 ? _b : true) {
                    url = createSourceBlobURL(`importScripts(${JSON.stringify(url)});`);
                }
            }
            super(url, options);
        }
    }
    class BlobWorker extends WebWorker {
        constructor(blob, options) {
            const url = window.URL.createObjectURL(blob);
            super(url, options);
        }
        static fromText(source, options) {
            const blob = new window.Blob([source], { type: "text/javascript" });
            return new BlobWorker(blob, options);
        }
    }
    return {
        blob: BlobWorker,
        default: WebWorker
    };
}
let implementation;
function getWorkerImplementation() {
    if (!implementation) {
        implementation = selectWorkerImplementation();
    }
    return implementation;
}
exports.getWorkerImplementation = getWorkerImplementation;
function isWorkerRuntime() {
    const isWindowContext = typeof self !== "undefined" && typeof Window !== "undefined" && self instanceof Window;
    return typeof self !== "undefined" && self.postMessage && !isWindowContext ? true : false;
}
exports.isWorkerRuntime = isWorkerRuntime;


/***/ }),

/***/ 5063:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Worker = exports.BlobWorker = exports.isWorkerRuntime = exports.Thread = exports.spawn = exports.Pool = void 0;
const implementation_1 = __webpack_require__(8390);
Object.defineProperty(exports, "isWorkerRuntime", ({ enumerable: true, get: function () { return implementation_1.isWorkerRuntime; } }));
var pool_1 = __webpack_require__(9337);
Object.defineProperty(exports, "Pool", ({ enumerable: true, get: function () { return pool_1.Pool; } }));
var spawn_1 = __webpack_require__(1264);
Object.defineProperty(exports, "spawn", ({ enumerable: true, get: function () { return spawn_1.spawn; } }));
var thread_1 = __webpack_require__(4235);
Object.defineProperty(exports, "Thread", ({ enumerable: true, get: function () { return thread_1.Thread; } }));
/** Separate class to spawn workers from source code blobs or strings. */
exports.BlobWorker = implementation_1.getWorkerImplementation().blob;
/** Worker implementation. Either web worker or a node.js Worker class. */
exports.Worker = implementation_1.getWorkerImplementation().default;


/***/ }),

/***/ 6891:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 * This source file contains the code for proxying calls in the master thread to calls in the workers
 * by `.postMessage()`-ing.
 *
 * Keep in mind that this code can make or break the program's performance! Need to optimize more…
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createProxyModule = exports.createProxyFunction = void 0;
const debug_1 = __importDefault(__webpack_require__(1227));
const observable_fns_1 = __webpack_require__(9599);
const common_1 = __webpack_require__(2467);
const observable_promise_1 = __webpack_require__(2015);
const transferable_1 = __webpack_require__(8180);
const messages_1 = __webpack_require__(3229);
const debugMessages = debug_1.default("threads:master:messages");
let nextJobUID = 1;
const dedupe = (array) => Array.from(new Set(array));
const isJobErrorMessage = (data) => data && data.type === messages_1.WorkerMessageType.error;
const isJobResultMessage = (data) => data && data.type === messages_1.WorkerMessageType.result;
const isJobStartMessage = (data) => data && data.type === messages_1.WorkerMessageType.running;
function createObservableForJob(worker, jobUID) {
    return new observable_fns_1.Observable(observer => {
        let asyncType;
        const messageHandler = ((event) => {
            debugMessages("Message from worker:", event.data);
            if (!event.data || event.data.uid !== jobUID)
                return;
            if (isJobStartMessage(event.data)) {
                asyncType = event.data.resultType;
            }
            else if (isJobResultMessage(event.data)) {
                if (asyncType === "promise") {
                    if (typeof event.data.payload !== "undefined") {
                        observer.next(common_1.deserialize(event.data.payload));
                    }
                    observer.complete();
                    worker.removeEventListener("message", messageHandler);
                }
                else {
                    if (event.data.payload) {
                        observer.next(common_1.deserialize(event.data.payload));
                    }
                    if (event.data.complete) {
                        observer.complete();
                        worker.removeEventListener("message", messageHandler);
                    }
                }
            }
            else if (isJobErrorMessage(event.data)) {
                const error = common_1.deserialize(event.data.error);
                if (asyncType === "promise" || !asyncType) {
                    observer.error(error);
                }
                else {
                    observer.error(error);
                }
                worker.removeEventListener("message", messageHandler);
            }
        });
        worker.addEventListener("message", messageHandler);
        return () => {
            if (asyncType === "observable" || !asyncType) {
                const cancelMessage = {
                    type: messages_1.MasterMessageType.cancel,
                    uid: jobUID
                };
                worker.postMessage(cancelMessage);
            }
            worker.removeEventListener("message", messageHandler);
        };
    });
}
function prepareArguments(rawArgs) {
    if (rawArgs.length === 0) {
        // Exit early if possible
        return {
            args: [],
            transferables: []
        };
    }
    const args = [];
    const transferables = [];
    for (const arg of rawArgs) {
        if (transferable_1.isTransferDescriptor(arg)) {
            args.push(common_1.serialize(arg.send));
            transferables.push(...arg.transferables);
        }
        else {
            args.push(common_1.serialize(arg));
        }
    }
    return {
        args,
        transferables: transferables.length === 0 ? transferables : dedupe(transferables)
    };
}
function createProxyFunction(worker, method) {
    return ((...rawArgs) => {
        const uid = nextJobUID++;
        const { args, transferables } = prepareArguments(rawArgs);
        const runMessage = {
            type: messages_1.MasterMessageType.run,
            uid,
            method,
            args
        };
        debugMessages("Sending command to run function to worker:", runMessage);
        try {
            worker.postMessage(runMessage, transferables);
        }
        catch (error) {
            return observable_promise_1.ObservablePromise.from(Promise.reject(error));
        }
        return observable_promise_1.ObservablePromise.from(observable_fns_1.multicast(createObservableForJob(worker, uid)));
    });
}
exports.createProxyFunction = createProxyFunction;
function createProxyModule(worker, methodNames) {
    const proxy = {};
    for (const methodName of methodNames) {
        proxy[methodName] = createProxyFunction(worker, methodName);
    }
    return proxy;
}
exports.createProxyModule = createProxyModule;


/***/ }),

/***/ 6774:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PoolEventType = void 0;
/** Pool event type. Specifies the type of each `PoolEvent`. */
var PoolEventType;
(function (PoolEventType) {
    PoolEventType["initialized"] = "initialized";
    PoolEventType["taskCanceled"] = "taskCanceled";
    PoolEventType["taskCompleted"] = "taskCompleted";
    PoolEventType["taskFailed"] = "taskFailed";
    PoolEventType["taskQueued"] = "taskQueued";
    PoolEventType["taskQueueDrained"] = "taskQueueDrained";
    PoolEventType["taskStart"] = "taskStart";
    PoolEventType["terminated"] = "terminated";
})(PoolEventType = exports.PoolEventType || (exports.PoolEventType = {}));


/***/ }),

/***/ 9337:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Pool = exports.Thread = exports.PoolEventType = void 0;
const debug_1 = __importDefault(__webpack_require__(1227));
const observable_fns_1 = __webpack_require__(9599);
const ponyfills_1 = __webpack_require__(531);
const implementation_1 = __webpack_require__(8390);
const pool_types_1 = __webpack_require__(6774);
Object.defineProperty(exports, "PoolEventType", ({ enumerable: true, get: function () { return pool_types_1.PoolEventType; } }));
const thread_1 = __webpack_require__(4235);
Object.defineProperty(exports, "Thread", ({ enumerable: true, get: function () { return thread_1.Thread; } }));
let nextPoolID = 1;
function createArray(size) {
    const array = [];
    for (let index = 0; index < size; index++) {
        array.push(index);
    }
    return array;
}
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
function flatMap(array, mapper) {
    return array.reduce((flattened, element) => [...flattened, ...mapper(element)], []);
}
function slugify(text) {
    return text.replace(/\W/g, " ").trim().replace(/\s+/g, "-");
}
function spawnWorkers(spawnWorker, count) {
    return createArray(count).map(() => ({
        init: spawnWorker(),
        runningTasks: []
    }));
}
class WorkerPool {
    constructor(spawnWorker, optionsOrSize) {
        this.eventSubject = new observable_fns_1.Subject();
        this.initErrors = [];
        this.isClosing = false;
        this.nextTaskID = 1;
        this.taskQueue = [];
        const options = typeof optionsOrSize === "number"
            ? { size: optionsOrSize }
            : optionsOrSize || {};
        const { size = implementation_1.defaultPoolSize } = options;
        this.debug = debug_1.default(`threads:pool:${slugify(options.name || String(nextPoolID++))}`);
        this.options = options;
        this.workers = spawnWorkers(spawnWorker, size);
        this.eventObservable = observable_fns_1.multicast(observable_fns_1.Observable.from(this.eventSubject));
        Promise.all(this.workers.map(worker => worker.init)).then(() => this.eventSubject.next({
            type: pool_types_1.PoolEventType.initialized,
            size: this.workers.length
        }), error => {
            this.debug("Error while initializing pool worker:", error);
            this.eventSubject.error(error);
            this.initErrors.push(error);
        });
    }
    findIdlingWorker() {
        const { concurrency = 1 } = this.options;
        return this.workers.find(worker => worker.runningTasks.length < concurrency);
    }
    runPoolTask(worker, task) {
        return __awaiter(this, void 0, void 0, function* () {
            const workerID = this.workers.indexOf(worker) + 1;
            this.debug(`Running task #${task.id} on worker #${workerID}...`);
            this.eventSubject.next({
                type: pool_types_1.PoolEventType.taskStart,
                taskID: task.id,
                workerID
            });
            try {
                const returnValue = yield task.run(yield worker.init);
                this.debug(`Task #${task.id} completed successfully`);
                this.eventSubject.next({
                    type: pool_types_1.PoolEventType.taskCompleted,
                    returnValue,
                    taskID: task.id,
                    workerID
                });
            }
            catch (error) {
                this.debug(`Task #${task.id} failed`);
                this.eventSubject.next({
                    type: pool_types_1.PoolEventType.taskFailed,
                    taskID: task.id,
                    error,
                    workerID
                });
            }
        });
    }
    run(worker, task) {
        return __awaiter(this, void 0, void 0, function* () {
            const runPromise = (() => __awaiter(this, void 0, void 0, function* () {
                const removeTaskFromWorkersRunningTasks = () => {
                    worker.runningTasks = worker.runningTasks.filter(someRunPromise => someRunPromise !== runPromise);
                };
                // Defer task execution by one tick to give handlers time to subscribe
                yield delay(0);
                try {
                    yield this.runPoolTask(worker, task);
                }
                finally {
                    removeTaskFromWorkersRunningTasks();
                    if (!this.isClosing) {
                        this.scheduleWork();
                    }
                }
            }))();
            worker.runningTasks.push(runPromise);
        });
    }
    scheduleWork() {
        this.debug(`Attempt de-queueing a task in order to run it...`);
        const availableWorker = this.findIdlingWorker();
        if (!availableWorker)
            return;
        const nextTask = this.taskQueue.shift();
        if (!nextTask) {
            this.debug(`Task queue is empty`);
            this.eventSubject.next({ type: pool_types_1.PoolEventType.taskQueueDrained });
            return;
        }
        this.run(availableWorker, nextTask);
    }
    taskCompletion(taskID) {
        return new Promise((resolve, reject) => {
            const eventSubscription = this.events().subscribe(event => {
                if (event.type === pool_types_1.PoolEventType.taskCompleted && event.taskID === taskID) {
                    eventSubscription.unsubscribe();
                    resolve(event.returnValue);
                }
                else if (event.type === pool_types_1.PoolEventType.taskFailed && event.taskID === taskID) {
                    eventSubscription.unsubscribe();
                    reject(event.error);
                }
                else if (event.type === pool_types_1.PoolEventType.terminated) {
                    eventSubscription.unsubscribe();
                    reject(Error("Pool has been terminated before task was run."));
                }
            });
        });
    }
    settled(allowResolvingImmediately = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const getCurrentlyRunningTasks = () => flatMap(this.workers, worker => worker.runningTasks);
            const taskFailures = [];
            const failureSubscription = this.eventObservable.subscribe(event => {
                if (event.type === pool_types_1.PoolEventType.taskFailed) {
                    taskFailures.push(event.error);
                }
            });
            if (this.initErrors.length > 0) {
                return Promise.reject(this.initErrors[0]);
            }
            if (allowResolvingImmediately && this.taskQueue.length === 0) {
                yield ponyfills_1.allSettled(getCurrentlyRunningTasks());
                return taskFailures;
            }
            yield new Promise((resolve, reject) => {
                const subscription = this.eventObservable.subscribe({
                    next(event) {
                        if (event.type === pool_types_1.PoolEventType.taskQueueDrained) {
                            subscription.unsubscribe();
                            resolve(void 0);
                        }
                    },
                    error: reject // make a pool-wide error reject the completed() result promise
                });
            });
            yield ponyfills_1.allSettled(getCurrentlyRunningTasks());
            failureSubscription.unsubscribe();
            return taskFailures;
        });
    }
    completed(allowResolvingImmediately = false) {
        return __awaiter(this, void 0, void 0, function* () {
            const settlementPromise = this.settled(allowResolvingImmediately);
            const earlyExitPromise = new Promise((resolve, reject) => {
                const subscription = this.eventObservable.subscribe({
                    next(event) {
                        if (event.type === pool_types_1.PoolEventType.taskQueueDrained) {
                            subscription.unsubscribe();
                            resolve(settlementPromise);
                        }
                        else if (event.type === pool_types_1.PoolEventType.taskFailed) {
                            subscription.unsubscribe();
                            reject(event.error);
                        }
                    },
                    error: reject // make a pool-wide error reject the completed() result promise
                });
            });
            const errors = yield Promise.race([
                settlementPromise,
                earlyExitPromise
            ]);
            if (errors.length > 0) {
                throw errors[0];
            }
        });
    }
    events() {
        return this.eventObservable;
    }
    queue(taskFunction) {
        const { maxQueuedJobs = Infinity } = this.options;
        if (this.isClosing) {
            throw Error(`Cannot schedule pool tasks after terminate() has been called.`);
        }
        if (this.initErrors.length > 0) {
            throw this.initErrors[0];
        }
        const taskID = this.nextTaskID++;
        const taskCompletion = this.taskCompletion(taskID);
        taskCompletion.catch((error) => {
            // Prevent unhandled rejections here as we assume the user will use
            // `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors
            this.debug(`Task #${taskID} errored:`, error);
        });
        const task = {
            id: taskID,
            run: taskFunction,
            cancel: () => {
                if (this.taskQueue.indexOf(task) === -1)
                    return;
                this.taskQueue = this.taskQueue.filter(someTask => someTask !== task);
                this.eventSubject.next({
                    type: pool_types_1.PoolEventType.taskCanceled,
                    taskID: task.id
                });
            },
            then: taskCompletion.then.bind(taskCompletion)
        };
        if (this.taskQueue.length >= maxQueuedJobs) {
            throw Error("Maximum number of pool tasks queued. Refusing to queue another one.\n" +
                "This usually happens for one of two reasons: We are either at peak " +
                "workload right now or some tasks just won't finish, thus blocking the pool.");
        }
        this.debug(`Queueing task #${task.id}...`);
        this.taskQueue.push(task);
        this.eventSubject.next({
            type: pool_types_1.PoolEventType.taskQueued,
            taskID: task.id
        });
        this.scheduleWork();
        return task;
    }
    terminate(force) {
        return __awaiter(this, void 0, void 0, function* () {
            this.isClosing = true;
            if (!force) {
                yield this.completed(true);
            }
            this.eventSubject.next({
                type: pool_types_1.PoolEventType.terminated,
                remainingQueue: [...this.taskQueue]
            });
            this.eventSubject.complete();
            yield Promise.all(this.workers.map((worker) => __awaiter(this, void 0, void 0, function* () { return thread_1.Thread.terminate(yield worker.init); })));
        });
    }
}
WorkerPool.EventType = pool_types_1.PoolEventType;
/**
 * Thread pool constructor. Creates a new pool and spawns its worker threads.
 */
function PoolConstructor(spawnWorker, optionsOrSize) {
    // The function exists only so we don't need to use `new` to create a pool (we still can, though).
    // If the Pool is a class or not is an implementation detail that should not concern the user.
    return new WorkerPool(spawnWorker, optionsOrSize);
}
PoolConstructor.EventType = pool_types_1.PoolEventType;
/**
 * Thread pool constructor. Creates a new pool and spawns its worker threads.
 */
exports.Pool = PoolConstructor;


/***/ }),

/***/ 1264:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";
/* provided dependency */ var process = __webpack_require__(4155);

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.spawn = void 0;
const debug_1 = __importDefault(__webpack_require__(1227));
const observable_fns_1 = __webpack_require__(9599);
const common_1 = __webpack_require__(2467);
const promise_1 = __webpack_require__(3104);
const symbols_1 = __webpack_require__(8258);
const master_1 = __webpack_require__(6356);
const invocation_proxy_1 = __webpack_require__(6891);
const debugMessages = debug_1.default("threads:master:messages");
const debugSpawn = debug_1.default("threads:master:spawn");
const debugThreadUtils = debug_1.default("threads:master:thread-utils");
const isInitMessage = (data) => data && data.type === "init";
const isUncaughtErrorMessage = (data) => data && data.type === "uncaughtError";
const initMessageTimeout = typeof process !== "undefined" && process.env.THREADS_WORKER_INIT_TIMEOUT
    ? Number.parseInt(process.env.THREADS_WORKER_INIT_TIMEOUT, 10)
    : 10000;
function withTimeout(promise, timeoutInMs, errorMessage) {
    return __awaiter(this, void 0, void 0, function* () {
        let timeoutHandle;
        const timeout = new Promise((resolve, reject) => {
            timeoutHandle = setTimeout(() => reject(Error(errorMessage)), timeoutInMs);
        });
        const result = yield Promise.race([
            promise,
            timeout
        ]);
        clearTimeout(timeoutHandle);
        return result;
    });
}
function receiveInitMessage(worker) {
    return new Promise((resolve, reject) => {
        const messageHandler = ((event) => {
            debugMessages("Message from worker before finishing initialization:", event.data);
            if (isInitMessage(event.data)) {
                worker.removeEventListener("message", messageHandler);
                resolve(event.data);
            }
            else if (isUncaughtErrorMessage(event.data)) {
                worker.removeEventListener("message", messageHandler);
                reject(common_1.deserialize(event.data.error));
            }
        });
        worker.addEventListener("message", messageHandler);
    });
}
function createEventObservable(worker, workerTermination) {
    return new observable_fns_1.Observable(observer => {
        const messageHandler = ((messageEvent) => {
            const workerEvent = {
                type: master_1.WorkerEventType.message,
                data: messageEvent.data
            };
            observer.next(workerEvent);
        });
        const rejectionHandler = ((errorEvent) => {
            debugThreadUtils("Unhandled promise rejection event in thread:", errorEvent);
            const workerEvent = {
                type: master_1.WorkerEventType.internalError,
                error: Error(errorEvent.reason)
            };
            observer.next(workerEvent);
        });
        worker.addEventListener("message", messageHandler);
        worker.addEventListener("unhandledrejection", rejectionHandler);
        workerTermination.then(() => {
            const terminationEvent = {
                type: master_1.WorkerEventType.termination
            };
            worker.removeEventListener("message", messageHandler);
            worker.removeEventListener("unhandledrejection", rejectionHandler);
            observer.next(terminationEvent);
            observer.complete();
        });
    });
}
function createTerminator(worker) {
    const [termination, resolver] = promise_1.createPromiseWithResolver();
    const terminate = () => __awaiter(this, void 0, void 0, function* () {
        debugThreadUtils("Terminating worker");
        // Newer versions of worker_threads workers return a promise
        yield worker.terminate();
        resolver();
    });
    return { terminate, termination };
}
function setPrivateThreadProps(raw, worker, workerEvents, terminate) {
    const workerErrors = workerEvents
        .filter(event => event.type === master_1.WorkerEventType.internalError)
        .map(errorEvent => errorEvent.error);
    // tslint:disable-next-line prefer-object-spread
    return Object.assign(raw, {
        [symbols_1.$errors]: workerErrors,
        [symbols_1.$events]: workerEvents,
        [symbols_1.$terminate]: terminate,
        [symbols_1.$worker]: worker
    });
}
/**
 * Spawn a new thread. Takes a fresh worker instance, wraps it in a thin
 * abstraction layer to provide the transparent API and verifies that
 * the worker has initialized successfully.
 *
 * @param worker Instance of `Worker`. Either a web worker, `worker_threads` worker or `tiny-worker` worker.
 * @param [options]
 * @param [options.timeout] Init message timeout. Default: 10000 or set by environment variable.
 */
function spawn(worker, options) {
    return __awaiter(this, void 0, void 0, function* () {
        debugSpawn("Initializing new thread");
        const timeout = options && options.timeout ? options.timeout : initMessageTimeout;
        const initMessage = yield withTimeout(receiveInitMessage(worker), timeout, `Timeout: Did not receive an init message from worker after ${timeout}ms. Make sure the worker calls expose().`);
        const exposed = initMessage.exposed;
        const { termination, terminate } = createTerminator(worker);
        const events = createEventObservable(worker, termination);
        if (exposed.type === "function") {
            const proxy = invocation_proxy_1.createProxyFunction(worker);
            return setPrivateThreadProps(proxy, worker, events, terminate);
        }
        else if (exposed.type === "module") {
            const proxy = invocation_proxy_1.createProxyModule(worker, exposed.methods);
            return setPrivateThreadProps(proxy, worker, events, terminate);
        }
        else {
            const type = exposed.type;
            throw Error(`Worker init message states unexpected type of expose(): ${type}`);
        }
    });
}
exports.spawn = spawn;


/***/ }),

/***/ 4235:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Thread = void 0;
const symbols_1 = __webpack_require__(8258);
function fail(message) {
    throw Error(message);
}
/** Thread utility functions. Use them to manage or inspect a `spawn()`-ed thread. */
exports.Thread = {
    /** Return an observable that can be used to subscribe to all errors happening in the thread. */
    errors(thread) {
        return thread[symbols_1.$errors] || fail("Error observable not found. Make sure to pass a thread instance as returned by the spawn() promise.");
    },
    /** Return an observable that can be used to subscribe to internal events happening in the thread. Useful for debugging. */
    events(thread) {
        return thread[symbols_1.$events] || fail("Events observable not found. Make sure to pass a thread instance as returned by the spawn() promise.");
    },
    /** Terminate a thread. Remember to terminate every thread when you are done using it. */
    terminate(thread) {
        return thread[symbols_1.$terminate]();
    }
};


/***/ }),

/***/ 2015:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ObservablePromise = void 0;
const observable_fns_1 = __webpack_require__(9599);
const doNothing = () => undefined;
const returnInput = (input) => input;
const runDeferred = (fn) => Promise.resolve().then(fn);
function fail(error) {
    throw error;
}
function isThenable(thing) {
    return thing && typeof thing.then === "function";
}
/**
 * Creates a hybrid, combining the APIs of an Observable and a Promise.
 *
 * It is used to proxy async process states when we are initially not sure
 * if that async process will yield values once (-> Promise) or multiple
 * times (-> Observable).
 *
 * Note that the observable promise inherits some of the observable's characteristics:
 * The `init` function will be called *once for every time anyone subscribes to it*.
 *
 * If this is undesired, derive a hot observable from it using `makeHot()` and
 * subscribe to that.
 */
class ObservablePromise extends observable_fns_1.Observable {
    constructor(init) {
        super((originalObserver) => {
            // tslint:disable-next-line no-this-assignment
            const self = this;
            const observer = Object.assign(Object.assign({}, originalObserver), { complete() {
                    originalObserver.complete();
                    self.onCompletion();
                }, error(error) {
                    originalObserver.error(error);
                    self.onError(error);
                },
                next(value) {
                    originalObserver.next(value);
                    self.onNext(value);
                } });
            try {
                this.initHasRun = true;
                return init(observer);
            }
            catch (error) {
                observer.error(error);
            }
        });
        this.initHasRun = false;
        this.fulfillmentCallbacks = [];
        this.rejectionCallbacks = [];
        this.firstValueSet = false;
        this.state = "pending";
    }
    onNext(value) {
        if (!this.firstValueSet) {
            this.firstValue = value;
            this.firstValueSet = true;
        }
    }
    onError(error) {
        this.state = "rejected";
        this.rejection = error;
        for (const onRejected of this.rejectionCallbacks) {
            // Promisifying the call to turn errors into unhandled promise rejections
            // instead of them failing sync and cancelling the iteration
            runDeferred(() => onRejected(error));
        }
    }
    onCompletion() {
        this.state = "fulfilled";
        for (const onFulfilled of this.fulfillmentCallbacks) {
            // Promisifying the call to turn errors into unhandled promise rejections
            // instead of them failing sync and cancelling the iteration
            runDeferred(() => onFulfilled(this.firstValue));
        }
    }
    then(onFulfilledRaw, onRejectedRaw) {
        const onFulfilled = onFulfilledRaw || returnInput;
        const onRejected = onRejectedRaw || fail;
        let onRejectedCalled = false;
        return new Promise((resolve, reject) => {
            const rejectionCallback = (error) => {
                if (onRejectedCalled)
                    return;
                onRejectedCalled = true;
                try {
                    resolve(onRejected(error));
                }
                catch (anotherError) {
                    reject(anotherError);
                }
            };
            const fulfillmentCallback = (value) => {
                try {
                    resolve(onFulfilled(value));
                }
                catch (error) {
                    rejectionCallback(error);
                }
            };
            if (!this.initHasRun) {
                this.subscribe({ error: rejectionCallback });
            }
            if (this.state === "fulfilled") {
                return resolve(onFulfilled(this.firstValue));
            }
            if (this.state === "rejected") {
                onRejectedCalled = true;
                return resolve(onRejected(this.rejection));
            }
            this.fulfillmentCallbacks.push(fulfillmentCallback);
            this.rejectionCallbacks.push(rejectionCallback);
        });
    }
    catch(onRejected) {
        return this.then(undefined, onRejected);
    }
    finally(onCompleted) {
        const handler = onCompleted || doNothing;
        return this.then((value) => {
            handler();
            return value;
        }, () => handler());
    }
    static from(thing) {
        if (isThenable(thing)) {
            return new ObservablePromise(observer => {
                const onFulfilled = (value) => {
                    observer.next(value);
                    observer.complete();
                };
                const onRejected = (error) => {
                    observer.error(error);
                };
                thing.then(onFulfilled, onRejected);
            });
        }
        else {
            return super.from(thing);
        }
    }
}
exports.ObservablePromise = ObservablePromise;


/***/ }),

/***/ 531:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.allSettled = void 0;
// Based on <https://github.com/es-shims/Promise.allSettled/blob/master/implementation.js>
function allSettled(values) {
    return Promise.all(values.map(item => {
        const onFulfill = (value) => {
            return { status: 'fulfilled', value };
        };
        const onReject = (reason) => {
            return { status: 'rejected', reason };
        };
        const itemPromise = Promise.resolve(item);
        try {
            return itemPromise.then(onFulfill, onReject);
        }
        catch (error) {
            return Promise.reject(error);
        }
    }));
}
exports.allSettled = allSettled;


/***/ }),

/***/ 3104:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createPromiseWithResolver = void 0;
const doNothing = () => undefined;
/**
 * Creates a new promise and exposes its resolver function.
 * Use with care!
 */
function createPromiseWithResolver() {
    let alreadyResolved = false;
    let resolvedTo;
    let resolver = doNothing;
    const promise = new Promise(resolve => {
        if (alreadyResolved) {
            resolve(resolvedTo);
        }
        else {
            resolver = resolve;
        }
    });
    const exposedResolver = (value) => {
        alreadyResolved = true;
        resolvedTo = value;
        resolver(resolvedTo);
    };
    return [promise, exposedResolver];
}
exports.createPromiseWithResolver = createPromiseWithResolver;


/***/ }),

/***/ 7381:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.DefaultSerializer = exports.extendSerializer = void 0;
function extendSerializer(extend, implementation) {
    const fallbackDeserializer = extend.deserialize.bind(extend);
    const fallbackSerializer = extend.serialize.bind(extend);
    return {
        deserialize(message) {
            return implementation.deserialize(message, fallbackDeserializer);
        },
        serialize(input) {
            return implementation.serialize(input, fallbackSerializer);
        }
    };
}
exports.extendSerializer = extendSerializer;
const DefaultErrorSerializer = {
    deserialize(message) {
        return Object.assign(Error(message.message), {
            name: message.name,
            stack: message.stack
        });
    },
    serialize(error) {
        return {
            __error_marker: "$$error",
            message: error.message,
            name: error.name,
            stack: error.stack
        };
    }
};
const isSerializedError = (thing) => thing && typeof thing === "object" && "__error_marker" in thing && thing.__error_marker === "$$error";
exports.DefaultSerializer = {
    deserialize(message) {
        if (isSerializedError(message)) {
            return DefaultErrorSerializer.deserialize(message);
        }
        else {
            return message;
        }
    },
    serialize(input) {
        if (input instanceof Error) {
            return DefaultErrorSerializer.serialize(input);
        }
        else {
            return input;
        }
    }
};


/***/ }),

/***/ 8258:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.$worker = exports.$transferable = exports.$terminate = exports.$events = exports.$errors = void 0;
exports.$errors = Symbol("thread.errors");
exports.$events = Symbol("thread.events");
exports.$terminate = Symbol("thread.terminate");
exports.$transferable = Symbol("thread.transferable");
exports.$worker = Symbol("thread.worker");


/***/ }),

/***/ 8180:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Transfer = exports.isTransferDescriptor = void 0;
const symbols_1 = __webpack_require__(8258);
function isTransferable(thing) {
    if (!thing || typeof thing !== "object")
        return false;
    // Don't check too thoroughly, since the list of transferable things in JS might grow over time
    return true;
}
function isTransferDescriptor(thing) {
    return thing && typeof thing === "object" && thing[symbols_1.$transferable];
}
exports.isTransferDescriptor = isTransferDescriptor;
function Transfer(payload, transferables) {
    if (!transferables) {
        if (!isTransferable(payload))
            throw Error();
        transferables = [payload];
    }
    return {
        [symbols_1.$transferable]: true,
        send: payload,
        transferables
    };
}
exports.Transfer = Transfer;


/***/ }),

/***/ 6356:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/// <reference lib="dom" />
// tslint:disable max-classes-per-file
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkerEventType = void 0;
const symbols_1 = __webpack_require__(8258);
/** Event as emitted by worker thread. Subscribe to using `Thread.events(thread)`. */
var WorkerEventType;
(function (WorkerEventType) {
    WorkerEventType["internalError"] = "internalError";
    WorkerEventType["message"] = "message";
    WorkerEventType["termination"] = "termination";
})(WorkerEventType = exports.WorkerEventType || (exports.WorkerEventType = {}));


/***/ }),

/***/ 3229:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.WorkerMessageType = exports.MasterMessageType = void 0;
/////////////////////////////
// Messages sent by master:
var MasterMessageType;
(function (MasterMessageType) {
    MasterMessageType["cancel"] = "cancel";
    MasterMessageType["run"] = "run";
})(MasterMessageType = exports.MasterMessageType || (exports.MasterMessageType = {}));
////////////////////////////
// Messages sent by worker:
var WorkerMessageType;
(function (WorkerMessageType) {
    WorkerMessageType["error"] = "error";
    WorkerMessageType["init"] = "init";
    WorkerMessageType["result"] = "result";
    WorkerMessageType["running"] = "running";
    WorkerMessageType["uncaughtError"] = "uncaughtError";
})(WorkerMessageType = exports.WorkerMessageType || (exports.WorkerMessageType = {}));


/***/ }),

/***/ 3447:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

/// <reference lib="dom" />
// tslint:disable no-shadowed-variable
Object.defineProperty(exports, "__esModule", ({ value: true }));
const isWorkerRuntime = function isWorkerRuntime() {
    const isWindowContext = typeof self !== "undefined" && typeof Window !== "undefined" && self instanceof Window;
    return typeof self !== "undefined" && self.postMessage && !isWindowContext ? true : false;
};
const postMessageToMaster = function postMessageToMaster(data, transferList) {
    self.postMessage(data, transferList);
};
const subscribeToMasterMessages = function subscribeToMasterMessages(onMessage) {
    const messageHandler = (messageEvent) => {
        onMessage(messageEvent.data);
    };
    const unsubscribe = () => {
        self.removeEventListener("message", messageHandler);
    };
    self.addEventListener("message", messageHandler);
    return unsubscribe;
};
exports["default"] = {
    isWorkerRuntime,
    postMessageToMaster,
    subscribeToMasterMessages
};


/***/ }),

/***/ 1934:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";
/* provided dependency */ var process = __webpack_require__(4155);

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.expose = exports.isWorkerRuntime = exports.Transfer = exports.registerSerializer = void 0;
const is_observable_1 = __importDefault(__webpack_require__(6898));
const common_1 = __webpack_require__(2467);
const transferable_1 = __webpack_require__(8180);
const messages_1 = __webpack_require__(3229);
const implementation_1 = __importDefault(__webpack_require__(3447));
var common_2 = __webpack_require__(2467);
Object.defineProperty(exports, "registerSerializer", ({ enumerable: true, get: function () { return common_2.registerSerializer; } }));
var transferable_2 = __webpack_require__(8180);
Object.defineProperty(exports, "Transfer", ({ enumerable: true, get: function () { return transferable_2.Transfer; } }));
/** Returns `true` if this code is currently running in a worker. */
exports.isWorkerRuntime = implementation_1.default.isWorkerRuntime;
let exposeCalled = false;
const activeSubscriptions = new Map();
const isMasterJobCancelMessage = (thing) => thing && thing.type === messages_1.MasterMessageType.cancel;
const isMasterJobRunMessage = (thing) => thing && thing.type === messages_1.MasterMessageType.run;
/**
 * There are issues with `is-observable` not recognizing zen-observable's instances.
 * We are using `observable-fns`, but it's based on zen-observable, too.
 */
const isObservable = (thing) => is_observable_1.default(thing) || isZenObservable(thing);
function isZenObservable(thing) {
    return thing && typeof thing === "object" && typeof thing.subscribe === "function";
}
function deconstructTransfer(thing) {
    return transferable_1.isTransferDescriptor(thing)
        ? { payload: thing.send, transferables: thing.transferables }
        : { payload: thing, transferables: undefined };
}
function postFunctionInitMessage() {
    const initMessage = {
        type: messages_1.WorkerMessageType.init,
        exposed: {
            type: "function"
        }
    };
    implementation_1.default.postMessageToMaster(initMessage);
}
function postModuleInitMessage(methodNames) {
    const initMessage = {
        type: messages_1.WorkerMessageType.init,
        exposed: {
            type: "module",
            methods: methodNames
        }
    };
    implementation_1.default.postMessageToMaster(initMessage);
}
function postJobErrorMessage(uid, rawError) {
    const { payload: error, transferables } = deconstructTransfer(rawError);
    const errorMessage = {
        type: messages_1.WorkerMessageType.error,
        uid,
        error: common_1.serialize(error)
    };
    implementation_1.default.postMessageToMaster(errorMessage, transferables);
}
function postJobResultMessage(uid, completed, resultValue) {
    const { payload, transferables } = deconstructTransfer(resultValue);
    const resultMessage = {
        type: messages_1.WorkerMessageType.result,
        uid,
        complete: completed ? true : undefined,
        payload
    };
    implementation_1.default.postMessageToMaster(resultMessage, transferables);
}
function postJobStartMessage(uid, resultType) {
    const startMessage = {
        type: messages_1.WorkerMessageType.running,
        uid,
        resultType
    };
    implementation_1.default.postMessageToMaster(startMessage);
}
function postUncaughtErrorMessage(error) {
    try {
        const errorMessage = {
            type: messages_1.WorkerMessageType.uncaughtError,
            error: common_1.serialize(error)
        };
        implementation_1.default.postMessageToMaster(errorMessage);
    }
    catch (subError) {
        // tslint:disable-next-line no-console
        console.error("Not reporting uncaught error back to master thread as it " +
            "occured while reporting an uncaught error already." +
            "\nLatest error:", subError, "\nOriginal error:", error);
    }
}
function runFunction(jobUID, fn, args) {
    return __awaiter(this, void 0, void 0, function* () {
        let syncResult;
        try {
            syncResult = fn(...args);
        }
        catch (error) {
            return postJobErrorMessage(jobUID, error);
        }
        const resultType = isObservable(syncResult) ? "observable" : "promise";
        postJobStartMessage(jobUID, resultType);
        if (isObservable(syncResult)) {
            const subscription = syncResult.subscribe(value => postJobResultMessage(jobUID, false, common_1.serialize(value)), error => {
                postJobErrorMessage(jobUID, common_1.serialize(error));
                activeSubscriptions.delete(jobUID);
            }, () => {
                postJobResultMessage(jobUID, true);
                activeSubscriptions.delete(jobUID);
            });
            activeSubscriptions.set(jobUID, subscription);
        }
        else {
            try {
                const result = yield syncResult;
                postJobResultMessage(jobUID, true, common_1.serialize(result));
            }
            catch (error) {
                postJobErrorMessage(jobUID, common_1.serialize(error));
            }
        }
    });
}
/**
 * Expose a function or a module (an object whose values are functions)
 * to the main thread. Must be called exactly once in every worker thread
 * to signal its API to the main thread.
 *
 * @param exposed Function or object whose values are functions
 */
function expose(exposed) {
    if (!implementation_1.default.isWorkerRuntime()) {
        throw Error("expose() called in the master thread.");
    }
    if (exposeCalled) {
        throw Error("expose() called more than once. This is not possible. Pass an object to expose() if you want to expose multiple functions.");
    }
    exposeCalled = true;
    if (typeof exposed === "function") {
        implementation_1.default.subscribeToMasterMessages(messageData => {
            if (isMasterJobRunMessage(messageData) && !messageData.method) {
                runFunction(messageData.uid, exposed, messageData.args.map(common_1.deserialize));
            }
        });
        postFunctionInitMessage();
    }
    else if (typeof exposed === "object" && exposed) {
        implementation_1.default.subscribeToMasterMessages(messageData => {
            if (isMasterJobRunMessage(messageData) && messageData.method) {
                runFunction(messageData.uid, exposed[messageData.method], messageData.args.map(common_1.deserialize));
            }
        });
        const methodNames = Object.keys(exposed).filter(key => typeof exposed[key] === "function");
        postModuleInitMessage(methodNames);
    }
    else {
        throw Error(`Invalid argument passed to expose(). Expected a function or an object, got: ${exposed}`);
    }
    implementation_1.default.subscribeToMasterMessages(messageData => {
        if (isMasterJobCancelMessage(messageData)) {
            const jobUID = messageData.uid;
            const subscription = activeSubscriptions.get(jobUID);
            if (subscription) {
                subscription.unsubscribe();
                activeSubscriptions.delete(jobUID);
            }
        }
    });
}
exports.expose = expose;
if (typeof self !== "undefined" && typeof self.addEventListener === "function" && implementation_1.default.isWorkerRuntime()) {
    self.addEventListener("error", event => {
        // Post with some delay, so the master had some time to subscribe to messages
        setTimeout(() => postUncaughtErrorMessage(event.error || event), 250);
    });
    self.addEventListener("unhandledrejection", event => {
        const error = event.reason;
        if (error && typeof error.message === "string") {
            // Post with some delay, so the master had some time to subscribe to messages
            setTimeout(() => postUncaughtErrorMessage(error), 250);
        }
    });
}
if (typeof process !== "undefined" && typeof process.on === "function" && implementation_1.default.isWorkerRuntime()) {
    process.on("uncaughtException", (error) => {
        // Post with some delay, so the master had some time to subscribe to messages
        setTimeout(() => postUncaughtErrorMessage(error), 250);
    });
    process.on("unhandledRejection", (error) => {
        if (error && typeof error.message === "string") {
            // Post with some delay, so the master had some time to subscribe to messages
            setTimeout(() => postUncaughtErrorMessage(error), 250);
        }
    });
}


/***/ }),

/***/ 2511:
/***/ (function(module, exports, __webpack_require__) {

/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.3.2 by @mathias */
;(function(root) {

	/** Detect free variables */
	var freeExports =  true && exports &&
		!exports.nodeType && exports;
	var freeModule =  true && module &&
		!module.nodeType && module;
	var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g;
	if (
		freeGlobal.global === freeGlobal ||
		freeGlobal.window === freeGlobal ||
		freeGlobal.self === freeGlobal
	) {
		root = freeGlobal;
	}

	/**
	 * The `punycode` object.
	 * @name punycode
	 * @type Object
	 */
	var punycode,

	/** Highest positive signed 32-bit float value */
	maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1

	/** Bootstring parameters */
	base = 36,
	tMin = 1,
	tMax = 26,
	skew = 38,
	damp = 700,
	initialBias = 72,
	initialN = 128, // 0x80
	delimiter = '-', // '\x2D'

	/** Regular expressions */
	regexPunycode = /^xn--/,
	regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
	regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators

	/** Error messages */
	errors = {
		'overflow': 'Overflow: input needs wider integers to process',
		'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
		'invalid-input': 'Invalid input'
	},

	/** Convenience shortcuts */
	baseMinusTMin = base - tMin,
	floor = Math.floor,
	stringFromCharCode = String.fromCharCode,

	/** Temporary variable */
	key;

	/*--------------------------------------------------------------------------*/

	/**
	 * A generic error utility function.
	 * @private
	 * @param {String} type The error type.
	 * @returns {Error} Throws a `RangeError` with the applicable error message.
	 */
	function error(type) {
		throw RangeError(errors[type]);
	}

	/**
	 * A generic `Array#map` utility function.
	 * @private
	 * @param {Array} array The array to iterate over.
	 * @param {Function} callback The function that gets called for every array
	 * item.
	 * @returns {Array} A new array of values returned by the callback function.
	 */
	function map(array, fn) {
		var length = array.length;
		var result = [];
		while (length--) {
			result[length] = fn(array[length]);
		}
		return result;
	}

	/**
	 * A simple `Array#map`-like wrapper to work with domain name strings or email
	 * addresses.
	 * @private
	 * @param {String} domain The domain name or email address.
	 * @param {Function} callback The function that gets called for every
	 * character.
	 * @returns {Array} A new string of characters returned by the callback
	 * function.
	 */
	function mapDomain(string, fn) {
		var parts = string.split('@');
		var result = '';
		if (parts.length > 1) {
			// In email addresses, only the domain name should be punycoded. Leave
			// the local part (i.e. everything up to `@`) intact.
			result = parts[0] + '@';
			string = parts[1];
		}
		// Avoid `split(regex)` for IE8 compatibility. See #17.
		string = string.replace(regexSeparators, '\x2E');
		var labels = string.split('.');
		var encoded = map(labels, fn).join('.');
		return result + encoded;
	}

	/**
	 * Creates an array containing the numeric code points of each Unicode
	 * character in the string. While JavaScript uses UCS-2 internally,
	 * this function will convert a pair of surrogate halves (each of which
	 * UCS-2 exposes as separate characters) into a single code point,
	 * matching UTF-16.
	 * @see `punycode.ucs2.encode`
	 * @see <https://mathiasbynens.be/notes/javascript-encoding>
	 * @memberOf punycode.ucs2
	 * @name decode
	 * @param {String} string The Unicode input string (UCS-2).
	 * @returns {Array} The new array of code points.
	 */
	function ucs2decode(string) {
		var output = [],
		    counter = 0,
		    length = string.length,
		    value,
		    extra;
		while (counter < length) {
			value = string.charCodeAt(counter++);
			if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
				// high surrogate, and there is a next character
				extra = string.charCodeAt(counter++);
				if ((extra & 0xFC00) == 0xDC00) { // low surrogate
					output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
				} else {
					// unmatched surrogate; only append this code unit, in case the next
					// code unit is the high surrogate of a surrogate pair
					output.push(value);
					counter--;
				}
			} else {
				output.push(value);
			}
		}
		return output;
	}

	/**
	 * Creates a string based on an array of numeric code points.
	 * @see `punycode.ucs2.decode`
	 * @memberOf punycode.ucs2
	 * @name encode
	 * @param {Array} codePoints The array of numeric code points.
	 * @returns {String} The new Unicode string (UCS-2).
	 */
	function ucs2encode(array) {
		return map(array, function(value) {
			var output = '';
			if (value > 0xFFFF) {
				value -= 0x10000;
				output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
				value = 0xDC00 | value & 0x3FF;
			}
			output += stringFromCharCode(value);
			return output;
		}).join('');
	}

	/**
	 * Converts a basic code point into a digit/integer.
	 * @see `digitToBasic()`
	 * @private
	 * @param {Number} codePoint The basic numeric code point value.
	 * @returns {Number} The numeric value of a basic code point (for use in
	 * representing integers) in the range `0` to `base - 1`, or `base` if
	 * the code point does not represent a value.
	 */
	function basicToDigit(codePoint) {
		if (codePoint - 48 < 10) {
			return codePoint - 22;
		}
		if (codePoint - 65 < 26) {
			return codePoint - 65;
		}
		if (codePoint - 97 < 26) {
			return codePoint - 97;
		}
		return base;
	}

	/**
	 * Converts a digit/integer into a basic code point.
	 * @see `basicToDigit()`
	 * @private
	 * @param {Number} digit The numeric value of a basic code point.
	 * @returns {Number} The basic code point whose value (when used for
	 * representing integers) is `digit`, which needs to be in the range
	 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
	 * used; else, the lowercase form is used. The behavior is undefined
	 * if `flag` is non-zero and `digit` has no uppercase form.
	 */
	function digitToBasic(digit, flag) {
		//  0..25 map to ASCII a..z or A..Z
		// 26..35 map to ASCII 0..9
		return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
	}

	/**
	 * Bias adaptation function as per section 3.4 of RFC 3492.
	 * http://tools.ietf.org/html/rfc3492#section-3.4
	 * @private
	 */
	function adapt(delta, numPoints, firstTime) {
		var k = 0;
		delta = firstTime ? floor(delta / damp) : delta >> 1;
		delta += floor(delta / numPoints);
		for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
			delta = floor(delta / baseMinusTMin);
		}
		return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
	}

	/**
	 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
	 * symbols.
	 * @memberOf punycode
	 * @param {String} input The Punycode string of ASCII-only symbols.
	 * @returns {String} The resulting string of Unicode symbols.
	 */
	function decode(input) {
		// Don't use UCS-2
		var output = [],
		    inputLength = input.length,
		    out,
		    i = 0,
		    n = initialN,
		    bias = initialBias,
		    basic,
		    j,
		    index,
		    oldi,
		    w,
		    k,
		    digit,
		    t,
		    /** Cached calculation results */
		    baseMinusT;

		// Handle the basic code points: let `basic` be the number of input code
		// points before the last delimiter, or `0` if there is none, then copy
		// the first basic code points to the output.

		basic = input.lastIndexOf(delimiter);
		if (basic < 0) {
			basic = 0;
		}

		for (j = 0; j < basic; ++j) {
			// if it's not a basic code point
			if (input.charCodeAt(j) >= 0x80) {
				error('not-basic');
			}
			output.push(input.charCodeAt(j));
		}

		// Main decoding loop: start just after the last delimiter if any basic code
		// points were copied; start at the beginning otherwise.

		for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {

			// `index` is the index of the next character to be consumed.
			// Decode a generalized variable-length integer into `delta`,
			// which gets added to `i`. The overflow checking is easier
			// if we increase `i` as we go, then subtract off its starting
			// value at the end to obtain `delta`.
			for (oldi = i, w = 1, k = base; /* no condition */; k += base) {

				if (index >= inputLength) {
					error('invalid-input');
				}

				digit = basicToDigit(input.charCodeAt(index++));

				if (digit >= base || digit > floor((maxInt - i) / w)) {
					error('overflow');
				}

				i += digit * w;
				t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);

				if (digit < t) {
					break;
				}

				baseMinusT = base - t;
				if (w > floor(maxInt / baseMinusT)) {
					error('overflow');
				}

				w *= baseMinusT;

			}

			out = output.length + 1;
			bias = adapt(i - oldi, out, oldi == 0);

			// `i` was supposed to wrap around from `out` to `0`,
			// incrementing `n` each time, so we'll fix that now:
			if (floor(i / out) > maxInt - n) {
				error('overflow');
			}

			n += floor(i / out);
			i %= out;

			// Insert `n` at position `i` of the output
			output.splice(i++, 0, n);

		}

		return ucs2encode(output);
	}

	/**
	 * Converts a string of Unicode symbols (e.g. a domain name label) to a
	 * Punycode string of ASCII-only symbols.
	 * @memberOf punycode
	 * @param {String} input The string of Unicode symbols.
	 * @returns {String} The resulting Punycode string of ASCII-only symbols.
	 */
	function encode(input) {
		var n,
		    delta,
		    handledCPCount,
		    basicLength,
		    bias,
		    j,
		    m,
		    q,
		    k,
		    t,
		    currentValue,
		    output = [],
		    /** `inputLength` will hold the number of code points in `input`. */
		    inputLength,
		    /** Cached calculation results */
		    handledCPCountPlusOne,
		    baseMinusT,
		    qMinusT;

		// Convert the input in UCS-2 to Unicode
		input = ucs2decode(input);

		// Cache the length
		inputLength = input.length;

		// Initialize the state
		n = initialN;
		delta = 0;
		bias = initialBias;

		// Handle the basic code points
		for (j = 0; j < inputLength; ++j) {
			currentValue = input[j];
			if (currentValue < 0x80) {
				output.push(stringFromCharCode(currentValue));
			}
		}

		handledCPCount = basicLength = output.length;

		// `handledCPCount` is the number of code points that have been handled;
		// `basicLength` is the number of basic code points.

		// Finish the basic string - if it is not empty - with a delimiter
		if (basicLength) {
			output.push(delimiter);
		}

		// Main encoding loop:
		while (handledCPCount < inputLength) {

			// All non-basic code points < n have been handled already. Find the next
			// larger one:
			for (m = maxInt, j = 0; j < inputLength; ++j) {
				currentValue = input[j];
				if (currentValue >= n && currentValue < m) {
					m = currentValue;
				}
			}

			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
			// but guard against overflow
			handledCPCountPlusOne = handledCPCount + 1;
			if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
				error('overflow');
			}

			delta += (m - n) * handledCPCountPlusOne;
			n = m;

			for (j = 0; j < inputLength; ++j) {
				currentValue = input[j];

				if (currentValue < n && ++delta > maxInt) {
					error('overflow');
				}

				if (currentValue == n) {
					// Represent delta as a generalized variable-length integer
					for (q = delta, k = base; /* no condition */; k += base) {
						t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
						if (q < t) {
							break;
						}
						qMinusT = q - t;
						baseMinusT = base - t;
						output.push(
							stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
						);
						q = floor(qMinusT / baseMinusT);
					}

					output.push(stringFromCharCode(digitToBasic(q, 0)));
					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
					delta = 0;
					++handledCPCount;
				}
			}

			++delta;
			++n;

		}
		return output.join('');
	}

	/**
	 * Converts a Punycode string representing a domain name or an email address
	 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
	 * it doesn't matter if you call it on a string that has already been
	 * converted to Unicode.
	 * @memberOf punycode
	 * @param {String} input The Punycoded domain name or email address to
	 * convert to Unicode.
	 * @returns {String} The Unicode representation of the given Punycode
	 * string.
	 */
	function toUnicode(input) {
		return mapDomain(input, function(string) {
			return regexPunycode.test(string)
				? decode(string.slice(4).toLowerCase())
				: string;
		});
	}

	/**
	 * Converts a Unicode string representing a domain name or an email address to
	 * Punycode. Only the non-ASCII parts of the domain name will be converted,
	 * i.e. it doesn't matter if you call it with a domain that's already in
	 * ASCII.
	 * @memberOf punycode
	 * @param {String} input The domain name or email address to convert, as a
	 * Unicode string.
	 * @returns {String} The Punycode representation of the given domain name or
	 * email address.
	 */
	function toASCII(input) {
		return mapDomain(input, function(string) {
			return regexNonASCII.test(string)
				? 'xn--' + encode(string)
				: string;
		});
	}

	/*--------------------------------------------------------------------------*/

	/** Define the public API */
	punycode = {
		/**
		 * A string representing the current Punycode.js version number.
		 * @memberOf punycode
		 * @type String
		 */
		'version': '1.3.2',
		/**
		 * An object of methods to convert from JavaScript's internal character
		 * representation (UCS-2) to Unicode code points, and back.
		 * @see <https://mathiasbynens.be/notes/javascript-encoding>
		 * @memberOf punycode
		 * @type Object
		 */
		'ucs2': {
			'decode': ucs2decode,
			'encode': ucs2encode
		},
		'decode': decode,
		'encode': encode,
		'toASCII': toASCII,
		'toUnicode': toUnicode
	};

	/** Expose `punycode` */
	// Some AMD build optimizers, like r.js, check for specific condition patterns
	// like the following:
	if (
		true
	) {
		!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
			return punycode;
		}).call(exports, __webpack_require__, exports, module),
		__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {}

}(this));


/***/ }),

/***/ 8575:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";
var __webpack_unused_export__;
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.



var punycode = __webpack_require__(2511);
var util = __webpack_require__(2502);

exports.Qc = urlParse;
exports.DB = urlResolve;
__webpack_unused_export__ = urlResolveObject;
exports.WU = urlFormat;

__webpack_unused_export__ = Url;

function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.host = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.query = null;
  this.pathname = null;
  this.path = null;
  this.href = null;
}

// Reference: RFC 3986, RFC 1808, RFC 2396

// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
    portPattern = /:[0-9]*$/,

    // Special case for a simple path URL
    simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,

    // RFC 2396: characters reserved for delimiting URLs.
    // We actually just auto-escape these.
    delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],

    // RFC 2396: characters not allowed for various reasons.
    unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),

    // Allowed by RFCs, but cause of XSS attacks.  Always escape these.
    autoEscape = ['\''].concat(unwise),
    // Characters that are never ever allowed in a hostname.
    // Note that any invalid chars are also handled, but these
    // are the ones that are *expected* to be seen, so we fast-path
    // them.
    nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
    hostEndingChars = ['/', '?', '#'],
    hostnameMaxLen = 255,
    hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
    hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
    // protocols that can allow "unsafe" and "unwise" chars.
    unsafeProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that never have a hostname.
    hostlessProtocol = {
      'javascript': true,
      'javascript:': true
    },
    // protocols that always contain a // bit.
    slashedProtocol = {
      'http': true,
      'https': true,
      'ftp': true,
      'gopher': true,
      'file': true,
      'http:': true,
      'https:': true,
      'ftp:': true,
      'gopher:': true,
      'file:': true
    },
    querystring = __webpack_require__(7673);

function urlParse(url, parseQueryString, slashesDenoteHost) {
  if (url && util.isObject(url) && url instanceof Url) return url;

  var u = new Url;
  u.parse(url, parseQueryString, slashesDenoteHost);
  return u;
}

Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  if (!util.isString(url)) {
    throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  }

  // Copy chrome, IE, opera backslash-handling behavior.
  // Back slashes before the query string get converted to forward slashes
  // See: https://code.google.com/p/chromium/issues/detail?id=25916
  var queryIndex = url.indexOf('?'),
      splitter =
          (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
      uSplit = url.split(splitter),
      slashRegex = /\\/g;
  uSplit[0] = uSplit[0].replace(slashRegex, '/');
  url = uSplit.join(splitter);

  var rest = url;

  // trim before proceeding.
  // This is to support parse stuff like "  http://foo.com  \n"
  rest = rest.trim();

  if (!slashesDenoteHost && url.split('#').length === 1) {
    // Try fast path regexp
    var simplePath = simplePathPattern.exec(rest);
    if (simplePath) {
      this.path = rest;
      this.href = rest;
      this.pathname = simplePath[1];
      if (simplePath[2]) {
        this.search = simplePath[2];
        if (parseQueryString) {
          this.query = querystring.parse(this.search.substr(1));
        } else {
          this.query = this.search.substr(1);
        }
      } else if (parseQueryString) {
        this.search = '';
        this.query = {};
      }
      return this;
    }
  }

  var proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    var lowerProto = proto.toLowerCase();
    this.protocol = lowerProto;
    rest = rest.substr(proto.length);
  }

  // figure out if it's got a host
  // user@server is *always* interpreted as a hostname, and url
  // resolution will treat //foo/bar as host=foo,path=bar because that's
  // how the browser resolves relative URLs.
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    var slashes = rest.substr(0, 2) === '//';
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      this.slashes = true;
    }
  }

  if (!hostlessProtocol[proto] &&
      (slashes || (proto && !slashedProtocol[proto]))) {

    // there's a hostname.
    // the first instance of /, ?, ;, or # ends the host.
    //
    // If there is an @ in the hostname, then non-host chars *are* allowed
    // to the left of the last @ sign, unless some host-ending character
    // comes *before* the @-sign.
    // URLs are obnoxious.
    //
    // ex:
    // http://a@b@c/ => user:a@b host:c
    // http://a@b?@c => user:a host:c path:/?@c

    // v0.12 TODO(isaacs): This is not quite how Chrome does things.
    // Review our test case against browsers more comprehensively.

    // find the first instance of any hostEndingChars
    var hostEnd = -1;
    for (var i = 0; i < hostEndingChars.length; i++) {
      var hec = rest.indexOf(hostEndingChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }

    // at this point, either we have an explicit point where the
    // auth portion cannot go past, or the last @ char is the decider.
    var auth, atSign;
    if (hostEnd === -1) {
      // atSign can be anywhere.
      atSign = rest.lastIndexOf('@');
    } else {
      // atSign must be in auth portion.
      // http://a@b/c@d => host:b auth:a path:/c@d
      atSign = rest.lastIndexOf('@', hostEnd);
    }

    // Now we have a portion which is definitely the auth.
    // Pull that off.
    if (atSign !== -1) {
      auth = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      this.auth = decodeURIComponent(auth);
    }

    // the host is the remaining to the left of the first non-host char
    hostEnd = -1;
    for (var i = 0; i < nonHostChars.length; i++) {
      var hec = rest.indexOf(nonHostChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }
    // if we still have not hit it, then the entire thing is a host.
    if (hostEnd === -1)
      hostEnd = rest.length;

    this.host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);

    // pull out port.
    this.parseHost();

    // we've indicated that there is a hostname,
    // so even if it's empty, it has to be present.
    this.hostname = this.hostname || '';

    // if hostname begins with [ and ends with ]
    // assume that it's an IPv6 address.
    var ipv6Hostname = this.hostname[0] === '[' &&
        this.hostname[this.hostname.length - 1] === ']';

    // validate a little.
    if (!ipv6Hostname) {
      var hostparts = this.hostname.split(/\./);
      for (var i = 0, l = hostparts.length; i < l; i++) {
        var part = hostparts[i];
        if (!part) continue;
        if (!part.match(hostnamePartPattern)) {
          var newpart = '';
          for (var j = 0, k = part.length; j < k; j++) {
            if (part.charCodeAt(j) > 127) {
              // we replace non-ASCII char with a temporary placeholder
              // we need this to make sure size of hostname is not
              // broken by replacing non-ASCII by nothing
              newpart += 'x';
            } else {
              newpart += part[j];
            }
          }
          // we test again with ASCII char only
          if (!newpart.match(hostnamePartPattern)) {
            var validParts = hostparts.slice(0, i);
            var notHost = hostparts.slice(i + 1);
            var bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = '/' + notHost.join('.') + rest;
            }
            this.hostname = validParts.join('.');
            break;
          }
        }
      }
    }

    if (this.hostname.length > hostnameMaxLen) {
      this.hostname = '';
    } else {
      // hostnames are always lower case.
      this.hostname = this.hostname.toLowerCase();
    }

    if (!ipv6Hostname) {
      // IDNA Support: Returns a punycoded representation of "domain".
      // It only converts parts of the domain name that
      // have non-ASCII characters, i.e. it doesn't matter if
      // you call it with a domain that already is ASCII-only.
      this.hostname = punycode.toASCII(this.hostname);
    }

    var p = this.port ? ':' + this.port : '';
    var h = this.hostname || '';
    this.host = h + p;
    this.href += this.host;

    // strip [ and ] from the hostname
    // the host field still retains them, though
    if (ipv6Hostname) {
      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
      if (rest[0] !== '/') {
        rest = '/' + rest;
      }
    }
  }

  // now rest is set to the post-host stuff.
  // chop off any delim chars.
  if (!unsafeProtocol[lowerProto]) {

    // First, make 100% sure that any "autoEscape" chars get
    // escaped, even if encodeURIComponent doesn't think they
    // need to be.
    for (var i = 0, l = autoEscape.length; i < l; i++) {
      var ae = autoEscape[i];
      if (rest.indexOf(ae) === -1)
        continue;
      var esc = encodeURIComponent(ae);
      if (esc === ae) {
        esc = escape(ae);
      }
      rest = rest.split(ae).join(esc);
    }
  }


  // chop off from the tail first.
  var hash = rest.indexOf('#');
  if (hash !== -1) {
    // got a fragment string.
    this.hash = rest.substr(hash);
    rest = rest.slice(0, hash);
  }
  var qm = rest.indexOf('?');
  if (qm !== -1) {
    this.search = rest.substr(qm);
    this.query = rest.substr(qm + 1);
    if (parseQueryString) {
      this.query = querystring.parse(this.query);
    }
    rest = rest.slice(0, qm);
  } else if (parseQueryString) {
    // no query string, but parseQueryString still requested
    this.search = '';
    this.query = {};
  }
  if (rest) this.pathname = rest;
  if (slashedProtocol[lowerProto] &&
      this.hostname && !this.pathname) {
    this.pathname = '/';
  }

  //to support http.request
  if (this.pathname || this.search) {
    var p = this.pathname || '';
    var s = this.search || '';
    this.path = p + s;
  }

  // finally, reconstruct the href based on what has been validated.
  this.href = this.format();
  return this;
};

// format a parsed object into a url string
function urlFormat(obj) {
  // ensure it's an object, and not a string url.
  // If it's an obj, this is a no-op.
  // this way, you can call url_format() on strings
  // to clean up potentially wonky urls.
  if (util.isString(obj)) obj = urlParse(obj);
  if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  return obj.format();
}

Url.prototype.format = function() {
  var auth = this.auth || '';
  if (auth) {
    auth = encodeURIComponent(auth);
    auth = auth.replace(/%3A/i, ':');
    auth += '@';
  }

  var protocol = this.protocol || '',
      pathname = this.pathname || '',
      hash = this.hash || '',
      host = false,
      query = '';

  if (this.host) {
    host = auth + this.host;
  } else if (this.hostname) {
    host = auth + (this.hostname.indexOf(':') === -1 ?
        this.hostname :
        '[' + this.hostname + ']');
    if (this.port) {
      host += ':' + this.port;
    }
  }

  if (this.query &&
      util.isObject(this.query) &&
      Object.keys(this.query).length) {
    query = querystring.stringify(this.query);
  }

  var search = this.search || (query && ('?' + query)) || '';

  if (protocol && protocol.substr(-1) !== ':') protocol += ':';

  // only the slashedProtocols get the //.  Not mailto:, xmpp:, etc.
  // unless they had them to begin with.
  if (this.slashes ||
      (!protocol || slashedProtocol[protocol]) && host !== false) {
    host = '//' + (host || '');
    if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  } else if (!host) {
    host = '';
  }

  if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  if (search && search.charAt(0) !== '?') search = '?' + search;

  pathname = pathname.replace(/[?#]/g, function(match) {
    return encodeURIComponent(match);
  });
  search = search.replace('#', '%23');

  return protocol + host + pathname + search + hash;
};

function urlResolve(source, relative) {
  return urlParse(source, false, true).resolve(relative);
}

Url.prototype.resolve = function(relative) {
  return this.resolveObject(urlParse(relative, false, true)).format();
};

function urlResolveObject(source, relative) {
  if (!source) return relative;
  return urlParse(source, false, true).resolveObject(relative);
}

Url.prototype.resolveObject = function(relative) {
  if (util.isString(relative)) {
    var rel = new Url();
    rel.parse(relative, false, true);
    relative = rel;
  }

  var result = new Url();
  var tkeys = Object.keys(this);
  for (var tk = 0; tk < tkeys.length; tk++) {
    var tkey = tkeys[tk];
    result[tkey] = this[tkey];
  }

  // hash is always overridden, no matter what.
  // even href="" will remove it.
  result.hash = relative.hash;

  // if the relative url is empty, then there's nothing left to do here.
  if (relative.href === '') {
    result.href = result.format();
    return result;
  }

  // hrefs like //foo/bar always cut to the protocol.
  if (relative.slashes && !relative.protocol) {
    // take everything except the protocol from relative
    var rkeys = Object.keys(relative);
    for (var rk = 0; rk < rkeys.length; rk++) {
      var rkey = rkeys[rk];
      if (rkey !== 'protocol')
        result[rkey] = relative[rkey];
    }

    //urlParse appends trailing / to urls like http://www.example.com
    if (slashedProtocol[result.protocol] &&
        result.hostname && !result.pathname) {
      result.path = result.pathname = '/';
    }

    result.href = result.format();
    return result;
  }

  if (relative.protocol && relative.protocol !== result.protocol) {
    // if it's a known url protocol, then changing
    // the protocol does weird things
    // first, if it's not file:, then we MUST have a host,
    // and if there was a path
    // to begin with, then we MUST have a path.
    // if it is file:, then the host is dropped,
    // because that's known to be hostless.
    // anything else is assumed to be absolute.
    if (!slashedProtocol[relative.protocol]) {
      var keys = Object.keys(relative);
      for (var v = 0; v < keys.length; v++) {
        var k = keys[v];
        result[k] = relative[k];
      }
      result.href = result.format();
      return result;
    }

    result.protocol = relative.protocol;
    if (!relative.host && !hostlessProtocol[relative.protocol]) {
      var relPath = (relative.pathname || '').split('/');
      while (relPath.length && !(relative.host = relPath.shift()));
      if (!relative.host) relative.host = '';
      if (!relative.hostname) relative.hostname = '';
      if (relPath[0] !== '') relPath.unshift('');
      if (relPath.length < 2) relPath.unshift('');
      result.pathname = relPath.join('/');
    } else {
      result.pathname = relative.pathname;
    }
    result.search = relative.search;
    result.query = relative.query;
    result.host = relative.host || '';
    result.auth = relative.auth;
    result.hostname = relative.hostname || relative.host;
    result.port = relative.port;
    // to support http.request
    if (result.pathname || result.search) {
      var p = result.pathname || '';
      var s = result.search || '';
      result.path = p + s;
    }
    result.slashes = result.slashes || relative.slashes;
    result.href = result.format();
    return result;
  }

  var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
      isRelAbs = (
          relative.host ||
          relative.pathname && relative.pathname.charAt(0) === '/'
      ),
      mustEndAbs = (isRelAbs || isSourceAbs ||
                    (result.host && relative.pathname)),
      removeAllDots = mustEndAbs,
      srcPath = result.pathname && result.pathname.split('/') || [],
      relPath = relative.pathname && relative.pathname.split('/') || [],
      psychotic = result.protocol && !slashedProtocol[result.protocol];

  // if the url is a non-slashed url, then relative
  // links like ../.. should be able
  // to crawl up to the hostname, as well.  This is strange.
  // result.protocol has already been set by now.
  // Later on, put the first path part into the host field.
  if (psychotic) {
    result.hostname = '';
    result.port = null;
    if (result.host) {
      if (srcPath[0] === '') srcPath[0] = result.host;
      else srcPath.unshift(result.host);
    }
    result.host = '';
    if (relative.protocol) {
      relative.hostname = null;
      relative.port = null;
      if (relative.host) {
        if (relPath[0] === '') relPath[0] = relative.host;
        else relPath.unshift(relative.host);
      }
      relative.host = null;
    }
    mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  }

  if (isRelAbs) {
    // it's absolute.
    result.host = (relative.host || relative.host === '') ?
                  relative.host : result.host;
    result.hostname = (relative.hostname || relative.hostname === '') ?
                      relative.hostname : result.hostname;
    result.search = relative.search;
    result.query = relative.query;
    srcPath = relPath;
    // fall through to the dot-handling below.
  } else if (relPath.length) {
    // it's relative
    // throw away the existing file, and take the new path instead.
    if (!srcPath) srcPath = [];
    srcPath.pop();
    srcPath = srcPath.concat(relPath);
    result.search = relative.search;
    result.query = relative.query;
  } else if (!util.isNullOrUndefined(relative.search)) {
    // just pull out the search.
    // like href='?foo'.
    // Put this after the other two cases because it simplifies the booleans
    if (psychotic) {
      result.hostname = result.host = srcPath.shift();
      //occationaly the auth can get stuck only in host
      //this especially happens in cases like
      //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
      var authInHost = result.host && result.host.indexOf('@') > 0 ?
                       result.host.split('@') : false;
      if (authInHost) {
        result.auth = authInHost.shift();
        result.host = result.hostname = authInHost.shift();
      }
    }
    result.search = relative.search;
    result.query = relative.query;
    //to support http.request
    if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
      result.path = (result.pathname ? result.pathname : '') +
                    (result.search ? result.search : '');
    }
    result.href = result.format();
    return result;
  }

  if (!srcPath.length) {
    // no path at all.  easy.
    // we've already handled the other stuff above.
    result.pathname = null;
    //to support http.request
    if (result.search) {
      result.path = '/' + result.search;
    } else {
      result.path = null;
    }
    result.href = result.format();
    return result;
  }

  // if a url ENDs in . or .., then it must get a trailing slash.
  // however, if it ends in anything else non-slashy,
  // then it must NOT get a trailing slash.
  var last = srcPath.slice(-1)[0];
  var hasTrailingSlash = (
      (result.host || relative.host || srcPath.length > 1) &&
      (last === '.' || last === '..') || last === '');

  // strip single dots, resolve double dots to parent dir
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = srcPath.length; i >= 0; i--) {
    last = srcPath[i];
    if (last === '.') {
      srcPath.splice(i, 1);
    } else if (last === '..') {
      srcPath.splice(i, 1);
      up++;
    } else if (up) {
      srcPath.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (!mustEndAbs && !removeAllDots) {
    for (; up--; up) {
      srcPath.unshift('..');
    }
  }

  if (mustEndAbs && srcPath[0] !== '' &&
      (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
    srcPath.unshift('');
  }

  if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
    srcPath.push('');
  }

  var isAbsolute = srcPath[0] === '' ||
      (srcPath[0] && srcPath[0].charAt(0) === '/');

  // put the host back
  if (psychotic) {
    result.hostname = result.host = isAbsolute ? '' :
                                    srcPath.length ? srcPath.shift() : '';
    //occationaly the auth can get stuck only in host
    //this especially happens in cases like
    //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
    var authInHost = result.host && result.host.indexOf('@') > 0 ?
                     result.host.split('@') : false;
    if (authInHost) {
      result.auth = authInHost.shift();
      result.host = result.hostname = authInHost.shift();
    }
  }

  mustEndAbs = mustEndAbs || (result.host && srcPath.length);

  if (mustEndAbs && !isAbsolute) {
    srcPath.unshift('');
  }

  if (!srcPath.length) {
    result.pathname = null;
    result.path = null;
  } else {
    result.pathname = srcPath.join('/');
  }

  //to support request.http
  if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
    result.path = (result.pathname ? result.pathname : '') +
                  (result.search ? result.search : '');
  }
  result.auth = relative.auth || result.auth;
  result.slashes = result.slashes || relative.slashes;
  result.href = result.format();
  return result;
};

Url.prototype.parseHost = function() {
  var host = this.host;
  var port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ':') {
      this.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host) this.hostname = host;
};


/***/ }),

/***/ 2502:
/***/ ((module) => {

"use strict";


module.exports = {
  isString: function(arg) {
    return typeof(arg) === 'string';
  },
  isObject: function(arg) {
    return typeof(arg) === 'object' && arg !== null;
  },
  isNull: function(arg) {
    return arg === null;
  },
  isNullOrUndefined: function(arg) {
    return arg == null;
  }
};


/***/ }),

/***/ 3162:
/***/ ((module) => {

"use strict";


// Maps for number <-> hex string conversion
var _byteToHex = [];
var _hexToByte = {};
for (var i = 0; i < 256; i++) {
  _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  _hexToByte[_byteToHex[i]] = i;
}

// **`parse()` - Parse a UUID into it's component bytes**
function parse(s, buf, offset) {
  var i = (buf && offset) || 0;
  var ii = 0;

  buf = buf || [];
  s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
    if (ii < 16) { // Don't overflow!
      buf[i + ii++] = _hexToByte[oct];
    }
  });

  // Zero out remaining bytes if string was short
  while (ii < 16) {
    buf[i + ii++] = 0;
  }

  return buf;
}

// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
function unparse(buf, offset) {
  var i = offset || 0;
  var bth = _byteToHex;
  return  bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] + '-' +
          bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]] +
          bth[buf[i++]] + bth[buf[i++]];
}

module.exports = {
  parse: parse,
  unparse: unparse
};


/***/ })

}]);